Files
hydra/public/bundle.js
2024-02-09 17:09:30 +01:00

45092 lines
1.6 MiB
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
const devtools = require('choo-devtools')
const choo = require('choo')
const store = require('./src/stores/store.js')
const languageStore = require('./src/stores/language-store.js')
const mainView = require('./src/views/main.js')
const app = choo()
app.use(devtools())
app.use(store)
app.use(languageStore)
app.route('/', mainView)
app.route('/hydra-backup', mainView)
app.mount('body')
},{"./src/stores/language-store.js":233,"./src/stores/store.js":234,"./src/views/main.js":246,"choo":51,"choo-devtools":38}],2:[function(require,module,exports){
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{}],3:[function(require,module,exports){
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
module.exports = _arrayWithHoles, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{}],4:[function(require,module,exports){
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
module.exports = _assertThisInitialized, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{}],5:[function(require,module,exports){
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
module.exports = _classCallCheck, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{}],6:[function(require,module,exports){
var toPropertyKey = require("./toPropertyKey.js");
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, toPropertyKey(descriptor.key), descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{"./toPropertyKey.js":16}],7:[function(require,module,exports){
var toPropertyKey = require("./toPropertyKey.js");
function _defineProperty(obj, key, value) {
key = toPropertyKey(key);
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{"./toPropertyKey.js":16}],8:[function(require,module,exports){
function _getPrototypeOf(o) {
module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
}, module.exports.__esModule = true, module.exports["default"] = module.exports;
return _getPrototypeOf(o);
}
module.exports = _getPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{}],9:[function(require,module,exports){
var setPrototypeOf = require("./setPrototypeOf.js");
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) setPrototypeOf(subClass, superClass);
}
module.exports = _inherits, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{"./setPrototypeOf.js":13}],10:[function(require,module,exports){
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
module.exports = _iterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{}],11:[function(require,module,exports){
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
module.exports = _nonIterableRest, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{}],12:[function(require,module,exports){
var _typeof = require("./typeof.js")["default"];
var assertThisInitialized = require("./assertThisInitialized.js");
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return assertThisInitialized(self);
}
module.exports = _possibleConstructorReturn, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{"./assertThisInitialized.js":4,"./typeof.js":17}],13:[function(require,module,exports){
function _setPrototypeOf(o, p) {
module.exports = _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
}, module.exports.__esModule = true, module.exports["default"] = module.exports;
return _setPrototypeOf(o, p);
}
module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{}],14:[function(require,module,exports){
var arrayWithHoles = require("./arrayWithHoles.js");
var iterableToArray = require("./iterableToArray.js");
var unsupportedIterableToArray = require("./unsupportedIterableToArray.js");
var nonIterableRest = require("./nonIterableRest.js");
function _toArray(arr) {
return arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest();
}
module.exports = _toArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{"./arrayWithHoles.js":3,"./iterableToArray.js":10,"./nonIterableRest.js":11,"./unsupportedIterableToArray.js":18}],15:[function(require,module,exports){
var _typeof = require("./typeof.js")["default"];
function _toPrimitive(input, hint) {
if (_typeof(input) !== "object" || input === null) return input;
var prim = input[Symbol.toPrimitive];
if (prim !== undefined) {
var res = prim.call(input, hint || "default");
if (_typeof(res) !== "object") return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
module.exports = _toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{"./typeof.js":17}],16:[function(require,module,exports){
var _typeof = require("./typeof.js")["default"];
var toPrimitive = require("./toPrimitive.js");
function _toPropertyKey(arg) {
var key = toPrimitive(arg, "string");
return _typeof(key) === "symbol" ? key : String(key);
}
module.exports = _toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{"./toPrimitive.js":15,"./typeof.js":17}],17:[function(require,module,exports){
function _typeof(obj) {
"@babel/helpers - typeof";
return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(obj);
}
module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{}],18:[function(require,module,exports){
var arrayLikeToArray = require("./arrayLikeToArray.js");
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);
}
module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
},{"./arrayLikeToArray.js":2}],19:[function(require,module,exports){
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.acorn = {}));
})(this, (function (exports) { 'use strict';
// This file was generated. Do not modify manually!
var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
// This file was generated. Do not modify manually!
var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938, 6, 4191];
// This file was generated. Do not modify manually!
var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
// This file was generated. Do not modify manually!
var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
// These are a run-length and offset encoded representation of the
// >0xffff code points that are a valid part of identifiers. The
// offset starts at 0x10000, and each pair of numbers represents an
// offset to the next range, and then a size of the range.
// Reserved word lists for various dialects of the language
var reservedWords = {
3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
5: "class enum extends super const export import",
6: "enum",
strict: "implements interface let package private protected public static yield",
strictBind: "eval arguments"
};
// And the keywords
var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
var keywords$1 = {
5: ecma5AndLessKeywords,
"5module": ecma5AndLessKeywords + " export import",
6: ecma5AndLessKeywords + " const class extends export import super"
};
var keywordRelationalOperator = /^in(stanceof)?$/;
// ## Character categories
var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
// This has a complexity linear to the value of the code. The
// assumption is that looking up astral identifier characters is
// rare.
function isInAstralSet(code, set) {
var pos = 0x10000;
for (var i = 0; i < set.length; i += 2) {
pos += set[i];
if (pos > code) { return false }
pos += set[i + 1];
if (pos >= code) { return true }
}
return false
}
// Test whether a given character code starts an identifier.
function isIdentifierStart(code, astral) {
if (code < 65) { return code === 36 }
if (code < 91) { return true }
if (code < 97) { return code === 95 }
if (code < 123) { return true }
if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
if (astral === false) { return false }
return isInAstralSet(code, astralIdentifierStartCodes)
}
// Test whether a given character is part of an identifier.
function isIdentifierChar(code, astral) {
if (code < 48) { return code === 36 }
if (code < 58) { return true }
if (code < 65) { return false }
if (code < 91) { return true }
if (code < 97) { return code === 95 }
if (code < 123) { return true }
if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
if (astral === false) { return false }
return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
}
// ## Token types
// The assignment of fine-grained, information-carrying type objects
// allows the tokenizer to store the information it has about a
// token in a way that is very cheap for the parser to look up.
// All token type variables start with an underscore, to make them
// easy to recognize.
// The `beforeExpr` property is used to disambiguate between regular
// expressions and divisions. It is set on all token types that can
// be followed by an expression (thus, a slash after them would be a
// regular expression).
//
// The `startsExpr` property is used to check if the token ends a
// `yield` expression. It is set on all token types that either can
// directly start an expression (like a quotation mark) or can
// continue an expression (like the body of a string).
//
// `isLoop` marks a keyword as starting a loop, which is important
// to know when parsing a label, in order to allow or disallow
// continue jumps to that label.
var TokenType = function TokenType(label, conf) {
if ( conf === void 0 ) conf = {};
this.label = label;
this.keyword = conf.keyword;
this.beforeExpr = !!conf.beforeExpr;
this.startsExpr = !!conf.startsExpr;
this.isLoop = !!conf.isLoop;
this.isAssign = !!conf.isAssign;
this.prefix = !!conf.prefix;
this.postfix = !!conf.postfix;
this.binop = conf.binop || null;
this.updateContext = null;
};
function binop(name, prec) {
return new TokenType(name, {beforeExpr: true, binop: prec})
}
var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
// Map keyword names to token types.
var keywords = {};
// Succinct definitions of keyword token types
function kw(name, options) {
if ( options === void 0 ) options = {};
options.keyword = name;
return keywords[name] = new TokenType(name, options)
}
var types$1 = {
num: new TokenType("num", startsExpr),
regexp: new TokenType("regexp", startsExpr),
string: new TokenType("string", startsExpr),
name: new TokenType("name", startsExpr),
privateId: new TokenType("privateId", startsExpr),
eof: new TokenType("eof"),
// Punctuation token types.
bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
bracketR: new TokenType("]"),
braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
braceR: new TokenType("}"),
parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
parenR: new TokenType(")"),
comma: new TokenType(",", beforeExpr),
semi: new TokenType(";", beforeExpr),
colon: new TokenType(":", beforeExpr),
dot: new TokenType("."),
question: new TokenType("?", beforeExpr),
questionDot: new TokenType("?."),
arrow: new TokenType("=>", beforeExpr),
template: new TokenType("template"),
invalidTemplate: new TokenType("invalidTemplate"),
ellipsis: new TokenType("...", beforeExpr),
backQuote: new TokenType("`", startsExpr),
dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
// Operators. These carry several kinds of properties to help the
// parser use them properly (the presence of these properties is
// what categorizes them as operators).
//
// `binop`, when present, specifies that this operator is a binary
// operator, and will refer to its precedence.
//
// `prefix` and `postfix` mark the operator as a prefix or postfix
// unary operator.
//
// `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
// binary operators with a very low precedence, that should result
// in AssignmentExpression nodes.
eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
logicalOR: binop("||", 1),
logicalAND: binop("&&", 2),
bitwiseOR: binop("|", 3),
bitwiseXOR: binop("^", 4),
bitwiseAND: binop("&", 5),
equality: binop("==/!=/===/!==", 6),
relational: binop("</>/<=/>=", 7),
bitShift: binop("<</>>/>>>", 8),
plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
modulo: binop("%", 10),
star: binop("*", 10),
slash: binop("/", 10),
starstar: new TokenType("**", {beforeExpr: true}),
coalesce: binop("??", 1),
// Keyword token types.
_break: kw("break"),
_case: kw("case", beforeExpr),
_catch: kw("catch"),
_continue: kw("continue"),
_debugger: kw("debugger"),
_default: kw("default", beforeExpr),
_do: kw("do", {isLoop: true, beforeExpr: true}),
_else: kw("else", beforeExpr),
_finally: kw("finally"),
_for: kw("for", {isLoop: true}),
_function: kw("function", startsExpr),
_if: kw("if"),
_return: kw("return", beforeExpr),
_switch: kw("switch"),
_throw: kw("throw", beforeExpr),
_try: kw("try"),
_var: kw("var"),
_const: kw("const"),
_while: kw("while", {isLoop: true}),
_with: kw("with"),
_new: kw("new", {beforeExpr: true, startsExpr: true}),
_this: kw("this", startsExpr),
_super: kw("super", startsExpr),
_class: kw("class", startsExpr),
_extends: kw("extends", beforeExpr),
_export: kw("export"),
_import: kw("import", startsExpr),
_null: kw("null", startsExpr),
_true: kw("true", startsExpr),
_false: kw("false", startsExpr),
_in: kw("in", {beforeExpr: true, binop: 7}),
_instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
_typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
_void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
_delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
};
// Matches a whole line break (where CRLF is considered a single
// line break). Used to count lines.
var lineBreak = /\r\n?|\n|\u2028|\u2029/;
var lineBreakG = new RegExp(lineBreak.source, "g");
function isNewLine(code) {
return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
}
function nextLineBreak(code, from, end) {
if ( end === void 0 ) end = code.length;
for (var i = from; i < end; i++) {
var next = code.charCodeAt(i);
if (isNewLine(next))
{ return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
}
return -1
}
var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
var ref = Object.prototype;
var hasOwnProperty = ref.hasOwnProperty;
var toString = ref.toString;
var hasOwn = Object.hasOwn || (function (obj, propName) { return (
hasOwnProperty.call(obj, propName)
); });
var isArray = Array.isArray || (function (obj) { return (
toString.call(obj) === "[object Array]"
); });
function wordsRegexp(words) {
return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
}
function codePointToString(code) {
// UTF-16 Decoding
if (code <= 0xFFFF) { return String.fromCharCode(code) }
code -= 0x10000;
return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
}
var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
// These are used when `options.locations` is on, for the
// `startLoc` and `endLoc` properties.
var Position = function Position(line, col) {
this.line = line;
this.column = col;
};
Position.prototype.offset = function offset (n) {
return new Position(this.line, this.column + n)
};
var SourceLocation = function SourceLocation(p, start, end) {
this.start = start;
this.end = end;
if (p.sourceFile !== null) { this.source = p.sourceFile; }
};
// The `getLineInfo` function is mostly useful when the
// `locations` option is off (for performance reasons) and you
// want to find the line/column position for a given character
// offset. `input` should be the code string that the offset refers
// into.
function getLineInfo(input, offset) {
for (var line = 1, cur = 0;;) {
var nextBreak = nextLineBreak(input, cur, offset);
if (nextBreak < 0) { return new Position(line, offset - cur) }
++line;
cur = nextBreak;
}
}
// A second argument must be given to configure the parser process.
// These options are recognized (only `ecmaVersion` is required):
var defaultOptions = {
// `ecmaVersion` indicates the ECMAScript version to parse. Must be
// either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
// (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"`
// (the latest version the library supports). This influences
// support for strict mode, the set of reserved words, and support
// for new syntax features.
ecmaVersion: null,
// `sourceType` indicates the mode the code should be parsed in.
// Can be either `"script"` or `"module"`. This influences global
// strict mode and parsing of `import` and `export` declarations.
sourceType: "script",
// `onInsertedSemicolon` can be a callback that will be called
// when a semicolon is automatically inserted. It will be passed
// the position of the comma as an offset, and if `locations` is
// enabled, it is given the location as a `{line, column}` object
// as second argument.
onInsertedSemicolon: null,
// `onTrailingComma` is similar to `onInsertedSemicolon`, but for
// trailing commas.
onTrailingComma: null,
// By default, reserved words are only enforced if ecmaVersion >= 5.
// Set `allowReserved` to a boolean value to explicitly turn this on
// an off. When this option has the value "never", reserved words
// and keywords can also not be used as property names.
allowReserved: null,
// When enabled, a return at the top level is not considered an
// error.
allowReturnOutsideFunction: false,
// When enabled, import/export statements are not constrained to
// appearing at the top of the program, and an import.meta expression
// in a script isn't considered an error.
allowImportExportEverywhere: false,
// By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
// When enabled, await identifiers are allowed to appear at the top-level scope,
// but they are still not allowed in non-async functions.
allowAwaitOutsideFunction: null,
// When enabled, super identifiers are not constrained to
// appearing in methods and do not raise an error when they appear elsewhere.
allowSuperOutsideMethod: null,
// When enabled, hashbang directive in the beginning of file is
// allowed and treated as a line comment. Enabled by default when
// `ecmaVersion` >= 2023.
allowHashBang: false,
// When `locations` is on, `loc` properties holding objects with
// `start` and `end` properties in `{line, column}` form (with
// line being 1-based and column 0-based) will be attached to the
// nodes.
locations: false,
// A function can be passed as `onToken` option, which will
// cause Acorn to call that function with object in the same
// format as tokens returned from `tokenizer().getToken()`. Note
// that you are not allowed to call the parser from the
// callback—that will corrupt its internal state.
onToken: null,
// A function can be passed as `onComment` option, which will
// cause Acorn to call that function with `(block, text, start,
// end)` parameters whenever a comment is skipped. `block` is a
// boolean indicating whether this is a block (`/* */`) comment,
// `text` is the content of the comment, and `start` and `end` are
// character offsets that denote the start and end of the comment.
// When the `locations` option is on, two more parameters are
// passed, the full `{line, column}` locations of the start and
// end of the comments. Note that you are not allowed to call the
// parser from the callback—that will corrupt its internal state.
onComment: null,
// Nodes have their start and end characters offsets recorded in
// `start` and `end` properties (directly on the node, rather than
// the `loc` object, which holds line/column data. To also add a
// [semi-standardized][range] `range` property holding a `[start,
// end]` array with the same numbers, set the `ranges` option to
// `true`.
//
// [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
ranges: false,
// It is possible to parse multiple files into a single AST by
// passing the tree produced by parsing the first file as
// `program` option in subsequent parses. This will add the
// toplevel forms of the parsed file to the `Program` (top) node
// of an existing parse tree.
program: null,
// When `locations` is on, you can pass this to record the source
// file in every node's `loc` object.
sourceFile: null,
// This value, if given, is stored in every node, whether
// `locations` is on or off.
directSourceFile: null,
// When enabled, parenthesized expressions are represented by
// (non-standard) ParenthesizedExpression nodes
preserveParens: false
};
// Interpret and default an options object
var warnedAboutEcmaVersion = false;
function getOptions(opts) {
var options = {};
for (var opt in defaultOptions)
{ options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }
if (options.ecmaVersion === "latest") {
options.ecmaVersion = 1e8;
} else if (options.ecmaVersion == null) {
if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
warnedAboutEcmaVersion = true;
console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
}
options.ecmaVersion = 11;
} else if (options.ecmaVersion >= 2015) {
options.ecmaVersion -= 2009;
}
if (options.allowReserved == null)
{ options.allowReserved = options.ecmaVersion < 5; }
if (!opts || opts.allowHashBang == null)
{ options.allowHashBang = options.ecmaVersion >= 14; }
if (isArray(options.onToken)) {
var tokens = options.onToken;
options.onToken = function (token) { return tokens.push(token); };
}
if (isArray(options.onComment))
{ options.onComment = pushComment(options, options.onComment); }
return options
}
function pushComment(options, array) {
return function(block, text, start, end, startLoc, endLoc) {
var comment = {
type: block ? "Block" : "Line",
value: text,
start: start,
end: end
};
if (options.locations)
{ comment.loc = new SourceLocation(this, startLoc, endLoc); }
if (options.ranges)
{ comment.range = [start, end]; }
array.push(comment);
}
}
// Each scope gets a bitset that may contain these flags
var
SCOPE_TOP = 1,
SCOPE_FUNCTION = 2,
SCOPE_ASYNC = 4,
SCOPE_GENERATOR = 8,
SCOPE_ARROW = 16,
SCOPE_SIMPLE_CATCH = 32,
SCOPE_SUPER = 64,
SCOPE_DIRECT_SUPER = 128,
SCOPE_CLASS_STATIC_BLOCK = 256,
SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
function functionFlags(async, generator) {
return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
}
// Used in checkLVal* and declareName to determine the type of a binding
var
BIND_NONE = 0, // Not a binding
BIND_VAR = 1, // Var-style binding
BIND_LEXICAL = 2, // Let- or const-style binding
BIND_FUNCTION = 3, // Function declaration
BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
var Parser = function Parser(options, input, startPos) {
this.options = options = getOptions(options);
this.sourceFile = options.sourceFile;
this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
var reserved = "";
if (options.allowReserved !== true) {
reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
if (options.sourceType === "module") { reserved += " await"; }
}
this.reservedWords = wordsRegexp(reserved);
var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
this.reservedWordsStrict = wordsRegexp(reservedStrict);
this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
this.input = String(input);
// Used to signal to callers of `readWord1` whether the word
// contained any escape sequences. This is needed because words with
// escape sequences must not be interpreted as keywords.
this.containsEsc = false;
// Set up token state
// The current position of the tokenizer in the input.
if (startPos) {
this.pos = startPos;
this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
} else {
this.pos = this.lineStart = 0;
this.curLine = 1;
}
// Properties of the current token:
// Its type
this.type = types$1.eof;
// For tokens that include more information than their type, the value
this.value = null;
// Its start and end offset
this.start = this.end = this.pos;
// And, if locations are used, the {line, column} object
// corresponding to those offsets
this.startLoc = this.endLoc = this.curPosition();
// Position information for the previous token
this.lastTokEndLoc = this.lastTokStartLoc = null;
this.lastTokStart = this.lastTokEnd = this.pos;
// The context stack is used to superficially track syntactic
// context to predict whether a regular expression is allowed in a
// given position.
this.context = this.initialContext();
this.exprAllowed = true;
// Figure out if it's a module code.
this.inModule = options.sourceType === "module";
this.strict = this.inModule || this.strictDirective(this.pos);
// Used to signify the start of a potential arrow function
this.potentialArrowAt = -1;
this.potentialArrowInForAwait = false;
// Positions to delayed-check that yield/await does not exist in default parameters.
this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
// Labels in scope.
this.labels = [];
// Thus-far undefined exports.
this.undefinedExports = Object.create(null);
// If enabled, skip leading hashbang line.
if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
{ this.skipLineComment(2); }
// Scope tracking for duplicate variable names (see scope.js)
this.scopeStack = [];
this.enterScope(SCOPE_TOP);
// For RegExp validation
this.regexpState = null;
// The stack of private names.
// Each element has two properties: 'declared' and 'used'.
// When it exited from the outermost class definition, all used private names must be declared.
this.privateNameStack = [];
};
var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } };
Parser.prototype.parse = function parse () {
var node = this.options.program || this.startNode();
this.nextToken();
return this.parseTopLevel(node)
};
prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
prototypeAccessors.canAwait.get = function () {
for (var i = this.scopeStack.length - 1; i >= 0; i--) {
var scope = this.scopeStack[i];
if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false }
if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
}
return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
};
prototypeAccessors.allowSuper.get = function () {
var ref = this.currentThisScope();
var flags = ref.flags;
var inClassFieldInit = ref.inClassFieldInit;
return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
};
prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
prototypeAccessors.allowNewDotTarget.get = function () {
var ref = this.currentThisScope();
var flags = ref.flags;
var inClassFieldInit = ref.inClassFieldInit;
return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
};
prototypeAccessors.inClassStaticBlock.get = function () {
return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0
};
Parser.extend = function extend () {
var plugins = [], len = arguments.length;
while ( len-- ) plugins[ len ] = arguments[ len ];
var cls = this;
for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
return cls
};
Parser.parse = function parse (input, options) {
return new this(options, input).parse()
};
Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
var parser = new this(options, input, pos);
parser.nextToken();
return parser.parseExpression()
};
Parser.tokenizer = function tokenizer (input, options) {
return new this(options, input)
};
Object.defineProperties( Parser.prototype, prototypeAccessors );
var pp$9 = Parser.prototype;
// ## Parser utilities
var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
pp$9.strictDirective = function(start) {
if (this.options.ecmaVersion < 5) { return false }
for (;;) {
// Try to find string literal.
skipWhiteSpace.lastIndex = start;
start += skipWhiteSpace.exec(this.input)[0].length;
var match = literal.exec(this.input.slice(start));
if (!match) { return false }
if ((match[1] || match[2]) === "use strict") {
skipWhiteSpace.lastIndex = start + match[0].length;
var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
var next = this.input.charAt(end);
return next === ";" || next === "}" ||
(lineBreak.test(spaceAfter[0]) &&
!(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
}
start += match[0].length;
// Skip semicolon, if any.
skipWhiteSpace.lastIndex = start;
start += skipWhiteSpace.exec(this.input)[0].length;
if (this.input[start] === ";")
{ start++; }
}
};
// Predicate that tests whether the next token is of the given
// type, and if yes, consumes it as a side effect.
pp$9.eat = function(type) {
if (this.type === type) {
this.next();
return true
} else {
return false
}
};
// Tests whether parsed token is a contextual keyword.
pp$9.isContextual = function(name) {
return this.type === types$1.name && this.value === name && !this.containsEsc
};
// Consumes contextual keyword if possible.
pp$9.eatContextual = function(name) {
if (!this.isContextual(name)) { return false }
this.next();
return true
};
// Asserts that following token is given contextual keyword.
pp$9.expectContextual = function(name) {
if (!this.eatContextual(name)) { this.unexpected(); }
};
// Test whether a semicolon can be inserted at the current position.
pp$9.canInsertSemicolon = function() {
return this.type === types$1.eof ||
this.type === types$1.braceR ||
lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
};
pp$9.insertSemicolon = function() {
if (this.canInsertSemicolon()) {
if (this.options.onInsertedSemicolon)
{ this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
return true
}
};
// Consume a semicolon, or, failing that, see if we are allowed to
// pretend that there is a semicolon at this position.
pp$9.semicolon = function() {
if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
};
pp$9.afterTrailingComma = function(tokType, notNext) {
if (this.type === tokType) {
if (this.options.onTrailingComma)
{ this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
if (!notNext)
{ this.next(); }
return true
}
};
// Expect a token of a given type. If found, consume it, otherwise,
// raise an unexpected token error.
pp$9.expect = function(type) {
this.eat(type) || this.unexpected();
};
// Raise an unexpected token error.
pp$9.unexpected = function(pos) {
this.raise(pos != null ? pos : this.start, "Unexpected token");
};
var DestructuringErrors = function DestructuringErrors() {
this.shorthandAssign =
this.trailingComma =
this.parenthesizedAssign =
this.parenthesizedBind =
this.doubleProto =
-1;
};
pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
if (!refDestructuringErrors) { return }
if (refDestructuringErrors.trailingComma > -1)
{ this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); }
};
pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
if (!refDestructuringErrors) { return false }
var shorthandAssign = refDestructuringErrors.shorthandAssign;
var doubleProto = refDestructuringErrors.doubleProto;
if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
if (shorthandAssign >= 0)
{ this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
if (doubleProto >= 0)
{ this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
};
pp$9.checkYieldAwaitInDefaultParams = function() {
if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
{ this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
if (this.awaitPos)
{ this.raise(this.awaitPos, "Await expression cannot be a default value"); }
};
pp$9.isSimpleAssignTarget = function(expr) {
if (expr.type === "ParenthesizedExpression")
{ return this.isSimpleAssignTarget(expr.expression) }
return expr.type === "Identifier" || expr.type === "MemberExpression"
};
var pp$8 = Parser.prototype;
// ### Statement parsing
// Parse a program. Initializes the parser, reads any number of
// statements, and wraps them in a Program node. Optionally takes a
// `program` argument. If present, the statements will be appended
// to its body instead of creating a new node.
pp$8.parseTopLevel = function(node) {
var exports = Object.create(null);
if (!node.body) { node.body = []; }
while (this.type !== types$1.eof) {
var stmt = this.parseStatement(null, true, exports);
node.body.push(stmt);
}
if (this.inModule)
{ for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
{
var name = list[i];
this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
} }
this.adaptDirectivePrologue(node.body);
this.next();
node.sourceType = this.options.sourceType;
return this.finishNode(node, "Program")
};
var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
pp$8.isLet = function(context) {
if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
skipWhiteSpace.lastIndex = this.pos;
var skip = skipWhiteSpace.exec(this.input);
var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
// For ambiguous cases, determine if a LexicalDeclaration (or only a
// Statement) is allowed here. If context is not empty then only a Statement
// is allowed. However, `let [` is an explicit negative lookahead for
// ExpressionStatement, so special-case it first.
if (nextCh === 91 || nextCh === 92) { return true } // '[', '/'
if (context) { return false }
if (nextCh === 123 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '{', astral
if (isIdentifierStart(nextCh, true)) {
var pos = next + 1;
while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
var ident = this.input.slice(next, pos);
if (!keywordRelationalOperator.test(ident)) { return true }
}
return false
};
// check 'async [no LineTerminator here] function'
// - 'async /*foo*/ function' is OK.
// - 'async /*\n*/ function' is invalid.
pp$8.isAsyncFunction = function() {
if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
{ return false }
skipWhiteSpace.lastIndex = this.pos;
var skip = skipWhiteSpace.exec(this.input);
var next = this.pos + skip[0].length, after;
return !lineBreak.test(this.input.slice(this.pos, next)) &&
this.input.slice(next, next + 8) === "function" &&
(next + 8 === this.input.length ||
!(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
};
// Parse a single statement.
//
// If expecting a statement and finding a slash operator, parse a
// regular expression literal. This is to handle cases like
// `if (foo) /blah/.exec(foo)`, where looking at the previous token
// does not help.
pp$8.parseStatement = function(context, topLevel, exports) {
var starttype = this.type, node = this.startNode(), kind;
if (this.isLet(context)) {
starttype = types$1._var;
kind = "let";
}
// Most types of statements are recognized by the keyword they
// start with. Many are trivial to parse, some require a bit of
// complexity.
switch (starttype) {
case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
case types$1._debugger: return this.parseDebuggerStatement(node)
case types$1._do: return this.parseDoStatement(node)
case types$1._for: return this.parseForStatement(node)
case types$1._function:
// Function as sole body of either an if statement or a labeled statement
// works, but not when it is part of a labeled statement that is the sole
// body of an if statement.
if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
return this.parseFunctionStatement(node, false, !context)
case types$1._class:
if (context) { this.unexpected(); }
return this.parseClass(node, true)
case types$1._if: return this.parseIfStatement(node)
case types$1._return: return this.parseReturnStatement(node)
case types$1._switch: return this.parseSwitchStatement(node)
case types$1._throw: return this.parseThrowStatement(node)
case types$1._try: return this.parseTryStatement(node)
case types$1._const: case types$1._var:
kind = kind || this.value;
if (context && kind !== "var") { this.unexpected(); }
return this.parseVarStatement(node, kind)
case types$1._while: return this.parseWhileStatement(node)
case types$1._with: return this.parseWithStatement(node)
case types$1.braceL: return this.parseBlock(true, node)
case types$1.semi: return this.parseEmptyStatement(node)
case types$1._export:
case types$1._import:
if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
skipWhiteSpace.lastIndex = this.pos;
var skip = skipWhiteSpace.exec(this.input);
var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
if (nextCh === 40 || nextCh === 46) // '(' or '.'
{ return this.parseExpressionStatement(node, this.parseExpression()) }
}
if (!this.options.allowImportExportEverywhere) {
if (!topLevel)
{ this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
if (!this.inModule)
{ this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
}
return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports)
// If the statement does not start with a statement keyword or a
// brace, it's an ExpressionStatement or LabeledStatement. We
// simply start parsing an expression, and afterwards, if the
// next token is a colon and the expression was a simple
// Identifier node, we switch to interpreting it as a label.
default:
if (this.isAsyncFunction()) {
if (context) { this.unexpected(); }
this.next();
return this.parseFunctionStatement(node, true, !context)
}
var maybeName = this.value, expr = this.parseExpression();
if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon))
{ return this.parseLabeledStatement(node, maybeName, expr, context) }
else { return this.parseExpressionStatement(node, expr) }
}
};
pp$8.parseBreakContinueStatement = function(node, keyword) {
var isBreak = keyword === "break";
this.next();
if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }
else if (this.type !== types$1.name) { this.unexpected(); }
else {
node.label = this.parseIdent();
this.semicolon();
}
// Verify that there is an actual destination to break or
// continue to.
var i = 0;
for (; i < this.labels.length; ++i) {
var lab = this.labels[i];
if (node.label == null || lab.name === node.label.name) {
if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
if (node.label && isBreak) { break }
}
}
if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
};
pp$8.parseDebuggerStatement = function(node) {
this.next();
this.semicolon();
return this.finishNode(node, "DebuggerStatement")
};
pp$8.parseDoStatement = function(node) {
this.next();
this.labels.push(loopLabel);
node.body = this.parseStatement("do");
this.labels.pop();
this.expect(types$1._while);
node.test = this.parseParenExpression();
if (this.options.ecmaVersion >= 6)
{ this.eat(types$1.semi); }
else
{ this.semicolon(); }
return this.finishNode(node, "DoWhileStatement")
};
// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
// loop is non-trivial. Basically, we have to parse the init `var`
// statement or expression, disallowing the `in` operator (see
// the second parameter to `parseExpression`), and then check
// whether the next token is `in` or `of`. When there is no init
// part (semicolon immediately after the opening parenthesis), it
// is a regular `for` loop.
pp$8.parseForStatement = function(node) {
this.next();
var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
this.labels.push(loopLabel);
this.enterScope(0);
this.expect(types$1.parenL);
if (this.type === types$1.semi) {
if (awaitAt > -1) { this.unexpected(awaitAt); }
return this.parseFor(node, null)
}
var isLet = this.isLet();
if (this.type === types$1._var || this.type === types$1._const || isLet) {
var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
this.next();
this.parseVar(init$1, true, kind);
this.finishNode(init$1, "VariableDeclaration");
if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
if (this.options.ecmaVersion >= 9) {
if (this.type === types$1._in) {
if (awaitAt > -1) { this.unexpected(awaitAt); }
} else { node.await = awaitAt > -1; }
}
return this.parseForIn(node, init$1)
}
if (awaitAt > -1) { this.unexpected(awaitAt); }
return this.parseFor(node, init$1)
}
var startsWithLet = this.isContextual("let"), isForOf = false;
var refDestructuringErrors = new DestructuringErrors;
var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
if (this.options.ecmaVersion >= 9) {
if (this.type === types$1._in) {
if (awaitAt > -1) { this.unexpected(awaitAt); }
} else { node.await = awaitAt > -1; }
}
if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }
this.toAssignable(init, false, refDestructuringErrors);
this.checkLValPattern(init);
return this.parseForIn(node, init)
} else {
this.checkExpressionErrors(refDestructuringErrors, true);
}
if (awaitAt > -1) { this.unexpected(awaitAt); }
return this.parseFor(node, init)
};
pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
this.next();
return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
};
pp$8.parseIfStatement = function(node) {
this.next();
node.test = this.parseParenExpression();
// allow function declarations in branches, but only in non-strict mode
node.consequent = this.parseStatement("if");
node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
return this.finishNode(node, "IfStatement")
};
pp$8.parseReturnStatement = function(node) {
if (!this.inFunction && !this.options.allowReturnOutsideFunction)
{ this.raise(this.start, "'return' outside of function"); }
this.next();
// In `return` (and `break`/`continue`), the keywords with
// optional arguments, we eagerly look for a semicolon or the
// possibility to insert one.
if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }
else { node.argument = this.parseExpression(); this.semicolon(); }
return this.finishNode(node, "ReturnStatement")
};
pp$8.parseSwitchStatement = function(node) {
this.next();
node.discriminant = this.parseParenExpression();
node.cases = [];
this.expect(types$1.braceL);
this.labels.push(switchLabel);
this.enterScope(0);
// Statements under must be grouped (by label) in SwitchCase
// nodes. `cur` is used to keep the node that we are currently
// adding statements to.
var cur;
for (var sawDefault = false; this.type !== types$1.braceR;) {
if (this.type === types$1._case || this.type === types$1._default) {
var isCase = this.type === types$1._case;
if (cur) { this.finishNode(cur, "SwitchCase"); }
node.cases.push(cur = this.startNode());
cur.consequent = [];
this.next();
if (isCase) {
cur.test = this.parseExpression();
} else {
if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
sawDefault = true;
cur.test = null;
}
this.expect(types$1.colon);
} else {
if (!cur) { this.unexpected(); }
cur.consequent.push(this.parseStatement(null));
}
}
this.exitScope();
if (cur) { this.finishNode(cur, "SwitchCase"); }
this.next(); // Closing brace
this.labels.pop();
return this.finishNode(node, "SwitchStatement")
};
pp$8.parseThrowStatement = function(node) {
this.next();
if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
{ this.raise(this.lastTokEnd, "Illegal newline after throw"); }
node.argument = this.parseExpression();
this.semicolon();
return this.finishNode(node, "ThrowStatement")
};
// Reused empty array added for node fields that are always empty.
var empty$1 = [];
pp$8.parseCatchClauseParam = function() {
var param = this.parseBindingAtom();
var simple = param.type === "Identifier";
this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
this.expect(types$1.parenR);
return param
};
pp$8.parseTryStatement = function(node) {
this.next();
node.block = this.parseBlock();
node.handler = null;
if (this.type === types$1._catch) {
var clause = this.startNode();
this.next();
if (this.eat(types$1.parenL)) {
clause.param = this.parseCatchClauseParam();
} else {
if (this.options.ecmaVersion < 10) { this.unexpected(); }
clause.param = null;
this.enterScope(0);
}
clause.body = this.parseBlock(false);
this.exitScope();
node.handler = this.finishNode(clause, "CatchClause");
}
node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
if (!node.handler && !node.finalizer)
{ this.raise(node.start, "Missing catch or finally clause"); }
return this.finishNode(node, "TryStatement")
};
pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) {
this.next();
this.parseVar(node, false, kind, allowMissingInitializer);
this.semicolon();
return this.finishNode(node, "VariableDeclaration")
};
pp$8.parseWhileStatement = function(node) {
this.next();
node.test = this.parseParenExpression();
this.labels.push(loopLabel);
node.body = this.parseStatement("while");
this.labels.pop();
return this.finishNode(node, "WhileStatement")
};
pp$8.parseWithStatement = function(node) {
if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
this.next();
node.object = this.parseParenExpression();
node.body = this.parseStatement("with");
return this.finishNode(node, "WithStatement")
};
pp$8.parseEmptyStatement = function(node) {
this.next();
return this.finishNode(node, "EmptyStatement")
};
pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
{
var label = list[i$1];
if (label.name === maybeName)
{ this.raise(expr.start, "Label '" + maybeName + "' is already declared");
} }
var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
for (var i = this.labels.length - 1; i >= 0; i--) {
var label$1 = this.labels[i];
if (label$1.statementStart === node.start) {
// Update information about previous labels on this node
label$1.statementStart = this.start;
label$1.kind = kind;
} else { break }
}
this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
this.labels.pop();
node.label = expr;
return this.finishNode(node, "LabeledStatement")
};
pp$8.parseExpressionStatement = function(node, expr) {
node.expression = expr;
this.semicolon();
return this.finishNode(node, "ExpressionStatement")
};
// Parse a semicolon-enclosed block of statements, handling `"use
// strict"` declarations when `allowStrict` is true (used for
// function bodies).
pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
if ( node === void 0 ) node = this.startNode();
node.body = [];
this.expect(types$1.braceL);
if (createNewLexicalScope) { this.enterScope(0); }
while (this.type !== types$1.braceR) {
var stmt = this.parseStatement(null);
node.body.push(stmt);
}
if (exitStrict) { this.strict = false; }
this.next();
if (createNewLexicalScope) { this.exitScope(); }
return this.finishNode(node, "BlockStatement")
};
// Parse a regular `for` loop. The disambiguation code in
// `parseStatement` will already have parsed the init statement or
// expression.
pp$8.parseFor = function(node, init) {
node.init = init;
this.expect(types$1.semi);
node.test = this.type === types$1.semi ? null : this.parseExpression();
this.expect(types$1.semi);
node.update = this.type === types$1.parenR ? null : this.parseExpression();
this.expect(types$1.parenR);
node.body = this.parseStatement("for");
this.exitScope();
this.labels.pop();
return this.finishNode(node, "ForStatement")
};
// Parse a `for`/`in` and `for`/`of` loop, which are almost
// same from parser's perspective.
pp$8.parseForIn = function(node, init) {
var isForIn = this.type === types$1._in;
this.next();
if (
init.type === "VariableDeclaration" &&
init.declarations[0].init != null &&
(
!isForIn ||
this.options.ecmaVersion < 8 ||
this.strict ||
init.kind !== "var" ||
init.declarations[0].id.type !== "Identifier"
)
) {
this.raise(
init.start,
((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
);
}
node.left = init;
node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
this.expect(types$1.parenR);
node.body = this.parseStatement("for");
this.exitScope();
this.labels.pop();
return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
};
// Parse a list of variable declarations.
pp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) {
node.declarations = [];
node.kind = kind;
for (;;) {
var decl = this.startNode();
this.parseVarId(decl, kind);
if (this.eat(types$1.eq)) {
decl.init = this.parseMaybeAssign(isFor);
} else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
this.unexpected();
} else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
} else {
decl.init = null;
}
node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
if (!this.eat(types$1.comma)) { break }
}
return node
};
pp$8.parseVarId = function(decl, kind) {
decl.id = this.parseBindingAtom();
this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
};
var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
// Parse a function declaration or literal (depending on the
// `statement & FUNC_STATEMENT`).
// Remove `allowExpressionBody` for 7.0.0, as it is only called with false
pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
this.initFunction(node);
if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))
{ this.unexpected(); }
node.generator = this.eat(types$1.star);
}
if (this.options.ecmaVersion >= 8)
{ node.async = !!isAsync; }
if (statement & FUNC_STATEMENT) {
node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent();
if (node.id && !(statement & FUNC_HANGING_STATEMENT))
// If it is a regular function declaration in sloppy mode, then it is
// subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
// mode depends on properties of the current scope (see
// treatFunctionsAsVar).
{ this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
}
var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
this.yieldPos = 0;
this.awaitPos = 0;
this.awaitIdentPos = 0;
this.enterScope(functionFlags(node.async, node.generator));
if (!(statement & FUNC_STATEMENT))
{ node.id = this.type === types$1.name ? this.parseIdent() : null; }
this.parseFunctionParams(node);
this.parseFunctionBody(node, allowExpressionBody, false, forInit);
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
this.awaitIdentPos = oldAwaitIdentPos;
return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
};
pp$8.parseFunctionParams = function(node) {
this.expect(types$1.parenL);
node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
this.checkYieldAwaitInDefaultParams();
};
// Parse a class declaration or literal (depending on the
// `isStatement` parameter).
pp$8.parseClass = function(node, isStatement) {
this.next();
// ecma-262 14.6 Class Definitions
// A class definition is always strict mode code.
var oldStrict = this.strict;
this.strict = true;
this.parseClassId(node, isStatement);
this.parseClassSuper(node);
var privateNameMap = this.enterClassBody();
var classBody = this.startNode();
var hadConstructor = false;
classBody.body = [];
this.expect(types$1.braceL);
while (this.type !== types$1.braceR) {
var element = this.parseClassElement(node.superClass !== null);
if (element) {
classBody.body.push(element);
if (element.type === "MethodDefinition" && element.kind === "constructor") {
if (hadConstructor) { this.raiseRecoverable(element.start, "Duplicate constructor in the same class"); }
hadConstructor = true;
} else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
}
}
}
this.strict = oldStrict;
this.next();
node.body = this.finishNode(classBody, "ClassBody");
this.exitClassBody();
return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
};
pp$8.parseClassElement = function(constructorAllowsSuper) {
if (this.eat(types$1.semi)) { return null }
var ecmaVersion = this.options.ecmaVersion;
var node = this.startNode();
var keyName = "";
var isGenerator = false;
var isAsync = false;
var kind = "method";
var isStatic = false;
if (this.eatContextual("static")) {
// Parse static init block
if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
this.parseClassStaticBlock(node);
return node
}
if (this.isClassElementNameStart() || this.type === types$1.star) {
isStatic = true;
} else {
keyName = "static";
}
}
node.static = isStatic;
if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
isAsync = true;
} else {
keyName = "async";
}
}
if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {
isGenerator = true;
}
if (!keyName && !isAsync && !isGenerator) {
var lastValue = this.value;
if (this.eatContextual("get") || this.eatContextual("set")) {
if (this.isClassElementNameStart()) {
kind = lastValue;
} else {
keyName = lastValue;
}
}
}
// Parse element name
if (keyName) {
// 'async', 'get', 'set', or 'static' were not a keyword contextually.
// The last token is any of those. Make it the element name.
node.computed = false;
node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
node.key.name = keyName;
this.finishNode(node.key, "Identifier");
} else {
this.parseClassElementName(node);
}
// Parse element value
if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
var isConstructor = !node.static && checkKeyName(node, "constructor");
var allowsDirectSuper = isConstructor && constructorAllowsSuper;
// Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
node.kind = isConstructor ? "constructor" : kind;
this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
} else {
this.parseClassField(node);
}
return node
};
pp$8.isClassElementNameStart = function() {
return (
this.type === types$1.name ||
this.type === types$1.privateId ||
this.type === types$1.num ||
this.type === types$1.string ||
this.type === types$1.bracketL ||
this.type.keyword
)
};
pp$8.parseClassElementName = function(element) {
if (this.type === types$1.privateId) {
if (this.value === "constructor") {
this.raise(this.start, "Classes can't have an element named '#constructor'");
}
element.computed = false;
element.key = this.parsePrivateIdent();
} else {
this.parsePropertyName(element);
}
};
pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
// Check key and flags
var key = method.key;
if (method.kind === "constructor") {
if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
} else if (method.static && checkKeyName(method, "prototype")) {
this.raise(key.start, "Classes may not have a static property named prototype");
}
// Parse value
var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
// Check value
if (method.kind === "get" && value.params.length !== 0)
{ this.raiseRecoverable(value.start, "getter should have no params"); }
if (method.kind === "set" && value.params.length !== 1)
{ this.raiseRecoverable(value.start, "setter should have exactly one param"); }
if (method.kind === "set" && value.params[0].type === "RestElement")
{ this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
return this.finishNode(method, "MethodDefinition")
};
pp$8.parseClassField = function(field) {
if (checkKeyName(field, "constructor")) {
this.raise(field.key.start, "Classes can't have a field named 'constructor'");
} else if (field.static && checkKeyName(field, "prototype")) {
this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
}
if (this.eat(types$1.eq)) {
// To raise SyntaxError if 'arguments' exists in the initializer.
var scope = this.currentThisScope();
var inClassFieldInit = scope.inClassFieldInit;
scope.inClassFieldInit = true;
field.value = this.parseMaybeAssign();
scope.inClassFieldInit = inClassFieldInit;
} else {
field.value = null;
}
this.semicolon();
return this.finishNode(field, "PropertyDefinition")
};
pp$8.parseClassStaticBlock = function(node) {
node.body = [];
var oldLabels = this.labels;
this.labels = [];
this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
while (this.type !== types$1.braceR) {
var stmt = this.parseStatement(null);
node.body.push(stmt);
}
this.next();
this.exitScope();
this.labels = oldLabels;
return this.finishNode(node, "StaticBlock")
};
pp$8.parseClassId = function(node, isStatement) {
if (this.type === types$1.name) {
node.id = this.parseIdent();
if (isStatement)
{ this.checkLValSimple(node.id, BIND_LEXICAL, false); }
} else {
if (isStatement === true)
{ this.unexpected(); }
node.id = null;
}
};
pp$8.parseClassSuper = function(node) {
node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null;
};
pp$8.enterClassBody = function() {
var element = {declared: Object.create(null), used: []};
this.privateNameStack.push(element);
return element.declared
};
pp$8.exitClassBody = function() {
var ref = this.privateNameStack.pop();
var declared = ref.declared;
var used = ref.used;
var len = this.privateNameStack.length;
var parent = len === 0 ? null : this.privateNameStack[len - 1];
for (var i = 0; i < used.length; ++i) {
var id = used[i];
if (!hasOwn(declared, id.name)) {
if (parent) {
parent.used.push(id);
} else {
this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
}
}
}
};
function isPrivateNameConflicted(privateNameMap, element) {
var name = element.key.name;
var curr = privateNameMap[name];
var next = "true";
if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
next = (element.static ? "s" : "i") + element.kind;
}
// `class { get #a(){}; static set #a(_){} }` is also conflict.
if (
curr === "iget" && next === "iset" ||
curr === "iset" && next === "iget" ||
curr === "sget" && next === "sset" ||
curr === "sset" && next === "sget"
) {
privateNameMap[name] = "true";
return false
} else if (!curr) {
privateNameMap[name] = next;
return false
} else {
return true
}
}
function checkKeyName(node, name) {
var computed = node.computed;
var key = node.key;
return !computed && (
key.type === "Identifier" && key.name === name ||
key.type === "Literal" && key.value === name
)
}
// Parses module export declaration.
pp$8.parseExportAllDeclaration = function(node, exports) {
if (this.options.ecmaVersion >= 11) {
if (this.eatContextual("as")) {
node.exported = this.parseModuleExportName();
this.checkExport(exports, node.exported, this.lastTokStart);
} else {
node.exported = null;
}
}
this.expectContextual("from");
if (this.type !== types$1.string) { this.unexpected(); }
node.source = this.parseExprAtom();
this.semicolon();
return this.finishNode(node, "ExportAllDeclaration")
};
pp$8.parseExport = function(node, exports) {
this.next();
// export * from '...'
if (this.eat(types$1.star)) {
return this.parseExportAllDeclaration(node, exports)
}
if (this.eat(types$1._default)) { // export default ...
this.checkExport(exports, "default", this.lastTokStart);
node.declaration = this.parseExportDefaultDeclaration();
return this.finishNode(node, "ExportDefaultDeclaration")
}
// export var|const|let|function|class ...
if (this.shouldParseExportStatement()) {
node.declaration = this.parseExportDeclaration(node);
if (node.declaration.type === "VariableDeclaration")
{ this.checkVariableExport(exports, node.declaration.declarations); }
else
{ this.checkExport(exports, node.declaration.id, node.declaration.id.start); }
node.specifiers = [];
node.source = null;
} else { // export { x, y as z } [from '...']
node.declaration = null;
node.specifiers = this.parseExportSpecifiers(exports);
if (this.eatContextual("from")) {
if (this.type !== types$1.string) { this.unexpected(); }
node.source = this.parseExprAtom();
} else {
for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
// check for keywords used as local names
var spec = list[i];
this.checkUnreserved(spec.local);
// check if export is defined
this.checkLocalExport(spec.local);
if (spec.local.type === "Literal") {
this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
}
}
node.source = null;
}
this.semicolon();
}
return this.finishNode(node, "ExportNamedDeclaration")
};
pp$8.parseExportDeclaration = function(node) {
return this.parseStatement(null)
};
pp$8.parseExportDefaultDeclaration = function() {
var isAsync;
if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
var fNode = this.startNode();
this.next();
if (isAsync) { this.next(); }
return this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync)
} else if (this.type === types$1._class) {
var cNode = this.startNode();
return this.parseClass(cNode, "nullableID")
} else {
var declaration = this.parseMaybeAssign();
this.semicolon();
return declaration
}
};
pp$8.checkExport = function(exports, name, pos) {
if (!exports) { return }
if (typeof name !== "string")
{ name = name.type === "Identifier" ? name.name : name.value; }
if (hasOwn(exports, name))
{ this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
exports[name] = true;
};
pp$8.checkPatternExport = function(exports, pat) {
var type = pat.type;
if (type === "Identifier")
{ this.checkExport(exports, pat, pat.start); }
else if (type === "ObjectPattern")
{ for (var i = 0, list = pat.properties; i < list.length; i += 1)
{
var prop = list[i];
this.checkPatternExport(exports, prop);
} }
else if (type === "ArrayPattern")
{ for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
var elt = list$1[i$1];
if (elt) { this.checkPatternExport(exports, elt); }
} }
else if (type === "Property")
{ this.checkPatternExport(exports, pat.value); }
else if (type === "AssignmentPattern")
{ this.checkPatternExport(exports, pat.left); }
else if (type === "RestElement")
{ this.checkPatternExport(exports, pat.argument); }
else if (type === "ParenthesizedExpression")
{ this.checkPatternExport(exports, pat.expression); }
};
pp$8.checkVariableExport = function(exports, decls) {
if (!exports) { return }
for (var i = 0, list = decls; i < list.length; i += 1)
{
var decl = list[i];
this.checkPatternExport(exports, decl.id);
}
};
pp$8.shouldParseExportStatement = function() {
return this.type.keyword === "var" ||
this.type.keyword === "const" ||
this.type.keyword === "class" ||
this.type.keyword === "function" ||
this.isLet() ||
this.isAsyncFunction()
};
// Parses a comma-separated list of module exports.
pp$8.parseExportSpecifier = function(exports) {
var node = this.startNode();
node.local = this.parseModuleExportName();
node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
this.checkExport(
exports,
node.exported,
node.exported.start
);
return this.finishNode(node, "ExportSpecifier")
};
pp$8.parseExportSpecifiers = function(exports) {
var nodes = [], first = true;
// export { x, y as z } [from '...']
this.expect(types$1.braceL);
while (!this.eat(types$1.braceR)) {
if (!first) {
this.expect(types$1.comma);
if (this.afterTrailingComma(types$1.braceR)) { break }
} else { first = false; }
nodes.push(this.parseExportSpecifier(exports));
}
return nodes
};
// Parses import declaration.
pp$8.parseImport = function(node) {
this.next();
// import '...'
if (this.type === types$1.string) {
node.specifiers = empty$1;
node.source = this.parseExprAtom();
} else {
node.specifiers = this.parseImportSpecifiers();
this.expectContextual("from");
node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
}
this.semicolon();
return this.finishNode(node, "ImportDeclaration")
};
// Parses a comma-separated list of module imports.
pp$8.parseImportSpecifier = function() {
var node = this.startNode();
node.imported = this.parseModuleExportName();
if (this.eatContextual("as")) {
node.local = this.parseIdent();
} else {
this.checkUnreserved(node.imported);
node.local = node.imported;
}
this.checkLValSimple(node.local, BIND_LEXICAL);
return this.finishNode(node, "ImportSpecifier")
};
pp$8.parseImportDefaultSpecifier = function() {
// import defaultObj, { x, y as z } from '...'
var node = this.startNode();
node.local = this.parseIdent();
this.checkLValSimple(node.local, BIND_LEXICAL);
return this.finishNode(node, "ImportDefaultSpecifier")
};
pp$8.parseImportNamespaceSpecifier = function() {
var node = this.startNode();
this.next();
this.expectContextual("as");
node.local = this.parseIdent();
this.checkLValSimple(node.local, BIND_LEXICAL);
return this.finishNode(node, "ImportNamespaceSpecifier")
};
pp$8.parseImportSpecifiers = function() {
var nodes = [], first = true;
if (this.type === types$1.name) {
nodes.push(this.parseImportDefaultSpecifier());
if (!this.eat(types$1.comma)) { return nodes }
}
if (this.type === types$1.star) {
nodes.push(this.parseImportNamespaceSpecifier());
return nodes
}
this.expect(types$1.braceL);
while (!this.eat(types$1.braceR)) {
if (!first) {
this.expect(types$1.comma);
if (this.afterTrailingComma(types$1.braceR)) { break }
} else { first = false; }
nodes.push(this.parseImportSpecifier());
}
return nodes
};
pp$8.parseModuleExportName = function() {
if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
var stringLiteral = this.parseLiteral(this.value);
if (loneSurrogate.test(stringLiteral.value)) {
this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
}
return stringLiteral
}
return this.parseIdent(true)
};
// Set `ExpressionStatement#directive` property for directive prologues.
pp$8.adaptDirectivePrologue = function(statements) {
for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
statements[i].directive = statements[i].expression.raw.slice(1, -1);
}
};
pp$8.isDirectiveCandidate = function(statement) {
return (
this.options.ecmaVersion >= 5 &&
statement.type === "ExpressionStatement" &&
statement.expression.type === "Literal" &&
typeof statement.expression.value === "string" &&
// Reject parenthesized strings.
(this.input[statement.start] === "\"" || this.input[statement.start] === "'")
)
};
var pp$7 = Parser.prototype;
// Convert existing expression atom to assignable pattern
// if possible.
pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
if (this.options.ecmaVersion >= 6 && node) {
switch (node.type) {
case "Identifier":
if (this.inAsync && node.name === "await")
{ this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
break
case "ObjectPattern":
case "ArrayPattern":
case "AssignmentPattern":
case "RestElement":
break
case "ObjectExpression":
node.type = "ObjectPattern";
if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
for (var i = 0, list = node.properties; i < list.length; i += 1) {
var prop = list[i];
this.toAssignable(prop, isBinding);
// Early error:
// AssignmentRestProperty[Yield, Await] :
// `...` DestructuringAssignmentTarget[Yield, Await]
//
// It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
if (
prop.type === "RestElement" &&
(prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
) {
this.raise(prop.argument.start, "Unexpected token");
}
}
break
case "Property":
// AssignmentProperty has type === "Property"
if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
this.toAssignable(node.value, isBinding);
break
case "ArrayExpression":
node.type = "ArrayPattern";
if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
this.toAssignableList(node.elements, isBinding);
break
case "SpreadElement":
node.type = "RestElement";
this.toAssignable(node.argument, isBinding);
if (node.argument.type === "AssignmentPattern")
{ this.raise(node.argument.start, "Rest elements cannot have a default value"); }
break
case "AssignmentExpression":
if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
node.type = "AssignmentPattern";
delete node.operator;
this.toAssignable(node.left, isBinding);
break
case "ParenthesizedExpression":
this.toAssignable(node.expression, isBinding, refDestructuringErrors);
break
case "ChainExpression":
this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
break
case "MemberExpression":
if (!isBinding) { break }
default:
this.raise(node.start, "Assigning to rvalue");
}
} else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
return node
};
// Convert list of expression atoms to binding list.
pp$7.toAssignableList = function(exprList, isBinding) {
var end = exprList.length;
for (var i = 0; i < end; i++) {
var elt = exprList[i];
if (elt) { this.toAssignable(elt, isBinding); }
}
if (end) {
var last = exprList[end - 1];
if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
{ this.unexpected(last.argument.start); }
}
return exprList
};
// Parses spread element.
pp$7.parseSpread = function(refDestructuringErrors) {
var node = this.startNode();
this.next();
node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
return this.finishNode(node, "SpreadElement")
};
pp$7.parseRestBinding = function() {
var node = this.startNode();
this.next();
// RestElement inside of a function parameter must be an identifier
if (this.options.ecmaVersion === 6 && this.type !== types$1.name)
{ this.unexpected(); }
node.argument = this.parseBindingAtom();
return this.finishNode(node, "RestElement")
};
// Parses lvalue (assignable) atom.
pp$7.parseBindingAtom = function() {
if (this.options.ecmaVersion >= 6) {
switch (this.type) {
case types$1.bracketL:
var node = this.startNode();
this.next();
node.elements = this.parseBindingList(types$1.bracketR, true, true);
return this.finishNode(node, "ArrayPattern")
case types$1.braceL:
return this.parseObj(true)
}
}
return this.parseIdent()
};
pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) {
var elts = [], first = true;
while (!this.eat(close)) {
if (first) { first = false; }
else { this.expect(types$1.comma); }
if (allowEmpty && this.type === types$1.comma) {
elts.push(null);
} else if (allowTrailingComma && this.afterTrailingComma(close)) {
break
} else if (this.type === types$1.ellipsis) {
var rest = this.parseRestBinding();
this.parseBindingListItem(rest);
elts.push(rest);
if (this.type === types$1.comma) { this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); }
this.expect(close);
break
} else {
elts.push(this.parseAssignableListItem(allowModifiers));
}
}
return elts
};
pp$7.parseAssignableListItem = function(allowModifiers) {
var elem = this.parseMaybeDefault(this.start, this.startLoc);
this.parseBindingListItem(elem);
return elem
};
pp$7.parseBindingListItem = function(param) {
return param
};
// Parses assignment pattern around given atom if possible.
pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
left = left || this.parseBindingAtom();
if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }
var node = this.startNodeAt(startPos, startLoc);
node.left = left;
node.right = this.parseMaybeAssign();
return this.finishNode(node, "AssignmentPattern")
};
// The following three functions all verify that a node is an lvalue —
// something that can be bound, or assigned to. In order to do so, they perform
// a variety of checks:
//
// - Check that none of the bound/assigned-to identifiers are reserved words.
// - Record name declarations for bindings in the appropriate scope.
// - Check duplicate argument names, if checkClashes is set.
//
// If a complex binding pattern is encountered (e.g., object and array
// destructuring), the entire pattern is recursively checked.
//
// There are three versions of checkLVal*() appropriate for different
// circumstances:
//
// - checkLValSimple() shall be used if the syntactic construct supports
// nothing other than identifiers and member expressions. Parenthesized
// expressions are also correctly handled. This is generally appropriate for
// constructs for which the spec says
//
// > It is a Syntax Error if AssignmentTargetType of [the production] is not
// > simple.
//
// It is also appropriate for checking if an identifier is valid and not
// defined elsewhere, like import declarations or function/class identifiers.
//
// Examples where this is used include:
// a += …;
// import a from '…';
// where a is the node to be checked.
//
// - checkLValPattern() shall be used if the syntactic construct supports
// anything checkLValSimple() supports, as well as object and array
// destructuring patterns. This is generally appropriate for constructs for
// which the spec says
//
// > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
// > an ArrayLiteral and AssignmentTargetType of [the production] is not
// > simple.
//
// Examples where this is used include:
// (a = …);
// const a = …;
// try { … } catch (a) { … }
// where a is the node to be checked.
//
// - checkLValInnerPattern() shall be used if the syntactic construct supports
// anything checkLValPattern() supports, as well as default assignment
// patterns, rest elements, and other constructs that may appear within an
// object or array destructuring pattern.
//
// As a special case, function parameters also use checkLValInnerPattern(),
// as they also support defaults and rest constructs.
//
// These functions deliberately support both assignment and binding constructs,
// as the logic for both is exceedingly similar. If the node is the target of
// an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
// should be set to the appropriate BIND_* constant, like BIND_VAR or
// BIND_LEXICAL.
//
// If the function is called with a non-BIND_NONE bindingType, then
// additionally a checkClashes object may be specified to allow checking for
// duplicate argument names. checkClashes is ignored if the provided construct
// is an assignment (i.e., bindingType is BIND_NONE).
pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
if ( bindingType === void 0 ) bindingType = BIND_NONE;
var isBind = bindingType !== BIND_NONE;
switch (expr.type) {
case "Identifier":
if (this.strict && this.reservedWordsStrictBind.test(expr.name))
{ this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
if (isBind) {
if (bindingType === BIND_LEXICAL && expr.name === "let")
{ this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
if (checkClashes) {
if (hasOwn(checkClashes, expr.name))
{ this.raiseRecoverable(expr.start, "Argument name clash"); }
checkClashes[expr.name] = true;
}
if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
}
break
case "ChainExpression":
this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
break
case "MemberExpression":
if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
break
case "ParenthesizedExpression":
if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
return this.checkLValSimple(expr.expression, bindingType, checkClashes)
default:
this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
}
};
pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
if ( bindingType === void 0 ) bindingType = BIND_NONE;
switch (expr.type) {
case "ObjectPattern":
for (var i = 0, list = expr.properties; i < list.length; i += 1) {
var prop = list[i];
this.checkLValInnerPattern(prop, bindingType, checkClashes);
}
break
case "ArrayPattern":
for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
var elem = list$1[i$1];
if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
}
break
default:
this.checkLValSimple(expr, bindingType, checkClashes);
}
};
pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
if ( bindingType === void 0 ) bindingType = BIND_NONE;
switch (expr.type) {
case "Property":
// AssignmentProperty has type === "Property"
this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
break
case "AssignmentPattern":
this.checkLValPattern(expr.left, bindingType, checkClashes);
break
case "RestElement":
this.checkLValPattern(expr.argument, bindingType, checkClashes);
break
default:
this.checkLValPattern(expr, bindingType, checkClashes);
}
};
// The algorithm used to determine whether a regexp can appear at a
// given point in the program is loosely based on sweet.js' approach.
// See https://github.com/mozilla/sweet.js/wiki/design
var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
this.token = token;
this.isExpr = !!isExpr;
this.preserveSpace = !!preserveSpace;
this.override = override;
this.generator = !!generator;
};
var types = {
b_stat: new TokContext("{", false),
b_expr: new TokContext("{", true),
b_tmpl: new TokContext("${", false),
p_stat: new TokContext("(", false),
p_expr: new TokContext("(", true),
q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
f_stat: new TokContext("function", false),
f_expr: new TokContext("function", true),
f_expr_gen: new TokContext("function", true, false, null, true),
f_gen: new TokContext("function", false, false, null, true)
};
var pp$6 = Parser.prototype;
pp$6.initialContext = function() {
return [types.b_stat]
};
pp$6.curContext = function() {
return this.context[this.context.length - 1]
};
pp$6.braceIsBlock = function(prevType) {
var parent = this.curContext();
if (parent === types.f_expr || parent === types.f_stat)
{ return true }
if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr))
{ return !parent.isExpr }
// The check for `tt.name && exprAllowed` detects whether we are
// after a `yield` or `of` construct. See the `updateContext` for
// `tt.name`.
if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)
{ return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)
{ return true }
if (prevType === types$1.braceL)
{ return parent === types.b_stat }
if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)
{ return false }
return !this.exprAllowed
};
pp$6.inGeneratorContext = function() {
for (var i = this.context.length - 1; i >= 1; i--) {
var context = this.context[i];
if (context.token === "function")
{ return context.generator }
}
return false
};
pp$6.updateContext = function(prevType) {
var update, type = this.type;
if (type.keyword && prevType === types$1.dot)
{ this.exprAllowed = false; }
else if (update = type.updateContext)
{ update.call(this, prevType); }
else
{ this.exprAllowed = type.beforeExpr; }
};
// Used to handle egde cases when token context could not be inferred correctly during tokenization phase
pp$6.overrideContext = function(tokenCtx) {
if (this.curContext() !== tokenCtx) {
this.context[this.context.length - 1] = tokenCtx;
}
};
// Token-specific context update code
types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
if (this.context.length === 1) {
this.exprAllowed = true;
return
}
var out = this.context.pop();
if (out === types.b_stat && this.curContext().token === "function") {
out = this.context.pop();
}
this.exprAllowed = !out.isExpr;
};
types$1.braceL.updateContext = function(prevType) {
this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
this.exprAllowed = true;
};
types$1.dollarBraceL.updateContext = function() {
this.context.push(types.b_tmpl);
this.exprAllowed = true;
};
types$1.parenL.updateContext = function(prevType) {
var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
this.context.push(statementParens ? types.p_stat : types.p_expr);
this.exprAllowed = true;
};
types$1.incDec.updateContext = function() {
// tokExprAllowed stays unchanged
};
types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
if (prevType.beforeExpr && prevType !== types$1._else &&
!(prevType === types$1.semi && this.curContext() !== types.p_stat) &&
!(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
!((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat))
{ this.context.push(types.f_expr); }
else
{ this.context.push(types.f_stat); }
this.exprAllowed = false;
};
types$1.backQuote.updateContext = function() {
if (this.curContext() === types.q_tmpl)
{ this.context.pop(); }
else
{ this.context.push(types.q_tmpl); }
this.exprAllowed = false;
};
types$1.star.updateContext = function(prevType) {
if (prevType === types$1._function) {
var index = this.context.length - 1;
if (this.context[index] === types.f_expr)
{ this.context[index] = types.f_expr_gen; }
else
{ this.context[index] = types.f_gen; }
}
this.exprAllowed = true;
};
types$1.name.updateContext = function(prevType) {
var allowed = false;
if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
if (this.value === "of" && !this.exprAllowed ||
this.value === "yield" && this.inGeneratorContext())
{ allowed = true; }
}
this.exprAllowed = allowed;
};
// A recursive descent parser operates by defining functions for all
// syntactic elements, and recursively calling those, each function
// advancing the input stream and returning an AST node. Precedence
// of constructs (for example, the fact that `!x[1]` means `!(x[1])`
// instead of `(!x)[1]` is handled by the fact that the parser
// function that parses unary prefix operators is called first, and
// in turn calls the function that parses `[]` subscripts — that
// way, it'll receive the node for `x[1]` already parsed, and wraps
// *that* in the unary operator node.
//
// Acorn uses an [operator precedence parser][opp] to handle binary
// operator precedence, because it is much more compact than using
// the technique outlined above, which uses different, nesting
// functions to specify precedence, for all of the ten binary
// precedence levels that JavaScript defines.
//
// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
var pp$5 = Parser.prototype;
// Check if property name clashes with already added.
// Object/class getters and setters are not allowed to clash —
// either with each other or with an init property — and in
// strict mode, init properties are also not allowed to be repeated.
pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
{ return }
if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
{ return }
var key = prop.key;
var name;
switch (key.type) {
case "Identifier": name = key.name; break
case "Literal": name = String(key.value); break
default: return
}
var kind = prop.kind;
if (this.options.ecmaVersion >= 6) {
if (name === "__proto__" && kind === "init") {
if (propHash.proto) {
if (refDestructuringErrors) {
if (refDestructuringErrors.doubleProto < 0) {
refDestructuringErrors.doubleProto = key.start;
}
} else {
this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
}
}
propHash.proto = true;
}
return
}
name = "$" + name;
var other = propHash[name];
if (other) {
var redefinition;
if (kind === "init") {
redefinition = this.strict && other.init || other.get || other.set;
} else {
redefinition = other.init || other[kind];
}
if (redefinition)
{ this.raiseRecoverable(key.start, "Redefinition of property"); }
} else {
other = propHash[name] = {
init: false,
get: false,
set: false
};
}
other[kind] = true;
};
// ### Expression parsing
// These nest, from the most general expression type at the top to
// 'atomic', nondivisible expression types at the bottom. Most of
// the functions will simply let the function(s) below them parse,
// and, *if* the syntactic construct they handle is present, wrap
// the AST node that the inner parser gave them in another node.
// Parse a full expression. The optional arguments are used to
// forbid the `in` operator (in for loops initalization expressions)
// and provide reference for storing '=' operator inside shorthand
// property assignment in contexts where both object expression
// and object pattern might appear (so it's possible to raise
// delayed syntax error at correct position).
pp$5.parseExpression = function(forInit, refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc;
var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
if (this.type === types$1.comma) {
var node = this.startNodeAt(startPos, startLoc);
node.expressions = [expr];
while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
return this.finishNode(node, "SequenceExpression")
}
return expr
};
// Parse an assignment expression. This includes applications of
// operators like `+=`.
pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
if (this.isContextual("yield")) {
if (this.inGenerator) { return this.parseYield(forInit) }
// The tokenizer will assume an expression is allowed after
// `yield`, but this isn't that kind of yield
else { this.exprAllowed = false; }
}
var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
if (refDestructuringErrors) {
oldParenAssign = refDestructuringErrors.parenthesizedAssign;
oldTrailingComma = refDestructuringErrors.trailingComma;
oldDoubleProto = refDestructuringErrors.doubleProto;
refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
} else {
refDestructuringErrors = new DestructuringErrors;
ownDestructuringErrors = true;
}
var startPos = this.start, startLoc = this.startLoc;
if (this.type === types$1.parenL || this.type === types$1.name) {
this.potentialArrowAt = this.start;
this.potentialArrowInForAwait = forInit === "await";
}
var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
if (this.type.isAssign) {
var node = this.startNodeAt(startPos, startLoc);
node.operator = this.value;
if (this.type === types$1.eq)
{ left = this.toAssignable(left, false, refDestructuringErrors); }
if (!ownDestructuringErrors) {
refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
}
if (refDestructuringErrors.shorthandAssign >= left.start)
{ refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
if (this.type === types$1.eq)
{ this.checkLValPattern(left); }
else
{ this.checkLValSimple(left); }
node.left = left;
this.next();
node.right = this.parseMaybeAssign(forInit);
if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }
return this.finishNode(node, "AssignmentExpression")
} else {
if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
}
if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
return left
};
// Parse a ternary conditional (`?:`) operator.
pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc;
var expr = this.parseExprOps(forInit, refDestructuringErrors);
if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
if (this.eat(types$1.question)) {
var node = this.startNodeAt(startPos, startLoc);
node.test = expr;
node.consequent = this.parseMaybeAssign();
this.expect(types$1.colon);
node.alternate = this.parseMaybeAssign(forInit);
return this.finishNode(node, "ConditionalExpression")
}
return expr
};
// Start the precedence parser.
pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc;
var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
};
// Parse binary operators with the operator precedence parsing
// algorithm. `left` is the left-hand side of the operator.
// `minPrec` provides context that allows the function to stop and
// defer further parser to one of its callers when it encounters an
// operator that has a lower precedence than the set it is parsing.
pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
var prec = this.type.binop;
if (prec != null && (!forInit || this.type !== types$1._in)) {
if (prec > minPrec) {
var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
var coalesce = this.type === types$1.coalesce;
if (coalesce) {
// Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
// In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
prec = types$1.logicalAND.binop;
}
var op = this.value;
this.next();
var startPos = this.start, startLoc = this.startLoc;
var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {
this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
}
return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
}
}
return left
};
pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }
var node = this.startNodeAt(startPos, startLoc);
node.left = left;
node.operator = op;
node.right = right;
return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
};
// Parse unary operators, both prefix and postfix.
pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
var startPos = this.start, startLoc = this.startLoc, expr;
if (this.isContextual("await") && this.canAwait) {
expr = this.parseAwait(forInit);
sawUnary = true;
} else if (this.type.prefix) {
var node = this.startNode(), update = this.type === types$1.incDec;
node.operator = this.value;
node.prefix = true;
this.next();
node.argument = this.parseMaybeUnary(null, true, update, forInit);
this.checkExpressionErrors(refDestructuringErrors, true);
if (update) { this.checkLValSimple(node.argument); }
else if (this.strict && node.operator === "delete" &&
node.argument.type === "Identifier")
{ this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
{ this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
else { sawUnary = true; }
expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
} else if (!sawUnary && this.type === types$1.privateId) {
if (forInit || this.privateNameStack.length === 0) { this.unexpected(); }
expr = this.parsePrivateIdent();
// only could be private fields in 'in', such as #x in obj
if (this.type !== types$1._in) { this.unexpected(); }
} else {
expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
while (this.type.postfix && !this.canInsertSemicolon()) {
var node$1 = this.startNodeAt(startPos, startLoc);
node$1.operator = this.value;
node$1.prefix = false;
node$1.argument = expr;
this.checkLValSimple(expr);
this.next();
expr = this.finishNode(node$1, "UpdateExpression");
}
}
if (!incDec && this.eat(types$1.starstar)) {
if (sawUnary)
{ this.unexpected(this.lastTokStart); }
else
{ return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }
} else {
return expr
}
};
function isPrivateFieldAccess(node) {
return (
node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
)
}
// Parse call, dot, and `[]`-subscript expressions.
pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
var startPos = this.start, startLoc = this.startLoc;
var expr = this.parseExprAtom(refDestructuringErrors, forInit);
if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
{ return expr }
var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
if (refDestructuringErrors && result.type === "MemberExpression") {
if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
}
return result
};
pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
this.potentialArrowAt === base.start;
var optionalChained = false;
while (true) {
var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
if (element.optional) { optionalChained = true; }
if (element === base || element.type === "ArrowFunctionExpression") {
if (optionalChained) {
var chainNode = this.startNodeAt(startPos, startLoc);
chainNode.expression = element;
element = this.finishNode(chainNode, "ChainExpression");
}
return element
}
base = element;
}
};
pp$5.shouldParseAsyncArrow = function() {
return !this.canInsertSemicolon() && this.eat(types$1.arrow)
};
pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) {
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
};
pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
var optionalSupported = this.options.ecmaVersion >= 11;
var optional = optionalSupported && this.eat(types$1.questionDot);
if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
var computed = this.eat(types$1.bracketL);
if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {
var node = this.startNodeAt(startPos, startLoc);
node.object = base;
if (computed) {
node.property = this.parseExpression();
this.expect(types$1.bracketR);
} else if (this.type === types$1.privateId && base.type !== "Super") {
node.property = this.parsePrivateIdent();
} else {
node.property = this.parseIdent(this.options.allowReserved !== "never");
}
node.computed = !!computed;
if (optionalSupported) {
node.optional = optional;
}
base = this.finishNode(node, "MemberExpression");
} else if (!noCalls && this.eat(types$1.parenL)) {
var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
this.yieldPos = 0;
this.awaitPos = 0;
this.awaitIdentPos = 0;
var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) {
this.checkPatternErrors(refDestructuringErrors, false);
this.checkYieldAwaitInDefaultParams();
if (this.awaitIdentPos > 0)
{ this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
this.awaitIdentPos = oldAwaitIdentPos;
return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit)
}
this.checkExpressionErrors(refDestructuringErrors, true);
this.yieldPos = oldYieldPos || this.yieldPos;
this.awaitPos = oldAwaitPos || this.awaitPos;
this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
var node$1 = this.startNodeAt(startPos, startLoc);
node$1.callee = base;
node$1.arguments = exprList;
if (optionalSupported) {
node$1.optional = optional;
}
base = this.finishNode(node$1, "CallExpression");
} else if (this.type === types$1.backQuote) {
if (optional || optionalChained) {
this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
}
var node$2 = this.startNodeAt(startPos, startLoc);
node$2.tag = base;
node$2.quasi = this.parseTemplate({isTagged: true});
base = this.finishNode(node$2, "TaggedTemplateExpression");
}
return base
};
// Parse an atomic expression — either a single token that is an
// expression, an expression started by a keyword like `function` or
// `new`, or an expression wrapped in punctuation like `()`, `[]`,
// or `{}`.
pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) {
// If a division operator appears in an expression position, the
// tokenizer got confused, and we force it to read a regexp instead.
if (this.type === types$1.slash) { this.readRegexp(); }
var node, canBeArrow = this.potentialArrowAt === this.start;
switch (this.type) {
case types$1._super:
if (!this.allowSuper)
{ this.raise(this.start, "'super' keyword outside a method"); }
node = this.startNode();
this.next();
if (this.type === types$1.parenL && !this.allowDirectSuper)
{ this.raise(node.start, "super() call outside constructor of a subclass"); }
// The `super` keyword can appear at below:
// SuperProperty:
// super [ Expression ]
// super . IdentifierName
// SuperCall:
// super ( Arguments )
if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)
{ this.unexpected(); }
return this.finishNode(node, "Super")
case types$1._this:
node = this.startNode();
this.next();
return this.finishNode(node, "ThisExpression")
case types$1.name:
var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
var id = this.parseIdent(false);
if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
this.overrideContext(types.f_expr);
return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
}
if (canBeArrow && !this.canInsertSemicolon()) {
if (this.eat(types$1.arrow))
{ return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc &&
(!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
id = this.parseIdent(false);
if (this.canInsertSemicolon() || !this.eat(types$1.arrow))
{ this.unexpected(); }
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
}
}
return id
case types$1.regexp:
var value = this.value;
node = this.parseLiteral(value.value);
node.regex = {pattern: value.pattern, flags: value.flags};
return node
case types$1.num: case types$1.string:
return this.parseLiteral(this.value)
case types$1._null: case types$1._true: case types$1._false:
node = this.startNode();
node.value = this.type === types$1._null ? null : this.type === types$1._true;
node.raw = this.type.keyword;
this.next();
return this.finishNode(node, "Literal")
case types$1.parenL:
var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
if (refDestructuringErrors) {
if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
{ refDestructuringErrors.parenthesizedAssign = start; }
if (refDestructuringErrors.parenthesizedBind < 0)
{ refDestructuringErrors.parenthesizedBind = start; }
}
return expr
case types$1.bracketL:
node = this.startNode();
this.next();
node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
return this.finishNode(node, "ArrayExpression")
case types$1.braceL:
this.overrideContext(types.b_expr);
return this.parseObj(false, refDestructuringErrors)
case types$1._function:
node = this.startNode();
this.next();
return this.parseFunction(node, 0)
case types$1._class:
return this.parseClass(this.startNode(), false)
case types$1._new:
return this.parseNew()
case types$1.backQuote:
return this.parseTemplate()
case types$1._import:
if (this.options.ecmaVersion >= 11) {
return this.parseExprImport(forNew)
} else {
return this.unexpected()
}
default:
return this.parseExprAtomDefault()
}
};
pp$5.parseExprAtomDefault = function() {
this.unexpected();
};
pp$5.parseExprImport = function(forNew) {
var node = this.startNode();
// Consume `import` as an identifier for `import.meta`.
// Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
var meta = this.parseIdent(true);
if (this.type === types$1.parenL && !forNew) {
return this.parseDynamicImport(node)
} else if (this.type === types$1.dot) {
node.meta = meta;
return this.parseImportMeta(node)
} else {
this.unexpected();
}
};
pp$5.parseDynamicImport = function(node) {
this.next(); // skip `(`
// Parse node.source.
node.source = this.parseMaybeAssign();
// Verify ending.
if (!this.eat(types$1.parenR)) {
var errorPos = this.start;
if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
} else {
this.unexpected(errorPos);
}
}
return this.finishNode(node, "ImportExpression")
};
pp$5.parseImportMeta = function(node) {
this.next(); // skip `.`
var containsEsc = this.containsEsc;
node.property = this.parseIdent(true);
if (node.property.name !== "meta")
{ this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
if (containsEsc)
{ this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
{ this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
return this.finishNode(node, "MetaProperty")
};
pp$5.parseLiteral = function(value) {
var node = this.startNode();
node.value = value;
node.raw = this.input.slice(this.start, this.end);
if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
this.next();
return this.finishNode(node, "Literal")
};
pp$5.parseParenExpression = function() {
this.expect(types$1.parenL);
var val = this.parseExpression();
this.expect(types$1.parenR);
return val
};
pp$5.shouldParseArrow = function(exprList) {
return !this.canInsertSemicolon()
};
pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
if (this.options.ecmaVersion >= 6) {
this.next();
var innerStartPos = this.start, innerStartLoc = this.startLoc;
var exprList = [], first = true, lastIsComma = false;
var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
this.yieldPos = 0;
this.awaitPos = 0;
// Do not save awaitIdentPos to allow checking awaits nested in parameters
while (this.type !== types$1.parenR) {
first ? first = false : this.expect(types$1.comma);
if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
lastIsComma = true;
break
} else if (this.type === types$1.ellipsis) {
spreadStart = this.start;
exprList.push(this.parseParenItem(this.parseRestBinding()));
if (this.type === types$1.comma) {
this.raiseRecoverable(
this.start,
"Comma is not permitted after the rest element"
);
}
break
} else {
exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
}
}
var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
this.expect(types$1.parenR);
if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) {
this.checkPatternErrors(refDestructuringErrors, false);
this.checkYieldAwaitInDefaultParams();
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
}
if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
if (spreadStart) { this.unexpected(spreadStart); }
this.checkExpressionErrors(refDestructuringErrors, true);
this.yieldPos = oldYieldPos || this.yieldPos;
this.awaitPos = oldAwaitPos || this.awaitPos;
if (exprList.length > 1) {
val = this.startNodeAt(innerStartPos, innerStartLoc);
val.expressions = exprList;
this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
} else {
val = exprList[0];
}
} else {
val = this.parseParenExpression();
}
if (this.options.preserveParens) {
var par = this.startNodeAt(startPos, startLoc);
par.expression = val;
return this.finishNode(par, "ParenthesizedExpression")
} else {
return val
}
};
pp$5.parseParenItem = function(item) {
return item
};
pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
};
// New's precedence is slightly tricky. It must allow its argument to
// be a `[]` or dot subscript expression, but not a call — at least,
// not without wrapping it in parentheses. Thus, it uses the noCalls
// argument to parseSubscripts to prevent it from consuming the
// argument list.
var empty = [];
pp$5.parseNew = function() {
if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
var node = this.startNode();
var meta = this.parseIdent(true);
if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) {
node.meta = meta;
var containsEsc = this.containsEsc;
node.property = this.parseIdent(true);
if (node.property.name !== "target")
{ this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
if (containsEsc)
{ this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
if (!this.allowNewDotTarget)
{ this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }
return this.finishNode(node, "MetaProperty")
}
var startPos = this.start, startLoc = this.startLoc;
node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false);
if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }
else { node.arguments = empty; }
return this.finishNode(node, "NewExpression")
};
// Parse template expression.
pp$5.parseTemplateElement = function(ref) {
var isTagged = ref.isTagged;
var elem = this.startNode();
if (this.type === types$1.invalidTemplate) {
if (!isTagged) {
this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
}
elem.value = {
raw: this.value,
cooked: null
};
} else {
elem.value = {
raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
cooked: this.value
};
}
this.next();
elem.tail = this.type === types$1.backQuote;
return this.finishNode(elem, "TemplateElement")
};
pp$5.parseTemplate = function(ref) {
if ( ref === void 0 ) ref = {};
var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
var node = this.startNode();
this.next();
node.expressions = [];
var curElt = this.parseTemplateElement({isTagged: isTagged});
node.quasis = [curElt];
while (!curElt.tail) {
if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
this.expect(types$1.dollarBraceL);
node.expressions.push(this.parseExpression());
this.expect(types$1.braceR);
node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
}
this.next();
return this.finishNode(node, "TemplateLiteral")
};
pp$5.isAsyncProp = function(prop) {
return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
(this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) &&
!lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
};
// Parse an object literal or binding pattern.
pp$5.parseObj = function(isPattern, refDestructuringErrors) {
var node = this.startNode(), first = true, propHash = {};
node.properties = [];
this.next();
while (!this.eat(types$1.braceR)) {
if (!first) {
this.expect(types$1.comma);
if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }
} else { first = false; }
var prop = this.parseProperty(isPattern, refDestructuringErrors);
if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
node.properties.push(prop);
}
return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
};
pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
if (isPattern) {
prop.argument = this.parseIdent(false);
if (this.type === types$1.comma) {
this.raiseRecoverable(this.start, "Comma is not permitted after the rest element");
}
return this.finishNode(prop, "RestElement")
}
// Parse argument.
prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
// To disallow trailing comma via `this.toAssignable()`.
if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
refDestructuringErrors.trailingComma = this.start;
}
// Finish
return this.finishNode(prop, "SpreadElement")
}
if (this.options.ecmaVersion >= 6) {
prop.method = false;
prop.shorthand = false;
if (isPattern || refDestructuringErrors) {
startPos = this.start;
startLoc = this.startLoc;
}
if (!isPattern)
{ isGenerator = this.eat(types$1.star); }
}
var containsEsc = this.containsEsc;
this.parsePropertyName(prop);
if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
isAsync = true;
isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
this.parsePropertyName(prop);
} else {
isAsync = false;
}
this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
return this.finishNode(prop, "Property")
};
pp$5.parseGetterSetter = function(prop) {
prop.kind = prop.key.name;
this.parsePropertyName(prop);
prop.value = this.parseMethod(false);
var paramCount = prop.kind === "get" ? 0 : 1;
if (prop.value.params.length !== paramCount) {
var start = prop.value.start;
if (prop.kind === "get")
{ this.raiseRecoverable(start, "getter should have no params"); }
else
{ this.raiseRecoverable(start, "setter should have exactly one param"); }
} else {
if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
{ this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
}
};
pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
if ((isGenerator || isAsync) && this.type === types$1.colon)
{ this.unexpected(); }
if (this.eat(types$1.colon)) {
prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
prop.kind = "init";
} else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
if (isPattern) { this.unexpected(); }
prop.kind = "init";
prop.method = true;
prop.value = this.parseMethod(isGenerator, isAsync);
} else if (!isPattern && !containsEsc &&
this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
(prop.key.name === "get" || prop.key.name === "set") &&
(this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
if (isGenerator || isAsync) { this.unexpected(); }
this.parseGetterSetter(prop);
} else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
if (isGenerator || isAsync) { this.unexpected(); }
this.checkUnreserved(prop.key);
if (prop.key.name === "await" && !this.awaitIdentPos)
{ this.awaitIdentPos = startPos; }
prop.kind = "init";
if (isPattern) {
prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
} else if (this.type === types$1.eq && refDestructuringErrors) {
if (refDestructuringErrors.shorthandAssign < 0)
{ refDestructuringErrors.shorthandAssign = this.start; }
prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
} else {
prop.value = this.copyNode(prop.key);
}
prop.shorthand = true;
} else { this.unexpected(); }
};
pp$5.parsePropertyName = function(prop) {
if (this.options.ecmaVersion >= 6) {
if (this.eat(types$1.bracketL)) {
prop.computed = true;
prop.key = this.parseMaybeAssign();
this.expect(types$1.bracketR);
return prop.key
} else {
prop.computed = false;
}
}
return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
};
// Initialize empty function node.
pp$5.initFunction = function(node) {
node.id = null;
if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
if (this.options.ecmaVersion >= 8) { node.async = false; }
};
// Parse object or class method.
pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
this.initFunction(node);
if (this.options.ecmaVersion >= 6)
{ node.generator = isGenerator; }
if (this.options.ecmaVersion >= 8)
{ node.async = !!isAsync; }
this.yieldPos = 0;
this.awaitPos = 0;
this.awaitIdentPos = 0;
this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
this.expect(types$1.parenL);
node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
this.checkYieldAwaitInDefaultParams();
this.parseFunctionBody(node, false, true, false);
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
this.awaitIdentPos = oldAwaitIdentPos;
return this.finishNode(node, "FunctionExpression")
};
// Parse arrow function expression with given parameters.
pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
this.initFunction(node);
if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
this.yieldPos = 0;
this.awaitPos = 0;
this.awaitIdentPos = 0;
node.params = this.toAssignableList(params, true);
this.parseFunctionBody(node, true, false, forInit);
this.yieldPos = oldYieldPos;
this.awaitPos = oldAwaitPos;
this.awaitIdentPos = oldAwaitIdentPos;
return this.finishNode(node, "ArrowFunctionExpression")
};
// Parse function body and check parameters.
pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
var isExpression = isArrowFunction && this.type !== types$1.braceL;
var oldStrict = this.strict, useStrict = false;
if (isExpression) {
node.body = this.parseMaybeAssign(forInit);
node.expression = true;
this.checkParams(node, false);
} else {
var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
if (!oldStrict || nonSimple) {
useStrict = this.strictDirective(this.end);
// If this is a strict mode function, verify that argument names
// are not repeated, and it does not try to bind the words `eval`
// or `arguments`.
if (useStrict && nonSimple)
{ this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
}
// Start a new scope with regard to labels and the `inFunction`
// flag (restore them to their old value afterwards).
var oldLabels = this.labels;
this.labels = [];
if (useStrict) { this.strict = true; }
// Add the params to varDeclaredNames to ensure that an error is thrown
// if a let/const declaration in the function clashes with one of the params.
this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
// Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
node.expression = false;
this.adaptDirectivePrologue(node.body.body);
this.labels = oldLabels;
}
this.exitScope();
};
pp$5.isSimpleParamList = function(params) {
for (var i = 0, list = params; i < list.length; i += 1)
{
var param = list[i];
if (param.type !== "Identifier") { return false
} }
return true
};
// Checks function params for various disallowed patterns such as using "eval"
// or "arguments" and duplicate parameters.
pp$5.checkParams = function(node, allowDuplicates) {
var nameHash = Object.create(null);
for (var i = 0, list = node.params; i < list.length; i += 1)
{
var param = list[i];
this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
}
};
// Parses a comma-separated list of expressions, and returns them as
// an array. `close` is the token type that ends the list, and
// `allowEmpty` can be turned on to allow subsequent commas with
// nothing in between them to be parsed as `null` (which is needed
// for array literals).
pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
var elts = [], first = true;
while (!this.eat(close)) {
if (!first) {
this.expect(types$1.comma);
if (allowTrailingComma && this.afterTrailingComma(close)) { break }
} else { first = false; }
var elt = (void 0);
if (allowEmpty && this.type === types$1.comma)
{ elt = null; }
else if (this.type === types$1.ellipsis) {
elt = this.parseSpread(refDestructuringErrors);
if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)
{ refDestructuringErrors.trailingComma = this.start; }
} else {
elt = this.parseMaybeAssign(false, refDestructuringErrors);
}
elts.push(elt);
}
return elts
};
pp$5.checkUnreserved = function(ref) {
var start = ref.start;
var end = ref.end;
var name = ref.name;
if (this.inGenerator && name === "yield")
{ this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
if (this.inAsync && name === "await")
{ this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
if (this.currentThisScope().inClassFieldInit && name === "arguments")
{ this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
{ this.raise(start, ("Cannot use " + name + " in class static initialization block")); }
if (this.keywords.test(name))
{ this.raise(start, ("Unexpected keyword '" + name + "'")); }
if (this.options.ecmaVersion < 6 &&
this.input.slice(start, end).indexOf("\\") !== -1) { return }
var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
if (re.test(name)) {
if (!this.inAsync && name === "await")
{ this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
}
};
// Parse the next token as an identifier. If `liberal` is true (used
// when parsing properties), it will also convert keywords into
// identifiers.
pp$5.parseIdent = function(liberal) {
var node = this.parseIdentNode();
this.next(!!liberal);
this.finishNode(node, "Identifier");
if (!liberal) {
this.checkUnreserved(node);
if (node.name === "await" && !this.awaitIdentPos)
{ this.awaitIdentPos = node.start; }
}
return node
};
pp$5.parseIdentNode = function() {
var node = this.startNode();
if (this.type === types$1.name) {
node.name = this.value;
} else if (this.type.keyword) {
node.name = this.type.keyword;
// To fix https://github.com/acornjs/acorn/issues/575
// `class` and `function` keywords push new context into this.context.
// But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
// If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
if ((node.name === "class" || node.name === "function") &&
(this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
this.context.pop();
}
} else {
this.unexpected();
}
return node
};
pp$5.parsePrivateIdent = function() {
var node = this.startNode();
if (this.type === types$1.privateId) {
node.name = this.value;
} else {
this.unexpected();
}
this.next();
this.finishNode(node, "PrivateIdentifier");
// For validating existence
if (this.privateNameStack.length === 0) {
this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
} else {
this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
}
return node
};
// Parses yield expression inside generator.
pp$5.parseYield = function(forInit) {
if (!this.yieldPos) { this.yieldPos = this.start; }
var node = this.startNode();
this.next();
if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {
node.delegate = false;
node.argument = null;
} else {
node.delegate = this.eat(types$1.star);
node.argument = this.parseMaybeAssign(forInit);
}
return this.finishNode(node, "YieldExpression")
};
pp$5.parseAwait = function(forInit) {
if (!this.awaitPos) { this.awaitPos = this.start; }
var node = this.startNode();
this.next();
node.argument = this.parseMaybeUnary(null, true, false, forInit);
return this.finishNode(node, "AwaitExpression")
};
var pp$4 = Parser.prototype;
// This function is used to raise exceptions on parse errors. It
// takes an offset integer (into the current `input`) to indicate
// the location of the error, attaches the position to the end
// of the error message, and then raises a `SyntaxError` with that
// message.
pp$4.raise = function(pos, message) {
var loc = getLineInfo(this.input, pos);
message += " (" + loc.line + ":" + loc.column + ")";
var err = new SyntaxError(message);
err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
throw err
};
pp$4.raiseRecoverable = pp$4.raise;
pp$4.curPosition = function() {
if (this.options.locations) {
return new Position(this.curLine, this.pos - this.lineStart)
}
};
var pp$3 = Parser.prototype;
var Scope = function Scope(flags) {
this.flags = flags;
// A list of var-declared names in the current lexical scope
this.var = [];
// A list of lexically-declared names in the current lexical scope
this.lexical = [];
// A list of lexically-declared FunctionDeclaration names in the current lexical scope
this.functions = [];
// A switch to disallow the identifier reference 'arguments'
this.inClassFieldInit = false;
};
// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
pp$3.enterScope = function(flags) {
this.scopeStack.push(new Scope(flags));
};
pp$3.exitScope = function() {
this.scopeStack.pop();
};
// The spec says:
// > At the top level of a function, or script, function declarations are
// > treated like var declarations rather than like lexical declarations.
pp$3.treatFunctionsAsVarInScope = function(scope) {
return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
};
pp$3.declareName = function(name, bindingType, pos) {
var redeclared = false;
if (bindingType === BIND_LEXICAL) {
var scope = this.currentScope();
redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
scope.lexical.push(name);
if (this.inModule && (scope.flags & SCOPE_TOP))
{ delete this.undefinedExports[name]; }
} else if (bindingType === BIND_SIMPLE_CATCH) {
var scope$1 = this.currentScope();
scope$1.lexical.push(name);
} else if (bindingType === BIND_FUNCTION) {
var scope$2 = this.currentScope();
if (this.treatFunctionsAsVar)
{ redeclared = scope$2.lexical.indexOf(name) > -1; }
else
{ redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
scope$2.functions.push(name);
} else {
for (var i = this.scopeStack.length - 1; i >= 0; --i) {
var scope$3 = this.scopeStack[i];
if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
!this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
redeclared = true;
break
}
scope$3.var.push(name);
if (this.inModule && (scope$3.flags & SCOPE_TOP))
{ delete this.undefinedExports[name]; }
if (scope$3.flags & SCOPE_VAR) { break }
}
}
if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
};
pp$3.checkLocalExport = function(id) {
// scope.functions must be empty as Module code is always strict.
if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
this.scopeStack[0].var.indexOf(id.name) === -1) {
this.undefinedExports[id.name] = id;
}
};
pp$3.currentScope = function() {
return this.scopeStack[this.scopeStack.length - 1]
};
pp$3.currentVarScope = function() {
for (var i = this.scopeStack.length - 1;; i--) {
var scope = this.scopeStack[i];
if (scope.flags & SCOPE_VAR) { return scope }
}
};
// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
pp$3.currentThisScope = function() {
for (var i = this.scopeStack.length - 1;; i--) {
var scope = this.scopeStack[i];
if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
}
};
var Node = function Node(parser, pos, loc) {
this.type = "";
this.start = pos;
this.end = 0;
if (parser.options.locations)
{ this.loc = new SourceLocation(parser, loc); }
if (parser.options.directSourceFile)
{ this.sourceFile = parser.options.directSourceFile; }
if (parser.options.ranges)
{ this.range = [pos, 0]; }
};
// Start an AST node, attaching a start offset.
var pp$2 = Parser.prototype;
pp$2.startNode = function() {
return new Node(this, this.start, this.startLoc)
};
pp$2.startNodeAt = function(pos, loc) {
return new Node(this, pos, loc)
};
// Finish an AST node, adding `type` and `end` properties.
function finishNodeAt(node, type, pos, loc) {
node.type = type;
node.end = pos;
if (this.options.locations)
{ node.loc.end = loc; }
if (this.options.ranges)
{ node.range[1] = pos; }
return node
}
pp$2.finishNode = function(node, type) {
return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
};
// Finish node at given position
pp$2.finishNodeAt = function(node, type, pos, loc) {
return finishNodeAt.call(this, node, type, pos, loc)
};
pp$2.copyNode = function(node) {
var newNode = new Node(this, node.start, this.startLoc);
for (var prop in node) { newNode[prop] = node[prop]; }
return newNode
};
// This file contains Unicode properties extracted from the ECMAScript specification.
// The lists are extracted like so:
// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
// #table-binary-unicode-properties
var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
var ecma11BinaryProperties = ecma10BinaryProperties;
var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
var ecma13BinaryProperties = ecma12BinaryProperties;
var ecma14BinaryProperties = ecma13BinaryProperties;
var unicodeBinaryProperties = {
9: ecma9BinaryProperties,
10: ecma10BinaryProperties,
11: ecma11BinaryProperties,
12: ecma12BinaryProperties,
13: ecma13BinaryProperties,
14: ecma14BinaryProperties
};
// #table-binary-unicode-properties-of-strings
var ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji";
var unicodeBinaryPropertiesOfStrings = {
9: "",
10: "",
11: "",
12: "",
13: "",
14: ecma14BinaryPropertiesOfStrings
};
// #table-unicode-general-category-values
var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
// #table-unicode-script-values
var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
var ecma14ScriptValues = ecma13ScriptValues + " Hrkt Katakana_Or_Hiragana Kawi Nag_Mundari Nagm Unknown Zzzz";
var unicodeScriptValues = {
9: ecma9ScriptValues,
10: ecma10ScriptValues,
11: ecma11ScriptValues,
12: ecma12ScriptValues,
13: ecma13ScriptValues,
14: ecma14ScriptValues
};
var data = {};
function buildUnicodeData(ecmaVersion) {
var d = data[ecmaVersion] = {
binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion]),
nonBinary: {
General_Category: wordsRegexp(unicodeGeneralCategoryValues),
Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
}
};
d.nonBinary.Script_Extensions = d.nonBinary.Script;
d.nonBinary.gc = d.nonBinary.General_Category;
d.nonBinary.sc = d.nonBinary.Script;
d.nonBinary.scx = d.nonBinary.Script_Extensions;
}
for (var i = 0, list = [9, 10, 11, 12, 13, 14]; i < list.length; i += 1) {
var ecmaVersion = list[i];
buildUnicodeData(ecmaVersion);
}
var pp$1 = Parser.prototype;
var RegExpValidationState = function RegExpValidationState(parser) {
this.parser = parser;
this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : "");
this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion];
this.source = "";
this.flags = "";
this.start = 0;
this.switchU = false;
this.switchV = false;
this.switchN = false;
this.pos = 0;
this.lastIntValue = 0;
this.lastStringValue = "";
this.lastAssertionIsQuantifiable = false;
this.numCapturingParens = 0;
this.maxBackReference = 0;
this.groupNames = [];
this.backReferenceNames = [];
};
RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
var unicodeSets = flags.indexOf("v") !== -1;
var unicode = flags.indexOf("u") !== -1;
this.start = start | 0;
this.source = pattern + "";
this.flags = flags;
if (unicodeSets && this.parser.options.ecmaVersion >= 15) {
this.switchU = true;
this.switchV = true;
this.switchN = true;
} else {
this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
this.switchV = false;
this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
}
};
RegExpValidationState.prototype.raise = function raise (message) {
this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
};
// If u flag is given, this returns the code point at the index (it combines a surrogate pair).
// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
RegExpValidationState.prototype.at = function at (i, forceU) {
if ( forceU === void 0 ) forceU = false;
var s = this.source;
var l = s.length;
if (i >= l) {
return -1
}
var c = s.charCodeAt(i);
if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
return c
}
var next = s.charCodeAt(i + 1);
return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
};
RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
if ( forceU === void 0 ) forceU = false;
var s = this.source;
var l = s.length;
if (i >= l) {
return l
}
var c = s.charCodeAt(i), next;
if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
(next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
return i + 1
}
return i + 2
};
RegExpValidationState.prototype.current = function current (forceU) {
if ( forceU === void 0 ) forceU = false;
return this.at(this.pos, forceU)
};
RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
if ( forceU === void 0 ) forceU = false;
return this.at(this.nextIndex(this.pos, forceU), forceU)
};
RegExpValidationState.prototype.advance = function advance (forceU) {
if ( forceU === void 0 ) forceU = false;
this.pos = this.nextIndex(this.pos, forceU);
};
RegExpValidationState.prototype.eat = function eat (ch, forceU) {
if ( forceU === void 0 ) forceU = false;
if (this.current(forceU) === ch) {
this.advance(forceU);
return true
}
return false
};
RegExpValidationState.prototype.eatChars = function eatChars (chs, forceU) {
if ( forceU === void 0 ) forceU = false;
var pos = this.pos;
for (var i = 0, list = chs; i < list.length; i += 1) {
var ch = list[i];
var current = this.at(pos, forceU);
if (current === -1 || current !== ch) {
return false
}
pos = this.nextIndex(pos, forceU);
}
this.pos = pos;
return true
};
/**
* Validate the flags part of a given RegExpLiteral.
*
* @param {RegExpValidationState} state The state to validate RegExp.
* @returns {void}
*/
pp$1.validateRegExpFlags = function(state) {
var validFlags = state.validFlags;
var flags = state.flags;
var u = false;
var v = false;
for (var i = 0; i < flags.length; i++) {
var flag = flags.charAt(i);
if (validFlags.indexOf(flag) === -1) {
this.raise(state.start, "Invalid regular expression flag");
}
if (flags.indexOf(flag, i + 1) > -1) {
this.raise(state.start, "Duplicate regular expression flag");
}
if (flag === "u") { u = true; }
if (flag === "v") { v = true; }
}
if (this.options.ecmaVersion >= 15 && u && v) {
this.raise(state.start, "Invalid regular expression flag");
}
};
/**
* Validate the pattern part of a given RegExpLiteral.
*
* @param {RegExpValidationState} state The state to validate RegExp.
* @returns {void}
*/
pp$1.validateRegExpPattern = function(state) {
this.regexp_pattern(state);
// The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
// parsing contains a |GroupName|, reparse with the goal symbol
// |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
// exception if _P_ did not conform to the grammar, if any elements of _P_
// were not matched by the parse, or if any Early Error conditions exist.
if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
state.switchN = true;
this.regexp_pattern(state);
}
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
pp$1.regexp_pattern = function(state) {
state.pos = 0;
state.lastIntValue = 0;
state.lastStringValue = "";
state.lastAssertionIsQuantifiable = false;
state.numCapturingParens = 0;
state.maxBackReference = 0;
state.groupNames.length = 0;
state.backReferenceNames.length = 0;
this.regexp_disjunction(state);
if (state.pos !== state.source.length) {
// Make the same messages as V8.
if (state.eat(0x29 /* ) */)) {
state.raise("Unmatched ')'");
}
if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
state.raise("Lone quantifier brackets");
}
}
if (state.maxBackReference > state.numCapturingParens) {
state.raise("Invalid escape");
}
for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
var name = list[i];
if (state.groupNames.indexOf(name) === -1) {
state.raise("Invalid named capture referenced");
}
}
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
pp$1.regexp_disjunction = function(state) {
this.regexp_alternative(state);
while (state.eat(0x7C /* | */)) {
this.regexp_alternative(state);
}
// Make the same message as V8.
if (this.regexp_eatQuantifier(state, true)) {
state.raise("Nothing to repeat");
}
if (state.eat(0x7B /* { */)) {
state.raise("Lone quantifier brackets");
}
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
pp$1.regexp_alternative = function(state) {
while (state.pos < state.source.length && this.regexp_eatTerm(state))
{ }
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
pp$1.regexp_eatTerm = function(state) {
if (this.regexp_eatAssertion(state)) {
// Handle `QuantifiableAssertion Quantifier` alternative.
// `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
// is a QuantifiableAssertion.
if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
// Make the same message as V8.
if (state.switchU) {
state.raise("Invalid quantifier");
}
}
return true
}
if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
this.regexp_eatQuantifier(state);
return true
}
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
pp$1.regexp_eatAssertion = function(state) {
var start = state.pos;
state.lastAssertionIsQuantifiable = false;
// ^, $
if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
return true
}
// \b \B
if (state.eat(0x5C /* \ */)) {
if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
return true
}
state.pos = start;
}
// Lookahead / Lookbehind
if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
var lookbehind = false;
if (this.options.ecmaVersion >= 9) {
lookbehind = state.eat(0x3C /* < */);
}
if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
this.regexp_disjunction(state);
if (!state.eat(0x29 /* ) */)) {
state.raise("Unterminated group");
}
state.lastAssertionIsQuantifiable = !lookbehind;
return true
}
}
state.pos = start;
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
pp$1.regexp_eatQuantifier = function(state, noError) {
if ( noError === void 0 ) noError = false;
if (this.regexp_eatQuantifierPrefix(state, noError)) {
state.eat(0x3F /* ? */);
return true
}
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
return (
state.eat(0x2A /* * */) ||
state.eat(0x2B /* + */) ||
state.eat(0x3F /* ? */) ||
this.regexp_eatBracedQuantifier(state, noError)
)
};
pp$1.regexp_eatBracedQuantifier = function(state, noError) {
var start = state.pos;
if (state.eat(0x7B /* { */)) {
var min = 0, max = -1;
if (this.regexp_eatDecimalDigits(state)) {
min = state.lastIntValue;
if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
max = state.lastIntValue;
}
if (state.eat(0x7D /* } */)) {
// SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
if (max !== -1 && max < min && !noError) {
state.raise("numbers out of order in {} quantifier");
}
return true
}
}
if (state.switchU && !noError) {
state.raise("Incomplete quantifier");
}
state.pos = start;
}
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
pp$1.regexp_eatAtom = function(state) {
return (
this.regexp_eatPatternCharacters(state) ||
state.eat(0x2E /* . */) ||
this.regexp_eatReverseSolidusAtomEscape(state) ||
this.regexp_eatCharacterClass(state) ||
this.regexp_eatUncapturingGroup(state) ||
this.regexp_eatCapturingGroup(state)
)
};
pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
var start = state.pos;
if (state.eat(0x5C /* \ */)) {
if (this.regexp_eatAtomEscape(state)) {
return true
}
state.pos = start;
}
return false
};
pp$1.regexp_eatUncapturingGroup = function(state) {
var start = state.pos;
if (state.eat(0x28 /* ( */)) {
if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
this.regexp_disjunction(state);
if (state.eat(0x29 /* ) */)) {
return true
}
state.raise("Unterminated group");
}
state.pos = start;
}
return false
};
pp$1.regexp_eatCapturingGroup = function(state) {
if (state.eat(0x28 /* ( */)) {
if (this.options.ecmaVersion >= 9) {
this.regexp_groupSpecifier(state);
} else if (state.current() === 0x3F /* ? */) {
state.raise("Invalid group");
}
this.regexp_disjunction(state);
if (state.eat(0x29 /* ) */)) {
state.numCapturingParens += 1;
return true
}
state.raise("Unterminated group");
}
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
pp$1.regexp_eatExtendedAtom = function(state) {
return (
state.eat(0x2E /* . */) ||
this.regexp_eatReverseSolidusAtomEscape(state) ||
this.regexp_eatCharacterClass(state) ||
this.regexp_eatUncapturingGroup(state) ||
this.regexp_eatCapturingGroup(state) ||
this.regexp_eatInvalidBracedQuantifier(state) ||
this.regexp_eatExtendedPatternCharacter(state)
)
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
if (this.regexp_eatBracedQuantifier(state, true)) {
state.raise("Nothing to repeat");
}
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
pp$1.regexp_eatSyntaxCharacter = function(state) {
var ch = state.current();
if (isSyntaxCharacter(ch)) {
state.lastIntValue = ch;
state.advance();
return true
}
return false
};
function isSyntaxCharacter(ch) {
return (
ch === 0x24 /* $ */ ||
ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
ch === 0x2E /* . */ ||
ch === 0x3F /* ? */ ||
ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
ch >= 0x7B /* { */ && ch <= 0x7D /* } */
)
}
// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
// But eat eager.
pp$1.regexp_eatPatternCharacters = function(state) {
var start = state.pos;
var ch = 0;
while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
state.advance();
}
return state.pos !== start
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
pp$1.regexp_eatExtendedPatternCharacter = function(state) {
var ch = state.current();
if (
ch !== -1 &&
ch !== 0x24 /* $ */ &&
!(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
ch !== 0x2E /* . */ &&
ch !== 0x3F /* ? */ &&
ch !== 0x5B /* [ */ &&
ch !== 0x5E /* ^ */ &&
ch !== 0x7C /* | */
) {
state.advance();
return true
}
return false
};
// GroupSpecifier ::
// [empty]
// `?` GroupName
pp$1.regexp_groupSpecifier = function(state) {
if (state.eat(0x3F /* ? */)) {
if (this.regexp_eatGroupName(state)) {
if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
state.raise("Duplicate capture group name");
}
state.groupNames.push(state.lastStringValue);
return
}
state.raise("Invalid group");
}
};
// GroupName ::
// `<` RegExpIdentifierName `>`
// Note: this updates `state.lastStringValue` property with the eaten name.
pp$1.regexp_eatGroupName = function(state) {
state.lastStringValue = "";
if (state.eat(0x3C /* < */)) {
if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
return true
}
state.raise("Invalid capture group name");
}
return false
};
// RegExpIdentifierName ::
// RegExpIdentifierStart
// RegExpIdentifierName RegExpIdentifierPart
// Note: this updates `state.lastStringValue` property with the eaten name.
pp$1.regexp_eatRegExpIdentifierName = function(state) {
state.lastStringValue = "";
if (this.regexp_eatRegExpIdentifierStart(state)) {
state.lastStringValue += codePointToString(state.lastIntValue);
while (this.regexp_eatRegExpIdentifierPart(state)) {
state.lastStringValue += codePointToString(state.lastIntValue);
}
return true
}
return false
};
// RegExpIdentifierStart ::
// UnicodeIDStart
// `$`
// `_`
// `\` RegExpUnicodeEscapeSequence[+U]
pp$1.regexp_eatRegExpIdentifierStart = function(state) {
var start = state.pos;
var forceU = this.options.ecmaVersion >= 11;
var ch = state.current(forceU);
state.advance(forceU);
if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
ch = state.lastIntValue;
}
if (isRegExpIdentifierStart(ch)) {
state.lastIntValue = ch;
return true
}
state.pos = start;
return false
};
function isRegExpIdentifierStart(ch) {
return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
}
// RegExpIdentifierPart ::
// UnicodeIDContinue
// `$`
// `_`
// `\` RegExpUnicodeEscapeSequence[+U]
// <ZWNJ>
// <ZWJ>
pp$1.regexp_eatRegExpIdentifierPart = function(state) {
var start = state.pos;
var forceU = this.options.ecmaVersion >= 11;
var ch = state.current(forceU);
state.advance(forceU);
if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
ch = state.lastIntValue;
}
if (isRegExpIdentifierPart(ch)) {
state.lastIntValue = ch;
return true
}
state.pos = start;
return false
};
function isRegExpIdentifierPart(ch) {
return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
}
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
pp$1.regexp_eatAtomEscape = function(state) {
if (
this.regexp_eatBackReference(state) ||
this.regexp_eatCharacterClassEscape(state) ||
this.regexp_eatCharacterEscape(state) ||
(state.switchN && this.regexp_eatKGroupName(state))
) {
return true
}
if (state.switchU) {
// Make the same message as V8.
if (state.current() === 0x63 /* c */) {
state.raise("Invalid unicode escape");
}
state.raise("Invalid escape");
}
return false
};
pp$1.regexp_eatBackReference = function(state) {
var start = state.pos;
if (this.regexp_eatDecimalEscape(state)) {
var n = state.lastIntValue;
if (state.switchU) {
// For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
if (n > state.maxBackReference) {
state.maxBackReference = n;
}
return true
}
if (n <= state.numCapturingParens) {
return true
}
state.pos = start;
}
return false
};
pp$1.regexp_eatKGroupName = function(state) {
if (state.eat(0x6B /* k */)) {
if (this.regexp_eatGroupName(state)) {
state.backReferenceNames.push(state.lastStringValue);
return true
}
state.raise("Invalid named reference");
}
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
pp$1.regexp_eatCharacterEscape = function(state) {
return (
this.regexp_eatControlEscape(state) ||
this.regexp_eatCControlLetter(state) ||
this.regexp_eatZero(state) ||
this.regexp_eatHexEscapeSequence(state) ||
this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
(!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
this.regexp_eatIdentityEscape(state)
)
};
pp$1.regexp_eatCControlLetter = function(state) {
var start = state.pos;
if (state.eat(0x63 /* c */)) {
if (this.regexp_eatControlLetter(state)) {
return true
}
state.pos = start;
}
return false
};
pp$1.regexp_eatZero = function(state) {
if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
state.lastIntValue = 0;
state.advance();
return true
}
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
pp$1.regexp_eatControlEscape = function(state) {
var ch = state.current();
if (ch === 0x74 /* t */) {
state.lastIntValue = 0x09; /* \t */
state.advance();
return true
}
if (ch === 0x6E /* n */) {
state.lastIntValue = 0x0A; /* \n */
state.advance();
return true
}
if (ch === 0x76 /* v */) {
state.lastIntValue = 0x0B; /* \v */
state.advance();
return true
}
if (ch === 0x66 /* f */) {
state.lastIntValue = 0x0C; /* \f */
state.advance();
return true
}
if (ch === 0x72 /* r */) {
state.lastIntValue = 0x0D; /* \r */
state.advance();
return true
}
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
pp$1.regexp_eatControlLetter = function(state) {
var ch = state.current();
if (isControlLetter(ch)) {
state.lastIntValue = ch % 0x20;
state.advance();
return true
}
return false
};
function isControlLetter(ch) {
return (
(ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
(ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
)
}
// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
if ( forceU === void 0 ) forceU = false;
var start = state.pos;
var switchU = forceU || state.switchU;
if (state.eat(0x75 /* u */)) {
if (this.regexp_eatFixedHexDigits(state, 4)) {
var lead = state.lastIntValue;
if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
var leadSurrogateEnd = state.pos;
if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
var trail = state.lastIntValue;
if (trail >= 0xDC00 && trail <= 0xDFFF) {
state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
return true
}
}
state.pos = leadSurrogateEnd;
state.lastIntValue = lead;
}
return true
}
if (
switchU &&
state.eat(0x7B /* { */) &&
this.regexp_eatHexDigits(state) &&
state.eat(0x7D /* } */) &&
isValidUnicode(state.lastIntValue)
) {
return true
}
if (switchU) {
state.raise("Invalid unicode escape");
}
state.pos = start;
}
return false
};
function isValidUnicode(ch) {
return ch >= 0 && ch <= 0x10FFFF
}
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
pp$1.regexp_eatIdentityEscape = function(state) {
if (state.switchU) {
if (this.regexp_eatSyntaxCharacter(state)) {
return true
}
if (state.eat(0x2F /* / */)) {
state.lastIntValue = 0x2F; /* / */
return true
}
return false
}
var ch = state.current();
if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
state.lastIntValue = ch;
state.advance();
return true
}
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
pp$1.regexp_eatDecimalEscape = function(state) {
state.lastIntValue = 0;
var ch = state.current();
if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
do {
state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
state.advance();
} while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
return true
}
return false
};
// Return values used by character set parsing methods, needed to
// forbid negation of sets that can match strings.
var CharSetNone = 0; // Nothing parsed
var CharSetOk = 1; // Construct parsed, cannot contain strings
var CharSetString = 2; // Construct parsed, can contain strings
// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
pp$1.regexp_eatCharacterClassEscape = function(state) {
var ch = state.current();
if (isCharacterClassEscape(ch)) {
state.lastIntValue = -1;
state.advance();
return CharSetOk
}
var negate = false;
if (
state.switchU &&
this.options.ecmaVersion >= 9 &&
((negate = ch === 0x50 /* P */) || ch === 0x70 /* p */)
) {
state.lastIntValue = -1;
state.advance();
var result;
if (
state.eat(0x7B /* { */) &&
(result = this.regexp_eatUnicodePropertyValueExpression(state)) &&
state.eat(0x7D /* } */)
) {
if (negate && result === CharSetString) { state.raise("Invalid property name"); }
return result
}
state.raise("Invalid property name");
}
return CharSetNone
};
function isCharacterClassEscape(ch) {
return (
ch === 0x64 /* d */ ||
ch === 0x44 /* D */ ||
ch === 0x73 /* s */ ||
ch === 0x53 /* S */ ||
ch === 0x77 /* w */ ||
ch === 0x57 /* W */
)
}
// UnicodePropertyValueExpression ::
// UnicodePropertyName `=` UnicodePropertyValue
// LoneUnicodePropertyNameOrValue
pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
var start = state.pos;
// UnicodePropertyName `=` UnicodePropertyValue
if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
var name = state.lastStringValue;
if (this.regexp_eatUnicodePropertyValue(state)) {
var value = state.lastStringValue;
this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
return CharSetOk
}
}
state.pos = start;
// LoneUnicodePropertyNameOrValue
if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
var nameOrValue = state.lastStringValue;
return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue)
}
return CharSetNone
};
pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
if (!hasOwn(state.unicodeProperties.nonBinary, name))
{ state.raise("Invalid property name"); }
if (!state.unicodeProperties.nonBinary[name].test(value))
{ state.raise("Invalid property value"); }
};
pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
if (state.unicodeProperties.binary.test(nameOrValue)) { return CharSetOk }
if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) { return CharSetString }
state.raise("Invalid property name");
};
// UnicodePropertyName ::
// UnicodePropertyNameCharacters
pp$1.regexp_eatUnicodePropertyName = function(state) {
var ch = 0;
state.lastStringValue = "";
while (isUnicodePropertyNameCharacter(ch = state.current())) {
state.lastStringValue += codePointToString(ch);
state.advance();
}
return state.lastStringValue !== ""
};
function isUnicodePropertyNameCharacter(ch) {
return isControlLetter(ch) || ch === 0x5F /* _ */
}
// UnicodePropertyValue ::
// UnicodePropertyValueCharacters
pp$1.regexp_eatUnicodePropertyValue = function(state) {
var ch = 0;
state.lastStringValue = "";
while (isUnicodePropertyValueCharacter(ch = state.current())) {
state.lastStringValue += codePointToString(ch);
state.advance();
}
return state.lastStringValue !== ""
};
function isUnicodePropertyValueCharacter(ch) {
return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
}
// LoneUnicodePropertyNameOrValue ::
// UnicodePropertyValueCharacters
pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
return this.regexp_eatUnicodePropertyValue(state)
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
pp$1.regexp_eatCharacterClass = function(state) {
if (state.eat(0x5B /* [ */)) {
var negate = state.eat(0x5E /* ^ */);
var result = this.regexp_classContents(state);
if (!state.eat(0x5D /* ] */))
{ state.raise("Unterminated character class"); }
if (negate && result === CharSetString)
{ state.raise("Negated character class may contain strings"); }
return true
}
return false
};
// https://tc39.es/ecma262/#prod-ClassContents
// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
pp$1.regexp_classContents = function(state) {
if (state.current() === 0x5D /* ] */) { return CharSetOk }
if (state.switchV) { return this.regexp_classSetExpression(state) }
this.regexp_nonEmptyClassRanges(state);
return CharSetOk
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
pp$1.regexp_nonEmptyClassRanges = function(state) {
while (this.regexp_eatClassAtom(state)) {
var left = state.lastIntValue;
if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
var right = state.lastIntValue;
if (state.switchU && (left === -1 || right === -1)) {
state.raise("Invalid character class");
}
if (left !== -1 && right !== -1 && left > right) {
state.raise("Range out of order in character class");
}
}
}
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
pp$1.regexp_eatClassAtom = function(state) {
var start = state.pos;
if (state.eat(0x5C /* \ */)) {
if (this.regexp_eatClassEscape(state)) {
return true
}
if (state.switchU) {
// Make the same message as V8.
var ch$1 = state.current();
if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
state.raise("Invalid class escape");
}
state.raise("Invalid escape");
}
state.pos = start;
}
var ch = state.current();
if (ch !== 0x5D /* ] */) {
state.lastIntValue = ch;
state.advance();
return true
}
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
pp$1.regexp_eatClassEscape = function(state) {
var start = state.pos;
if (state.eat(0x62 /* b */)) {
state.lastIntValue = 0x08; /* <BS> */
return true
}
if (state.switchU && state.eat(0x2D /* - */)) {
state.lastIntValue = 0x2D; /* - */
return true
}
if (!state.switchU && state.eat(0x63 /* c */)) {
if (this.regexp_eatClassControlLetter(state)) {
return true
}
state.pos = start;
}
return (
this.regexp_eatCharacterClassEscape(state) ||
this.regexp_eatCharacterEscape(state)
)
};
// https://tc39.es/ecma262/#prod-ClassSetExpression
// https://tc39.es/ecma262/#prod-ClassUnion
// https://tc39.es/ecma262/#prod-ClassIntersection
// https://tc39.es/ecma262/#prod-ClassSubtraction
pp$1.regexp_classSetExpression = function(state) {
var result = CharSetOk, subResult;
if (this.regexp_eatClassSetRange(state)) ; else if (subResult = this.regexp_eatClassSetOperand(state)) {
if (subResult === CharSetString) { result = CharSetString; }
// https://tc39.es/ecma262/#prod-ClassIntersection
var start = state.pos;
while (state.eatChars([0x26, 0x26] /* && */)) {
if (
state.current() !== 0x26 /* & */ &&
(subResult = this.regexp_eatClassSetOperand(state))
) {
if (subResult !== CharSetString) { result = CharSetOk; }
continue
}
state.raise("Invalid character in character class");
}
if (start !== state.pos) { return result }
// https://tc39.es/ecma262/#prod-ClassSubtraction
while (state.eatChars([0x2D, 0x2D] /* -- */)) {
if (this.regexp_eatClassSetOperand(state)) { continue }
state.raise("Invalid character in character class");
}
if (start !== state.pos) { return result }
} else {
state.raise("Invalid character in character class");
}
// https://tc39.es/ecma262/#prod-ClassUnion
for (;;) {
if (this.regexp_eatClassSetRange(state)) { continue }
subResult = this.regexp_eatClassSetOperand(state);
if (!subResult) { return result }
if (subResult === CharSetString) { result = CharSetString; }
}
};
// https://tc39.es/ecma262/#prod-ClassSetRange
pp$1.regexp_eatClassSetRange = function(state) {
var start = state.pos;
if (this.regexp_eatClassSetCharacter(state)) {
var left = state.lastIntValue;
if (state.eat(0x2D /* - */) && this.regexp_eatClassSetCharacter(state)) {
var right = state.lastIntValue;
if (left !== -1 && right !== -1 && left > right) {
state.raise("Range out of order in character class");
}
return true
}
state.pos = start;
}
return false
};
// https://tc39.es/ecma262/#prod-ClassSetOperand
pp$1.regexp_eatClassSetOperand = function(state) {
if (this.regexp_eatClassSetCharacter(state)) { return CharSetOk }
return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state)
};
// https://tc39.es/ecma262/#prod-NestedClass
pp$1.regexp_eatNestedClass = function(state) {
var start = state.pos;
if (state.eat(0x5B /* [ */)) {
var negate = state.eat(0x5E /* ^ */);
var result = this.regexp_classContents(state);
if (state.eat(0x5D /* ] */)) {
if (negate && result === CharSetString) {
state.raise("Negated character class may contain strings");
}
return result
}
state.pos = start;
}
if (state.eat(0x5C /* \ */)) {
var result$1 = this.regexp_eatCharacterClassEscape(state);
if (result$1) {
return result$1
}
state.pos = start;
}
return null
};
// https://tc39.es/ecma262/#prod-ClassStringDisjunction
pp$1.regexp_eatClassStringDisjunction = function(state) {
var start = state.pos;
if (state.eatChars([0x5C, 0x71] /* \q */)) {
if (state.eat(0x7B /* { */)) {
var result = this.regexp_classStringDisjunctionContents(state);
if (state.eat(0x7D /* } */)) {
return result
}
} else {
// Make the same message as V8.
state.raise("Invalid escape");
}
state.pos = start;
}
return null
};
// https://tc39.es/ecma262/#prod-ClassStringDisjunctionContents
pp$1.regexp_classStringDisjunctionContents = function(state) {
var result = this.regexp_classString(state);
while (state.eat(0x7C /* | */)) {
if (this.regexp_classString(state) === CharSetString) { result = CharSetString; }
}
return result
};
// https://tc39.es/ecma262/#prod-ClassString
// https://tc39.es/ecma262/#prod-NonEmptyClassString
pp$1.regexp_classString = function(state) {
var count = 0;
while (this.regexp_eatClassSetCharacter(state)) { count++; }
return count === 1 ? CharSetOk : CharSetString
};
// https://tc39.es/ecma262/#prod-ClassSetCharacter
pp$1.regexp_eatClassSetCharacter = function(state) {
var start = state.pos;
if (state.eat(0x5C /* \ */)) {
if (
this.regexp_eatCharacterEscape(state) ||
this.regexp_eatClassSetReservedPunctuator(state)
) {
return true
}
if (state.eat(0x62 /* b */)) {
state.lastIntValue = 0x08; /* <BS> */
return true
}
state.pos = start;
return false
}
var ch = state.current();
if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) { return false }
if (isClassSetSyntaxCharacter(ch)) { return false }
state.advance();
state.lastIntValue = ch;
return true
};
// https://tc39.es/ecma262/#prod-ClassSetReservedDoublePunctuator
function isClassSetReservedDoublePunctuatorCharacter(ch) {
return (
ch === 0x21 /* ! */ ||
ch >= 0x23 /* # */ && ch <= 0x26 /* & */ ||
ch >= 0x2A /* * */ && ch <= 0x2C /* , */ ||
ch === 0x2E /* . */ ||
ch >= 0x3A /* : */ && ch <= 0x40 /* @ */ ||
ch === 0x5E /* ^ */ ||
ch === 0x60 /* ` */ ||
ch === 0x7E /* ~ */
)
}
// https://tc39.es/ecma262/#prod-ClassSetSyntaxCharacter
function isClassSetSyntaxCharacter(ch) {
return (
ch === 0x28 /* ( */ ||
ch === 0x29 /* ) */ ||
ch === 0x2D /* - */ ||
ch === 0x2F /* / */ ||
ch >= 0x5B /* [ */ && ch <= 0x5D /* ] */ ||
ch >= 0x7B /* { */ && ch <= 0x7D /* } */
)
}
// https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator
pp$1.regexp_eatClassSetReservedPunctuator = function(state) {
var ch = state.current();
if (isClassSetReservedPunctuator(ch)) {
state.lastIntValue = ch;
state.advance();
return true
}
return false
};
// https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator
function isClassSetReservedPunctuator(ch) {
return (
ch === 0x21 /* ! */ ||
ch === 0x23 /* # */ ||
ch === 0x25 /* % */ ||
ch === 0x26 /* & */ ||
ch === 0x2C /* , */ ||
ch === 0x2D /* - */ ||
ch >= 0x3A /* : */ && ch <= 0x3E /* > */ ||
ch === 0x40 /* @ */ ||
ch === 0x60 /* ` */ ||
ch === 0x7E /* ~ */
)
}
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
pp$1.regexp_eatClassControlLetter = function(state) {
var ch = state.current();
if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
state.lastIntValue = ch % 0x20;
state.advance();
return true
}
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
pp$1.regexp_eatHexEscapeSequence = function(state) {
var start = state.pos;
if (state.eat(0x78 /* x */)) {
if (this.regexp_eatFixedHexDigits(state, 2)) {
return true
}
if (state.switchU) {
state.raise("Invalid escape");
}
state.pos = start;
}
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
pp$1.regexp_eatDecimalDigits = function(state) {
var start = state.pos;
var ch = 0;
state.lastIntValue = 0;
while (isDecimalDigit(ch = state.current())) {
state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
state.advance();
}
return state.pos !== start
};
function isDecimalDigit(ch) {
return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
}
// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
pp$1.regexp_eatHexDigits = function(state) {
var start = state.pos;
var ch = 0;
state.lastIntValue = 0;
while (isHexDigit(ch = state.current())) {
state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
state.advance();
}
return state.pos !== start
};
function isHexDigit(ch) {
return (
(ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
(ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
(ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
)
}
function hexToInt(ch) {
if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
return 10 + (ch - 0x41 /* A */)
}
if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
return 10 + (ch - 0x61 /* a */)
}
return ch - 0x30 /* 0 */
}
// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
// Allows only 0-377(octal) i.e. 0-255(decimal).
pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
if (this.regexp_eatOctalDigit(state)) {
var n1 = state.lastIntValue;
if (this.regexp_eatOctalDigit(state)) {
var n2 = state.lastIntValue;
if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
} else {
state.lastIntValue = n1 * 8 + n2;
}
} else {
state.lastIntValue = n1;
}
return true
}
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
pp$1.regexp_eatOctalDigit = function(state) {
var ch = state.current();
if (isOctalDigit(ch)) {
state.lastIntValue = ch - 0x30; /* 0 */
state.advance();
return true
}
state.lastIntValue = 0;
return false
};
function isOctalDigit(ch) {
return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
}
// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
pp$1.regexp_eatFixedHexDigits = function(state, length) {
var start = state.pos;
state.lastIntValue = 0;
for (var i = 0; i < length; ++i) {
var ch = state.current();
if (!isHexDigit(ch)) {
state.pos = start;
return false
}
state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
state.advance();
}
return true
};
// Object type used to represent tokens. Note that normally, tokens
// simply exist as properties on the parser object. This is only
// used for the onToken callback and the external tokenizer.
var Token = function Token(p) {
this.type = p.type;
this.value = p.value;
this.start = p.start;
this.end = p.end;
if (p.options.locations)
{ this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
if (p.options.ranges)
{ this.range = [p.start, p.end]; }
};
// ## Tokenizer
var pp = Parser.prototype;
// Move to the next token
pp.next = function(ignoreEscapeSequenceInKeyword) {
if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
{ this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
if (this.options.onToken)
{ this.options.onToken(new Token(this)); }
this.lastTokEnd = this.end;
this.lastTokStart = this.start;
this.lastTokEndLoc = this.endLoc;
this.lastTokStartLoc = this.startLoc;
this.nextToken();
};
pp.getToken = function() {
this.next();
return new Token(this)
};
// If we're in an ES6 environment, make parsers iterable
if (typeof Symbol !== "undefined")
{ pp[Symbol.iterator] = function() {
var this$1$1 = this;
return {
next: function () {
var token = this$1$1.getToken();
return {
done: token.type === types$1.eof,
value: token
}
}
}
}; }
// Toggle strict mode. Re-reads the next number or string to please
// pedantic tests (`"use strict"; 010;` should fail).
// Read a single token, updating the parser object's token-related
// properties.
pp.nextToken = function() {
var curContext = this.curContext();
if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
this.start = this.pos;
if (this.options.locations) { this.startLoc = this.curPosition(); }
if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }
if (curContext.override) { return curContext.override(this) }
else { this.readToken(this.fullCharCodeAtPos()); }
};
pp.readToken = function(code) {
// Identifier or keyword. '\uXXXX' sequences are allowed in
// identifiers, so '\' also dispatches to that.
if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
{ return this.readWord() }
return this.getTokenFromCode(code)
};
pp.fullCharCodeAtPos = function() {
var code = this.input.charCodeAt(this.pos);
if (code <= 0xd7ff || code >= 0xdc00) { return code }
var next = this.input.charCodeAt(this.pos + 1);
return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
};
pp.skipBlockComment = function() {
var startLoc = this.options.onComment && this.curPosition();
var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
this.pos = end + 2;
if (this.options.locations) {
for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
++this.curLine;
pos = this.lineStart = nextBreak;
}
}
if (this.options.onComment)
{ this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
startLoc, this.curPosition()); }
};
pp.skipLineComment = function(startSkip) {
var start = this.pos;
var startLoc = this.options.onComment && this.curPosition();
var ch = this.input.charCodeAt(this.pos += startSkip);
while (this.pos < this.input.length && !isNewLine(ch)) {
ch = this.input.charCodeAt(++this.pos);
}
if (this.options.onComment)
{ this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
startLoc, this.curPosition()); }
};
// Called at the start of the parse and after every token. Skips
// whitespace and comments, and.
pp.skipSpace = function() {
loop: while (this.pos < this.input.length) {
var ch = this.input.charCodeAt(this.pos);
switch (ch) {
case 32: case 160: // ' '
++this.pos;
break
case 13:
if (this.input.charCodeAt(this.pos + 1) === 10) {
++this.pos;
}
case 10: case 8232: case 8233:
++this.pos;
if (this.options.locations) {
++this.curLine;
this.lineStart = this.pos;
}
break
case 47: // '/'
switch (this.input.charCodeAt(this.pos + 1)) {
case 42: // '*'
this.skipBlockComment();
break
case 47:
this.skipLineComment(2);
break
default:
break loop
}
break
default:
if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
++this.pos;
} else {
break loop
}
}
}
};
// Called at the end of every token. Sets `end`, `val`, and
// maintains `context` and `exprAllowed`, and skips the space after
// the token, so that the next one's `start` will point at the
// right position.
pp.finishToken = function(type, val) {
this.end = this.pos;
if (this.options.locations) { this.endLoc = this.curPosition(); }
var prevType = this.type;
this.type = type;
this.value = val;
this.updateContext(prevType);
};
// ### Token reading
// This is the function that is called to fetch the next token. It
// is somewhat obscure, because it works in character codes rather
// than characters, and because operator parsing has been inlined
// into it.
//
// All in the name of speed.
//
pp.readToken_dot = function() {
var next = this.input.charCodeAt(this.pos + 1);
if (next >= 48 && next <= 57) { return this.readNumber(true) }
var next2 = this.input.charCodeAt(this.pos + 2);
if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
this.pos += 3;
return this.finishToken(types$1.ellipsis)
} else {
++this.pos;
return this.finishToken(types$1.dot)
}
};
pp.readToken_slash = function() { // '/'
var next = this.input.charCodeAt(this.pos + 1);
if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
if (next === 61) { return this.finishOp(types$1.assign, 2) }
return this.finishOp(types$1.slash, 1)
};
pp.readToken_mult_modulo_exp = function(code) { // '%*'
var next = this.input.charCodeAt(this.pos + 1);
var size = 1;
var tokentype = code === 42 ? types$1.star : types$1.modulo;
// exponentiation operator ** and **=
if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
++size;
tokentype = types$1.starstar;
next = this.input.charCodeAt(this.pos + 2);
}
if (next === 61) { return this.finishOp(types$1.assign, size + 1) }
return this.finishOp(tokentype, size)
};
pp.readToken_pipe_amp = function(code) { // '|&'
var next = this.input.charCodeAt(this.pos + 1);
if (next === code) {
if (this.options.ecmaVersion >= 12) {
var next2 = this.input.charCodeAt(this.pos + 2);
if (next2 === 61) { return this.finishOp(types$1.assign, 3) }
}
return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)
}
if (next === 61) { return this.finishOp(types$1.assign, 2) }
return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)
};
pp.readToken_caret = function() { // '^'
var next = this.input.charCodeAt(this.pos + 1);
if (next === 61) { return this.finishOp(types$1.assign, 2) }
return this.finishOp(types$1.bitwiseXOR, 1)
};
pp.readToken_plus_min = function(code) { // '+-'
var next = this.input.charCodeAt(this.pos + 1);
if (next === code) {
if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
(this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
// A `-->` line comment
this.skipLineComment(3);
this.skipSpace();
return this.nextToken()
}
return this.finishOp(types$1.incDec, 2)
}
if (next === 61) { return this.finishOp(types$1.assign, 2) }
return this.finishOp(types$1.plusMin, 1)
};
pp.readToken_lt_gt = function(code) { // '<>'
var next = this.input.charCodeAt(this.pos + 1);
var size = 1;
if (next === code) {
size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }
return this.finishOp(types$1.bitShift, size)
}
if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
this.input.charCodeAt(this.pos + 3) === 45) {
// `<!--`, an XML-style comment that should be interpreted as a line comment
this.skipLineComment(4);
this.skipSpace();
return this.nextToken()
}
if (next === 61) { size = 2; }
return this.finishOp(types$1.relational, size)
};
pp.readToken_eq_excl = function(code) { // '=!'
var next = this.input.charCodeAt(this.pos + 1);
if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
this.pos += 2;
return this.finishToken(types$1.arrow)
}
return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)
};
pp.readToken_question = function() { // '?'
var ecmaVersion = this.options.ecmaVersion;
if (ecmaVersion >= 11) {
var next = this.input.charCodeAt(this.pos + 1);
if (next === 46) {
var next2 = this.input.charCodeAt(this.pos + 2);
if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }
}
if (next === 63) {
if (ecmaVersion >= 12) {
var next2$1 = this.input.charCodeAt(this.pos + 2);
if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }
}
return this.finishOp(types$1.coalesce, 2)
}
}
return this.finishOp(types$1.question, 1)
};
pp.readToken_numberSign = function() { // '#'
var ecmaVersion = this.options.ecmaVersion;
var code = 35; // '#'
if (ecmaVersion >= 13) {
++this.pos;
code = this.fullCharCodeAtPos();
if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
return this.finishToken(types$1.privateId, this.readWord1())
}
}
this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
};
pp.getTokenFromCode = function(code) {
switch (code) {
// The interpretation of a dot depends on whether it is followed
// by a digit or another two dots.
case 46: // '.'
return this.readToken_dot()
// Punctuation tokens.
case 40: ++this.pos; return this.finishToken(types$1.parenL)
case 41: ++this.pos; return this.finishToken(types$1.parenR)
case 59: ++this.pos; return this.finishToken(types$1.semi)
case 44: ++this.pos; return this.finishToken(types$1.comma)
case 91: ++this.pos; return this.finishToken(types$1.bracketL)
case 93: ++this.pos; return this.finishToken(types$1.bracketR)
case 123: ++this.pos; return this.finishToken(types$1.braceL)
case 125: ++this.pos; return this.finishToken(types$1.braceR)
case 58: ++this.pos; return this.finishToken(types$1.colon)
case 96: // '`'
if (this.options.ecmaVersion < 6) { break }
++this.pos;
return this.finishToken(types$1.backQuote)
case 48: // '0'
var next = this.input.charCodeAt(this.pos + 1);
if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
if (this.options.ecmaVersion >= 6) {
if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
}
// Anything else beginning with a digit is an integer, octal
// number, or float.
case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
return this.readNumber(false)
// Quotes produce strings.
case 34: case 39: // '"', "'"
return this.readString(code)
// Operators are parsed inline in tiny state machines. '=' (61) is
// often referred to. `finishOp` simply skips the amount of
// characters it is given as second argument, and returns a token
// of the type given by its first argument.
case 47: // '/'
return this.readToken_slash()
case 37: case 42: // '%*'
return this.readToken_mult_modulo_exp(code)
case 124: case 38: // '|&'
return this.readToken_pipe_amp(code)
case 94: // '^'
return this.readToken_caret()
case 43: case 45: // '+-'
return this.readToken_plus_min(code)
case 60: case 62: // '<>'
return this.readToken_lt_gt(code)
case 61: case 33: // '=!'
return this.readToken_eq_excl(code)
case 63: // '?'
return this.readToken_question()
case 126: // '~'
return this.finishOp(types$1.prefix, 1)
case 35: // '#'
return this.readToken_numberSign()
}
this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
};
pp.finishOp = function(type, size) {
var str = this.input.slice(this.pos, this.pos + size);
this.pos += size;
return this.finishToken(type, str)
};
pp.readRegexp = function() {
var escaped, inClass, start = this.pos;
for (;;) {
if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
var ch = this.input.charAt(this.pos);
if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
if (!escaped) {
if (ch === "[") { inClass = true; }
else if (ch === "]" && inClass) { inClass = false; }
else if (ch === "/" && !inClass) { break }
escaped = ch === "\\";
} else { escaped = false; }
++this.pos;
}
var pattern = this.input.slice(start, this.pos);
++this.pos;
var flagsStart = this.pos;
var flags = this.readWord1();
if (this.containsEsc) { this.unexpected(flagsStart); }
// Validate pattern
var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
state.reset(start, pattern, flags);
this.validateRegExpFlags(state);
this.validateRegExpPattern(state);
// Create Literal#value property value.
var value = null;
try {
value = new RegExp(pattern, flags);
} catch (e) {
// ESTree requires null if it failed to instantiate RegExp object.
// https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
}
return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})
};
// Read an integer in the given radix. Return null if zero digits
// were read, the integer value otherwise. When `len` is given, this
// will return `null` unless the integer has exactly `len` digits.
pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
// `len` is used for character escape sequences. In that case, disallow separators.
var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
// `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
// and isn't fraction part nor exponent part. In that case, if the first digit
// is zero then disallow separators.
var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
var start = this.pos, total = 0, lastCode = 0;
for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
var code = this.input.charCodeAt(this.pos), val = (void 0);
if (allowSeparators && code === 95) {
if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
lastCode = code;
continue
}
if (code >= 97) { val = code - 97 + 10; } // a
else if (code >= 65) { val = code - 65 + 10; } // A
else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
else { val = Infinity; }
if (val >= radix) { break }
lastCode = code;
total = total * radix + val;
}
if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
if (this.pos === start || len != null && this.pos - start !== len) { return null }
return total
};
function stringToNumber(str, isLegacyOctalNumericLiteral) {
if (isLegacyOctalNumericLiteral) {
return parseInt(str, 8)
}
// `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
return parseFloat(str.replace(/_/g, ""))
}
function stringToBigInt(str) {
if (typeof BigInt !== "function") {
return null
}
// `BigInt(value)` throws syntax error if the string contains numeric separators.
return BigInt(str.replace(/_/g, ""))
}
pp.readRadixNumber = function(radix) {
var start = this.pos;
this.pos += 2; // 0x
var val = this.readInt(radix);
if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
val = stringToBigInt(this.input.slice(start, this.pos));
++this.pos;
} else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
return this.finishToken(types$1.num, val)
};
// Read an integer, octal integer, or floating-point number.
pp.readNumber = function(startsWithDot) {
var start = this.pos;
if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
if (octal && this.strict) { this.raise(start, "Invalid number"); }
var next = this.input.charCodeAt(this.pos);
if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
var val$1 = stringToBigInt(this.input.slice(start, this.pos));
++this.pos;
if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
return this.finishToken(types$1.num, val$1)
}
if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
if (next === 46 && !octal) { // '.'
++this.pos;
this.readInt(10);
next = this.input.charCodeAt(this.pos);
}
if ((next === 69 || next === 101) && !octal) { // 'eE'
next = this.input.charCodeAt(++this.pos);
if (next === 43 || next === 45) { ++this.pos; } // '+-'
if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
}
if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
var val = stringToNumber(this.input.slice(start, this.pos), octal);
return this.finishToken(types$1.num, val)
};
// Read a string value, interpreting backslash-escapes.
pp.readCodePoint = function() {
var ch = this.input.charCodeAt(this.pos), code;
if (ch === 123) { // '{'
if (this.options.ecmaVersion < 6) { this.unexpected(); }
var codePos = ++this.pos;
code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
++this.pos;
if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
} else {
code = this.readHexChar(4);
}
return code
};
pp.readString = function(quote) {
var out = "", chunkStart = ++this.pos;
for (;;) {
if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
var ch = this.input.charCodeAt(this.pos);
if (ch === quote) { break }
if (ch === 92) { // '\'
out += this.input.slice(chunkStart, this.pos);
out += this.readEscapedChar(false);
chunkStart = this.pos;
} else if (ch === 0x2028 || ch === 0x2029) {
if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }
++this.pos;
if (this.options.locations) {
this.curLine++;
this.lineStart = this.pos;
}
} else {
if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
++this.pos;
}
}
out += this.input.slice(chunkStart, this.pos++);
return this.finishToken(types$1.string, out)
};
// Reads template string tokens.
var INVALID_TEMPLATE_ESCAPE_ERROR = {};
pp.tryReadTemplateToken = function() {
this.inTemplateElement = true;
try {
this.readTmplToken();
} catch (err) {
if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
this.readInvalidTemplateToken();
} else {
throw err
}
}
this.inTemplateElement = false;
};
pp.invalidStringToken = function(position, message) {
if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
throw INVALID_TEMPLATE_ESCAPE_ERROR
} else {
this.raise(position, message);
}
};
pp.readTmplToken = function() {
var out = "", chunkStart = this.pos;
for (;;) {
if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
var ch = this.input.charCodeAt(this.pos);
if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
if (ch === 36) {
this.pos += 2;
return this.finishToken(types$1.dollarBraceL)
} else {
++this.pos;
return this.finishToken(types$1.backQuote)
}
}
out += this.input.slice(chunkStart, this.pos);
return this.finishToken(types$1.template, out)
}
if (ch === 92) { // '\'
out += this.input.slice(chunkStart, this.pos);
out += this.readEscapedChar(true);
chunkStart = this.pos;
} else if (isNewLine(ch)) {
out += this.input.slice(chunkStart, this.pos);
++this.pos;
switch (ch) {
case 13:
if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
case 10:
out += "\n";
break
default:
out += String.fromCharCode(ch);
break
}
if (this.options.locations) {
++this.curLine;
this.lineStart = this.pos;
}
chunkStart = this.pos;
} else {
++this.pos;
}
}
};
// Reads a template token to search for the end, without validating any escape sequences
pp.readInvalidTemplateToken = function() {
for (; this.pos < this.input.length; this.pos++) {
switch (this.input[this.pos]) {
case "\\":
++this.pos;
break
case "$":
if (this.input[this.pos + 1] !== "{") {
break
}
// falls through
case "`":
return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))
// no default
}
}
this.raise(this.start, "Unterminated template");
};
// Used to read escaped characters
pp.readEscapedChar = function(inTemplate) {
var ch = this.input.charCodeAt(++this.pos);
++this.pos;
switch (ch) {
case 110: return "\n" // 'n' -> '\n'
case 114: return "\r" // 'r' -> '\r'
case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
case 117: return codePointToString(this.readCodePoint()) // 'u'
case 116: return "\t" // 't' -> '\t'
case 98: return "\b" // 'b' -> '\b'
case 118: return "\u000b" // 'v' -> '\u000b'
case 102: return "\f" // 'f' -> '\f'
case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
case 10: // ' \n'
if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
return ""
case 56:
case 57:
if (this.strict) {
this.invalidStringToken(
this.pos - 1,
"Invalid escape sequence"
);
}
if (inTemplate) {
var codePos = this.pos - 1;
this.invalidStringToken(
codePos,
"Invalid escape sequence in template string"
);
}
default:
if (ch >= 48 && ch <= 55) {
var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
var octal = parseInt(octalStr, 8);
if (octal > 255) {
octalStr = octalStr.slice(0, -1);
octal = parseInt(octalStr, 8);
}
this.pos += octalStr.length - 1;
ch = this.input.charCodeAt(this.pos);
if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
this.invalidStringToken(
this.pos - 1 - octalStr.length,
inTemplate
? "Octal literal in template string"
: "Octal literal in strict mode"
);
}
return String.fromCharCode(octal)
}
if (isNewLine(ch)) {
// Unicode new line characters after \ get removed from output in both
// template literals and strings
return ""
}
return String.fromCharCode(ch)
}
};
// Used to read character escape sequences ('\x', '\u', '\U').
pp.readHexChar = function(len) {
var codePos = this.pos;
var n = this.readInt(16, len);
if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
return n
};
// Read an identifier, and return it as a string. Sets `this.containsEsc`
// to whether the word contained a '\u' escape.
//
// Incrementally adds only escaped chars, adding other chunks as-is
// as a micro-optimization.
pp.readWord1 = function() {
this.containsEsc = false;
var word = "", first = true, chunkStart = this.pos;
var astral = this.options.ecmaVersion >= 6;
while (this.pos < this.input.length) {
var ch = this.fullCharCodeAtPos();
if (isIdentifierChar(ch, astral)) {
this.pos += ch <= 0xffff ? 1 : 2;
} else if (ch === 92) { // "\"
this.containsEsc = true;
word += this.input.slice(chunkStart, this.pos);
var escStart = this.pos;
if (this.input.charCodeAt(++this.pos) !== 117) // "u"
{ this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
++this.pos;
var esc = this.readCodePoint();
if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
{ this.invalidStringToken(escStart, "Invalid Unicode escape"); }
word += codePointToString(esc);
chunkStart = this.pos;
} else {
break
}
first = false;
}
return word + this.input.slice(chunkStart, this.pos)
};
// Read an identifier or keyword token. Will check for reserved
// words when necessary.
pp.readWord = function() {
var word = this.readWord1();
var type = types$1.name;
if (this.keywords.test(word)) {
type = keywords[word];
}
return this.finishToken(type, word)
};
// Acorn is a tiny, fast JavaScript parser written in JavaScript.
//
// Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and
// various contributors and released under an MIT license.
//
// Git repositories for Acorn are available at
//
// http://marijnhaverbeke.nl/git/acorn
// https://github.com/acornjs/acorn.git
//
// Please use the [github bug tracker][ghbt] to report issues.
//
// [ghbt]: https://github.com/acornjs/acorn/issues
//
// [walk]: util/walk.js
var version = "8.9.0";
Parser.acorn = {
Parser: Parser,
version: version,
defaultOptions: defaultOptions,
Position: Position,
SourceLocation: SourceLocation,
getLineInfo: getLineInfo,
Node: Node,
TokenType: TokenType,
tokTypes: types$1,
keywordTypes: keywords,
TokContext: TokContext,
tokContexts: types,
isIdentifierChar: isIdentifierChar,
isIdentifierStart: isIdentifierStart,
Token: Token,
isNewLine: isNewLine,
lineBreak: lineBreak,
lineBreakG: lineBreakG,
nonASCIIwhitespace: nonASCIIwhitespace
};
// The main exported interface (under `self.acorn` when in the
// browser) is a `parse` function that takes a code string and
// returns an abstract syntax tree as specified by [Mozilla parser
// API][api].
//
// [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
function parse(input, options) {
return Parser.parse(input, options)
}
// This function tries to parse a single expression at a given
// offset in a string. Useful for parsing mixed-language formats
// that embed JavaScript expressions.
function parseExpressionAt(input, pos, options) {
return Parser.parseExpressionAt(input, pos, options)
}
// Acorn is organized as a tokenizer and a recursive-descent parser.
// The `tokenizer` export provides an interface to the tokenizer.
function tokenizer(input, options) {
return Parser.tokenizer(input, options)
}
exports.Node = Node;
exports.Parser = Parser;
exports.Position = Position;
exports.SourceLocation = SourceLocation;
exports.TokContext = TokContext;
exports.Token = Token;
exports.TokenType = TokenType;
exports.defaultOptions = defaultOptions;
exports.getLineInfo = getLineInfo;
exports.isIdentifierChar = isIdentifierChar;
exports.isIdentifierStart = isIdentifierStart;
exports.isNewLine = isNewLine;
exports.keywordTypes = keywords;
exports.lineBreak = lineBreak;
exports.lineBreakG = lineBreakG;
exports.nonASCIIwhitespace = nonASCIIwhitespace;
exports.parse = parse;
exports.parseExpressionAt = parseExpressionAt;
exports.tokContexts = types;
exports.tokTypes = types$1;
exports.tokenizer = tokenizer;
exports.version = version;
}));
},{}],20:[function(require,module,exports){
module.exports = after
function after(count, callback, err_cb) {
var bail = false
err_cb = err_cb || noop
proxy.count = count
return (count === 0) ? callback() : proxy
function proxy(err, result) {
if (proxy.count <= 0) {
throw new Error('after called too many times')
}
--proxy.count
// after first error, rest are passed to err_cb
if (err) {
bail = true
callback(err)
// future error callbacks will go to error handler
callback = err_cb
} else if (proxy.count === 0 && !bail) {
callback(null, result)
}
}
}
function noop() {}
},{}],21:[function(require,module,exports){
/**
* An abstraction for slicing an arraybuffer even when
* ArrayBuffer.prototype.slice is not supported
*
* @api public
*/
module.exports = function(arraybuffer, start, end) {
var bytes = arraybuffer.byteLength;
start = start || 0;
end = end || bytes;
if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
if (start < 0) { start += bytes; }
if (end < 0) { end += bytes; }
if (end > bytes) { end = bytes; }
if (start >= bytes || start >= end || bytes === 0) {
return new ArrayBuffer(0);
}
var abv = new Uint8Array(arraybuffer);
var result = new Uint8Array(end - start);
for (var i = start, ii = 0; i < end; i++, ii++) {
result[ii] = abv[i];
}
return result.buffer;
};
},{}],22:[function(require,module,exports){
(function (global){(function (){
'use strict';
var objectAssign = require('object-assign');
// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
// original notice:
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
function compare(a, b) {
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;
}
function isBuffer(b) {
if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
return global.Buffer.isBuffer(b);
}
return !!(b != null && b._isBuffer);
}
// based on node assert, original notice:
// NB: The URL to the CommonJS spec is kept just for tradition.
// node-assert has evolved a lot since then, both in API and behavior.
// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
//
// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
//
// Originally from narwhal.js (http://narwhaljs.org)
// Copyright (c) 2009 Thomas Robinson <280north.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
var util = require('util/');
var hasOwn = Object.prototype.hasOwnProperty;
var pSlice = Array.prototype.slice;
var functionsHaveNames = (function () {
return function foo() {}.name === 'foo';
}());
function pToString (obj) {
return Object.prototype.toString.call(obj);
}
function isView(arrbuf) {
if (isBuffer(arrbuf)) {
return false;
}
if (typeof global.ArrayBuffer !== 'function') {
return false;
}
if (typeof ArrayBuffer.isView === 'function') {
return ArrayBuffer.isView(arrbuf);
}
if (!arrbuf) {
return false;
}
if (arrbuf instanceof DataView) {
return true;
}
if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
return true;
}
return false;
}
// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.
var assert = module.exports = ok;
// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
// actual: actual,
// expected: expected })
var regex = /\s*function\s+([^\(\s]*)\s*/;
// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
function getName(func) {
if (!util.isFunction(func)) {
return;
}
if (functionsHaveNames) {
return func.name;
}
var str = func.toString();
var match = str.match(regex);
return match && match[1];
}
assert.AssertionError = function AssertionError(options) {
this.name = 'AssertionError';
this.actual = options.actual;
this.expected = options.expected;
this.operator = options.operator;
if (options.message) {
this.message = options.message;
this.generatedMessage = false;
} else {
this.message = getMessage(this);
this.generatedMessage = true;
}
var stackStartFunction = options.stackStartFunction || fail;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, stackStartFunction);
} else {
// non v8 browsers so we can have a stacktrace
var err = new Error();
if (err.stack) {
var out = err.stack;
// try to strip useless frames
var fn_name = getName(stackStartFunction);
var idx = out.indexOf('\n' + fn_name);
if (idx >= 0) {
// once we have located the function frame
// we need to strip out everything before it (and its line)
var next_line = out.indexOf('\n', idx + 1);
out = out.substring(next_line + 1);
}
this.stack = out;
}
}
};
// assert.AssertionError instanceof Error
util.inherits(assert.AssertionError, Error);
function truncate(s, n) {
if (typeof s === 'string') {
return s.length < n ? s : s.slice(0, n);
} else {
return s;
}
}
function inspect(something) {
if (functionsHaveNames || !util.isFunction(something)) {
return util.inspect(something);
}
var rawname = getName(something);
var name = rawname ? ': ' + rawname : '';
return '[Function' + name + ']';
}
function getMessage(self) {
return truncate(inspect(self.actual), 128) + ' ' +
self.operator + ' ' +
truncate(inspect(self.expected), 128);
}
// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.
// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided. All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.
function fail(actual, expected, message, operator, stackStartFunction) {
throw new assert.AssertionError({
message: message,
actual: actual,
expected: expected,
operator: operator,
stackStartFunction: stackStartFunction
});
}
// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;
// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.
function ok(value, message) {
if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;
// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);
assert.equal = function equal(actual, expected, message) {
if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};
// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);
assert.notEqual = function notEqual(actual, expected, message) {
if (actual == expected) {
fail(actual, expected, message, '!=', assert.notEqual);
}
};
// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);
assert.deepEqual = function deepEqual(actual, expected, message) {
if (!_deepEqual(actual, expected, false)) {
fail(actual, expected, message, 'deepEqual', assert.deepEqual);
}
};
assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
if (!_deepEqual(actual, expected, true)) {
fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
}
};
function _deepEqual(actual, expected, strict, memos) {
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (isBuffer(actual) && isBuffer(expected)) {
return compare(actual, expected) === 0;
// 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time.
} else if (util.isDate(actual) && util.isDate(expected)) {
return actual.getTime() === expected.getTime();
// 7.3 If the expected value is a RegExp object, the actual value is
// equivalent if it is also a RegExp object with the same source and
// properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
} else if (util.isRegExp(actual) && util.isRegExp(expected)) {
return actual.source === expected.source &&
actual.global === expected.global &&
actual.multiline === expected.multiline &&
actual.lastIndex === expected.lastIndex &&
actual.ignoreCase === expected.ignoreCase;
// 7.4. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if ((actual === null || typeof actual !== 'object') &&
(expected === null || typeof expected !== 'object')) {
return strict ? actual === expected : actual == expected;
// If both values are instances of typed arrays, wrap their underlying
// ArrayBuffers in a Buffer each to increase performance
// This optimization requires the arrays to have the same type as checked by
// Object.prototype.toString (aka pToString). Never perform binary
// comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
// bit patterns are not identical.
} else if (isView(actual) && isView(expected) &&
pToString(actual) === pToString(expected) &&
!(actual instanceof Float32Array ||
actual instanceof Float64Array)) {
return compare(new Uint8Array(actual.buffer),
new Uint8Array(expected.buffer)) === 0;
// 7.5 For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else if (isBuffer(actual) !== isBuffer(expected)) {
return false;
} else {
memos = memos || {actual: [], expected: []};
var actualIndex = memos.actual.indexOf(actual);
if (actualIndex !== -1) {
if (actualIndex === memos.expected.indexOf(expected)) {
return true;
}
}
memos.actual.push(actual);
memos.expected.push(expected);
return objEquiv(actual, expected, strict, memos);
}
}
function isArguments(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
}
function objEquiv(a, b, strict, actualVisitedObjects) {
if (a === null || a === undefined || b === null || b === undefined)
return false;
// if one is a primitive, the other must be same
if (util.isPrimitive(a) || util.isPrimitive(b))
return a === b;
if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
return false;
var aIsArgs = isArguments(a);
var bIsArgs = isArguments(b);
if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
return false;
if (aIsArgs) {
a = pSlice.call(a);
b = pSlice.call(b);
return _deepEqual(a, b, strict);
}
var ka = objectKeys(a);
var kb = objectKeys(b);
var key, i;
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length !== kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] !== kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
return false;
}
return true;
}
// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);
assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
if (_deepEqual(actual, expected, false)) {
fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
}
};
assert.notDeepStrictEqual = notDeepStrictEqual;
function notDeepStrictEqual(actual, expected, message) {
if (_deepEqual(actual, expected, true)) {
fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
}
}
// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);
assert.strictEqual = function strictEqual(actual, expected, message) {
if (actual !== expected) {
fail(actual, expected, message, '===', assert.strictEqual);
}
};
// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
if (actual === expected) {
fail(actual, expected, message, '!==', assert.notStrictEqual);
}
};
function expectedException(actual, expected) {
if (!actual || !expected) {
return false;
}
if (Object.prototype.toString.call(expected) == '[object RegExp]') {
return expected.test(actual);
}
try {
if (actual instanceof expected) {
return true;
}
} catch (e) {
// Ignore. The instanceof check doesn't work for arrow functions.
}
if (Error.isPrototypeOf(expected)) {
return false;
}
return expected.call({}, actual) === true;
}
function _tryBlock(block) {
var error;
try {
block();
} catch (e) {
error = e;
}
return error;
}
function _throws(shouldThrow, block, expected, message) {
var actual;
if (typeof block !== 'function') {
throw new TypeError('"block" argument must be a function');
}
if (typeof expected === 'string') {
message = expected;
expected = null;
}
actual = _tryBlock(block);
message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
(message ? ' ' + message : '.');
if (shouldThrow && !actual) {
fail(actual, expected, 'Missing expected exception' + message);
}
var userProvidedMessage = typeof message === 'string';
var isUnwantedException = !shouldThrow && util.isError(actual);
var isUnexpectedException = !shouldThrow && actual && !expected;
if ((isUnwantedException &&
userProvidedMessage &&
expectedException(actual, expected)) ||
isUnexpectedException) {
fail(actual, expected, 'Got unwanted exception' + message);
}
if ((shouldThrow && actual && expected &&
!expectedException(actual, expected)) || (!shouldThrow && actual)) {
throw actual;
}
}
// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);
assert.throws = function(block, /*optional*/error, /*optional*/message) {
_throws(true, block, error, message);
};
// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
_throws(false, block, error, message);
};
assert.ifError = function(err) { if (err) throw err; };
// Expose a strict only variant of assert
function strict(value, message) {
if (!value) fail(value, true, message, '==', strict);
}
assert.strict = objectAssign(strict, assert, {
equal: assert.strictEqual,
deepEqual: assert.deepStrictEqual,
notEqual: assert.notStrictEqual,
notDeepEqual: assert.notDeepStrictEqual
});
assert.strict.strict = assert.strict;
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
if (hasOwn.call(obj, key)) keys.push(key);
}
return keys;
};
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"object-assign":151,"util/":25}],23:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],24:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],25:[function(require,module,exports){
(function (process,global){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":24,"_process":160,"inherits":23}],26:[function(require,module,exports){
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['exports', './defaultTraveler', './attachComments'], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require('./defaultTraveler'), require('./attachComments'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.defaultTraveler, global.attachComments);
global.astravel = mod.exports;
}
})(this, function (exports, _defaultTraveler, _attachComments) {
'use strict';
exports.__esModule = true;
exports.makeTraveler = exports.attachComments = exports.defaultTraveler = undefined;
var _defaultTraveler2 = _interopRequireDefault(_defaultTraveler);
var _attachComments2 = _interopRequireDefault(_attachComments);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
// Astravel is tiny and fast ESTree-compliant AST walker and modifier.
//
// Astravel was written by David Bonnet and released under an MIT license.
//
// The Git repository for Astravel is available at:
// https://github.com/davidbonnet/astravel.git
//
// Please use the GitHub bug tracker to report issues:
// https://github.com/davidbonnet/astravel/issues
function makeTraveler(properties) {
/*
Returns a custom AST traveler that inherits from the `defaultTraveler` with its own provided `properties` and the property `super` that points to the parent traveler object.
*/
return _defaultTraveler2.default.makeChild(properties);
}
exports.defaultTraveler = _defaultTraveler2.default;
exports.attachComments = _attachComments2.default;
exports.makeTraveler = makeTraveler;
});
},{"./attachComments":27,"./defaultTraveler":28}],27:[function(require,module,exports){
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['exports', './defaultTraveler'], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require('./defaultTraveler'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.defaultTraveler);
global.attachComments = mod.exports;
}
})(this, function (exports, _defaultTraveler) {
'use strict';
exports.__esModule = true;
exports.default = function (node, comments) {
/*
Modifies in-place the AST starting at `node` by attaching the provided `comments` and returns that AST.
*/
customTraveler[node.type](node, {
comments: comments,
index: 0
});
return node;
};
var _defaultTraveler2 = _interopRequireDefault(_defaultTraveler);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function attachComments(parent, children, findHeadingComments, state, traveler) {
var index = state.index,
comments = state.comments;
var comment = comments[index];
// Define them in the blocks where there are used once
// https://github.com/babel/minify/issues/485 is resolved
var boundComments = void 0,
trailingComments = void 0;
if (comment != null) {
if (children == null || children.length === 0) {
// No children, attach comments to parent
boundComments = parent.comments != null ? parent.comments : [];
while (comment != null && comment.end < parent.end) {
boundComments.push(comment);
comment = comments[++index];
}
state.index = index;
if (boundComments.length !== 0 && parent.comments == null) parent.comments = boundComments;
} else {
// Look for heading block comments
if (findHeadingComments) {
boundComments = parent.comments != null ? parent.comments : [];
var start = children[0].start;
while (comment != null && comment.type[0] === 'B' && comment.end < start) {
boundComments.push(comment);
comment = comments[++index];
}
if (boundComments.length !== 0 && parent.comments == null) parent.comments = boundComments;
}
// Attach comments to children
for (var i = 0, length = children.length; comment != null && i < length; i++) {
var child = children[i];
boundComments = [];
while (comment != null && comment.end < child.start) {
boundComments.push(comment);
comment = comments[++index];
}
// Check if next comment is line comment and on the same line
if (comment != null && comment.type[0] === 'L') {
if (comment.loc.start.line === child.loc.end.line) {
boundComments.push(comment);
comment = comments[++index];
}
}
if (boundComments.length !== 0) child.comments = boundComments;
// Travel through child
state.index = index;
traveler[child.type](child, state);
index = state.index;
comment = comments[index];
}
// Look for remaining comments
trailingComments = [];
while (comment != null && comment.end < parent.end) {
trailingComments.push(comment);
comment = comments[++index];
}
if (trailingComments.length !== 0) parent.trailingComments = trailingComments;
state.index = index;
}
}
}
var Program = void 0;
var customTraveler = _defaultTraveler2.default.makeChild({
Program: Program = function Program(node, state) {
attachComments(node, node.body, true, state, this);
},
BlockStatement: Program,
ObjectExpression: function ObjectExpression(node, state) {
attachComments(node, node.properties, true, state, this);
},
ArrayExpression: function ArrayExpression(node, state) {
attachComments(node, node.elements, true, state, this);
},
SwitchStatement: function SwitchStatement(node, state) {
attachComments(node, node.cases, false, state, this);
},
SwitchCase: function SwitchCase(node, state) {
attachComments(node, node.consequent, false, state, this);
}
}
// TODO: Consider ArrayExpression ?
);
});
},{"./defaultTraveler":28}],28:[function(require,module,exports){
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['exports'], factory);
} else if (typeof exports !== "undefined") {
factory(exports);
} else {
var mod = {
exports: {}
};
factory(mod.exports);
global.defaultTraveler = mod.exports;
}
})(this, function (exports) {
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var ForInStatement = void 0,
FunctionDeclaration = void 0,
RestElement = void 0,
BinaryExpression = void 0,
ArrayExpression = void 0;
var ignore = Function.prototype;
var Found = function Found(node, state) {
_classCallCheck(this, Found);
this.node = node;
this.state = state;
};
exports.default = {
// Basic methods
go: function go(node, state) {
/*
Starts travelling through the specified AST `node` with the provided `state`.
This method is recursively called by each node handler.
*/
this[node.type](node, state);
},
find: function find(predicate, node, state) {
/*
Returns { node, state } for which `predicate(node, state)` returns truthy,
starting at the specified AST `node` and with the provided `state`.
Otherwise, returns `undefined`.
*/
var finder = Object.create(this);
finder.go = function (node, state) {
if (predicate(node, state)) {
throw new Found(node, state);
}
this[node.type](node, state);
};
try {
finder.go(node, state);
} catch (error) {
if (error instanceof Found) {
return error;
} else {
throw error;
}
}
},
makeChild: function makeChild() {
var properties = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
/*
Returns a custom AST traveler that inherits from `this` traveler with its own provided `properties` and the property `super` that points to the parent traveler object.
*/
var traveler = Object.create(this);
traveler.super = this;
for (var key in properties) {
traveler[key] = properties[key];
}
return traveler;
},
// JavaScript 5
Program: function Program(node, state) {
var statements = node.body,
length = statements.length;
for (var i = 0; i < length; i++) {
this.go(statements[i], state);
}
},
BlockStatement: function BlockStatement(node, state) {
var statements = node.body;
if (statements != null) {
for (var i = 0, length = statements.length; i < length; i++) {
this.go(statements[i], state);
}
}
},
EmptyStatement: ignore,
ExpressionStatement: function ExpressionStatement(node, state) {
this.go(node.expression, state);
},
IfStatement: function IfStatement(node, state) {
this.go(node.test, state);
this.go(node.consequent, state);
if (node.alternate != null) {
this.go(node.alternate, state);
}
},
LabeledStatement: function LabeledStatement(node, state) {
this.go(node.label, state);
this.go(node.body, state);
},
BreakStatement: function BreakStatement(node, state) {
if (node.label) {
this.go(node.label, state);
}
},
ContinueStatement: function ContinueStatement(node, state) {
if (node.label) {
this.go(node.label, state);
}
},
WithStatement: function WithStatement(node, state) {
this.go(node.object, state);
this.go(node.body, state);
},
SwitchStatement: function SwitchStatement(node, state) {
this.go(node.discriminant, state);
var cases = node.cases,
length = cases.length;
for (var i = 0; i < length; i++) {
this.go(cases[i], state);
}
},
SwitchCase: function SwitchCase(node, state) {
if (node.test != null) {
this.go(node.test, state);
}
var statements = node.consequent,
length = statements.length;
for (var i = 0; i < length; i++) {
this.go(statements[i], state);
}
},
ReturnStatement: function ReturnStatement(node, state) {
if (node.argument) {
this.go(node.argument, state);
}
},
ThrowStatement: function ThrowStatement(node, state) {
this.go(node.argument, state);
},
TryStatement: function TryStatement(node, state) {
this.go(node.block, state);
if (node.handler != null) {
this.go(node.handler, state);
}
if (node.finalizer != null) {
this.go(node.finalizer, state);
}
},
CatchClause: function CatchClause(node, state) {
if (node.param != null) {
this.go(node.param, state);
}
this.go(node.body, state);
},
WhileStatement: function WhileStatement(node, state) {
this.go(node.test, state);
this.go(node.body, state);
},
DoWhileStatement: function DoWhileStatement(node, state) {
this.go(node.body, state);
this.go(node.test, state);
},
ForStatement: function ForStatement(node, state) {
if (node.init != null) {
this.go(node.init, state);
}
if (node.test != null) {
this.go(node.test, state);
}
if (node.update != null) {
this.go(node.update, state);
}
this.go(node.body, state);
},
ForInStatement: ForInStatement = function ForInStatement(node, state) {
this.go(node.left, state);
this.go(node.right, state);
this.go(node.body, state);
},
DebuggerStatement: ignore,
FunctionDeclaration: FunctionDeclaration = function FunctionDeclaration(node, state) {
if (node.id != null) {
this.go(node.id, state);
}
var params = node.params;
if (params != null) {
for (var i = 0, length = params.length; i < length; i++) {
this.go(params[i], state);
}
}
this.go(node.body, state);
},
VariableDeclaration: function VariableDeclaration(node, state) {
var declarations = node.declarations,
length = declarations.length;
for (var i = 0; i < length; i++) {
this.go(declarations[i], state);
}
},
VariableDeclarator: function VariableDeclarator(node, state) {
this.go(node.id, state);
if (node.init != null) {
this.go(node.init, state);
}
},
ArrowFunctionExpression: function ArrowFunctionExpression(node, state) {
var params = node.params;
if (params != null) {
for (var i = 0, length = params.length; i < length; i++) {
this.go(params[i], state);
}
}
this.go(node.body, state);
},
ThisExpression: ignore,
ArrayExpression: ArrayExpression = function ArrayExpression(node, state) {
var elements = node.elements,
length = elements.length;
for (var i = 0; i < length; i++) {
var element = elements[i];
if (element != null) {
this.go(elements[i], state);
}
}
},
ObjectExpression: function ObjectExpression(node, state) {
var properties = node.properties,
length = properties.length;
for (var i = 0; i < length; i++) {
this.go(properties[i], state);
}
},
Property: function Property(node, state) {
this.go(node.key, state);
if (!node.shorthand) {
this.go(node.value, state);
}
},
FunctionExpression: FunctionDeclaration,
SequenceExpression: function SequenceExpression(node, state) {
var expressions = node.expressions,
length = expressions.length;
for (var i = 0; i < length; i++) {
this.go(expressions[i], state);
}
},
UnaryExpression: function UnaryExpression(node, state) {
this.go(node.argument, state);
},
UpdateExpression: function UpdateExpression(node, state) {
this.go(node.argument, state);
},
AssignmentExpression: function AssignmentExpression(node, state) {
this.go(node.left, state);
this.go(node.right, state);
},
BinaryExpression: BinaryExpression = function BinaryExpression(node, state) {
this.go(node.left, state);
this.go(node.right, state);
},
LogicalExpression: BinaryExpression,
ConditionalExpression: function ConditionalExpression(node, state) {
this.go(node.test, state);
this.go(node.consequent, state);
this.go(node.alternate, state);
},
NewExpression: function NewExpression(node, state) {
this.CallExpression(node, state);
},
CallExpression: function CallExpression(node, state) {
this.go(node.callee, state);
var args = node['arguments'],
length = args.length;
for (var i = 0; i < length; i++) {
this.go(args[i], state);
}
},
MemberExpression: function MemberExpression(node, state) {
this.go(node.object, state);
this.go(node.property, state);
},
Identifier: ignore,
Literal: ignore,
// JavaScript 6
ForOfStatement: ForInStatement,
ClassDeclaration: function ClassDeclaration(node, state) {
if (node.id) {
this.go(node.id, state);
}
if (node.superClass) {
this.go(node.superClass, state);
}
this.go(node.body, state);
},
ClassBody: function ClassBody(node, state) {
var body = node.body,
length = body.length;
for (var i = 0; i < length; i++) {
this.go(body[i], state);
}
},
ImportDeclaration: function ImportDeclaration(node, state) {
var specifiers = node.specifiers,
length = specifiers.length;
for (var i = 0; i < length; i++) {
this.go(specifiers[i], state);
}
this.go(node.source, state);
},
ImportNamespaceSpecifier: function ImportNamespaceSpecifier(node, state) {
this.go(node.local, state);
},
ImportDefaultSpecifier: function ImportDefaultSpecifier(node, state) {
this.go(node.local, state);
},
ImportSpecifier: function ImportSpecifier(node, state) {
this.go(node.imported, state);
this.go(node.local, state);
},
ExportDefaultDeclaration: function ExportDefaultDeclaration(node, state) {
this.go(node.declaration, state);
},
ExportNamedDeclaration: function ExportNamedDeclaration(node, state) {
if (node.declaration) {
this.go(node.declaration, state);
}
var specifiers = node.specifiers,
length = specifiers.length;
for (var i = 0; i < length; i++) {
this.go(specifiers[i], state);
}
if (node.source) {
this.go(node.source, state);
}
},
ExportSpecifier: function ExportSpecifier(node, state) {
this.go(node.local, state);
this.go(node.exported, state);
},
ExportAllDeclaration: function ExportAllDeclaration(node, state) {
this.go(node.source, state);
},
MethodDefinition: function MethodDefinition(node, state) {
this.go(node.key, state);
this.go(node.value, state);
},
ClassExpression: function ClassExpression(node, state) {
this.ClassDeclaration(node, state);
},
Super: ignore,
RestElement: RestElement = function RestElement(node, state) {
this.go(node.argument, state);
},
SpreadElement: RestElement,
YieldExpression: function YieldExpression(node, state) {
if (node.argument) {
this.go(node.argument, state);
}
},
TaggedTemplateExpression: function TaggedTemplateExpression(node, state) {
this.go(node.tag, state);
this.go(node.quasi, state);
},
TemplateLiteral: function TemplateLiteral(node, state) {
var quasis = node.quasis,
expressions = node.expressions;
for (var i = 0, length = expressions.length; i < length; i++) {
this.go(expressions[i], state);
}
for (var _i = 0, _length = quasis.length; _i < _length; _i++) {
this.go(quasis[_i], state);
}
},
TemplateElement: ignore,
ObjectPattern: function ObjectPattern(node, state) {
var properties = node.properties,
length = properties.length;
for (var i = 0; i < length; i++) {
this.go(properties[i], state);
}
},
ArrayPattern: ArrayExpression,
AssignmentPattern: function AssignmentPattern(node, state) {
this.go(node.left, state);
this.go(node.right, state);
},
MetaProperty: function MetaProperty(node, state) {
this.go(node.meta, state);
this.go(node.property, state);
},
// JavaScript 7
AwaitExpression: function AwaitExpression(node, state) {
this.go(node.argument, state);
}
};
});
},{}],29:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.generate = generate;
exports.baseGenerator = exports.GENERATOR = exports.EXPRESSIONS_PRECEDENCE = exports.NEEDS_PARENTHESES = void 0;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var stringify = JSON.stringify;
if (!String.prototype.repeat) {
throw new Error('String.prototype.repeat is undefined, see https://github.com/davidbonnet/astring#installation');
}
if (!String.prototype.endsWith) {
throw new Error('String.prototype.endsWith is undefined, see https://github.com/davidbonnet/astring#installation');
}
var OPERATOR_PRECEDENCE = {
'||': 2,
'??': 3,
'&&': 4,
'|': 5,
'^': 6,
'&': 7,
'==': 8,
'!=': 8,
'===': 8,
'!==': 8,
'<': 9,
'>': 9,
'<=': 9,
'>=': 9,
"in": 9,
"instanceof": 9,
'<<': 10,
'>>': 10,
'>>>': 10,
'+': 11,
'-': 11,
'*': 12,
'%': 12,
'/': 12,
'**': 13
};
var NEEDS_PARENTHESES = 17;
exports.NEEDS_PARENTHESES = NEEDS_PARENTHESES;
var EXPRESSIONS_PRECEDENCE = {
ArrayExpression: 20,
TaggedTemplateExpression: 20,
ThisExpression: 20,
Identifier: 20,
PrivateIdentifier: 20,
Literal: 18,
TemplateLiteral: 20,
Super: 20,
SequenceExpression: 20,
MemberExpression: 19,
ChainExpression: 19,
CallExpression: 19,
NewExpression: 19,
ArrowFunctionExpression: NEEDS_PARENTHESES,
ClassExpression: NEEDS_PARENTHESES,
FunctionExpression: NEEDS_PARENTHESES,
ObjectExpression: NEEDS_PARENTHESES,
UpdateExpression: 16,
UnaryExpression: 15,
AwaitExpression: 15,
BinaryExpression: 14,
LogicalExpression: 13,
ConditionalExpression: 4,
AssignmentExpression: 3,
YieldExpression: 2,
RestElement: 1
};
exports.EXPRESSIONS_PRECEDENCE = EXPRESSIONS_PRECEDENCE;
function formatSequence(state, nodes) {
var generator = state.generator;
state.write('(');
if (nodes != null && nodes.length > 0) {
generator[nodes[0].type](nodes[0], state);
var length = nodes.length;
for (var i = 1; i < length; i++) {
var param = nodes[i];
state.write(', ');
generator[param.type](param, state);
}
}
state.write(')');
}
function expressionNeedsParenthesis(state, node, parentNode, isRightHand) {
var nodePrecedence = state.expressionsPrecedence[node.type];
if (nodePrecedence === NEEDS_PARENTHESES) {
return true;
}
var parentNodePrecedence = state.expressionsPrecedence[parentNode.type];
if (nodePrecedence !== parentNodePrecedence) {
return !isRightHand && nodePrecedence === 15 && parentNodePrecedence === 14 && parentNode.operator === '**' || nodePrecedence < parentNodePrecedence;
}
if (nodePrecedence !== 13 && nodePrecedence !== 14) {
return false;
}
if (node.operator === '**' && parentNode.operator === '**') {
return !isRightHand;
}
if (nodePrecedence === 13 && parentNodePrecedence === 13 && (node.operator === '??' || parentNode.operator === '??')) {
return true;
}
if (isRightHand) {
return OPERATOR_PRECEDENCE[node.operator] <= OPERATOR_PRECEDENCE[parentNode.operator];
}
return OPERATOR_PRECEDENCE[node.operator] < OPERATOR_PRECEDENCE[parentNode.operator];
}
function formatExpression(state, node, parentNode, isRightHand) {
var generator = state.generator;
if (expressionNeedsParenthesis(state, node, parentNode, isRightHand)) {
state.write('(');
generator[node.type](node, state);
state.write(')');
} else {
generator[node.type](node, state);
}
}
function reindent(state, text, indent, lineEnd) {
var lines = text.split('\n');
var end = lines.length - 1;
state.write(lines[0].trim());
if (end > 0) {
state.write(lineEnd);
for (var i = 1; i < end; i++) {
state.write(indent + lines[i].trim() + lineEnd);
}
state.write(indent + lines[end].trim());
}
}
function formatComments(state, comments, indent, lineEnd) {
var length = comments.length;
for (var i = 0; i < length; i++) {
var comment = comments[i];
state.write(indent);
if (comment.type[0] === 'L') {
state.write('// ' + comment.value.trim() + '\n', comment);
} else {
state.write('/*');
reindent(state, comment.value, indent, lineEnd);
state.write('*/' + lineEnd);
}
}
}
function hasCallExpression(node) {
var currentNode = node;
while (currentNode != null) {
var _currentNode = currentNode,
type = _currentNode.type;
if (type[0] === 'C' && type[1] === 'a') {
return true;
} else if (type[0] === 'M' && type[1] === 'e' && type[2] === 'm') {
currentNode = currentNode.object;
} else {
return false;
}
}
}
function formatVariableDeclaration(state, node) {
var generator = state.generator;
var declarations = node.declarations;
state.write(node.kind + ' ');
var length = declarations.length;
if (length > 0) {
generator.VariableDeclarator(declarations[0], state);
for (var i = 1; i < length; i++) {
state.write(', ');
generator.VariableDeclarator(declarations[i], state);
}
}
}
var ForInStatement, FunctionDeclaration, RestElement, BinaryExpression, ArrayExpression, BlockStatement;
var GENERATOR = {
Program: function Program(node, state) {
var indent = state.indent.repeat(state.indentLevel);
var lineEnd = state.lineEnd,
writeComments = state.writeComments;
if (writeComments && node.comments != null) {
formatComments(state, node.comments, indent, lineEnd);
}
var statements = node.body;
var length = statements.length;
for (var i = 0; i < length; i++) {
var statement = statements[i];
if (writeComments && statement.comments != null) {
formatComments(state, statement.comments, indent, lineEnd);
}
state.write(indent);
this[statement.type](statement, state);
state.write(lineEnd);
}
if (writeComments && node.trailingComments != null) {
formatComments(state, node.trailingComments, indent, lineEnd);
}
},
BlockStatement: BlockStatement = function BlockStatement(node, state) {
var indent = state.indent.repeat(state.indentLevel++);
var lineEnd = state.lineEnd,
writeComments = state.writeComments;
var statementIndent = indent + state.indent;
state.write('{');
var statements = node.body;
if (statements != null && statements.length > 0) {
state.write(lineEnd);
if (writeComments && node.comments != null) {
formatComments(state, node.comments, statementIndent, lineEnd);
}
var length = statements.length;
for (var i = 0; i < length; i++) {
var statement = statements[i];
if (writeComments && statement.comments != null) {
formatComments(state, statement.comments, statementIndent, lineEnd);
}
state.write(statementIndent);
this[statement.type](statement, state);
state.write(lineEnd);
}
state.write(indent);
} else {
if (writeComments && node.comments != null) {
state.write(lineEnd);
formatComments(state, node.comments, statementIndent, lineEnd);
state.write(indent);
}
}
if (writeComments && node.trailingComments != null) {
formatComments(state, node.trailingComments, statementIndent, lineEnd);
}
state.write('}');
state.indentLevel--;
},
ClassBody: BlockStatement,
StaticBlock: function StaticBlock(node, state) {
state.write('static ');
this.BlockStatement(node, state);
},
EmptyStatement: function EmptyStatement(node, state) {
state.write(';');
},
ExpressionStatement: function ExpressionStatement(node, state) {
var precedence = state.expressionsPrecedence[node.expression.type];
if (precedence === NEEDS_PARENTHESES || precedence === 3 && node.expression.left.type[0] === 'O') {
state.write('(');
this[node.expression.type](node.expression, state);
state.write(')');
} else {
this[node.expression.type](node.expression, state);
}
state.write(';');
},
IfStatement: function IfStatement(node, state) {
state.write('if (');
this[node.test.type](node.test, state);
state.write(') ');
this[node.consequent.type](node.consequent, state);
if (node.alternate != null) {
state.write(' else ');
this[node.alternate.type](node.alternate, state);
}
},
LabeledStatement: function LabeledStatement(node, state) {
this[node.label.type](node.label, state);
state.write(': ');
this[node.body.type](node.body, state);
},
BreakStatement: function BreakStatement(node, state) {
state.write('break');
if (node.label != null) {
state.write(' ');
this[node.label.type](node.label, state);
}
state.write(';');
},
ContinueStatement: function ContinueStatement(node, state) {
state.write('continue');
if (node.label != null) {
state.write(' ');
this[node.label.type](node.label, state);
}
state.write(';');
},
WithStatement: function WithStatement(node, state) {
state.write('with (');
this[node.object.type](node.object, state);
state.write(') ');
this[node.body.type](node.body, state);
},
SwitchStatement: function SwitchStatement(node, state) {
var indent = state.indent.repeat(state.indentLevel++);
var lineEnd = state.lineEnd,
writeComments = state.writeComments;
state.indentLevel++;
var caseIndent = indent + state.indent;
var statementIndent = caseIndent + state.indent;
state.write('switch (');
this[node.discriminant.type](node.discriminant, state);
state.write(') {' + lineEnd);
var occurences = node.cases;
var occurencesCount = occurences.length;
for (var i = 0; i < occurencesCount; i++) {
var occurence = occurences[i];
if (writeComments && occurence.comments != null) {
formatComments(state, occurence.comments, caseIndent, lineEnd);
}
if (occurence.test) {
state.write(caseIndent + 'case ');
this[occurence.test.type](occurence.test, state);
state.write(':' + lineEnd);
} else {
state.write(caseIndent + 'default:' + lineEnd);
}
var consequent = occurence.consequent;
var consequentCount = consequent.length;
for (var _i = 0; _i < consequentCount; _i++) {
var statement = consequent[_i];
if (writeComments && statement.comments != null) {
formatComments(state, statement.comments, statementIndent, lineEnd);
}
state.write(statementIndent);
this[statement.type](statement, state);
state.write(lineEnd);
}
}
state.indentLevel -= 2;
state.write(indent + '}');
},
ReturnStatement: function ReturnStatement(node, state) {
state.write('return');
if (node.argument) {
state.write(' ');
this[node.argument.type](node.argument, state);
}
state.write(';');
},
ThrowStatement: function ThrowStatement(node, state) {
state.write('throw ');
this[node.argument.type](node.argument, state);
state.write(';');
},
TryStatement: function TryStatement(node, state) {
state.write('try ');
this[node.block.type](node.block, state);
if (node.handler) {
var handler = node.handler;
if (handler.param == null) {
state.write(' catch ');
} else {
state.write(' catch (');
this[handler.param.type](handler.param, state);
state.write(') ');
}
this[handler.body.type](handler.body, state);
}
if (node.finalizer) {
state.write(' finally ');
this[node.finalizer.type](node.finalizer, state);
}
},
WhileStatement: function WhileStatement(node, state) {
state.write('while (');
this[node.test.type](node.test, state);
state.write(') ');
this[node.body.type](node.body, state);
},
DoWhileStatement: function DoWhileStatement(node, state) {
state.write('do ');
this[node.body.type](node.body, state);
state.write(' while (');
this[node.test.type](node.test, state);
state.write(');');
},
ForStatement: function ForStatement(node, state) {
state.write('for (');
if (node.init != null) {
var init = node.init;
if (init.type[0] === 'V') {
formatVariableDeclaration(state, init);
} else {
this[init.type](init, state);
}
}
state.write('; ');
if (node.test) {
this[node.test.type](node.test, state);
}
state.write('; ');
if (node.update) {
this[node.update.type](node.update, state);
}
state.write(') ');
this[node.body.type](node.body, state);
},
ForInStatement: ForInStatement = function ForInStatement(node, state) {
state.write("for ".concat(node["await"] ? 'await ' : '', "("));
var left = node.left;
if (left.type[0] === 'V') {
formatVariableDeclaration(state, left);
} else {
this[left.type](left, state);
}
state.write(node.type[3] === 'I' ? ' in ' : ' of ');
this[node.right.type](node.right, state);
state.write(') ');
this[node.body.type](node.body, state);
},
ForOfStatement: ForInStatement,
DebuggerStatement: function DebuggerStatement(node, state) {
state.write('debugger;', node);
},
FunctionDeclaration: FunctionDeclaration = function FunctionDeclaration(node, state) {
state.write((node.async ? 'async ' : '') + (node.generator ? 'function* ' : 'function ') + (node.id ? node.id.name : ''), node);
formatSequence(state, node.params);
state.write(' ');
this[node.body.type](node.body, state);
},
FunctionExpression: FunctionDeclaration,
VariableDeclaration: function VariableDeclaration(node, state) {
formatVariableDeclaration(state, node);
state.write(';');
},
VariableDeclarator: function VariableDeclarator(node, state) {
this[node.id.type](node.id, state);
if (node.init != null) {
state.write(' = ');
this[node.init.type](node.init, state);
}
},
ClassDeclaration: function ClassDeclaration(node, state) {
state.write('class ' + (node.id ? "".concat(node.id.name, " ") : ''), node);
if (node.superClass) {
state.write('extends ');
var superClass = node.superClass;
var type = superClass.type;
var precedence = state.expressionsPrecedence[type];
if ((type[0] !== 'C' || type[1] !== 'l' || type[5] !== 'E') && (precedence === NEEDS_PARENTHESES || precedence < state.expressionsPrecedence.ClassExpression)) {
state.write('(');
this[node.superClass.type](superClass, state);
state.write(')');
} else {
this[superClass.type](superClass, state);
}
state.write(' ');
}
this.ClassBody(node.body, state);
},
ImportDeclaration: function ImportDeclaration(node, state) {
state.write('import ');
var specifiers = node.specifiers;
var length = specifiers.length;
var i = 0;
if (length > 0) {
for (; i < length;) {
if (i > 0) {
state.write(', ');
}
var specifier = specifiers[i];
var type = specifier.type[6];
if (type === 'D') {
state.write(specifier.local.name, specifier);
i++;
} else if (type === 'N') {
state.write('* as ' + specifier.local.name, specifier);
i++;
} else {
break;
}
}
if (i < length) {
state.write('{');
for (;;) {
var _specifier = specifiers[i];
var name = _specifier.imported.name;
state.write(name, _specifier);
if (name !== _specifier.local.name) {
state.write(' as ' + _specifier.local.name);
}
if (++i < length) {
state.write(', ');
} else {
break;
}
}
state.write('}');
}
state.write(' from ');
}
this.Literal(node.source, state);
state.write(';');
},
ImportExpression: function ImportExpression(node, state) {
state.write('import(');
this[node.source.type](node.source, state);
state.write(')');
},
ExportDefaultDeclaration: function ExportDefaultDeclaration(node, state) {
state.write('export default ');
this[node.declaration.type](node.declaration, state);
if (state.expressionsPrecedence[node.declaration.type] != null && node.declaration.type[0] !== 'F') {
state.write(';');
}
},
ExportNamedDeclaration: function ExportNamedDeclaration(node, state) {
state.write('export ');
if (node.declaration) {
this[node.declaration.type](node.declaration, state);
} else {
state.write('{');
var specifiers = node.specifiers,
length = specifiers.length;
if (length > 0) {
for (var i = 0;;) {
var specifier = specifiers[i];
var name = specifier.local.name;
state.write(name, specifier);
if (name !== specifier.exported.name) {
state.write(' as ' + specifier.exported.name);
}
if (++i < length) {
state.write(', ');
} else {
break;
}
}
}
state.write('}');
if (node.source) {
state.write(' from ');
this.Literal(node.source, state);
}
state.write(';');
}
},
ExportAllDeclaration: function ExportAllDeclaration(node, state) {
if (node.exported != null) {
state.write('export * as ' + node.exported.name + ' from ');
} else {
state.write('export * from ');
}
this.Literal(node.source, state);
state.write(';');
},
MethodDefinition: function MethodDefinition(node, state) {
if (node["static"]) {
state.write('static ');
}
var kind = node.kind[0];
if (kind === 'g' || kind === 's') {
state.write(node.kind + ' ');
}
if (node.value.async) {
state.write('async ');
}
if (node.value.generator) {
state.write('*');
}
if (node.computed) {
state.write('[');
this[node.key.type](node.key, state);
state.write(']');
} else {
this[node.key.type](node.key, state);
}
formatSequence(state, node.value.params);
state.write(' ');
this[node.value.body.type](node.value.body, state);
},
ClassExpression: function ClassExpression(node, state) {
this.ClassDeclaration(node, state);
},
ArrowFunctionExpression: function ArrowFunctionExpression(node, state) {
state.write(node.async ? 'async ' : '', node);
var params = node.params;
if (params != null) {
if (params.length === 1 && params[0].type[0] === 'I') {
state.write(params[0].name, params[0]);
} else {
formatSequence(state, node.params);
}
}
state.write(' => ');
if (node.body.type[0] === 'O') {
state.write('(');
this.ObjectExpression(node.body, state);
state.write(')');
} else {
this[node.body.type](node.body, state);
}
},
ThisExpression: function ThisExpression(node, state) {
state.write('this', node);
},
Super: function Super(node, state) {
state.write('super', node);
},
RestElement: RestElement = function RestElement(node, state) {
state.write('...');
this[node.argument.type](node.argument, state);
},
SpreadElement: RestElement,
YieldExpression: function YieldExpression(node, state) {
state.write(node.delegate ? 'yield*' : 'yield');
if (node.argument) {
state.write(' ');
this[node.argument.type](node.argument, state);
}
},
AwaitExpression: function AwaitExpression(node, state) {
state.write('await ', node);
formatExpression(state, node.argument, node);
},
TemplateLiteral: function TemplateLiteral(node, state) {
var quasis = node.quasis,
expressions = node.expressions;
state.write('`');
var length = expressions.length;
for (var i = 0; i < length; i++) {
var expression = expressions[i];
var _quasi = quasis[i];
state.write(_quasi.value.raw, _quasi);
state.write('${');
this[expression.type](expression, state);
state.write('}');
}
var quasi = quasis[quasis.length - 1];
state.write(quasi.value.raw, quasi);
state.write('`');
},
TemplateElement: function TemplateElement(node, state) {
state.write(node.value.raw, node);
},
TaggedTemplateExpression: function TaggedTemplateExpression(node, state) {
formatExpression(state, node.tag, node);
this[node.quasi.type](node.quasi, state);
},
ArrayExpression: ArrayExpression = function ArrayExpression(node, state) {
state.write('[');
if (node.elements.length > 0) {
var elements = node.elements,
length = elements.length;
for (var i = 0;;) {
var element = elements[i];
if (element != null) {
this[element.type](element, state);
}
if (++i < length) {
state.write(', ');
} else {
if (element == null) {
state.write(', ');
}
break;
}
}
}
state.write(']');
},
ArrayPattern: ArrayExpression,
ObjectExpression: function ObjectExpression(node, state) {
var indent = state.indent.repeat(state.indentLevel++);
var lineEnd = state.lineEnd,
writeComments = state.writeComments;
var propertyIndent = indent + state.indent;
state.write('{');
if (node.properties.length > 0) {
state.write(lineEnd);
if (writeComments && node.comments != null) {
formatComments(state, node.comments, propertyIndent, lineEnd);
}
var comma = ',' + lineEnd;
var properties = node.properties,
length = properties.length;
for (var i = 0;;) {
var property = properties[i];
if (writeComments && property.comments != null) {
formatComments(state, property.comments, propertyIndent, lineEnd);
}
state.write(propertyIndent);
this[property.type](property, state);
if (++i < length) {
state.write(comma);
} else {
break;
}
}
state.write(lineEnd);
if (writeComments && node.trailingComments != null) {
formatComments(state, node.trailingComments, propertyIndent, lineEnd);
}
state.write(indent + '}');
} else if (writeComments) {
if (node.comments != null) {
state.write(lineEnd);
formatComments(state, node.comments, propertyIndent, lineEnd);
if (node.trailingComments != null) {
formatComments(state, node.trailingComments, propertyIndent, lineEnd);
}
state.write(indent + '}');
} else if (node.trailingComments != null) {
state.write(lineEnd);
formatComments(state, node.trailingComments, propertyIndent, lineEnd);
state.write(indent + '}');
} else {
state.write('}');
}
} else {
state.write('}');
}
state.indentLevel--;
},
Property: function Property(node, state) {
if (node.method || node.kind[0] !== 'i') {
this.MethodDefinition(node, state);
} else {
if (!node.shorthand) {
if (node.computed) {
state.write('[');
this[node.key.type](node.key, state);
state.write(']');
} else {
this[node.key.type](node.key, state);
}
state.write(': ');
}
this[node.value.type](node.value, state);
}
},
PropertyDefinition: function PropertyDefinition(node, state) {
if (node["static"]) {
state.write('static ');
}
if (node.computed) {
state.write('[');
}
this[node.key.type](node.key, state);
if (node.computed) {
state.write(']');
}
if (node.value == null) {
if (node.key.type[0] !== 'F') {
state.write(';');
}
return;
}
state.write(' = ');
this[node.value.type](node.value, state);
state.write(';');
},
ObjectPattern: function ObjectPattern(node, state) {
state.write('{');
if (node.properties.length > 0) {
var properties = node.properties,
length = properties.length;
for (var i = 0;;) {
this[properties[i].type](properties[i], state);
if (++i < length) {
state.write(', ');
} else {
break;
}
}
}
state.write('}');
},
SequenceExpression: function SequenceExpression(node, state) {
formatSequence(state, node.expressions);
},
UnaryExpression: function UnaryExpression(node, state) {
if (node.prefix) {
var operator = node.operator,
argument = node.argument,
type = node.argument.type;
state.write(operator);
var needsParentheses = expressionNeedsParenthesis(state, argument, node);
if (!needsParentheses && (operator.length > 1 || type[0] === 'U' && (type[1] === 'n' || type[1] === 'p') && argument.prefix && argument.operator[0] === operator && (operator === '+' || operator === '-'))) {
state.write(' ');
}
if (needsParentheses) {
state.write(operator.length > 1 ? ' (' : '(');
this[type](argument, state);
state.write(')');
} else {
this[type](argument, state);
}
} else {
this[node.argument.type](node.argument, state);
state.write(node.operator);
}
},
UpdateExpression: function UpdateExpression(node, state) {
if (node.prefix) {
state.write(node.operator);
this[node.argument.type](node.argument, state);
} else {
this[node.argument.type](node.argument, state);
state.write(node.operator);
}
},
AssignmentExpression: function AssignmentExpression(node, state) {
this[node.left.type](node.left, state);
state.write(' ' + node.operator + ' ');
this[node.right.type](node.right, state);
},
AssignmentPattern: function AssignmentPattern(node, state) {
this[node.left.type](node.left, state);
state.write(' = ');
this[node.right.type](node.right, state);
},
BinaryExpression: BinaryExpression = function BinaryExpression(node, state) {
var isIn = node.operator === 'in';
if (isIn) {
state.write('(');
}
formatExpression(state, node.left, node, false);
state.write(' ' + node.operator + ' ');
formatExpression(state, node.right, node, true);
if (isIn) {
state.write(')');
}
},
LogicalExpression: BinaryExpression,
ConditionalExpression: function ConditionalExpression(node, state) {
var test = node.test;
var precedence = state.expressionsPrecedence[test.type];
if (precedence === NEEDS_PARENTHESES || precedence <= state.expressionsPrecedence.ConditionalExpression) {
state.write('(');
this[test.type](test, state);
state.write(')');
} else {
this[test.type](test, state);
}
state.write(' ? ');
this[node.consequent.type](node.consequent, state);
state.write(' : ');
this[node.alternate.type](node.alternate, state);
},
NewExpression: function NewExpression(node, state) {
state.write('new ');
var precedence = state.expressionsPrecedence[node.callee.type];
if (precedence === NEEDS_PARENTHESES || precedence < state.expressionsPrecedence.CallExpression || hasCallExpression(node.callee)) {
state.write('(');
this[node.callee.type](node.callee, state);
state.write(')');
} else {
this[node.callee.type](node.callee, state);
}
formatSequence(state, node['arguments']);
},
CallExpression: function CallExpression(node, state) {
var precedence = state.expressionsPrecedence[node.callee.type];
if (precedence === NEEDS_PARENTHESES || precedence < state.expressionsPrecedence.CallExpression) {
state.write('(');
this[node.callee.type](node.callee, state);
state.write(')');
} else {
this[node.callee.type](node.callee, state);
}
if (node.optional) {
state.write('?.');
}
formatSequence(state, node['arguments']);
},
ChainExpression: function ChainExpression(node, state) {
this[node.expression.type](node.expression, state);
},
MemberExpression: function MemberExpression(node, state) {
var precedence = state.expressionsPrecedence[node.object.type];
if (precedence === NEEDS_PARENTHESES || precedence < state.expressionsPrecedence.MemberExpression) {
state.write('(');
this[node.object.type](node.object, state);
state.write(')');
} else {
this[node.object.type](node.object, state);
}
if (node.computed) {
if (node.optional) {
state.write('?.');
}
state.write('[');
this[node.property.type](node.property, state);
state.write(']');
} else {
if (node.optional) {
state.write('?.');
} else {
state.write('.');
}
this[node.property.type](node.property, state);
}
},
MetaProperty: function MetaProperty(node, state) {
state.write(node.meta.name + '.' + node.property.name, node);
},
Identifier: function Identifier(node, state) {
state.write(node.name, node);
},
PrivateIdentifier: function PrivateIdentifier(node, state) {
state.write("#".concat(node.name), node);
},
Literal: function Literal(node, state) {
if (node.raw != null) {
state.write(node.raw, node);
} else if (node.regex != null) {
this.RegExpLiteral(node, state);
} else if (node.bigint != null) {
state.write(node.bigint + 'n', node);
} else {
state.write(stringify(node.value), node);
}
},
RegExpLiteral: function RegExpLiteral(node, state) {
var regex = node.regex;
state.write("/".concat(regex.pattern, "/").concat(regex.flags), node);
}
};
exports.GENERATOR = GENERATOR;
var EMPTY_OBJECT = {};
var baseGenerator = GENERATOR;
exports.baseGenerator = baseGenerator;
var State = function () {
function State(options) {
_classCallCheck(this, State);
var setup = options == null ? EMPTY_OBJECT : options;
this.output = '';
if (setup.output != null) {
this.output = setup.output;
this.write = this.writeToStream;
} else {
this.output = '';
}
this.generator = setup.generator != null ? setup.generator : GENERATOR;
this.expressionsPrecedence = setup.expressionsPrecedence != null ? setup.expressionsPrecedence : EXPRESSIONS_PRECEDENCE;
this.indent = setup.indent != null ? setup.indent : ' ';
this.lineEnd = setup.lineEnd != null ? setup.lineEnd : '\n';
this.indentLevel = setup.startingIndentLevel != null ? setup.startingIndentLevel : 0;
this.writeComments = setup.comments ? setup.comments : false;
if (setup.sourceMap != null) {
this.write = setup.output == null ? this.writeAndMap : this.writeToStreamAndMap;
this.sourceMap = setup.sourceMap;
this.line = 1;
this.column = 0;
this.lineEndSize = this.lineEnd.split('\n').length - 1;
this.mapping = {
original: null,
generated: this,
name: undefined,
source: setup.sourceMap.file || setup.sourceMap._file
};
}
}
_createClass(State, [{
key: "write",
value: function write(code) {
this.output += code;
}
}, {
key: "writeToStream",
value: function writeToStream(code) {
this.output.write(code);
}
}, {
key: "writeAndMap",
value: function writeAndMap(code, node) {
this.output += code;
this.map(code, node);
}
}, {
key: "writeToStreamAndMap",
value: function writeToStreamAndMap(code, node) {
this.output.write(code);
this.map(code, node);
}
}, {
key: "map",
value: function map(code, node) {
if (node != null) {
var type = node.type;
if (type[0] === 'L' && type[2] === 'n') {
this.column = 0;
this.line++;
return;
}
if (node.loc != null) {
var mapping = this.mapping;
mapping.original = node.loc.start;
mapping.name = node.name;
this.sourceMap.addMapping(mapping);
}
if (type[0] === 'T' && type[8] === 'E' || type[0] === 'L' && type[1] === 'i' && typeof node.value === 'string') {
var _length = code.length;
var column = this.column,
line = this.line;
for (var i = 0; i < _length; i++) {
if (code[i] === '\n') {
column = 0;
line++;
} else {
column++;
}
}
this.column = column;
this.line = line;
return;
}
}
var length = code.length;
var lineEnd = this.lineEnd;
if (length > 0) {
if (this.lineEndSize > 0 && (lineEnd.length === 1 ? code[length - 1] === lineEnd : code.endsWith(lineEnd))) {
this.line += this.lineEndSize;
this.column = 0;
} else {
this.column += length;
}
}
}
}, {
key: "toString",
value: function toString() {
return this.output;
}
}]);
return State;
}();
function generate(node, options) {
var state = new State(options);
state.generator[node.type](node, state);
return state.output;
}
},{}],30:[function(require,module,exports){
/**
* Expose `Backoff`.
*/
module.exports = Backoff;
/**
* Initialize backoff timer with `opts`.
*
* - `min` initial timeout in milliseconds [100]
* - `max` max timeout [10000]
* - `jitter` [0]
* - `factor` [2]
*
* @param {Object} opts
* @api public
*/
function Backoff(opts) {
opts = opts || {};
this.ms = opts.min || 100;
this.max = opts.max || 10000;
this.factor = opts.factor || 2;
this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
this.attempts = 0;
}
/**
* Return the backoff duration.
*
* @return {Number}
* @api public
*/
Backoff.prototype.duration = function(){
var ms = this.ms * Math.pow(this.factor, this.attempts++);
if (this.jitter) {
var rand = Math.random();
var deviation = Math.floor(rand * this.jitter * ms);
ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
}
return Math.min(ms, this.max) | 0;
};
/**
* Reset the number of attempts.
*
* @api public
*/
Backoff.prototype.reset = function(){
this.attempts = 0;
};
/**
* Set the minimum duration
*
* @api public
*/
Backoff.prototype.setMin = function(min){
this.ms = min;
};
/**
* Set the maximum duration
*
* @api public
*/
Backoff.prototype.setMax = function(max){
this.max = max;
};
/**
* Set the jitter
*
* @api public
*/
Backoff.prototype.setJitter = function(jitter){
this.jitter = jitter;
};
},{}],31:[function(require,module,exports){
/*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
(function(chars){
"use strict";
exports.encode = function(arraybuffer) {
var bytes = new Uint8Array(arraybuffer),
i, len = bytes.length, base64 = "";
for (i = 0; i < len; i+=3) {
base64 += chars[bytes[i] >> 2];
base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64 += chars[bytes[i + 2] & 63];
}
if ((len % 3) === 2) {
base64 = base64.substring(0, base64.length - 1) + "=";
} else if (len % 3 === 1) {
base64 = base64.substring(0, base64.length - 2) + "==";
}
return base64;
};
exports.decode = function(base64) {
var bufferLength = base64.length * 0.75,
len = base64.length, i, p = 0,
encoded1, encoded2, encoded3, encoded4;
if (base64[base64.length - 1] === "=") {
bufferLength--;
if (base64[base64.length - 2] === "=") {
bufferLength--;
}
}
var arraybuffer = new ArrayBuffer(bufferLength),
bytes = new Uint8Array(arraybuffer);
for (i = 0; i < len; i+=4) {
encoded1 = chars.indexOf(base64[i]);
encoded2 = chars.indexOf(base64[i+1]);
encoded3 = chars.indexOf(base64[i+2]);
encoded4 = chars.indexOf(base64[i+3]);
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return arraybuffer;
};
})("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
},{}],32:[function(require,module,exports){
'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('')
}
},{}],33:[function(require,module,exports){
/**
* Create a blob builder even when vendor prefixes exist
*/
var BlobBuilder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
typeof WebKitBlobBuilder !== 'undefined' ? WebKitBlobBuilder :
typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
false;
/**
* Check if Blob constructor is supported
*/
var blobSupported = (function() {
try {
var a = new Blob(['hi']);
return a.size === 2;
} catch(e) {
return false;
}
})();
/**
* Check if Blob constructor supports ArrayBufferViews
* Fails in Safari 6, so we need to map to ArrayBuffers there.
*/
var blobSupportsArrayBufferView = blobSupported && (function() {
try {
var b = new Blob([new Uint8Array([1,2])]);
return b.size === 2;
} catch(e) {
return false;
}
})();
/**
* Check if BlobBuilder is supported
*/
var blobBuilderSupported = BlobBuilder
&& BlobBuilder.prototype.append
&& BlobBuilder.prototype.getBlob;
/**
* Helper function that maps ArrayBufferViews to ArrayBuffers
* Used by BlobBuilder constructor and old browsers that didn't
* support it in the Blob constructor.
*/
function mapArrayBufferViews(ary) {
return ary.map(function(chunk) {
if (chunk.buffer instanceof ArrayBuffer) {
var buf = chunk.buffer;
// if this is a subarray, make a copy so we only
// include the subarray region from the underlying buffer
if (chunk.byteLength !== buf.byteLength) {
var copy = new Uint8Array(chunk.byteLength);
copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
buf = copy.buffer;
}
return buf;
}
return chunk;
});
}
function BlobBuilderConstructor(ary, options) {
options = options || {};
var bb = new BlobBuilder();
mapArrayBufferViews(ary).forEach(function(part) {
bb.append(part);
});
return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
};
function BlobConstructor(ary, options) {
return new Blob(mapArrayBufferViews(ary), options || {});
};
if (typeof Blob !== 'undefined') {
BlobBuilderConstructor.prototype = Blob.prototype;
BlobConstructor.prototype = Blob.prototype;
}
module.exports = (function() {
if (blobSupported) {
return blobSupportsArrayBufferView ? Blob : BlobConstructor;
} else if (blobBuilderSupported) {
return BlobBuilderConstructor;
} else {
return undefined;
}
})();
},{}],34:[function(require,module,exports){
},{}],35:[function(require,module,exports){
(function (Buffer){(function (){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an 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+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
typeof console.error === 'function') {
console.error(
'This browser lacks typed array (Uint8Array) support which is required by ' +
'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
)
}
function typedArraySupport () {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1)
arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
return arr.foo() === 42
} catch (e) {
return false
}
}
Object.defineProperty(Buffer.prototype, 'parent', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.buffer
}
})
Object.defineProperty(Buffer.prototype, 'offset', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.byteOffset
}
})
function createBuffer (length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('The value "' + length + '" is invalid for option "size"')
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length)
buf.__proto__ = Buffer.prototype
return buf
}
/**
* 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) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new TypeError(
'The "string" argument must be of type string. Received type number'
)
}
return allocUnsafe(arg)
}
return from(arg, encodingOrOffset, length)
}
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species != null &&
Buffer[Symbol.species] === Buffer) {
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
enumerable: false,
writable: false
})
}
Buffer.poolSize = 8192 // not used by this implementation
function from (value, encodingOrOffset, length) {
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
if (ArrayBuffer.isView(value)) {
return fromArrayLike(value)
}
if (value == null) {
throw TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
if (isInstance(value, ArrayBuffer) ||
(value && isInstance(value.buffer, ArrayBuffer))) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'number') {
throw new TypeError(
'The "value" argument must not be of type number. Received type number'
)
}
var valueOf = value.valueOf && value.valueOf()
if (valueOf != null && valueOf !== value) {
return Buffer.from(valueOf, encodingOrOffset, length)
}
var b = fromObject(value)
if (b) return b
if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
typeof value[Symbol.toPrimitive] === 'function') {
return Buffer.from(
value[Symbol.toPrimitive]('string'), encodingOrOffset, length
)
}
throw new TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof 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(value, encodingOrOffset, length)
}
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be of type number')
} else if (size < 0) {
throw new RangeError('The value "' + size + '" is invalid for option "size"')
}
}
function alloc (size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(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(size).fill(fill, encoding)
: createBuffer(size).fill(fill)
}
return createBuffer(size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding)
}
function allocUnsafe (size) {
assertSize(size)
return createBuffer(size < 0 ? 0 : checked(size) | 0)
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size)
}
function fromString (string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
var length = byteLength(string, encoding) | 0
var buf = createBuffer(length)
var actual = buf.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')
buf = buf.slice(0, actual)
}
return buf
}
function fromArrayLike (array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
var buf = createBuffer(length)
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255
}
return buf
}
function fromArrayBuffer (array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('"offset" is outside of buffer bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('"length" is outside of buffer bounds')
}
var buf
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array)
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset)
} else {
buf = new Uint8Array(array, byteOffset, length)
}
// Return an augmented `Uint8Array` instance
buf.__proto__ = Buffer.prototype
return buf
}
function fromObject (obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
var buf = createBuffer(len)
if (buf.length === 0) {
return buf
}
obj.copy(buf, 0, 0, len)
return buf
}
if (obj.length !== undefined) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0)
}
return fromArrayLike(obj)
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data)
}
}
function checked (length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + K_MAX_LENGTH.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 === true &&
b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
}
Buffer.compare = function compare (a, b) {
if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError(
'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
)
}
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 (!Array.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 (isInstance(buf, Uint8Array)) {
buf = Buffer.from(buf)
}
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 (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
throw new TypeError(
'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
'Received type ' + typeof string
)
}
var len = string.length
var mustMatch = (arguments.length > 2 && arguments[2] === true)
if (!mustMatch && 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':
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 mustMatch ? -1 : 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
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
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
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.toLocaleString = Buffer.prototype.toString
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
str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
if (this.length > max) str += ' ... '
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (isInstance(target, Uint8Array)) {
target = Buffer.from(target, target.offset, target.byteLength)
}
if (!Buffer.isBuffer(target)) {
throw new TypeError(
'The "target" argument must be one of type Buffer or Uint8Array. ' +
'Received type ' + (typeof target)
)
}
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 (numberIsNaN(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 (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
}
}
var strLen = string.length
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (numberIsNaN(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
}
} 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 = this.subarray(start, end)
// Return an augmented `Uint8Array` instance
newBuf.__proto__ = Buffer.prototype
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) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
offset = offset >>> 0
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) {
offset = offset >>> 0
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) {
offset = offset >>> 0
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) {
offset = offset >>> 0
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) {
offset = offset >>> 0
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) {
offset = offset >>> 0
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) {
offset = offset >>> 0
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) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
offset = offset >>> 0
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)
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
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)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
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)
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
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 (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)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
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)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
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)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
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
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
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) {
value = +value
offset = offset >>> 0
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) {
value = +value
offset = offset >>> 0
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 (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
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('Index out of range')
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
if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
// Use built-in when available, missing from IE11
this.copyWithin(targetStart, start, end)
} else if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (var i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, end),
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 (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)
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if ((encoding === 'utf8' && code < 128) ||
encoding === 'latin1') {
// Fast path: If `val` fits into a single byte, use that numeric value.
val = code
}
}
} 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
: Buffer.from(val, encoding)
var len = bytes.length
if (len === 0) {
throw new TypeError('The value "' + val +
'" is invalid for argument "value"')
}
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 takes equal signs as end of the Base64 encoding
str = str.split('=')[0]
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().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 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
}
// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
// the `instanceof` check but they should be treated as of that type.
// See: https://github.com/feross/buffer/issues/166
function isInstance (obj, type) {
return obj instanceof type ||
(obj != null && obj.constructor != null && obj.constructor.name != null &&
obj.constructor.name === type.name)
}
function numberIsNaN (obj) {
// For IE11 support
return obj !== obj // eslint-disable-line no-self-compare
}
}).call(this)}).call(this,require("buffer").Buffer)
},{"base64-js":32,"buffer":35,"ieee754":100}],36:[function(require,module,exports){
'use strict';
var GetIntrinsic = require('get-intrinsic');
var callBind = require('./');
var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
module.exports = function callBoundIntrinsic(name, allowMissing) {
var intrinsic = GetIntrinsic(name, !!allowMissing);
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
return callBind(intrinsic);
}
return intrinsic;
};
},{"./":37,"get-intrinsic":86}],37:[function(require,module,exports){
'use strict';
var bind = require('function-bind');
var GetIntrinsic = require('get-intrinsic');
var $apply = GetIntrinsic('%Function.prototype.apply%');
var $call = GetIntrinsic('%Function.prototype.call%');
var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);
var $defineProperty = GetIntrinsic('%Object.defineProperty%', true);
var $max = GetIntrinsic('%Math.max%');
if ($defineProperty) {
try {
$defineProperty({}, 'a', { value: 1 });
} catch (e) {
// IE 8 has a broken defineProperty
$defineProperty = null;
}
}
module.exports = function callBind(originalFunction) {
var func = $reflectApply(bind, $call, arguments);
if ($gOPD && $defineProperty) {
var desc = $gOPD(func, 'length');
if (desc.configurable) {
// original length, plus the receiver, minus any additional arguments (after the receiver)
$defineProperty(
func,
'length',
{ value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) }
);
}
}
return func;
};
var applyBind = function applyBind() {
return $reflectApply(bind, $apply, arguments);
};
if ($defineProperty) {
$defineProperty(module.exports, 'apply', { value: applyBind });
} else {
module.exports.apply = applyBind;
}
},{"function-bind":84,"get-intrinsic":86}],38:[function(require,module,exports){
var EventEmitter = require('events').EventEmitter
var storage = require('./lib/storage')
var logger = require('./lib/logger')
var debug = require('./lib/debug')
var copy = require('./lib/copy')
var help = require('./lib/help')
var perf = require('./lib/perf')
var log = require('./lib/log')
var getAllRoutes = require('wayfarer/get-all-routes')
module.exports = expose
function expose (opts) {
opts = opts || {}
store.storeName = 'choo-devtools'
return store
function store (state, emitter, app) {
var localEmitter = new EventEmitter()
if (typeof window !== 'undefined') {
logger(state, emitter, opts)
}
emitter.on('DOMContentLoaded', function () {
if (typeof window === 'undefined') return
window.choo = {}
window.choo.state = state
window.choo.emit = function () {
emitter.emit.apply(emitter, arguments)
}
window.choo.on = function (eventName, listener) {
emitter.on(eventName, listener)
}
debug(state, emitter, app, localEmitter)
log(state, emitter, app, localEmitter)
perf(state, emitter, app, localEmitter)
window.choo.copy = copy
if (app.router && app.router.router) {
window.choo.routes = Object.keys(getAllRoutes(app.router.router))
}
storage()
help()
})
}
}
},{"./lib/copy":39,"./lib/debug":40,"./lib/help":41,"./lib/log":42,"./lib/logger":43,"./lib/perf":44,"./lib/storage":45,"events":81,"wayfarer/get-all-routes":224}],39:[function(require,module,exports){
var stateCopy = require('state-copy')
var pluck = require('plucker')
module.exports = copy
function copy (state) {
var isStateString = state && typeof state === 'string'
var isChooPath = isStateString && arguments.length === 1 && state.indexOf('state.') === 0
if (!state || typeof state === 'function') state = window.choo.state
if (isChooPath) [].push.call(arguments, { state: window.choo.state })
stateCopy(isStateString ? pluck.apply(this, arguments) : state)
}
},{"plucker":158,"state-copy":215}],40:[function(require,module,exports){
/* eslint-disable node/no-deprecated-api */
var onChange = require('object-change-callsite')
var nanologger = require('nanologger')
var assert = require('assert')
var enabledMessage = 'Debugging enabled. To disable run: `choo.debug = false`'
var disabledMessage = 'Debugging disabled. We hope it was helpful! 🙌'
module.exports = debug
function debug (state, emitter, app, localEmitter) {
var log = nanologger('choo-devtools')
var enabled = window.localStorage.logLevel === 'debug'
if (enabled) log.info(enabledMessage)
state = onChange(state, function (attr, value, callsite) {
if (!enabled) return
callsite = callsite.split('\n')[1].replace(/^ +/, '')
log.info('state.' + attr, value, '\n' + callsite)
})
app.state = state
Object.defineProperty(window.choo, 'debug', {
get: function () {
window.localStorage.logLevel = 'debug'
localEmitter.emit('debug', true)
enabled = true
return enabledMessage
},
set: function (bool) {
assert.equal(typeof bool, 'boolean', 'choo-devtools.debug: bool should be type boolean')
window.localStorage.logLevel = bool ? 'debug' : 'info'
enabled = bool
localEmitter.emit('debug', enabled)
if (enabled) log.info(enabledMessage)
else log.info(disabledMessage)
}
})
}
},{"assert":22,"nanologger":141,"object-change-callsite":152}],41:[function(require,module,exports){
module.exports = help
function help () {
Object.defineProperty(window.choo, 'help', {
get: get,
set: noop
})
function get () {
setTimeout(function () {
print('copy', 'Serialize the current state to the clipboard.')
print('debug', 'Enable Choo debug mode.')
print('emit', 'Emit an event in the Choo emitter.')
print('help', 'Print usage information.')
print('log', 'Print the last 150 events emitted.')
print('on', 'Listen for an event in the Choo emitter.')
print('once', 'Listen for an event once in the Choo emitter.')
print('perf', 'Print out performance metrics')
print('state', 'Print the Choo state object.')
print('storage', 'Print browser storage information.')
}, 0)
return 'Choo command overview'
}
}
function print (cmd, desc) {
var color = '#cc99cc'
console.log(' %cchoo.' + cmd, 'color: ' + color, '— ' + desc)
}
function noop () {}
},{}],42:[function(require,module,exports){
var removeItems = require('remove-array-items')
var scheduler = require('nanoscheduler')()
var nanologger = require('nanologger')
var _log = nanologger('choo')
var clone = require('clone')
var MAX_HISTORY_LENGTH = 150 // How many items we should keep around
module.exports = log
function log (state, emitter, app, localEmitter) {
var shouldDebug = window.localStorage.logLevel === 'debug'
var history = []
var i = 0
var shouldWarn = true
localEmitter.on('debug', function (bool) {
shouldDebug = bool
})
window.choo._history = history
window.choo.history = showHistory
Object.defineProperty(window.choo, 'log', { get: showHistory, set: noop })
Object.defineProperty(window.choo, 'history', { get: showHistory, set: noop })
emitter.on('*', function (name, data) {
i += 1
var entry = new Event(name, data, state)
history.push(entry)
scheduler.push(function () {
var length = history.length
if (length > MAX_HISTORY_LENGTH) {
removeItems(history, 0, length - MAX_HISTORY_LENGTH)
}
})
})
function showHistory () {
setTimeout(function () {
console.table(history)
}, 0)
var events = i === 1 ? 'event' : 'events'
var msg = i + ' ' + events + ' recorded, showing the last ' + MAX_HISTORY_LENGTH + '.'
if (shouldDebug === false) {
msg += ' Enable state capture by calling `choo.debug`.'
} else {
msg += ' Disable state capture by calling `choo.debug = false`.'
}
return msg
}
function Event (name, data, state) {
this.name = name
this.data = data === undefined ? '<no data>' : data
this.state = shouldDebug
? tryClone(state)
: '<disabled>'
}
function tryClone (state) {
try {
var _state = clone(state)
if (!shouldWarn) shouldWarn = true
return _state
} catch (ex) {
if (shouldWarn) {
_log.warn('Could not clone your app state. Make sure to have a serializable state so it can be cloned')
shouldWarn = false
}
return '<unserializable>'
}
}
}
function noop () {}
},{"clone":53,"nanologger":141,"nanoscheduler":149,"remove-array-items":168}],43:[function(require,module,exports){
var scheduler = require('nanoscheduler')()
var nanologger = require('nanologger')
var Hooks = require('choo-hooks')
module.exports = logger
function logger (state, emitter, opts) {
var initialRender = true
var hooks = Hooks(emitter)
var log = nanologger('choo')
hooks.on('log:debug', logger('debug'))
hooks.on('log:info', logger('info'))
hooks.on('log:warn', logger('warn'))
hooks.on('log:error', logger('error'))
hooks.on('log:fatal', logger('fatal'))
hooks.on('event', function (eventName, data, timing) {
if (opts.filter && !opts.filter(eventName, data, timing)) return
if (timing) {
var duration = timing.duration.toFixed()
var level = duration < 50 ? 'info' : 'warn'
if (data !== undefined) logger(level)(eventName, data, duration + 'ms')
else logger(level)(eventName, duration + 'ms')
} else {
if (data !== undefined) logger('info')(eventName, data)
else logger('info')(eventName)
}
})
hooks.on('unhandled', function (eventName, data) {
logger('error')('No listeners for ' + eventName)
})
hooks.on('DOMContentLoaded', function (timing) {
if (!timing) return logger('info')('DOMContentLoaded')
var level = timing.interactive < 1000 ? 'info' : 'warn'
logger(level)('DOMContentLoaded', timing.interactive + 'ms to interactive')
})
hooks.on('render', function (timings) {
if (!timings || !timings.render) return logger('info')('render')
var duration = timings.render.duration.toFixed()
var msg = 'render'
if (initialRender) {
initialRender = false
msg = 'initial ' + msg
}
// each frame has 10ms available for userland stuff
var fps = Math.min((600 / duration).toFixed(), 60)
if (fps === 60) {
logger('info')(msg, fps + 'fps', duration + 'ms')
} else {
var times = {
render: timings.render.duration.toFixed() + 'ms'
}
if (timings.morph) times.morph = timings.morph.duration.toFixed() + 'ms'
logger('warn')(msg, fps + 'fps', duration + 'ms', times)
}
})
hooks.on('resource-timing-buffer-full', function () {
logger('error')("The browser's Resource Resource timing buffer is full. Cannot store any more timing information")
})
hooks.start()
function logger (level) {
return function () {
var args = []
for (var i = 0, len = arguments.length; i < len; i++) {
args.push(arguments[i])
}
scheduler.push(function () {
log[level].apply(log, args)
})
}
}
}
},{"choo-hooks":46,"nanologger":141,"nanoscheduler":149}],44:[function(require,module,exports){
var onPerformance = require('on-performance')
var BAR = '█'
module.exports = perf
function perf (state, emitter, app, localEmitter) {
var stats = {}
window.choo.perf = {}
// Print all events
var all = new Perf(stats, 'all')
Object.defineProperty(window.choo.perf, 'all', {
get: all.get.bind(all),
set: noop
})
// Print only Choo core events
var core = new Perf(stats, 'core', function (name) {
return /^choo/.test(name)
})
Object.defineProperty(window.choo.perf, 'core', {
get: core.get.bind(core),
set: noop
})
// Print component data
var components = new Perf(stats, 'components', function (name) {
return !/^choo/.test(name) && !/^bankai/.test(name)
})
Object.defineProperty(window.choo.perf, 'components', {
get: components.get.bind(components),
set: noop
})
// Print choo userland events (event emitter)
var events = new Perf(stats, 'events', function (name) {
return /^choo\.emit/.test(name)
}, function (name) {
return name.replace(/^choo\.emit\('/, '').replace(/'\)$/, '')
})
Object.defineProperty(window.choo.perf, 'events', {
get: events.get.bind(events),
set: noop
})
onPerformance(function (entry) {
if (entry.entryType !== 'measure') return
var name = entry.name.replace(/ .*$/, '')
if (!stats[name]) {
stats[name] = {
name: name,
count: 0,
entries: []
}
}
var stat = stats[name]
stat.count += 1
stat.entries.push(entry.duration)
})
}
// Create a new Perf instance by passing it a filter
function Perf (stats, name, filter, rename) {
this.stats = stats
this.name = name
this.filter = filter || function () { return true }
this.rename = rename || function (name) { return name }
}
// Compute a table of performance entries based on a filter
Perf.prototype.get = function () {
var filtered = Object.keys(this.stats).filter(this.filter)
var self = this
var maxTime = 0
var maxMedian = 0
var fmt = filtered.map(function (key) {
var stat = self.stats[key]
var totalTime = Number(stat.entries.reduce(function (time, entry) {
return time + entry
}, 0).toFixed(2))
if (totalTime > maxTime) maxTime = totalTime
var median = getMedian(stat.entries)
if (median > maxMedian) maxMedian = median
var name = self.rename(stat.name)
return new PerfEntry(name, totalTime, median, stat.count)
})
var barLength = 10
fmt.forEach(function (entry) {
var totalTime = entry['Total Time (ms)']
var median = entry['Median (ms)']
entry[' '] = createBar(totalTime / maxTime * 100 / barLength)
entry[' '] = createBar(median / maxMedian * 100 / barLength)
})
function createBar (len) {
var str = ''
for (var i = 0, max = Math.round(len); i < max; i++) {
str += BAR
}
return str
}
var res = fmt.sort(function (a, b) {
return b['Total Time (ms)'] - a['Total Time (ms)']
})
console.table(res)
return "Showing performance events for '" + this.name + "'"
}
// An entry for the performance timeline.
function PerfEntry (name, totalTime, median, count) {
this.Name = name
this['Total Time (ms)'] = totalTime
this[' '] = 0
this['Median (ms)'] = median
this[' '] = 0
this['Total Count'] = count
}
// Get the median from an array of numbers.
function getMedian (args) {
if (!args.length) return 0
var numbers = args.slice(0).sort(function (a, b) { return a - b })
var middle = Math.floor(numbers.length / 2)
var isEven = numbers.length % 2 === 0
var res = isEven ? (numbers[middle] + numbers[middle - 1]) / 2 : numbers[middle]
return Number(res.toFixed(2))
}
// Do nothing.
function noop () {}
},{"on-performance":155}],45:[function(require,module,exports){
var pretty = require('prettier-bytes')
module.exports = storage
function storage () {
Object.defineProperty(window.choo, 'storage', {
get: get,
set: noop
})
function get () {
if (navigator.storage) {
navigator.storage.estimate().then(function (estimate) {
var value = (estimate.usage / estimate.quota).toFixed()
clr('Max storage:', fmt(estimate.quota))
clr('Storage used:', fmt(estimate.usage) + ' (' + value + '%)')
navigator.storage.persisted().then(function (bool) {
var val = bool ? 'enabled' : 'disabled'
clr('Persistent storage:', val)
})
})
return 'Calculating storage quota…'
} else {
var protocol = window.location.protocol
return (/https/.test(protocol))
? "The Storage API is unavailable in this browser. We're sorry!"
: 'The Storage API is unavailable. Serving this site over HTTPS might help enable it!'
}
}
}
function clr (msg, arg) {
var color = '#cc99cc'
console.log('%c' + msg, 'color: ' + color, arg)
}
function fmt (num) {
return pretty(num).replace(' ', '')
}
function noop () {}
},{"prettier-bytes":159}],46:[function(require,module,exports){
var onPerformance = require('on-performance')
var scheduler = require('nanoscheduler')()
var assert = require('assert')
module.exports = ChooHooks
function ChooHooks (emitter) {
if (!(this instanceof ChooHooks)) return new ChooHooks(emitter)
assert.equal(typeof emitter, 'object')
this.hasWindow = typeof window !== 'undefined'
this.hasIdleCallback = this.hasWindow && window.requestIdleCallback
this.hasPerformance = this.hasWindow &&
window.performance &&
window.performance.getEntriesByName
this.emitter = emitter
this.listeners = {}
this.buffer = {
render: {},
events: {}
}
}
ChooHooks.prototype.on = function (name, handler) {
this.listeners[name] = handler
}
ChooHooks.prototype.start = function () {
var self = this
if (this.hasPerformance) {
window.performance.onresourcetimingbufferfull = function () {
var listener = self.listeners['resource-timing-buffer-full']
if (listener) listener()
}
}
// TODO also handle log events
onPerformance(function (timing) {
if (!timing) return
if (timing.entryType !== 'measure') return
var eventName = timing.name
if (/choo\.morph/.test(eventName)) {
self.buffer.render.morph = timing
} else if (/choo\.route/.test(eventName)) {
self.buffer.render.route = timing
} else if (/choo\.render/.test(eventName)) {
self.buffer.render.render = timing
} else if (/choo\.emit/.test(eventName) && !/log:/.test(eventName)) {
var eventListener = self.listeners['event']
if (eventListener) {
var timingName = eventName.match(/choo\.emit\('(.*)'\)/)[1]
if (timingName === 'render' || timingName === 'DOMContentLoaded') return
var traceId = eventName.match(/\[(\d+)\]/)[1]
var data = self.buffer.events[traceId]
self.buffer.events[traceId] = null
eventListener(timingName, data, timing)
}
}
var rBuf = self.buffer.render
if (rBuf.render && rBuf.route && rBuf.morph) {
var renderListener = self.listeners['render']
if (!renderListener) return
var timings = {}
while (self.buffer.render.length) {
var _timing = self.buffer.render.pop()
var name = _timing.name
if (/choo\.render/.test(name)) timings.render = _timing
else if (/choo\.morph/.test(name)) timings.morph = _timing
else timings.route = _timing
}
rBuf.render = rBuf.route = rBuf.morph = void 0
renderListener(timings)
}
})
// Check if there's timings without any listeners
// and trigger the DOMContentLoaded event.
// If the timing API is not available, we handle all events here
this.emitter.on('*', function (eventName, data, uuid) {
var logLevel = /^log:(\w{4,5})/.exec(eventName)
if (!self.hasPerformance && eventName === 'render') {
// Render
var renderListener = self.listeners['render']
if (renderListener) renderListener()
} else if (eventName === 'DOMContentLoaded') {
// DOMContentLoaded
self._emitLoaded()
} else if (logLevel) {
logLevel = logLevel[1]
// Log:*
var logListener = self.listeners['log:' + logLevel]
if (logListener) {
logListener.apply(null, Array.prototype.slice.call(arguments, 0, arguments.length - 1))
}
} else if (!self.emitter.listeners(eventName).length) {
// Unhandled
var unhandledListener = self.listeners['unhandled']
if (unhandledListener) unhandledListener(eventName, data)
} else if (eventName !== 'render') {
// *
if (self.hasPerformance) self.buffer.events[uuid] = data
}
})
}
// compute and log time till interactive when DOMContentLoaded event fires
ChooHooks.prototype._emitLoaded = function () {
var self = this
scheduler.push(function clear () {
var listener = self.listeners['DOMContentLoaded']
var timing = self.hasWindow && window.performance && window.performance.timing
if (listener && timing) {
listener({
interactive: timing.domInteractive - timing.navigationStart,
loaded: timing.domContentLoadedEventEnd - timing.navigationStart
})
}
})
}
},{"assert":22,"nanoscheduler":149,"on-performance":155}],47:[function(require,module,exports){
var assert = require('assert')
var LRU = require('nanolru')
module.exports = ChooComponentCache
function ChooComponentCache (state, emit, lru) {
assert.ok(this instanceof ChooComponentCache, 'ChooComponentCache should be created with `new`')
assert.equal(typeof state, 'object', 'ChooComponentCache: state should be type object')
assert.equal(typeof emit, 'function', 'ChooComponentCache: emit should be type function')
if (typeof lru === 'number') this.cache = new LRU(lru)
else this.cache = lru || new LRU(100)
this.state = state
this.emit = emit
}
// Get & create component instances.
ChooComponentCache.prototype.render = function (Component, id) {
assert.equal(typeof Component, 'function', 'ChooComponentCache.render: Component should be type function')
assert.ok(typeof id === 'string' || typeof id === 'number', 'ChooComponentCache.render: id should be type string or type number')
var el = this.cache.get(id)
if (!el) {
var args = []
for (var i = 2, len = arguments.length; i < len; i++) {
args.push(arguments[i])
}
args.unshift(Component, id, this.state, this.emit)
el = newCall.apply(newCall, args)
this.cache.set(id, el)
}
return el
}
// Because you can't call `new` and `.apply()` at the same time. This is a mad
// hack, but hey it works so we gonna go for it. Whoop.
function newCall (Cls) {
return new (Cls.bind.apply(Cls, arguments)) // eslint-disable-line
}
},{"assert":127,"nanolru":142}],48:[function(require,module,exports){
module.exports = require('nanocomponent')
},{"nanocomponent":130}],49:[function(require,module,exports){
module.exports = require('nanohtml')
},{"nanohtml":135}],50:[function(require,module,exports){
module.exports = require('nanohtml/raw')
},{"nanohtml/raw":138}],51:[function(require,module,exports){
var scrollToAnchor = require('scroll-to-anchor')
var documentReady = require('document-ready')
var nanotiming = require('nanotiming')
var nanorouter = require('nanorouter')
var nanomorph = require('nanomorph')
var nanoquery = require('nanoquery')
var nanohref = require('nanohref')
var nanoraf = require('nanoraf')
var nanobus = require('nanobus')
var assert = require('assert')
var Cache = require('./component/cache')
module.exports = Choo
var HISTORY_OBJECT = {}
function Choo (opts) {
var timing = nanotiming('choo.constructor')
if (!(this instanceof Choo)) return new Choo(opts)
opts = opts || {}
assert.equal(typeof opts, 'object', 'choo: opts should be type object')
var self = this
// define events used by choo
this._events = {
DOMCONTENTLOADED: 'DOMContentLoaded',
DOMTITLECHANGE: 'DOMTitleChange',
REPLACESTATE: 'replaceState',
PUSHSTATE: 'pushState',
NAVIGATE: 'navigate',
POPSTATE: 'popState',
RENDER: 'render'
}
// properties for internal use only
this._historyEnabled = opts.history === undefined ? true : opts.history
this._hrefEnabled = opts.href === undefined ? true : opts.href
this._hashEnabled = opts.hash === undefined ? false : opts.hash
this._hasWindow = typeof window !== 'undefined'
this._cache = opts.cache
this._loaded = false
this._stores = [ondomtitlechange]
this._tree = null
// state
var _state = {
events: this._events,
components: {}
}
if (this._hasWindow) {
this.state = window.initialState
? Object.assign({}, window.initialState, _state)
: _state
delete window.initialState
} else {
this.state = _state
}
// properties that are part of the API
this.router = nanorouter({ curry: true })
this.emitter = nanobus('choo.emit')
this.emit = this.emitter.emit.bind(this.emitter)
// listen for title changes; available even when calling .toString()
if (this._hasWindow) this.state.title = document.title
function ondomtitlechange (state) {
self.emitter.prependListener(self._events.DOMTITLECHANGE, function (title) {
assert.equal(typeof title, 'string', 'events.DOMTitleChange: title should be type string')
state.title = title
if (self._hasWindow) document.title = title
})
}
timing()
}
Choo.prototype.route = function (route, handler) {
var routeTiming = nanotiming("choo.route('" + route + "')")
assert.equal(typeof route, 'string', 'choo.route: route should be type string')
assert.equal(typeof handler, 'function', 'choo.handler: route should be type function')
this.router.on(route, handler)
routeTiming()
}
Choo.prototype.use = function (cb) {
assert.equal(typeof cb, 'function', 'choo.use: cb should be type function')
var self = this
this._stores.push(function (state) {
var msg = 'choo.use'
msg = cb.storeName ? msg + '(' + cb.storeName + ')' : msg
var endTiming = nanotiming(msg)
cb(state, self.emitter, self)
endTiming()
})
}
Choo.prototype.start = function () {
assert.equal(typeof window, 'object', 'choo.start: window was not found. .start() must be called in a browser, use .toString() if running in Node')
var startTiming = nanotiming('choo.start')
var self = this
if (this._historyEnabled) {
this.emitter.prependListener(this._events.NAVIGATE, function () {
self._matchRoute(self.state)
if (self._loaded) {
self.emitter.emit(self._events.RENDER)
setTimeout(scrollToAnchor.bind(null, window.location.hash), 0)
}
})
this.emitter.prependListener(this._events.POPSTATE, function () {
self.emitter.emit(self._events.NAVIGATE)
})
this.emitter.prependListener(this._events.PUSHSTATE, function (href) {
assert.equal(typeof href, 'string', 'events.pushState: href should be type string')
window.history.pushState(HISTORY_OBJECT, null, href)
self.emitter.emit(self._events.NAVIGATE)
})
this.emitter.prependListener(this._events.REPLACESTATE, function (href) {
assert.equal(typeof href, 'string', 'events.replaceState: href should be type string')
window.history.replaceState(HISTORY_OBJECT, null, href)
self.emitter.emit(self._events.NAVIGATE)
})
window.onpopstate = function () {
self.emitter.emit(self._events.POPSTATE)
}
if (self._hrefEnabled) {
nanohref(function (location) {
var href = location.href
var hash = location.hash
if (href === window.location.href) {
if (!self._hashEnabled && hash) scrollToAnchor(hash)
return
}
self.emitter.emit(self._events.PUSHSTATE, href)
})
}
}
this._setCache(this.state)
this._matchRoute(this.state)
this._stores.forEach(function (initStore) {
initStore(self.state)
})
this._tree = this._prerender(this.state)
assert.ok(this._tree, 'choo.start: no valid DOM node returned for location ' + this.state.href)
this.emitter.prependListener(self._events.RENDER, nanoraf(function () {
var renderTiming = nanotiming('choo.render')
var newTree = self._prerender(self.state)
assert.ok(newTree, 'choo.render: no valid DOM node returned for location ' + self.state.href)
assert.equal(self._tree.nodeName, newTree.nodeName, 'choo.render: The target node <' +
self._tree.nodeName.toLowerCase() + '> is not the same type as the new node <' +
newTree.nodeName.toLowerCase() + '>.')
var morphTiming = nanotiming('choo.morph')
nanomorph(self._tree, newTree)
morphTiming()
renderTiming()
}))
documentReady(function () {
self.emitter.emit(self._events.DOMCONTENTLOADED)
self._loaded = true
})
startTiming()
return this._tree
}
Choo.prototype.mount = function mount (selector) {
var mountTiming = nanotiming("choo.mount('" + selector + "')")
if (typeof window !== 'object') {
assert.ok(typeof selector === 'string', 'choo.mount: selector should be type String')
this.selector = selector
mountTiming()
return this
}
assert.ok(typeof selector === 'string' || typeof selector === 'object', 'choo.mount: selector should be type String or HTMLElement')
var self = this
documentReady(function () {
var renderTiming = nanotiming('choo.render')
var newTree = self.start()
if (typeof selector === 'string') {
self._tree = document.querySelector(selector)
} else {
self._tree = selector
}
assert.ok(self._tree, 'choo.mount: could not query selector: ' + selector)
assert.equal(self._tree.nodeName, newTree.nodeName, 'choo.mount: The target node <' +
self._tree.nodeName.toLowerCase() + '> is not the same type as the new node <' +
newTree.nodeName.toLowerCase() + '>.')
var morphTiming = nanotiming('choo.morph')
nanomorph(self._tree, newTree)
morphTiming()
renderTiming()
})
mountTiming()
}
Choo.prototype.toString = function (location, state) {
state = state || {}
state.components = state.components || {}
state.events = Object.assign({}, state.events, this._events)
assert.notEqual(typeof window, 'object', 'choo.mount: window was found. .toString() must be called in Node, use .start() or .mount() if running in the browser')
assert.equal(typeof location, 'string', 'choo.toString: location should be type string')
assert.equal(typeof state, 'object', 'choo.toString: state should be type object')
this._setCache(state)
this._matchRoute(state, location)
this.emitter.removeAllListeners()
this._stores.forEach(function (initStore) {
initStore(state)
})
var html = this._prerender(state)
assert.ok(html, 'choo.toString: no valid value returned for the route ' + location)
assert(!Array.isArray(html), 'choo.toString: return value was an array for the route ' + location)
return typeof html.outerHTML === 'string' ? html.outerHTML : html.toString()
}
Choo.prototype._matchRoute = function (state, locationOverride) {
var location, queryString
if (locationOverride) {
location = locationOverride.replace(/\?.+$/, '').replace(/\/$/, '')
if (!this._hashEnabled) location = location.replace(/#.+$/, '')
queryString = locationOverride
} else {
location = window.location.pathname.replace(/\/$/, '')
if (this._hashEnabled) location += window.location.hash.replace(/^#/, '/')
queryString = window.location.search
}
var matched = this.router.match(location)
this._handler = matched.cb
state.href = location
state.query = nanoquery(queryString)
state.route = matched.route
state.params = matched.params
}
Choo.prototype._prerender = function (state) {
var routeTiming = nanotiming("choo.prerender('" + state.route + "')")
var res = this._handler(state, this.emit)
routeTiming()
return res
}
Choo.prototype._setCache = function (state) {
var cache = new Cache(state, this.emitter.emit.bind(this.emitter), this._cache)
state.cache = renderComponent
function renderComponent (Component, id) {
assert.equal(typeof Component, 'function', 'choo.state.cache: Component should be type function')
var args = []
for (var i = 0, len = arguments.length; i < len; i++) {
args.push(arguments[i])
}
return cache.render.apply(cache, args)
}
// When the state gets stringified, make sure `state.cache` isn't
// stringified too.
renderComponent.toJSON = function () {
return null
}
}
},{"./component/cache":47,"assert":127,"document-ready":63,"nanobus":128,"nanohref":132,"nanomorph":143,"nanoquery":146,"nanoraf":147,"nanorouter":148,"nanotiming":150,"scroll-to-anchor":170}],52:[function(require,module,exports){
/*! clipboard-copy. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
/* global DOMException */
module.exports = clipboardCopy
function clipboardCopy (text) {
// Use the Async Clipboard API when available. Requires a secure browsing
// context (i.e. HTTPS)
if (navigator.clipboard) {
return navigator.clipboard.writeText(text).catch(function (err) {
throw (err !== undefined ? err : new DOMException('The request is not allowed', 'NotAllowedError'))
})
}
// ...Otherwise, use document.execCommand() fallback
// Put the text to copy into a <span>
var span = document.createElement('span')
span.textContent = text
// Preserve consecutive spaces and newlines
span.style.whiteSpace = 'pre'
span.style.webkitUserSelect = 'auto'
span.style.userSelect = 'all'
// Add the <span> to the page
document.body.appendChild(span)
// Make a selection object representing the range of text selected by the user
var selection = window.getSelection()
var range = window.document.createRange()
selection.removeAllRanges()
range.selectNode(span)
selection.addRange(range)
// Copy text to the clipboard
var success = false
try {
success = window.document.execCommand('copy')
} catch (err) {
console.log('error', err)
}
// Cleanup
selection.removeAllRanges()
window.document.body.removeChild(span)
return success
? Promise.resolve()
: Promise.reject(new DOMException('The request is not allowed', 'NotAllowedError'))
}
},{}],53:[function(require,module,exports){
(function (Buffer){(function (){
var clone = (function() {
'use strict';
function _instanceof(obj, type) {
return type != null && obj instanceof type;
}
var nativeMap;
try {
nativeMap = Map;
} catch(_) {
// maybe a reference error because no `Map`. Give it a dummy value that no
// value will ever be an instanceof.
nativeMap = function() {};
}
var nativeSet;
try {
nativeSet = Set;
} catch(_) {
nativeSet = function() {};
}
var nativePromise;
try {
nativePromise = Promise;
} catch(_) {
nativePromise = function() {};
}
/**
* Clones (copies) an Object using deep copying.
*
* This function supports circular references by default, but if you are certain
* there are no circular references in your object, you can save some CPU time
* by calling clone(obj, false).
*
* Caution: if `circular` is false and `parent` contains circular references,
* your program may enter an infinite loop and crash.
*
* @param `parent` - the object to be cloned
* @param `circular` - set to true if the object to be cloned may contain
* circular references. (optional - true by default)
* @param `depth` - set to a number if the object is only to be cloned to
* a particular depth. (optional - defaults to Infinity)
* @param `prototype` - sets the prototype to be used when cloning an object.
* (optional - defaults to parent prototype).
* @param `includeNonEnumerable` - set to true if the non-enumerable properties
* should be cloned as well. Non-enumerable properties on the prototype
* chain will be ignored. (optional - false by default)
*/
function clone(parent, circular, depth, prototype, includeNonEnumerable) {
if (typeof circular === 'object') {
depth = circular.depth;
prototype = circular.prototype;
includeNonEnumerable = circular.includeNonEnumerable;
circular = circular.circular;
}
// maintain two arrays for circular references, where corresponding parents
// and children have the same index
var allParents = [];
var allChildren = [];
var useBuffer = typeof Buffer != 'undefined';
if (typeof circular == 'undefined')
circular = true;
if (typeof depth == 'undefined')
depth = Infinity;
// recurse this function so we don't reset allParents and allChildren
function _clone(parent, depth) {
// cloning null always returns null
if (parent === null)
return null;
if (depth === 0)
return parent;
var child;
var proto;
if (typeof parent != 'object') {
return parent;
}
if (_instanceof(parent, nativeMap)) {
child = new nativeMap();
} else if (_instanceof(parent, nativeSet)) {
child = new nativeSet();
} else if (_instanceof(parent, nativePromise)) {
child = new nativePromise(function (resolve, reject) {
parent.then(function(value) {
resolve(_clone(value, depth - 1));
}, function(err) {
reject(_clone(err, depth - 1));
});
});
} else if (clone.__isArray(parent)) {
child = [];
} else if (clone.__isRegExp(parent)) {
child = new RegExp(parent.source, __getRegExpFlags(parent));
if (parent.lastIndex) child.lastIndex = parent.lastIndex;
} else if (clone.__isDate(parent)) {
child = new Date(parent.getTime());
} else if (useBuffer && Buffer.isBuffer(parent)) {
if (Buffer.allocUnsafe) {
// Node.js >= 4.5.0
child = Buffer.allocUnsafe(parent.length);
} else {
// Older Node.js versions
child = new Buffer(parent.length);
}
parent.copy(child);
return child;
} else if (_instanceof(parent, Error)) {
child = Object.create(parent);
} else {
if (typeof prototype == 'undefined') {
proto = Object.getPrototypeOf(parent);
child = Object.create(proto);
}
else {
child = Object.create(prototype);
proto = prototype;
}
}
if (circular) {
var index = allParents.indexOf(parent);
if (index != -1) {
return allChildren[index];
}
allParents.push(parent);
allChildren.push(child);
}
if (_instanceof(parent, nativeMap)) {
parent.forEach(function(value, key) {
var keyChild = _clone(key, depth - 1);
var valueChild = _clone(value, depth - 1);
child.set(keyChild, valueChild);
});
}
if (_instanceof(parent, nativeSet)) {
parent.forEach(function(value) {
var entryChild = _clone(value, depth - 1);
child.add(entryChild);
});
}
for (var i in parent) {
var attrs;
if (proto) {
attrs = Object.getOwnPropertyDescriptor(proto, i);
}
if (attrs && attrs.set == null) {
continue;
}
child[i] = _clone(parent[i], depth - 1);
}
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(parent);
for (var i = 0; i < symbols.length; i++) {
// Don't need to worry about cloning a symbol because it is a primitive,
// like a number or string.
var symbol = symbols[i];
var descriptor = Object.getOwnPropertyDescriptor(parent, symbol);
if (descriptor && !descriptor.enumerable && !includeNonEnumerable) {
continue;
}
child[symbol] = _clone(parent[symbol], depth - 1);
if (!descriptor.enumerable) {
Object.defineProperty(child, symbol, {
enumerable: false
});
}
}
}
if (includeNonEnumerable) {
var allPropertyNames = Object.getOwnPropertyNames(parent);
for (var i = 0; i < allPropertyNames.length; i++) {
var propertyName = allPropertyNames[i];
var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName);
if (descriptor && descriptor.enumerable) {
continue;
}
child[propertyName] = _clone(parent[propertyName], depth - 1);
Object.defineProperty(child, propertyName, {
enumerable: false
});
}
}
return child;
}
return _clone(parent, depth);
}
/**
* Simple flat clone using prototype, accepts only objects, usefull for property
* override on FLAT configuration object (no nested props).
*
* USE WITH CAUTION! This may not behave as you wish if you do not know how this
* works.
*/
clone.clonePrototype = function clonePrototype(parent) {
if (parent === null)
return null;
var c = function () {};
c.prototype = parent;
return new c();
};
// private utility functions
function __objToStr(o) {
return Object.prototype.toString.call(o);
}
clone.__objToStr = __objToStr;
function __isDate(o) {
return typeof o === 'object' && __objToStr(o) === '[object Date]';
}
clone.__isDate = __isDate;
function __isArray(o) {
return typeof o === 'object' && __objToStr(o) === '[object Array]';
}
clone.__isArray = __isArray;
function __isRegExp(o) {
return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
}
clone.__isRegExp = __isRegExp;
function __getRegExpFlags(re) {
var flags = '';
if (re.global) flags += 'g';
if (re.ignoreCase) flags += 'i';
if (re.multiline) flags += 'm';
return flags;
}
clone.__getRegExpFlags = __getRegExpFlags;
return clone;
})();
if (typeof module === 'object' && module.exports) {
module.exports = clone;
}
}).call(this)}).call(this,require("buffer").Buffer)
},{"buffer":35}],54:[function(require,module,exports){
(function(r){"object"==typeof exports&&"object"==typeof module?r(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],r):r(CodeMirror)})(function(r){function I(c){c=c.search(u);return-1==c?0:c}function J(c,d,a){return/\bstring\b/.test(c.getTokenTypeAt(l(d.line,0)))&&!/^['"`]/.test(a)}function G(c,d){var a=c.getMode();return!1!==a.useInnerComments&&a.innerMode?c.getModeAt(d):a}var E={},u=/[^\s\u00a0]/,l=r.Pos,K=r.cmpPos;r.commands.toggleComment=function(c){c.toggleComment()};
r.defineExtension("toggleComment",function(c){c||(c=E);for(var d=Infinity,a=this.listSelections(),b=null,e=a.length-1;0<=e;e--){var g=a[e].from(),f=a[e].to();g.line>=d||(f.line>=d&&(f=l(d,0)),d=g.line,null==b?this.uncomment(g,f,c)?b="un":(this.lineComment(g,f,c),b="line"):"un"==b?this.uncomment(g,f,c):this.lineComment(g,f,c))}});r.defineExtension("lineComment",function(c,d,a){a||(a=E);var b=this,e=G(b,c),g=b.getLine(c.line);if(null!=g&&!J(b,c,g)){var f=a.lineComment||e.lineComment;if(f){var m=Math.min(0!=
d.ch||d.line==c.line?d.line+1:d.line,b.lastLine()+1),v=null==a.padding?" ":a.padding,k=a.commentBlankLines||c.line==d.line;b.operation(function(){if(a.indent){for(var q=null,h=c.line;h<m;++h){var n=b.getLine(h);n=-1===n.search(u)?n:n.slice(0,I(n));if(null==q||q.length>n.length)q=n}for(h=c.line;h<m;++h){n=b.getLine(h);var t=q.length;if(k||u.test(n))n.slice(0,t)!=q&&(t=I(n)),b.replaceRange(q+f+v,l(h,0),l(h,t))}}else for(h=c.line;h<m;++h)(k||u.test(b.getLine(h)))&&b.replaceRange(f+v,l(h,0))})}else if(a.blockCommentStart||
e.blockCommentStart)a.fullLines=!0,b.blockComment(c,d,a)}});r.defineExtension("blockComment",function(c,d,a){a||(a=E);var b=this,e=G(b,c),g=a.blockCommentStart||e.blockCommentStart,f=a.blockCommentEnd||e.blockCommentEnd;if(!g||!f)(a.lineComment||e.lineComment)&&0!=a.fullLines&&b.lineComment(c,d,a);else if(!/\bcomment\b/.test(b.getTokenTypeAt(l(c.line,0)))){var m=Math.min(d.line,b.lastLine());m!=c.line&&0==d.ch&&u.test(b.getLine(m))&&--m;var v=null==a.padding?" ":a.padding;c.line>m||b.operation(function(){if(0!=
a.fullLines){var k=u.test(b.getLine(m));b.replaceRange(v+f,l(m));b.replaceRange(g+v,l(c.line,0));var q=a.blockCommentLead||e.blockCommentLead;if(null!=q)for(var h=c.line+1;h<=m;++h)(h!=m||k)&&b.replaceRange(q+v,l(h,0))}else k=0==K(b.getCursor("to"),d),q=!b.somethingSelected(),b.replaceRange(f,d),k&&b.setSelection(q?d:b.getCursor("from"),d),b.replaceRange(g,c)})}});r.defineExtension("uncomment",function(c,d,a){a||(a=E);var b=this,e=G(b,c),g=Math.min(0!=d.ch||d.line==c.line?d.line:d.line-1,b.lastLine()),
f=Math.min(c.line,g),m=a.lineComment||e.lineComment,v=[],k=null==a.padding?" ":a.padding,q;a:if(m){for(var h=f;h<=g;++h){var n=b.getLine(h),t=n.indexOf(m);-1<t&&!/comment/.test(b.getTokenTypeAt(l(h,t+1)))&&(t=-1);if(-1==t&&u.test(n))break a;if(-1<t&&u.test(n.slice(0,t)))break a;v.push(n)}b.operation(function(){for(var p=f;p<=g;++p){var A=v[p-f],x=A.indexOf(m),w=x+m.length;0>x||(A.slice(w,w+k.length)==k&&(w+=k.length),q=!0,b.replaceRange("",l(p,x),l(p,w)))}});if(q)return!0}var y=a.blockCommentStart||
e.blockCommentStart,z=a.blockCommentEnd||e.blockCommentEnd;if(!y||!z)return!1;var H=a.blockCommentLead||e.blockCommentLead,C=b.getLine(f),D=C.indexOf(y);if(-1==D)return!1;var F=g==f?C:b.getLine(g),B=F.indexOf(z,g==f?D+y.length:0);a=l(f,D+1);e=l(g,B+1);if(-1==B||!/comment/.test(b.getTokenTypeAt(a))||!/comment/.test(b.getTokenTypeAt(e))||-1<b.getRange(a,e,"\n").indexOf(z))return!1;e=C.lastIndexOf(y,c.ch);a=-1==e?-1:C.slice(0,c.ch).indexOf(z,e+y.length);if(-1!=e&&-1!=a&&a+z.length!=c.ch)return!1;a=F.indexOf(z,
d.ch);c=F.slice(d.ch).lastIndexOf(y,a-d.ch);e=-1==a||-1==c?-1:d.ch+c;if(-1!=a&&-1!=e&&e!=d.ch)return!1;b.operation(function(){b.replaceRange("",l(g,B-(k&&F.slice(B-k.length,B)==k?k.length:0)),l(g,B+z.length));var p=D+y.length;k&&C.slice(p,p+k.length)==k&&(p+=k.length);b.replaceRange("",l(f,D),l(f,p));if(H)for(p=f+1;p<=g;++p){var A=b.getLine(p),x=A.indexOf(H);if(-1!=x&&!u.test(A.slice(0,x))){var w=x+H.length;k&&A.slice(w,w+k.length)==k&&(w+=k.length);b.replaceRange("",l(p,x),l(p,w))}}});return!0})});
},{"../../lib/codemirror":58}],55:[function(require,module,exports){
(function(m){"object"==typeof exports&&"object"==typeof module?m(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],m):m(CodeMirror)})(function(m){function q(a,b){for(var l=0,e=a.length;l<e;++l)b(a[l])}function t(a,b,l,e){var c=a.getCursor(),d=l(a,c);if(!/\b(?:string|comment)\b/.test(d.type)){var g=m.innerMode(a.getMode(),d.state);if("json"!==g.mode.helperType){d.state=g.state;/^[\w$_]*$/.test(d.string)?d.end>c.ch&&(d.end=c.ch,d.string=d.string.slice(0,
c.ch-d.start)):d={start:c.ch,end:c.ch,string:"",state:d.state,type:"."==d.string?"property":null};for(g=d;"property"==g.type;){g=l(a,r(c.line,g.start));if("."!=g.string)return;g=l(a,r(c.line,g.start));if(!p)var p=[];p.push(g)}return{list:u(d,p,b,e),from:r(c.line,d.start),to:r(c.line,d.end)}}}}function v(a,b){a=a.getTokenAt(b);b.ch==a.start+1&&"."==a.string.charAt(0)?(a.end=a.start,a.string=".",a.type="property"):/^\.[\w$_]*$/.test(a.string)&&(a.type="property",a.start++,a.string=a.string.replace(/\./,
""));return a}function u(a,b,l,e){function c(h){var k;if(k=0==h.lastIndexOf(p,0)){a:if(Array.prototype.indexOf)k=-1!=g.indexOf(h);else{for(k=g.length;k--;)if(g[k]===h){k=!0;break a}k=!1}k=!k}k&&g.push(h)}function d(h){"string"==typeof h?q(w,c):h instanceof Array?q(x,c):h instanceof Function&&q(y,c);if(Object.getOwnPropertyNames&&Object.getPrototypeOf)for(;h;h=Object.getPrototypeOf(h))Object.getOwnPropertyNames(h).forEach(c);else for(var k in h)c(k)}var g=[],p=a.string,n=e&&e.globalScope||window;if(b&&
b.length){a=b.pop();var f;a.type&&0===a.type.indexOf("variable")?(e&&e.additionalContext&&(f=e.additionalContext[a.string]),e&&!1===e.useGlobalScope||(f=f||n[a.string])):"string"==a.type?f="":"atom"==a.type?f=1:"function"==a.type&&(null==n.jQuery||"$"!=a.string&&"jQuery"!=a.string||"function"!=typeof n.jQuery?null!=n._&&"_"==a.string&&"function"==typeof n._&&(f=n._()):f=n.jQuery());for(;null!=f&&b.length;)f=f[b.pop().string];null!=f&&d(f)}else{for(b=a.state.localVars;b;b=b.next)c(b.name);for(f=a.state.context;f;f=
f.prev)for(b=f.vars;b;b=b.next)c(b.name);for(b=a.state.globalVars;b;b=b.next)c(b.name);if(e&&null!=e.additionalContext)for(var z in e.additionalContext)c(z);e&&!1===e.useGlobalScope||d(n);q(l,c)}return g}var r=m.Pos;m.registerHelper("hint","javascript",function(a,b){return t(a,A,function(l,e){return l.getTokenAt(e)},b)});m.registerHelper("hint","coffeescript",function(a,b){return t(a,B,v,b)});var w="charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight toUpperCase toLowerCase split concat match replace search".split(" "),
x="length concat join splice push pop shift unshift slice reverse sort indexOf lastIndexOf every some filter forEach map reduce reduceRight ".split(" "),y=["prototype","apply","call","bind"],A="break case catch class const continue debugger default delete do else export extends false finally for function if in import instanceof new null return super switch this throw true try typeof var void while with yield".split(" "),B="and break catch class continue delete do else extends false finally for if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes".split(" ")});
},{"../../lib/codemirror":58}],56:[function(require,module,exports){
(function(h){"object"==typeof exports&&"object"==typeof module?h(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],h):h(CodeMirror)})(function(h){function B(a,b){this.cm=a;this.options=b;this.widget=null;this.tick=this.debounce=0;this.startPos=this.cm.getCursor("start");this.startLen=this.cm.getLine(this.startPos.line).length-this.cm.getSelection().length;if(this.options.updateOnCursorActivity){var c=this;a.on("cursorActivity",this.activityFunc=
function(){c.cursorActivity()})}}function K(a,b){function c(r,g){var m="string"!=typeof g?function(k){return g(k,b)}:d.hasOwnProperty(g)?d[g]:g;p[r]=m}var d={Up:function(){b.moveFocus(-1)},Down:function(){b.moveFocus(1)},PageUp:function(){b.moveFocus(-b.menuSize()+1,!0)},PageDown:function(){b.moveFocus(b.menuSize()-1,!0)},Home:function(){b.setFocus(0)},End:function(){b.setFocus(b.length-1)},Enter:b.pick,Tab:b.pick,Esc:b.close};/Mac/.test(navigator.platform)&&(d["Ctrl-P"]=function(){b.moveFocus(-1)},
d["Ctrl-N"]=function(){b.moveFocus(1)});var e=a.options.customKeys,p=e?{}:d;if(e)for(var f in e)e.hasOwnProperty(f)&&c(f,e[f]);if(a=a.options.extraKeys)for(f in a)a.hasOwnProperty(f)&&c(f,a[f]);return p}function C(a,b){for(;b&&b!=a;){if("LI"===b.nodeName.toUpperCase()&&b.parentNode==a)return b;b=b.parentNode}}function D(a,b){this.id="cm-complete-"+Math.floor(Math.random(1E6));this.completion=a;this.data=b;this.picked=!1;var c=this,d=a.cm,e=d.getInputField().ownerDocument,p=e.defaultView||e.parentWindow,
f=this.hints=e.createElement("ul");f.setAttribute("role","listbox");f.setAttribute("aria-expanded","true");f.id=this.id;f.className="CodeMirror-hints "+a.cm.options.theme;this.selectedHint=b.selectedHint||0;for(var r=b.list,g=0;g<r.length;++g){var m=f.appendChild(e.createElement("li")),k=r[g],q="CodeMirror-hint"+(g!=this.selectedHint?"":" CodeMirror-hint-active");null!=k.className&&(q=k.className+" "+q);m.className=q;g==this.selectedHint&&m.setAttribute("aria-selected","true");m.id=this.id+"-"+g;
m.setAttribute("role","option");k.render?k.render(m,b,k):m.appendChild(e.createTextNode(k.displayText||("string"==typeof k?k:k.text)));m.hintId=g}var n=a.options.container||e.body;g=d.cursorCoords(a.options.alignWithWord?b.from:null);var w=g.left,x=g.bottom,E=!0;q=m=0;if(n!==e.body){k=-1!==["absolute","relative","fixed"].indexOf(p.getComputedStyle(n).position)?n:n.offsetParent;q=k.getBoundingClientRect();var t=e.body.getBoundingClientRect();m=q.left-t.left-k.scrollLeft;q=q.top-t.top-k.scrollTop}f.style.left=
w-m+"px";f.style.top=x-q+"px";k=p.innerWidth||Math.max(e.body.offsetWidth,e.documentElement.offsetWidth);t=p.innerHeight||Math.max(e.body.offsetHeight,e.documentElement.offsetHeight);n.appendChild(f);d.getInputField().setAttribute("aria-autocomplete","list");d.getInputField().setAttribute("aria-owns",this.id);d.getInputField().setAttribute("aria-activedescendant",this.id+"-"+this.selectedHint);n=a.options.moveOnOverlap?f.getBoundingClientRect():new DOMRect;var F=a.options.paddingForScrollbar?f.scrollHeight>
f.clientHeight+1:!1,u;setTimeout(function(){u=d.getScrollInfo()});if(0<n.bottom-t){var y=n.bottom-n.top,z=n.top-(g.bottom-g.top)-2;t-n.top<z?(y>z&&(f.style.height=(y=z)+"px"),f.style.top=(x=g.top-y)+q+"px",E=!1):f.style.height=t-n.top-2+"px"}q=n.right-k;F&&(q+=d.display.nativeBarWidth);0<q&&(n.right-n.left>k&&(f.style.width=k-5+"px",q-=n.right-n.left-k),f.style.left=(w=Math.max(g.left-q-m,0))+"px");if(F)for(g=f.firstChild;g;g=g.nextSibling)g.style.paddingRight=d.display.nativeBarWidth+"px";d.addKeyMap(this.keyMap=
K(a,{moveFocus:function(l,v){c.changeActive(c.selectedHint+l,v)},setFocus:function(l){c.changeActive(l)},menuSize:function(){return c.screenAmount()},length:r.length,close:function(){a.close()},pick:function(){c.pick()},data:b}));if(a.options.closeOnUnfocus){var G;d.on("blur",this.onBlur=function(){G=setTimeout(function(){a.close()},100)});d.on("focus",this.onFocus=function(){clearTimeout(G)})}d.on("scroll",this.onScroll=function(){var l=d.getScrollInfo(),v=d.getWrapperElement().getBoundingClientRect();
u||(u=d.getScrollInfo());var H=x+u.top-l.top,A=H-(p.pageYOffset||(e.documentElement||e.body).scrollTop);E||(A+=f.offsetHeight);if(A<=v.top||A>=v.bottom)return a.close();f.style.top=H+"px";f.style.left=w+u.left-l.left+"px"});h.on(f,"dblclick",function(l){(l=C(f,l.target||l.srcElement))&&null!=l.hintId&&(c.changeActive(l.hintId),c.pick())});h.on(f,"click",function(l){(l=C(f,l.target||l.srcElement))&&null!=l.hintId&&(c.changeActive(l.hintId),a.options.completeOnSingleClick&&c.pick())});h.on(f,"mousedown",
function(){setTimeout(function(){d.focus()},20)});g=this.getSelectedHintRange();0===g.from&&0===g.to||this.scrollToActive();h.signal(b,"select",r[this.selectedHint],f.childNodes[this.selectedHint]);return!0}function L(a,b){if(!a.somethingSelected())return b;a=[];for(var c=0;c<b.length;c++)b[c].supportsSelection&&a.push(b[c]);return a}function I(a,b,c,d){a.async?a(b,d,c):(a=a(b,c))&&a.then?a.then(d):d(a)}h.showHint=function(a,b,c){if(!b)return a.showHint(c);c&&c.async&&(b.async=!0);b={hint:b};if(c)for(var d in c)b[d]=
c[d];return a.showHint(b)};h.defineExtension("showHint",function(a){var b=this.getCursor("start"),c=this.options.hintOptions,d={},e;for(e in J)d[e]=J[e];if(c)for(e in c)void 0!==c[e]&&(d[e]=c[e]);if(a)for(e in a)void 0!==a[e]&&(d[e]=a[e]);d.hint.resolve&&(d.hint=d.hint.resolve(this,b));a=d;b=this.listSelections();if(!(1<b.length)){if(this.somethingSelected()){if(!a.hint.supportsSelection)return;for(e=0;e<b.length;e++)if(b[e].head.line!=b[e].anchor.line)return}this.state.completionActive&&this.state.completionActive.close();
b=this.state.completionActive=new B(this,a);b.options.hint&&(h.signal(this,"startCompletion",this),b.update(!0))}});h.defineExtension("closeHint",function(){this.state.completionActive&&this.state.completionActive.close()});var M=window.requestAnimationFrame||function(a){return setTimeout(a,1E3/60)},N=window.cancelAnimationFrame||clearTimeout;B.prototype={close:function(){this.active()&&(this.tick=this.cm.state.completionActive=null,this.options.updateOnCursorActivity&&this.cm.off("cursorActivity",
this.activityFunc),this.widget&&this.data&&h.signal(this.data,"close"),this.widget&&this.widget.close(),h.signal(this.cm,"endCompletion",this.cm))},active:function(){return this.cm.state.completionActive==this},pick:function(a,b){var c=a.list[b],d=this;this.cm.operation(function(){c.hint?c.hint(d.cm,a,c):d.cm.replaceRange("string"==typeof c?c:c.text,c.from||a.from,c.to||a.to,"complete");h.signal(a,"pick",c);d.cm.scrollIntoView()});this.options.closeOnPick&&this.close()},cursorActivity:function(){this.debounce&&
(N(this.debounce),this.debounce=0);var a=this.startPos;this.data&&(a=this.data.from);var b=this.cm.getCursor(),c=this.cm.getLine(b.line);if(b.line!=this.startPos.line||c.length-b.ch!=this.startLen-this.startPos.ch||b.ch<a.ch||this.cm.somethingSelected()||!b.ch||this.options.closeCharacters.test(c.charAt(b.ch-1)))this.close();else{var d=this;this.debounce=M(function(){d.update()});this.widget&&this.widget.disable()}},update:function(a){if(null!=this.tick){var b=this,c=++this.tick;I(this.options.hint,
this.cm,this.options,function(d){b.tick==c&&b.finishUpdate(d,a)})}},finishUpdate:function(a,b){this.data&&h.signal(this.data,"update");b=this.widget&&this.widget.picked||b&&this.options.completeSingle;this.widget&&this.widget.close();(this.data=a)&&a.list.length&&(b&&1==a.list.length?this.pick(a,0):(this.widget=new D(this,a),h.signal(a,"shown")))}};D.prototype={close:function(){if(this.completion.widget==this){this.completion.widget=null;this.hints.parentNode&&this.hints.parentNode.removeChild(this.hints);
this.completion.cm.removeKeyMap(this.keyMap);var a=this.completion.cm.getInputField();a.removeAttribute("aria-activedescendant");a.removeAttribute("aria-owns");a=this.completion.cm;this.completion.options.closeOnUnfocus&&(a.off("blur",this.onBlur),a.off("focus",this.onFocus));a.off("scroll",this.onScroll)}},disable:function(){this.completion.cm.removeKeyMap(this.keyMap);var a=this;this.keyMap={Enter:function(){a.picked=!0}};this.completion.cm.addKeyMap(this.keyMap)},pick:function(){this.completion.pick(this.data,
this.selectedHint)},changeActive:function(a,b){a>=this.data.list.length?a=b?this.data.list.length-1:0:0>a&&(a=b?0:this.data.list.length-1);if(this.selectedHint!=a){if(b=this.hints.childNodes[this.selectedHint])b.className=b.className.replace(" CodeMirror-hint-active",""),b.removeAttribute("aria-selected");b=this.hints.childNodes[this.selectedHint=a];b.className+=" CodeMirror-hint-active";b.setAttribute("aria-selected","true");this.completion.cm.getInputField().setAttribute("aria-activedescendant",
b.id);this.scrollToActive();h.signal(this.data,"select",this.data.list[this.selectedHint],b)}},scrollToActive:function(){var a=this.getSelectedHintRange(),b=this.hints.childNodes[a.from];a=this.hints.childNodes[a.to];var c=this.hints.firstChild;b.offsetTop<this.hints.scrollTop?this.hints.scrollTop=b.offsetTop-c.offsetTop:a.offsetTop+a.offsetHeight>this.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=a.offsetTop+a.offsetHeight-this.hints.clientHeight+c.offsetTop)},screenAmount:function(){return Math.floor(this.hints.clientHeight/
this.hints.firstChild.offsetHeight)||1},getSelectedHintRange:function(){var a=this.completion.options.scrollMargin||0;return{from:Math.max(0,this.selectedHint-a),to:Math.min(this.data.list.length-1,this.selectedHint+a)}}};h.registerHelper("hint","auto",{resolve:function(a,b){var c=a.getHelpers(b,"hint"),d;return c.length?(a=function(e,p,f){function r(m){if(m==g.length)return p(null);I(g[m],e,f,function(k){k&&0<k.list.length?p(k):r(m+1)})}var g=L(e,c);r(0)},a.async=!0,a.supportsSelection=!0,a):(d=
a.getHelper(a.getCursor(),"hintWords"))?function(e){return h.hint.fromList(e,{words:d})}:h.hint.anyword?function(e,p){return h.hint.anyword(e,p)}:function(){}}});h.registerHelper("hint","fromList",function(a,b){var c=a.getCursor(),d=a.getTokenAt(c);a=h.Pos(c.line,d.start);d.start<c.ch&&/\w/.test(d.string.charAt(c.ch-d.start-1))?d=d.string.substr(0,c.ch-d.start):(d="",a=c);for(var e=[],p=0;p<b.words.length;p++){var f=b.words[p];f.slice(0,d.length)==d&&e.push(f)}if(e.length)return{list:e,from:a,to:c}});
h.commands.autocomplete=h.showHint;var J={hint:h.hint.auto,completeSingle:!0,alignWithWord:!0,closeCharacters:/[\s()\[\]{};:>,]/,closeOnPick:!0,closeOnUnfocus:!0,updateOnCursorActivity:!0,completeOnSingleClick:!0,container:null,customKeys:null,extraKeys:null,paddingForScrollbar:!0,moveOnOverlap:!0};h.defineOption("hintOptions",null)});
},{"../../lib/codemirror":58}],57:[function(require,module,exports){
(function (global){(function (){
var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.findInternal=function(a,d,c){a instanceof String&&(a=String(a));for(var e=a.length,f=0;f<e;f++){var m=a[f];if(d.call(c,m,f,a))return{i:f,v:m}}return{i:-1,v:void 0}};$jscomp.ASSUME_ES5=!1;$jscomp.ASSUME_NO_NATIVE_MAP=!1;$jscomp.ASSUME_NO_NATIVE_SET=!1;$jscomp.SIMPLE_FROUND_POLYFILL=!1;$jscomp.ISOLATE_POLYFILLS=!1;$jscomp.FORCE_POLYFILL_PROMISE=!1;$jscomp.FORCE_POLYFILL_PROMISE_WHEN_NO_UNHANDLED_REJECTION=!1;
$jscomp.defineProperty=$jscomp.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(a,d,c){if(a==Array.prototype||a==Object.prototype)return a;a[d]=c.value;return a};$jscomp.getGlobal=function(a){a=["object"==typeof globalThis&&globalThis,a,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global];for(var d=0;d<a.length;++d){var c=a[d];if(c&&c.Math==Math)return c}throw Error("Cannot find global object");};$jscomp.global=$jscomp.getGlobal(this);
$jscomp.IS_SYMBOL_NATIVE="function"===typeof Symbol&&"symbol"===typeof Symbol("x");$jscomp.TRUST_ES6_POLYFILLS=!$jscomp.ISOLATE_POLYFILLS||$jscomp.IS_SYMBOL_NATIVE;$jscomp.polyfills={};$jscomp.propertyToPolyfillSymbol={};$jscomp.POLYFILL_PREFIX="$jscp$";var $jscomp$lookupPolyfilledValue=function(a,d){var c=$jscomp.propertyToPolyfillSymbol[d];if(null==c)return a[d];c=a[c];return void 0!==c?c:a[d]};
$jscomp.polyfill=function(a,d,c,e){d&&($jscomp.ISOLATE_POLYFILLS?$jscomp.polyfillIsolated(a,d,c,e):$jscomp.polyfillUnisolated(a,d,c,e))};$jscomp.polyfillUnisolated=function(a,d,c,e){c=$jscomp.global;a=a.split(".");for(e=0;e<a.length-1;e++){var f=a[e];if(!(f in c))return;c=c[f]}a=a[a.length-1];e=c[a];d=d(e);d!=e&&null!=d&&$jscomp.defineProperty(c,a,{configurable:!0,writable:!0,value:d})};
$jscomp.polyfillIsolated=function(a,d,c,e){var f=a.split(".");a=1===f.length;e=f[0];e=!a&&e in $jscomp.polyfills?$jscomp.polyfills:$jscomp.global;for(var m=0;m<f.length-1;m++){var r=f[m];if(!(r in e))return;e=e[r]}f=f[f.length-1];c=$jscomp.IS_SYMBOL_NATIVE&&"es6"===c?e[f]:null;d=d(c);null!=d&&(a?$jscomp.defineProperty($jscomp.polyfills,f,{configurable:!0,writable:!0,value:d}):d!==c&&(void 0===$jscomp.propertyToPolyfillSymbol[f]&&(c=1E9*Math.random()>>>0,$jscomp.propertyToPolyfillSymbol[f]=$jscomp.IS_SYMBOL_NATIVE?
$jscomp.global.Symbol(f):$jscomp.POLYFILL_PREFIX+c+"$"+f),$jscomp.defineProperty(e,$jscomp.propertyToPolyfillSymbol[f],{configurable:!0,writable:!0,value:d})))};$jscomp.polyfill("Array.prototype.find",function(a){return a?a:function(d,c){return $jscomp.findInternal(this,d,c).v}},"es6","es3");
(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})(function(a){function d(b){b.state.markedSelection&&b.operation(function(){r(b)})}function c(b){b.state.markedSelection&&b.state.markedSelection.length&&b.operation(function(){f(b)})}function e(b,g,h,k){if(0!=p(g,h))for(var l=b.state.markedSelection,n=b.state.markedSelectionStyle,q=g.line;;){var t=q==g.line?g:v(q,
0);q+=u;var w=q>=h.line,x=w?h:v(q,0);t=b.markText(t,x,{className:n});null==k?l.push(t):l.splice(k++,0,t);if(w)break}}function f(b){b=b.state.markedSelection;for(var g=0;g<b.length;++g)b[g].clear();b.length=0}function m(b){f(b);for(var g=b.listSelections(),h=0;h<g.length;h++)e(b,g[h].from(),g[h].to())}function r(b){if(!b.somethingSelected())return f(b);if(1<b.listSelections().length)return m(b);var g=b.getCursor("start"),h=b.getCursor("end"),k=b.state.markedSelection;if(!k.length)return e(b,g,h);var l=
k[0].find(),n=k[k.length-1].find();if(!l||!n||h.line-g.line<=u||0<=p(g,n.to)||0>=p(h,l.from))return m(b);for(;0<p(g,l.from);)k.shift().clear(),l=k[0].find();0>p(g,l.from)&&(l.to.line-g.line<u?(k.shift().clear(),e(b,g,l.to,0)):e(b,g,l.from,0));for(;0>p(h,n.to);)k.pop().clear(),n=k[k.length-1].find();0<p(h,n.to)&&(h.line-n.from.line<u?(k.pop().clear(),e(b,n.from,h)):e(b,n.to,h))}a.defineOption("styleSelectedText",!1,function(b,g,h){h=h&&h!=a.Init;g&&!h?(b.state.markedSelection=[],b.state.markedSelectionStyle=
"string"==typeof g?g:"CodeMirror-selectedtext",m(b),b.on("cursorActivity",d),b.on("change",c)):!g&&h&&(b.off("cursorActivity",d),b.off("change",c),f(b),b.state.markedSelection=b.state.markedSelectionStyle=null)});var u=8,v=a.Pos,p=a.cmpPos});
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../../lib/codemirror":58}],58:[function(require,module,exports){
(function (global){(function (){
var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.findInternal=function(y,E,D){y instanceof String&&(y=String(y));for(var v=y.length,M=0;M<v;M++){var ja=y[M];if(E.call(D,ja,M,y))return{i:M,v:ja}}return{i:-1,v:void 0}};$jscomp.ASSUME_ES5=!1;$jscomp.ASSUME_NO_NATIVE_MAP=!1;$jscomp.ASSUME_NO_NATIVE_SET=!1;$jscomp.SIMPLE_FROUND_POLYFILL=!1;$jscomp.ISOLATE_POLYFILLS=!1;$jscomp.FORCE_POLYFILL_PROMISE=!1;$jscomp.FORCE_POLYFILL_PROMISE_WHEN_NO_UNHANDLED_REJECTION=!1;
$jscomp.defineProperty=$jscomp.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(y,E,D){if(y==Array.prototype||y==Object.prototype)return y;y[E]=D.value;return y};$jscomp.getGlobal=function(y){y=["object"==typeof globalThis&&globalThis,y,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global];for(var E=0;E<y.length;++E){var D=y[E];if(D&&D.Math==Math)return D}throw Error("Cannot find global object");};$jscomp.global=$jscomp.getGlobal(this);
$jscomp.IS_SYMBOL_NATIVE="function"===typeof Symbol&&"symbol"===typeof Symbol("x");$jscomp.TRUST_ES6_POLYFILLS=!$jscomp.ISOLATE_POLYFILLS||$jscomp.IS_SYMBOL_NATIVE;$jscomp.polyfills={};$jscomp.propertyToPolyfillSymbol={};$jscomp.POLYFILL_PREFIX="$jscp$";var $jscomp$lookupPolyfilledValue=function(y,E){var D=$jscomp.propertyToPolyfillSymbol[E];if(null==D)return y[E];D=y[D];return void 0!==D?D:y[E]};
$jscomp.polyfill=function(y,E,D,v){E&&($jscomp.ISOLATE_POLYFILLS?$jscomp.polyfillIsolated(y,E,D,v):$jscomp.polyfillUnisolated(y,E,D,v))};$jscomp.polyfillUnisolated=function(y,E,D,v){D=$jscomp.global;y=y.split(".");for(v=0;v<y.length-1;v++){var M=y[v];if(!(M in D))return;D=D[M]}y=y[y.length-1];v=D[y];E=E(v);E!=v&&null!=E&&$jscomp.defineProperty(D,y,{configurable:!0,writable:!0,value:E})};
$jscomp.polyfillIsolated=function(y,E,D,v){var M=y.split(".");y=1===M.length;v=M[0];v=!y&&v in $jscomp.polyfills?$jscomp.polyfills:$jscomp.global;for(var ja=0;ja<M.length-1;ja++){var ka=M[ja];if(!(ka in v))return;v=v[ka]}M=M[M.length-1];D=$jscomp.IS_SYMBOL_NATIVE&&"es6"===D?v[M]:null;E=E(D);null!=E&&(y?$jscomp.defineProperty($jscomp.polyfills,M,{configurable:!0,writable:!0,value:E}):E!==D&&(void 0===$jscomp.propertyToPolyfillSymbol[M]&&(D=1E9*Math.random()>>>0,$jscomp.propertyToPolyfillSymbol[M]=
$jscomp.IS_SYMBOL_NATIVE?$jscomp.global.Symbol(M):$jscomp.POLYFILL_PREFIX+D+"$"+M),$jscomp.defineProperty(v,$jscomp.propertyToPolyfillSymbol[M],{configurable:!0,writable:!0,value:E})))};$jscomp.polyfill("Array.prototype.find",function(y){return y?y:function(E,D){return $jscomp.findInternal(this,E,D).v}},"es6","es3");
(function(y,E){"object"===typeof exports&&"undefined"!==typeof module?module.exports=E():"function"===typeof define&&define.amd?define(E):(y=y||self,y.CodeMirror=E())})(this,function(){function y(a){return new RegExp("(^|\\s)"+a+"(?:$|\\s)\\s*")}function E(a){for(var b=a.childNodes.length;0<b;--b)a.removeChild(a.firstChild);return a}function D(a,b){return E(a).appendChild(b)}function v(a,b,d,c){a=document.createElement(a);d&&(a.className=d);c&&(a.style.cssText=c);if("string"==typeof b)a.appendChild(document.createTextNode(b));
else if(b)for(d=0;d<b.length;++d)a.appendChild(b[d]);return a}function M(a,b,d,c){a=v(a,b,d,c);a.setAttribute("role","presentation");return a}function ja(a,b){3==b.nodeType&&(b=b.parentNode);if(a.contains)return a.contains(b);do if(11==b.nodeType&&(b=b.host),b==a)return!0;while(b=b.parentNode)}function ka(a){try{var b=a.activeElement}catch(d){b=a.body||null}for(;b&&b.shadowRoot&&b.shadowRoot.activeElement;)b=b.shadowRoot.activeElement;return b}function Ya(a,b){var d=a.className;y(b).test(d)||(a.className+=
(d?" ":"")+b)}function fd(a,b){a=a.split(" ");for(var d=0;d<a.length;d++)a[d]&&!y(a[d]).test(b)&&(b+=" "+a[d]);return b}function qa(a){return a.display.wrapper.ownerDocument}function gd(a){var b=Array.prototype.slice.call(arguments,1);return function(){return a.apply(null,b)}}function Za(a,b,d){b||(b={});for(var c in a)!a.hasOwnProperty(c)||!1===d&&b.hasOwnProperty(c)||(b[c]=a[c]);return b}function wa(a,b,d,c,e){null==b&&(b=a.search(/[^\s\u00a0]/),-1==b&&(b=a.length));c=c||0;for(e=e||0;;){var f=a.indexOf("\t",
c);if(0>f||f>=b)return e+(b-c);e+=f-c;e+=d-e%d;c=f+1}}function ea(a,b){for(var d=0;d<a.length;++d)if(a[d]==b)return d;return-1}function hd(a,b,d){for(var c=0,e=0;;){var f=a.indexOf("\t",c);-1==f&&(f=a.length);var g=f-c;if(f==a.length||e+g>=b)return c+Math.min(g,b-e);e+=f-c;e+=d-e%d;c=f+1;if(e>=b)return c}}function id(a){for(;vc.length<=a;)vc.push(J(vc)+" ");return vc[a]}function J(a){return a[a.length-1]}function wc(a,b){for(var d=[],c=0;c<a.length;c++)d[c]=b(a[c],c);return d}function yg(a,b,d){for(var c=
0,e=d(b);c<a.length&&d(a[c])<=e;)c++;a.splice(c,0,b)}function pe(){}function qe(a,b){Object.create?a=Object.create(a):(pe.prototype=a,a=new pe);b&&Za(b,a);return a}function jd(a){return/\w/.test(a)||"\u0080"<a&&(a.toUpperCase()!=a.toLowerCase()||zg.test(a))}function xc(a,b){return b?-1<b.source.indexOf("\\w")&&jd(a)?!0:b.test(a):jd(a)}function re(a){for(var b in a)if(a.hasOwnProperty(b)&&a[b])return!1;return!0}function kd(a){return 768<=a.charCodeAt(0)&&Ag.test(a)}function se(a,b,d){for(;(0>d?0<b:
b<a.length)&&kd(a.charAt(b));)b+=d;return b}function Jb(a,b,d){for(var c=b>d?-1:1;;){if(b==d)return b;var e=(b+d)/2;e=0>c?Math.ceil(e):Math.floor(e);if(e==b)return a(e)?b:d;a(e)?d=e:b=e+c}}function Bg(a,b,d,c){if(!a)return c(b,d,"ltr",0);for(var e=!1,f=0;f<a.length;++f){var g=a[f];if(g.from<d&&g.to>b||b==d&&g.to==b)c(Math.max(g.from,b),Math.min(g.to,d),1==g.level?"rtl":"ltr",f),e=!0}e||c(b,d,"ltr")}function Kb(a,b,d){var c;Lb=null;for(var e=0;e<a.length;++e){var f=a[e];if(f.from<b&&f.to>b)return e;
f.to==b&&(f.from!=f.to&&"before"==d?c=e:Lb=e);f.from==b&&(f.from!=f.to&&"before"!=d?c=e:Lb=e)}return null!=c?c:Lb}function Ja(a,b){var d=a.order;null==d&&(d=a.order=Cg(a.text,b));return d}function ta(a,b,d){if(a.removeEventListener)a.removeEventListener(b,d,!1);else if(a.detachEvent)a.detachEvent("on"+b,d);else{var c=(a=a._handlers)&&a[b];c&&(d=ea(c,d),-1<d&&(a[b]=c.slice(0,d).concat(c.slice(d+1))))}}function W(a,b){var d=a._handlers&&a._handlers[b]||yc;if(d.length)for(var c=Array.prototype.slice.call(arguments,
2),e=0;e<d.length;++e)d[e].apply(null,c)}function Z(a,b,d){"string"==typeof b&&(b={type:b,preventDefault:function(){this.defaultPrevented=!0}});W(a,d||b.type,a,b);return ld(b)||b.codemirrorIgnore}function te(a){var b=a._handlers&&a._handlers.cursorActivity;if(b){a=a.curOp.cursorActivityHandlers||(a.curOp.cursorActivityHandlers=[]);for(var d=0;d<b.length;++d)-1==ea(a,b[d])&&a.push(b[d])}}function xa(a,b){return 0<(a._handlers&&a._handlers[b]||yc).length}function pb(a){a.prototype.on=function(b,d){z(this,
b,d)};a.prototype.off=function(b,d){ta(this,b,d)}}function la(a){a.preventDefault?a.preventDefault():a.returnValue=!1}function ue(a){a.stopPropagation?a.stopPropagation():a.cancelBubble=!0}function ld(a){return null!=a.defaultPrevented?a.defaultPrevented:0==a.returnValue}function Mb(a){la(a);ue(a)}function ve(a){var b=a.which;null==b&&(a.button&1?b=1:a.button&2?b=3:a.button&4&&(b=2));ya&&a.ctrlKey&&1==b&&(b=3);return b}function Dg(a,b){2<arguments.length&&(b.dependencies=Array.prototype.slice.call(arguments,
2));md[a]=b}function zc(a){if("string"==typeof a&&qb.hasOwnProperty(a))a=qb[a];else if(a&&"string"==typeof a.name&&qb.hasOwnProperty(a.name)){var b=qb[a.name];"string"==typeof b&&(b={name:b});a=qe(b,a);a.name=b.name}else{if("string"==typeof a&&/^[\w\-]+\/[\w\-]+\+xml$/.test(a))return zc("application/xml");if("string"==typeof a&&/^[\w\-]+\/[\w\-]+\+json$/.test(a))return zc("application/json")}return"string"==typeof a?{name:a}:a||{name:"null"}}function nd(a,b){b=zc(b);var d=md[b.name];if(!d)return nd(a,
"text/plain");a=d(a,b);if(rb.hasOwnProperty(b.name)){d=rb[b.name];for(var c in d)d.hasOwnProperty(c)&&(a.hasOwnProperty(c)&&(a["_"+c]=a[c]),a[c]=d[c])}a.name=b.name;b.helperType&&(a.helperType=b.helperType);if(b.modeProps)for(var e in b.modeProps)a[e]=b.modeProps[e];return a}function Eg(a,b){a=rb.hasOwnProperty(a)?rb[a]:rb[a]={};Za(b,a)}function $a(a,b){if(!0===b)return b;if(a.copyState)return a.copyState(b);a={};for(var d in b){var c=b[d];c instanceof Array&&(c=c.concat([]));a[d]=c}return a}function od(a,
b){for(var d;a.innerMode;){d=a.innerMode(b);if(!d||d.mode==a)break;b=d.state;a=d.mode}return d||{mode:a,state:b}}function we(a,b,d){return a.startState?a.startState(b,d):!0}function w(a,b){b-=a.first;if(0>b||b>=a.size)throw Error("There is no line "+(b+a.first)+" in the document.");for(;!a.lines;)for(var d=0;;++d){var c=a.children[d],e=c.chunkSize();if(b<e){a=c;break}b-=e}return a.lines[b]}function ab(a,b,d){var c=[],e=b.line;a.iter(b.line,d.line+1,function(f){f=f.text;e==d.line&&(f=f.slice(0,d.ch));
e==b.line&&(f=f.slice(b.ch));c.push(f);++e});return c}function pd(a,b,d){var c=[];a.iter(b,d,function(e){c.push(e.text)});return c}function Ea(a,b){if(b-=a.height)for(;a;a=a.parent)a.height+=b}function N(a){if(null==a.parent)return null;var b=a.parent;a=ea(b.lines,a);for(var d=b.parent;d;b=d,d=d.parent)for(var c=0;d.children[c]!=b;++c)a+=d.children[c].chunkSize();return a+b.first}function bb(a,b){var d=a.first;a:do{for(var c=0;c<a.children.length;++c){var e=a.children[c],f=e.height;if(b<f){a=e;continue a}b-=
f;d+=e.chunkSize()}return d}while(!a.lines);for(c=0;c<a.lines.length;++c){e=a.lines[c].height;if(b<e)break;b-=e}return d+c}function Nb(a,b){return b>=a.first&&b<a.first+a.size}function qd(a,b){return String(a.lineNumberFormatter(b+a.firstLineNumber))}function t(a,b,d){void 0===d&&(d=null);if(!(this instanceof t))return new t(a,b,d);this.line=a;this.ch=b;this.sticky=d}function B(a,b){return a.line-b.line||a.ch-b.ch}function rd(a,b){return a.sticky==b.sticky&&0==B(a,b)}function sd(a){return t(a.line,
a.ch)}function Ac(a,b){return 0>B(a,b)?b:a}function Bc(a,b){return 0>B(a,b)?a:b}function C(a,b){if(b.line<a.first)return t(a.first,0);var d=a.first+a.size-1;if(b.line>d)return t(d,w(a,d).text.length);a=w(a,b.line).text.length;d=b.ch;b=null==d||d>a?t(b.line,a):0>d?t(b.line,0):b;return b}function xe(a,b){for(var d=[],c=0;c<b.length;c++)d[c]=C(a,b[c]);return d}function ye(a,b,d,c){var e=[a.state.modeGen],f={};ze(a,b.text,a.doc.mode,d,function(k,l){return e.push(k,l)},f,c);var g=d.state;c=function(k){d.baseTokens=
e;var l=a.state.overlays[k],m=1,n=0;d.state=!0;ze(a,b.text,l.mode,d,function(p,q){for(var r=m;n<p;){var u=e[m];u>p&&e.splice(m,1,p,e[m+1],u);m+=2;n=Math.min(p,u)}if(q)if(l.opaque)e.splice(r,m-r,p,"overlay "+q),m=r+2;else for(;r<m;r+=2)p=e[r+1],e[r+1]=(p?p+" ":"")+"overlay "+q},f);d.state=g;d.baseTokens=null;d.baseTokenPos=1};for(var h=0;h<a.state.overlays.length;++h)c(h);return{styles:e,classes:f.bgClass||f.textClass?f:null}}function Ae(a,b,d){if(!b.styles||b.styles[0]!=a.state.modeGen){var c=Ob(a,
N(b)),e=b.text.length>a.options.maxHighlightLength&&$a(a.doc.mode,c.state),f=ye(a,b,c);e&&(c.state=e);b.stateAfter=c.save(!e);b.styles=f.styles;f.classes?b.styleClasses=f.classes:b.styleClasses&&(b.styleClasses=null);d===a.doc.highlightFrontier&&(a.doc.modeFrontier=Math.max(a.doc.modeFrontier,++a.doc.highlightFrontier))}return b.styles}function Ob(a,b,d){var c=a.doc,e=a.display;if(!c.mode.startState)return new Fa(c,!0,b);var f=Fg(a,b,d),g=f>c.first&&w(c,f-1).stateAfter,h=g?Fa.fromSaved(c,g,f):new Fa(c,
we(c.mode),f);c.iter(f,b,function(k){td(a,k.text,h);var l=h.line;k.stateAfter=l==b-1||0==l%5||l>=e.viewFrom&&l<e.viewTo?h.save():null;h.nextLine()});d&&(c.modeFrontier=h.line);return h}function td(a,b,d,c){var e=a.doc.mode;a=new X(b,a.options.tabSize,d);a.start=a.pos=c||0;for(""==b&&Be(e,d.state);!a.eol();)ud(e,a,d.state),a.start=a.pos}function Be(a,b){if(a.blankLine)return a.blankLine(b);if(a.innerMode&&(a=od(a,b),a.mode.blankLine))return a.mode.blankLine(a.state)}function ud(a,b,d,c){for(var e=
0;10>e;e++){c&&(c[0]=od(a,d).mode);var f=a.token(b,d);if(b.pos>b.start)return f}throw Error("Mode "+a.name+" failed to advance stream.");}function Ce(a,b,d,c){var e=a.doc,f=e.mode;b=C(e,b);var g=w(e,b.line);d=Ob(a,b.line,d);a=new X(g.text,a.options.tabSize,d);var h;for(c&&(h=[]);(c||a.pos<b.ch)&&!a.eol();){a.start=a.pos;var k=ud(f,a,d.state);c&&h.push(new De(a,k,$a(e.mode,d.state)))}return c?h:new De(a,k,d.state)}function Ee(a,b){if(a)for(;;){var d=a.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!d)break;
a=a.slice(0,d.index)+a.slice(d.index+d[0].length);var c=d[1]?"bgClass":"textClass";null==b[c]?b[c]=d[2]:(new RegExp("(?:^|\\s)"+d[2]+"(?:$|\\s)")).test(b[c])||(b[c]+=" "+d[2])}return a}function ze(a,b,d,c,e,f,g){var h=d.flattenSpans;null==h&&(h=a.options.flattenSpans);var k=0,l=null,m=new X(b,a.options.tabSize,c),n=a.options.addModeClass&&[null];for(""==b&&Ee(Be(d,c.state),f);!m.eol();){if(m.pos>a.options.maxHighlightLength){h=!1;g&&td(a,b,c,m.pos);m.pos=b.length;var p=null}else p=Ee(ud(d,m,c.state,
n),f);if(n){var q=n[0].name;q&&(p="m-"+(p?q+" "+p:q))}if(!h||l!=p){for(;k<m.start;)k=Math.min(m.start,k+5E3),e(k,l);l=p}m.start=m.pos}for(;k<m.pos;)a=Math.min(m.pos,k+5E3),e(a,l),k=a}function Fg(a,b,d){for(var c,e,f=a.doc,g=d?-1:b-(a.doc.mode.innerMode?1E3:100);b>g;--b){if(b<=f.first)return f.first;var h=w(f,b-1),k=h.stateAfter;if(k&&(!d||b+(k instanceof Cc?k.lookAhead:0)<=f.modeFrontier))return b;h=wa(h.text,null,a.options.tabSize);if(null==e||c>h)e=b-1,c=h}return e}function Gg(a,b){a.modeFrontier=
Math.min(a.modeFrontier,b);if(!(a.highlightFrontier<b-10)){for(var d=a.first,c=b-1;c>d;c--){var e=w(a,c).stateAfter;if(e&&(!(e instanceof Cc)||c+e.lookAhead<b)){d=c+1;break}}a.highlightFrontier=Math.min(a.highlightFrontier,d)}}function Dc(a,b,d){this.marker=a;this.from=b;this.to=d}function Pb(a,b){if(a)for(var d=0;d<a.length;++d){var c=a[d];if(c.marker==b)return c}}function vd(a,b){if(b.full)return null;var d=Nb(a,b.from.line)&&w(a,b.from.line).markedSpans,c=Nb(a,b.to.line)&&w(a,b.to.line).markedSpans;
if(!d&&!c)return null;a=b.from.ch;var e=b.to.ch,f=0==B(b.from,b.to),g;if(d)for(var h=0;h<d.length;++h){var k=d[h],l=k.marker;if(null==k.from||(l.inclusiveLeft?k.from<=a:k.from<a)||!(k.from!=a||"bookmark"!=l.type||f&&k.marker.insertLeft)){var m=null==k.to||(l.inclusiveRight?k.to>=a:k.to>a);(g||(g=[])).push(new Dc(l,k.from,m?null:k.to))}}d=g;var n;if(c)for(g=0;g<c.length;++g)if(h=c[g],k=h.marker,null==h.to||(k.inclusiveRight?h.to>=e:h.to>e)||h.from==e&&"bookmark"==k.type&&(!f||h.marker.insertLeft))l=
null==h.from||(k.inclusiveLeft?h.from<=e:h.from<e),(n||(n=[])).push(new Dc(k,l?null:h.from-e,null==h.to?null:h.to-e));c=1==b.text.length;e=J(b.text).length+(c?a:0);if(d)for(f=0;f<d.length;++f)if(g=d[f],null==g.to)(h=Pb(n,g.marker),h)?c&&(g.to=null==h.to?null:h.to+e):g.to=a;if(n)for(a=0;a<n.length;++a)f=n[a],null!=f.to&&(f.to+=e),null==f.from?Pb(d,f.marker)||(f.from=e,c&&(d||(d=[])).push(f)):(f.from+=e,c&&(d||(d=[])).push(f));d&&(d=Fe(d));n&&n!=d&&(n=Fe(n));a=[d];if(!c){b=b.text.length-2;var p;if(0<
b&&d)for(c=0;c<d.length;++c)null==d[c].to&&(p||(p=[])).push(new Dc(d[c].marker,null,null));for(d=0;d<b;++d)a.push(p);a.push(n)}return a}function Fe(a){for(var b=0;b<a.length;++b){var d=a[b];null!=d.from&&d.from==d.to&&!1!==d.marker.clearWhenEmpty&&a.splice(b--,1)}return a.length?a:null}function Hg(a,b,d){var c=null;a.iter(b.line,d.line+1,function(m){if(m.markedSpans)for(var n=0;n<m.markedSpans.length;++n){var p=m.markedSpans[n].marker;!p.readOnly||c&&-1!=ea(c,p)||(c||(c=[])).push(p)}});if(!c)return null;
a=[{from:b,to:d}];for(b=0;b<c.length;++b){d=c[b];for(var e=d.find(0),f=0;f<a.length;++f){var g=a[f];if(!(0>B(g.to,e.from)||0<B(g.from,e.to))){var h=[f,1],k=B(g.from,e.from),l=B(g.to,e.to);(0>k||!d.inclusiveLeft&&!k)&&h.push({from:g.from,to:e.from});(0<l||!d.inclusiveRight&&!l)&&h.push({from:e.to,to:g.to});a.splice.apply(a,h);f+=h.length-3}}}return a}function Ge(a){var b=a.markedSpans;if(b){for(var d=0;d<b.length;++d)b[d].marker.detachLine(a);a.markedSpans=null}}function He(a,b){if(b){for(var d=0;d<
b.length;++d)b[d].marker.attachLine(a);a.markedSpans=b}}function wd(a,b){var d=a.lines.length-b.lines.length;if(0!=d)return d;d=a.find();var c=b.find(),e=B(d.from,c.from)||(a.inclusiveLeft?-1:0)-(b.inclusiveLeft?-1:0);return e?-e:(d=B(d.to,c.to)||(a.inclusiveRight?1:0)-(b.inclusiveRight?1:0))?d:b.id-a.id}function sb(a,b){a=Ka&&a.markedSpans;if(a)for(var d,c=0;c<a.length;++c)if(d=a[c],d.marker.collapsed&&null==(b?d.from:d.to)&&(!e||0>wd(e,d.marker)))var e=d.marker;return e}function Ie(a,b,d,c,e){a=
w(a,b);if(a=Ka&&a.markedSpans)for(b=0;b<a.length;++b){var f=a[b];if(f.marker.collapsed){var g=f.marker.find(0),h=B(g.from,d)||(f.marker.inclusiveLeft?-1:0)-(e.inclusiveLeft?-1:0),k=B(g.to,c)||(f.marker.inclusiveRight?1:0)-(e.inclusiveRight?1:0);if(!(0<=h&&0>=k||0>=h&&0<=k)&&(0>=h&&(f.marker.inclusiveRight&&e.inclusiveLeft?0<=B(g.to,d):0<B(g.to,d))||0<=h&&(f.marker.inclusiveRight&&e.inclusiveLeft?0>=B(g.from,c):0>B(g.from,c))))return!0}}}function za(a){for(var b;b=sb(a,!0);)a=b.find(-1,!0).line;return a}
function xd(a,b){a=w(a,b);var d=za(a);return a==d?b:N(d)}function Je(a,b){if(b>a.lastLine())return b;var d=w(a,b);if(!Pa(a,d))return b;for(;a=sb(d,!1);)d=a.find(1,!0).line;return N(d)+1}function Pa(a,b){var d=Ka&&b.markedSpans;if(d)for(var c,e=0;e<d.length;++e)if(c=d[e],c.marker.collapsed&&(null==c.from||!c.marker.widgetNode&&0==c.from&&c.marker.inclusiveLeft&&yd(a,b,c)))return!0}function yd(a,b,d){if(null==d.to)return b=d.marker.find(1,!0),yd(a,b.line,Pb(b.line.markedSpans,d.marker));if(d.marker.inclusiveRight&&
d.to==b.text.length)return!0;for(var c,e=0;e<b.markedSpans.length;++e)if(c=b.markedSpans[e],c.marker.collapsed&&!c.marker.widgetNode&&c.from==d.to&&(null==c.to||c.to!=d.from)&&(c.marker.inclusiveLeft||d.marker.inclusiveRight)&&yd(a,b,c))return!0}function Ga(a){a=za(a);for(var b=0,d=a.parent,c=0;c<d.lines.length;++c){var e=d.lines[c];if(e==a)break;else b+=e.height}for(a=d.parent;a;d=a,a=d.parent)for(c=0;c<a.children.length&&(e=a.children[c],e!=d);++c)b+=e.height;return b}function Ec(a){if(0==a.height)return 0;
for(var b=a.text.length,d,c=a;d=sb(c,!0);)d=d.find(0,!0),c=d.from.line,b+=d.from.ch-d.to.ch;for(c=a;d=sb(c,!1);)a=d.find(0,!0),b-=c.text.length-a.from.ch,c=a.to.line,b+=c.text.length-a.to.ch;return b}function zd(a){var b=a.display;a=a.doc;b.maxLine=w(a,a.first);b.maxLineLength=Ec(b.maxLine);b.maxLineChanged=!0;a.iter(function(d){var c=Ec(d);c>b.maxLineLength&&(b.maxLineLength=c,b.maxLine=d)})}function Ke(a,b){if(!a||/^\s*$/.test(a))return null;b=b.addModeClass?Ig:Jg;return b[a]||(b[a]=a.replace(/\S+/g,
"cm-$&"))}function Le(a,b){var d=M("span",null,null,fa?"padding-right: .1px":null);d={pre:M("pre",[d],"CodeMirror-line"),content:d,col:0,pos:0,cm:a,trailingSpace:!1,splitSpaces:a.getOption("lineWrapping")};b.measure={};for(var c=0;c<=(b.rest?b.rest.length:0);c++){var e=c?b.rest[c-1]:b.line,f=void 0;d.pos=0;d.addToken=Kg;var g=a.display.measure;if(null!=Ad)g=Ad;else{var h=D(g,document.createTextNode("A\u062eA")),k=Qb(h,0,1).getBoundingClientRect();h=Qb(h,1,2).getBoundingClientRect();E(g);g=k&&k.left!=
k.right?Ad=3>h.right-k.right:!1}g&&(f=Ja(e,a.doc.direction))&&(d.addToken=Lg(d.addToken,f));d.map=[];var l=b!=a.display.externalMeasured&&N(e);a:{var m=h=k=g=void 0,n=void 0,p=void 0,q=void 0;f=d;l=Ae(a,e,l);var r=e.markedSpans,u=e.text,A=0;if(r)for(var Y=u.length,x=0,P=1,K="",Q=0;;){if(Q==x){n=m=h=p="";k=g=null;Q=Infinity;for(var S=[],F=void 0,R=0;R<r.length;++R){var H=r[R],L=H.marker;if("bookmark"==L.type&&H.from==x&&L.widgetNode)S.push(L);else if(H.from<=x&&(null==H.to||H.to>x||L.collapsed&&H.to==
x&&H.from==x)){null!=H.to&&H.to!=x&&Q>H.to&&(Q=H.to,m="");L.className&&(n+=" "+L.className);L.css&&(p=(p?p+";":"")+L.css);L.startStyle&&H.from==x&&(h+=" "+L.startStyle);L.endStyle&&H.to==Q&&(F||(F=[])).push(L.endStyle,H.to);L.title&&((g||(g={})).title=L.title);if(L.attributes)for(var ha in L.attributes)(g||(g={}))[ha]=L.attributes[ha];L.collapsed&&(!k||0>wd(k.marker,L))&&(k=H)}else H.from>x&&Q>H.from&&(Q=H.from)}if(F)for(R=0;R<F.length;R+=2)F[R+1]==Q&&(m+=" "+F[R]);if(!k||k.from==x)for(F=0;F<S.length;++F)Me(f,
0,S[F]);if(k&&(k.from||0)==x){Me(f,(null==k.to?Y+1:k.to)-x,k.marker,null==k.from);if(null==k.to)break a;k.to==x&&(k=!1)}}if(x>=Y)break;for(S=Math.min(Y,Q);;){if(K){F=x+K.length;k||(R=F>S?K.slice(0,S-x):K,f.addToken(f,R,q?q+n:n,h,x+R.length==Q?m:"",p,g));if(F>=S){K=K.slice(S-x);x=S;break}x=F;h=""}K=u.slice(A,A=l[P++]);q=Ke(l[P++],f.cm.options)}}else for(g=1;g<l.length;g+=2)f.addToken(f,u.slice(A,A=l[g]),Ke(l[g+1],f.cm.options))}e.styleClasses&&(e.styleClasses.bgClass&&(d.bgClass=fd(e.styleClasses.bgClass,
d.bgClass||"")),e.styleClasses.textClass&&(d.textClass=fd(e.styleClasses.textClass,d.textClass||"")));0==d.map.length&&(e=d.map,f=e.push,g=d.content,k=g.appendChild,h=a.display.measure,null==Bd&&(m=v("span","\u200b"),D(h,v("span",[m,document.createTextNode("x")])),0!=h.firstChild.offsetHeight&&(Bd=1>=m.offsetWidth&&2<m.offsetHeight&&!(G&&8>T))),h=Bd?v("span","\u200b"):v("span","\u00a0",null,"display: inline-block; width: 1px; margin-right: -1px"),h.setAttribute("cm-text",""),f.call(e,0,0,k.call(g,
h)));0==c?(b.measure.map=d.map,b.measure.cache={}):((b.measure.maps||(b.measure.maps=[])).push(d.map),(b.measure.caches||(b.measure.caches=[])).push({}))}fa&&(ha=d.content.lastChild,/\bcm-tab\b/.test(ha.className)||ha.querySelector&&ha.querySelector(".cm-tab"))&&(d.content.className="cm-tab-wrap-hack");W(a,"renderLine",a,b.line,d.pre);d.pre.className&&(d.textClass=fd(d.pre.className,d.textClass||""));return d}function Mg(a){var b=v("span","\u2022","cm-invalidchar");b.title="\\u"+a.charCodeAt(0).toString(16);
b.setAttribute("aria-label",b.title);return b}function Kg(a,b,d,c,e,f,g){if(b){if(a.splitSpaces){var h=a.trailingSpace;if(1<b.length&&!/ /.test(b))h=b;else{for(var k="",l=0;l<b.length;l++){var m=b.charAt(l);" "!=m||!h||l!=b.length-1&&32!=b.charCodeAt(l+1)||(m="\u00a0");k+=m;h=" "==m}h=k}}else h=b;k=h;l=a.cm.state.specialChars;m=!1;if(l.test(b)){h=document.createDocumentFragment();for(var n=0;;){l.lastIndex=n;var p=l.exec(b),q=p?p.index-n:b.length-n;if(q){var r=document.createTextNode(k.slice(n,n+
q));G&&9>T?h.appendChild(v("span",[r])):h.appendChild(r);a.map.push(a.pos,a.pos+q,r);a.col+=q;a.pos+=q}if(!p)break;n+=q+1;"\t"==p[0]?(p=a.cm.options.tabSize,p-=a.col%p,q=h.appendChild(v("span",id(p),"cm-tab")),q.setAttribute("role","presentation"),q.setAttribute("cm-text","\t"),a.col+=p):("\r"==p[0]||"\n"==p[0]?(q=h.appendChild(v("span","\r"==p[0]?"\u240d":"\u2424","cm-invalidchar")),q.setAttribute("cm-text",p[0])):(q=a.cm.options.specialCharPlaceholder(p[0]),q.setAttribute("cm-text",p[0]),G&&9>T?
h.appendChild(v("span",[q])):h.appendChild(q)),a.col+=1);a.map.push(a.pos,a.pos+1,q);a.pos++}}else a.col+=b.length,h=document.createTextNode(k),a.map.push(a.pos,a.pos+b.length,h),G&&9>T&&(m=!0),a.pos+=b.length;a.trailingSpace=32==k.charCodeAt(b.length-1);if(d||c||e||m||f||g){b=d||"";c&&(b+=c);e&&(b+=e);c=v("span",[h],b,f);if(g)for(var u in g)g.hasOwnProperty(u)&&"style"!=u&&"class"!=u&&c.setAttribute(u,g[u]);return a.content.appendChild(c)}a.content.appendChild(h)}}function Lg(a,b){return function(d,
c,e,f,g,h,k){e=e?e+" cm-force-border":"cm-force-border";for(var l=d.pos,m=l+c.length;;){for(var n=void 0,p=0;p<b.length&&!(n=b[p],n.to>l&&n.from<=l);p++);if(n.to>=m)return a(d,c,e,f,g,h,k);a(d,c.slice(0,n.to-l),e,f,null,h,k);f=null;c=c.slice(n.to-l);l=n.to}}}function Me(a,b,d,c){var e=!c&&d.widgetNode;e&&a.map.push(a.pos,a.pos+b,e);!c&&a.cm.display.input.needsContentAttribute&&(e||(e=a.content.appendChild(document.createElement("span"))),e.setAttribute("cm-marker",d.id));e&&(a.cm.display.input.setUneditable(e),
a.content.appendChild(e));a.pos+=b;a.trailingSpace=!1}function Ne(a,b,d){for(var c=this.line=b,e;c=sb(c,!1);)c=c.find(1,!0).line,(e||(e=[])).push(c);this.size=(this.rest=e)?N(J(this.rest))-d+1:1;this.node=this.text=null;this.hidden=Pa(a,b)}function Fc(a,b,d){var c=[],e;for(e=b;e<d;)b=new Ne(a.doc,w(a.doc,e),e),e+=b.size,c.push(b);return c}function Ng(a,b){if(a=a.ownsGroup)try{var d=a.delayedCallbacks,c=0;do{for(;c<d.length;c++)d[c].call(null);for(var e=0;e<a.ops.length;e++){var f=a.ops[e];if(f.cursorActivityHandlers)for(;f.cursorActivityCalled<
f.cursorActivityHandlers.length;)f.cursorActivityHandlers[f.cursorActivityCalled++].call(null,f.cm)}}while(c<d.length)}finally{tb=null,b(a)}}function aa(a,b){var d=a._handlers&&a._handlers[b]||yc;if(d.length){var c=Array.prototype.slice.call(arguments,2);if(tb)var e=tb.delayedCallbacks;else Rb?e=Rb:(e=Rb=[],setTimeout(Og,0));for(var f=function(h){e.push(function(){return d[h].apply(null,c)})},g=0;g<d.length;++g)f(g)}}function Og(){var a=Rb;Rb=null;for(var b=0;b<a.length;++b)a[b]()}function Oe(a,b,
d,c){for(var e=0;e<b.changes.length;e++){var f=b.changes[e];if("text"==f){f=a;var g=b,h=g.text.className,k=Pe(f,g);g.text==g.node&&(g.node=k.pre);g.text.parentNode.replaceChild(k.pre,g.text);g.text=k.pre;k.bgClass!=g.bgClass||k.textClass!=g.textClass?(g.bgClass=k.bgClass,g.textClass=k.textClass,Cd(f,g)):h&&(g.text.className=h)}else if("gutter"==f)Qe(a,b,d,c);else if("class"==f)Cd(a,b);else if("widget"==f){f=a;g=b;h=c;g.alignable&&(g.alignable=null);k=y("CodeMirror-linewidget");for(var l=g.node.firstChild,
m;l;l=m)m=l.nextSibling,k.test(l.className)&&g.node.removeChild(l);Re(f,g,h)}}b.changes=null}function Sb(a){a.node==a.text&&(a.node=v("div",null,null,"position: relative"),a.text.parentNode&&a.text.parentNode.replaceChild(a.node,a.text),a.node.appendChild(a.text),G&&8>T&&(a.node.style.zIndex=2));return a.node}function Pe(a,b){var d=a.display.externalMeasured;return d&&d.line==b.line?(a.display.externalMeasured=null,b.measure=d.measure,d.built):Le(a,b)}function Cd(a,b){var d=b.bgClass?b.bgClass+" "+
(b.line.bgClass||""):b.line.bgClass;d&&(d+=" CodeMirror-linebackground");if(b.background)d?b.background.className=d:(b.background.parentNode.removeChild(b.background),b.background=null);else if(d){var c=Sb(b);b.background=c.insertBefore(v("div",null,d),c.firstChild);a.display.input.setUneditable(b.background)}b.line.wrapClass?Sb(b).className=b.line.wrapClass:b.node!=b.text&&(b.node.className="");b.text.className=(b.textClass?b.textClass+" "+(b.line.textClass||""):b.line.textClass)||""}function Qe(a,
b,d,c){b.gutter&&(b.node.removeChild(b.gutter),b.gutter=null);b.gutterBackground&&(b.node.removeChild(b.gutterBackground),b.gutterBackground=null);if(b.line.gutterClass){var e=Sb(b);b.gutterBackground=v("div",null,"CodeMirror-gutter-background "+b.line.gutterClass,"left: "+(a.options.fixedGutter?c.fixedPos:-c.gutterTotalWidth)+"px; width: "+c.gutterTotalWidth+"px");a.display.input.setUneditable(b.gutterBackground);e.insertBefore(b.gutterBackground,b.text)}e=b.line.gutterMarkers;if(a.options.lineNumbers||
e){var f=Sb(b),g=b.gutter=v("div",null,"CodeMirror-gutter-wrapper","left: "+(a.options.fixedGutter?c.fixedPos:-c.gutterTotalWidth)+"px");g.setAttribute("aria-hidden","true");a.display.input.setUneditable(g);f.insertBefore(g,b.text);b.line.gutterClass&&(g.className+=" "+b.line.gutterClass);!a.options.lineNumbers||e&&e["CodeMirror-linenumbers"]||(b.lineNumber=g.appendChild(v("div",qd(a.options,d),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+c.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+
a.display.lineNumInnerWidth+"px")));if(e)for(b=0;b<a.display.gutterSpecs.length;++b)d=a.display.gutterSpecs[b].className,(f=e.hasOwnProperty(d)&&e[d])&&g.appendChild(v("div",[f],"CodeMirror-gutter-elt","left: "+c.gutterLeft[d]+"px; width: "+c.gutterWidth[d]+"px"))}}function Pg(a,b,d,c){var e=Pe(a,b);b.text=b.node=e.pre;e.bgClass&&(b.bgClass=e.bgClass);e.textClass&&(b.textClass=e.textClass);Cd(a,b);Qe(a,b,d,c);Re(a,b,c);return b.node}function Re(a,b,d){Se(a,b.line,b,d,!0);if(b.rest)for(var c=0;c<b.rest.length;c++)Se(a,
b.rest[c],b,d,!1)}function Se(a,b,d,c,e){if(b.widgets){var f=Sb(d),g=0;for(b=b.widgets;g<b.length;++g){var h=b[g],k=v("div",[h.node],"CodeMirror-linewidget"+(h.className?" "+h.className:""));h.handleMouseEvents||k.setAttribute("cm-ignore-events","true");var l=h,m=k,n=c;if(l.noHScroll){(d.alignable||(d.alignable=[])).push(m);var p=n.wrapperWidth;m.style.left=n.fixedPos+"px";l.coverGutter||(p-=n.gutterTotalWidth,m.style.paddingLeft=n.gutterTotalWidth+"px");m.style.width=p+"px"}l.coverGutter&&(m.style.zIndex=
5,m.style.position="relative",l.noHScroll||(m.style.marginLeft=-n.gutterTotalWidth+"px"));a.display.input.setUneditable(k);e&&h.above?f.insertBefore(k,d.gutter||d.text):f.appendChild(k);aa(h,"redraw")}}}function Tb(a){if(null!=a.height)return a.height;var b=a.doc.cm;if(!b)return 0;if(!ja(document.body,a.node)){var d="position: relative;";a.coverGutter&&(d+="margin-left: -"+b.display.gutters.offsetWidth+"px;");a.noHScroll&&(d+="width: "+b.display.wrapper.clientWidth+"px;");D(b.display.measure,v("div",
[a.node],null,d))}return a.height=a.node.parentNode.offsetHeight}function La(a,b){for(b=b.target||b.srcElement;b!=a.wrapper;b=b.parentNode)if(!b||1==b.nodeType&&"true"==b.getAttribute("cm-ignore-events")||b.parentNode==a.sizer&&b!=a.mover)return!0}function Dd(a){return a.mover.offsetHeight-a.lineSpace.offsetHeight}function Te(a){if(a.cachedPaddingH)return a.cachedPaddingH;var b=D(a.measure,v("pre","x","CodeMirror-line-like"));b=window.getComputedStyle?window.getComputedStyle(b):b.currentStyle;b={left:parseInt(b.paddingLeft),
right:parseInt(b.paddingRight)};isNaN(b.left)||isNaN(b.right)||(a.cachedPaddingH=b);return b}function Ha(a){return 50-a.display.nativeBarWidth}function cb(a){return a.display.scroller.clientWidth-Ha(a)-a.display.barWidth}function Ed(a){return a.display.scroller.clientHeight-Ha(a)-a.display.barHeight}function Ue(a,b,d){if(a.line==b)return{map:a.measure.map,cache:a.measure.cache};if(a.rest){for(var c=0;c<a.rest.length;c++)if(a.rest[c]==b)return{map:a.measure.maps[c],cache:a.measure.caches[c]};for(b=
0;b<a.rest.length;b++)if(N(a.rest[b])>d)return{map:a.measure.maps[b],cache:a.measure.caches[b],before:!0}}}function Fd(a,b){if(b>=a.display.viewFrom&&b<a.display.viewTo)return a.display.view[db(a,b)];if((a=a.display.externalMeasured)&&b>=a.lineN&&b<a.lineN+a.size)return a}function eb(a,b){var d=N(b),c=Fd(a,d);c&&!c.text?c=null:c&&c.changes&&(Oe(a,c,d,Gd(a)),a.curOp.forceUpdate=!0);if(!c){var e=za(b);c=N(e);e=a.display.externalMeasured=new Ne(a.doc,e,c);e.lineN=c;c=e.built=Le(a,e);e.text=c.pre;D(a.display.lineMeasure,
c.pre);c=e}a=Ue(c,b,d);return{line:b,view:c,rect:null,map:a.map,cache:a.cache,before:a.before,hasHeights:!1}}function Aa(a,b,d,c,e){b.before&&(d=-1);var f=d+(c||"");if(b.cache.hasOwnProperty(f))a=b.cache[f];else{b.rect||(b.rect=b.view.text.getBoundingClientRect());if(!b.hasHeights){var g=b.view,h=b.rect,k=a.options.lineWrapping,l=k&&cb(a);if(!g.measure.heights||k&&g.measure.width!=l){var m=g.measure.heights=[];if(k)for(g.measure.width=l,g=g.text.firstChild.getClientRects(),k=0;k<g.length-1;k++){l=
g[k];var n=g[k+1];2<Math.abs(l.bottom-n.bottom)&&m.push((l.bottom+n.top)/2-h.top)}m.push(h.bottom-h.top)}b.hasHeights=!0}m=c;g=Ve(b.map,d,m);c=g.node;h=g.start;k=g.end;d=g.collapse;if(3==c.nodeType){for(var p=0;4>p;p++){for(;h&&kd(b.line.text.charAt(g.coverStart+h));)--h;for(;g.coverStart+k<g.coverEnd&&kd(b.line.text.charAt(g.coverStart+k));)++k;if(G&&9>T&&0==h&&k==g.coverEnd-g.coverStart)var q=c.parentNode.getBoundingClientRect();else{q=Qb(c,h,k).getClientRects();k=We;if("left"==m)for(l=0;l<q.length&&
(k=q[l]).left==k.right;l++);else for(l=q.length-1;0<=l&&(k=q[l]).left==k.right;l--);q=k}if(q.left||q.right||0==h)break;k=h;--h;d="right"}G&&11>T&&((p=!window.screen||null==screen.logicalXDPI||screen.logicalXDPI==screen.deviceXDPI)||(null!=Hd?p=Hd:(m=D(a.display.measure,v("span","x")),p=m.getBoundingClientRect(),m=Qb(m,0,1).getBoundingClientRect(),p=Hd=1<Math.abs(p.left-m.left)),p=!p),p||(p=screen.logicalXDPI/screen.deviceXDPI,m=screen.logicalYDPI/screen.deviceYDPI,q={left:q.left*p,right:q.right*p,
top:q.top*m,bottom:q.bottom*m}))}else 0<h&&(d=m="right"),q=a.options.lineWrapping&&1<(p=c.getClientRects()).length?p["right"==m?p.length-1:0]:c.getBoundingClientRect();!(G&&9>T)||h||q&&(q.left||q.right)||(q=(q=c.parentNode.getClientRects()[0])?{left:q.left,right:q.left+ub(a.display),top:q.top,bottom:q.bottom}:We);c=q.top-b.rect.top;h=q.bottom-b.rect.top;p=(c+h)/2;m=b.view.measure.heights;for(g=0;g<m.length-1&&!(p<m[g]);g++);d={left:("right"==d?q.right:q.left)-b.rect.left,right:("left"==d?q.left:q.right)-
b.rect.left,top:g?m[g-1]:0,bottom:m[g]};q.left||q.right||(d.bogus=!0);a.options.singleCursorHeightPerLine||(d.rtop=c,d.rbottom=h);a=d;a.bogus||(b.cache[f]=a)}return{left:a.left,right:a.right,top:e?a.rtop:a.top,bottom:e?a.rbottom:a.bottom}}function Ve(a,b,d){for(var c,e,f,g,h,k,l=0;l<a.length;l+=3){h=a[l];k=a[l+1];if(b<h)e=0,f=1,g="left";else if(b<k)e=b-h,f=e+1;else if(l==a.length-3||b==k&&a[l+3]>b)f=k-h,e=f-1,b>=k&&(g="right");if(null!=e){c=a[l+2];h==k&&d==(c.insertLeft?"left":"right")&&(g=d);if("left"==
d&&0==e)for(;l&&a[l-2]==a[l-3]&&a[l-1].insertLeft;)c=a[(l-=3)+2],g="left";if("right"==d&&e==k-h)for(;l<a.length-3&&a[l+3]==a[l+4]&&!a[l+5].insertLeft;)c=a[(l+=3)+2],g="right";break}}return{node:c,start:e,end:f,collapse:g,coverStart:h,coverEnd:k}}function Xe(a){if(a.measure&&(a.measure.cache={},a.measure.heights=null,a.rest))for(var b=0;b<a.rest.length;b++)a.measure.caches[b]={}}function Ye(a){a.display.externalMeasure=null;E(a.display.lineMeasure);for(var b=0;b<a.display.view.length;b++)Xe(a.display.view[b])}
function Ub(a){Ye(a);a.display.cachedCharWidth=a.display.cachedTextHeight=a.display.cachedPaddingH=null;a.options.lineWrapping||(a.display.maxLineChanged=!0);a.display.lineNumChars=null}function Ze(a){return Qa&&Gc?-(a.body.getBoundingClientRect().left-parseInt(getComputedStyle(a.body).marginLeft)):a.defaultView.pageXOffset||(a.documentElement||a.body).scrollLeft}function $e(a){return Qa&&Gc?-(a.body.getBoundingClientRect().top-parseInt(getComputedStyle(a.body).marginTop)):a.defaultView.pageYOffset||
(a.documentElement||a.body).scrollTop}function Id(a){a=za(a).widgets;var b=0;if(a)for(var d=0;d<a.length;++d)a[d].above&&(b+=Tb(a[d]));return b}function Hc(a,b,d,c,e){e||(e=Id(b),d.top+=e,d.bottom+=e);if("line"==c)return d;c||(c="local");b=Ga(b);b="local"==c?b+a.display.lineSpace.offsetTop:b-a.display.viewOffset;if("page"==c||"window"==c)e=a.display.lineSpace.getBoundingClientRect(),b+=e.top+("window"==c?0:$e(qa(a))),a=e.left+("window"==c?0:Ze(qa(a))),d.left+=a,d.right+=a;d.top+=b;d.bottom+=b;return d}
function af(a,b,d){if("div"==d)return b;var c=b.left;b=b.top;"page"==d?(c-=Ze(qa(a)),b-=$e(qa(a))):"local"!=d&&d||(d=a.display.sizer.getBoundingClientRect(),c+=d.left,b+=d.top);a=a.display.lineSpace.getBoundingClientRect();return{left:c-a.left,top:b-a.top}}function Ic(a,b,d,c,e){c||(c=w(a.doc,b.line));var f=c;b=b.ch;c=Aa(a,eb(a,c),b,e);return Hc(a,f,c,d)}function Ba(a,b,d,c,e,f){function g(p,q){p=Aa(a,e,p,q?"right":"left",f);q?p.left=p.right:p.right=p.left;return Hc(a,c,p,d)}function h(p,q,r){return g(r?
p-1:p,1==k[q].level!=r)}c=c||w(a.doc,b.line);e||(e=eb(a,c));var k=Ja(c,a.doc.direction),l=b.ch;b=b.sticky;l>=c.text.length?(l=c.text.length,b="before"):0>=l&&(l=0,b="after");if(!k)return g("before"==b?l-1:l,"before"==b);var m=Kb(k,l,b),n=Lb;m=h(l,m,"before"==b);null!=n&&(m.other=h(l,n,"before"!=b));return m}function bf(a,b){var d=0;b=C(a.doc,b);a.options.lineWrapping||(d=ub(a.display)*b.ch);b=w(a.doc,b.line);a=Ga(b)+a.display.lineSpace.offsetTop;return{left:d,right:d,top:a,bottom:a+b.height}}function Jd(a,
b,d,c,e){a=t(a,b,d);a.xRel=e;c&&(a.outside=c);return a}function Kd(a,b,d){var c=a.doc;d+=a.display.viewOffset;if(0>d)return Jd(c.first,0,null,-1,-1);var e=bb(c,d),f=c.first+c.size-1;if(e>f)return Jd(c.first+c.size-1,w(c,f).text.length,null,1,1);0>b&&(b=0);for(var g=w(c,e);;){f=Qg(a,g,e,b,d);var h=void 0;var k=f.ch+(0<f.xRel||0<f.outside?1:0);if(g=Ka&&g.markedSpans)for(var l=0;l<g.length;++l){var m=g[l];m.marker.collapsed&&(null==m.from||m.from<k)&&(null==m.to||m.to>k)&&(!h||0>wd(h,m.marker))&&(h=
m.marker)}if(!h)return f;f=h.find(1);if(f.line==e)return f;g=w(c,e=f.line)}}function cf(a,b,d,c){c-=Id(b);b=b.text.length;var e=Jb(function(f){return Aa(a,d,f-1).bottom<=c},b,0);b=Jb(function(f){return Aa(a,d,f).top>c},e,b);return{begin:e,end:b}}function df(a,b,d,c){d||(d=eb(a,b));c=Hc(a,b,Aa(a,d,c),"line").top;return cf(a,b,d,c)}function Ld(a,b,d,c){return a.bottom<=d?!1:a.top>d?!0:(c?a.left:a.right)>b}function Qg(a,b,d,c,e){e-=Ga(b);var f=eb(a,b),g=Id(b),h=0,k=b.text.length,l=!0,m=Ja(b,a.doc.direction);
m&&(m=(a.options.lineWrapping?Rg:Sg)(a,b,d,f,m,c,e),h=(l=1!=m.level)?m.from:m.to-1,k=l?m.to:m.from-1);var n=null,p=null;m=Jb(function(r){var u=Aa(a,f,r);u.top+=g;u.bottom+=g;if(!Ld(u,c,e,!1))return!1;u.top<=e&&u.left<=c&&(n=r,p=u);return!0},h,k);var q=!1;p?(h=c-p.left<p.right-c,l=h==l,m=n+(l?0:1),l=l?"after":"before",h=h?p.left:p.right):(l||m!=k&&m!=h||m++,l=0==m?"after":m==b.text.length?"before":Aa(a,f,m-(l?1:0)).bottom+g<=e==l?"after":"before",q=Ba(a,t(d,m,l),"line",b,f),h=q.left,q=e<q.top?-1:e>=
q.bottom?1:0);m=se(b.text,m,1);return Jd(d,m,l,q,c-h)}function Sg(a,b,d,c,e,f,g){var h=Jb(function(m){m=e[m];var n=1!=m.level;return Ld(Ba(a,t(d,n?m.to:m.from,n?"before":"after"),"line",b,c),f,g,!0)},0,e.length-1),k=e[h];if(0<h){var l=1!=k.level;l=Ba(a,t(d,l?k.from:k.to,l?"after":"before"),"line",b,c);Ld(l,f,g,!0)&&l.top>g&&(k=e[h-1])}return k}function Rg(a,b,d,c,e,f,g){g=cf(a,b,c,g);d=g.begin;g=g.end;/\s/.test(b.text.charAt(g-1))&&g--;for(var h=b=null,k=0;k<e.length;k++){var l=e[k];if(!(l.from>=
g||l.to<=d)){var m=Aa(a,c,1!=l.level?Math.min(g,l.to)-1:Math.max(d,l.from)).right;m=m<f?f-m+1E9:m-f;if(!b||h>m)b=l,h=m}}b||(b=e[e.length-1]);b.from<d&&(b={from:d,to:b.to,level:b.level});b.to>g&&(b={from:b.from,to:g,level:b.level});return b}function vb(a){if(null!=a.cachedTextHeight)return a.cachedTextHeight;if(null==fb){fb=v("pre",null,"CodeMirror-line-like");for(var b=0;49>b;++b)fb.appendChild(document.createTextNode("x")),fb.appendChild(v("br"));fb.appendChild(document.createTextNode("x"))}D(a.measure,
fb);b=fb.offsetHeight/50;3<b&&(a.cachedTextHeight=b);E(a.measure);return b||1}function ub(a){if(null!=a.cachedCharWidth)return a.cachedCharWidth;var b=v("span","xxxxxxxxxx"),d=v("pre",[b],"CodeMirror-line-like");D(a.measure,d);b=b.getBoundingClientRect();b=(b.right-b.left)/10;2<b&&(a.cachedCharWidth=b);return b||10}function Gd(a){for(var b=a.display,d={},c={},e=b.gutters.clientLeft,f=b.gutters.firstChild,g=0;f;f=f.nextSibling,++g){var h=a.display.gutterSpecs[g].className;d[h]=f.offsetLeft+f.clientLeft+
e;c[h]=f.clientWidth}return{fixedPos:Md(b),gutterTotalWidth:b.gutters.offsetWidth,gutterLeft:d,gutterWidth:c,wrapperWidth:b.wrapper.clientWidth}}function Md(a){return a.scroller.getBoundingClientRect().left-a.sizer.getBoundingClientRect().left}function ef(a){var b=vb(a.display),d=a.options.lineWrapping,c=d&&Math.max(5,a.display.scroller.clientWidth/ub(a.display)-3);return function(e){if(Pa(a.doc,e))return 0;var f=0;if(e.widgets)for(var g=0;g<e.widgets.length;g++)e.widgets[g].height&&(f+=e.widgets[g].height);
return d?f+(Math.ceil(e.text.length/c)||1)*b:f+b}}function Nd(a){var b=a.doc,d=ef(a);b.iter(function(c){var e=d(c);e!=c.height&&Ea(c,e)})}function gb(a,b,d,c){var e=a.display;if(!d&&"true"==(b.target||b.srcElement).getAttribute("cm-not-content"))return null;d=e.lineSpace.getBoundingClientRect();try{var f=b.clientX-d.left;var g=b.clientY-d.top}catch(k){return null}b=Kd(a,f,g);var h;c&&0<b.xRel&&(h=w(a.doc,b.line).text).length==b.ch&&(c=wa(h,h.length,a.options.tabSize)-h.length,b=t(b.line,Math.max(0,
Math.round((f-Te(a.display).left)/ub(a.display))-c)));return b}function db(a,b){if(b>=a.display.viewTo)return null;b-=a.display.viewFrom;if(0>b)return null;a=a.display.view;for(var d=0;d<a.length;d++)if(b-=a[d].size,0>b)return d}function ma(a,b,d,c){null==b&&(b=a.doc.first);null==d&&(d=a.doc.first+a.doc.size);c||(c=0);var e=a.display;c&&d<e.viewTo&&(null==e.updateLineNumbers||e.updateLineNumbers>b)&&(e.updateLineNumbers=b);a.curOp.viewChanged=!0;if(b>=e.viewTo)Ka&&xd(a.doc,b)<e.viewTo&&Ra(a);else if(d<=
e.viewFrom)Ka&&Je(a.doc,d+c)>e.viewFrom?Ra(a):(e.viewFrom+=c,e.viewTo+=c);else if(b<=e.viewFrom&&d>=e.viewTo)Ra(a);else if(b<=e.viewFrom){var f=Jc(a,d,d+c,1);f?(e.view=e.view.slice(f.index),e.viewFrom=f.lineN,e.viewTo+=c):Ra(a)}else if(d>=e.viewTo)(f=Jc(a,b,b,-1))?(e.view=e.view.slice(0,f.index),e.viewTo=f.lineN):Ra(a);else{f=Jc(a,b,b,-1);var g=Jc(a,d,d+c,1);f&&g?(e.view=e.view.slice(0,f.index).concat(Fc(a,f.lineN,g.lineN)).concat(e.view.slice(g.index)),e.viewTo+=c):Ra(a)}if(a=e.externalMeasured)d<
a.lineN?a.lineN+=c:b<a.lineN+a.size&&(e.externalMeasured=null)}function Sa(a,b,d){a.curOp.viewChanged=!0;var c=a.display,e=a.display.externalMeasured;e&&b>=e.lineN&&b<e.lineN+e.size&&(c.externalMeasured=null);b<c.viewFrom||b>=c.viewTo||(a=c.view[db(a,b)],null!=a.node&&(a=a.changes||(a.changes=[]),-1==ea(a,d)&&a.push(d)))}function Ra(a){a.display.viewFrom=a.display.viewTo=a.doc.first;a.display.view=[];a.display.viewOffset=0}function Jc(a,b,d,c){var e=db(a,b),f=a.display.view;if(!Ka||d==a.doc.first+
a.doc.size)return{index:e,lineN:d};for(var g=a.display.viewFrom,h=0;h<e;h++)g+=f[h].size;if(g!=b){if(0<c){if(e==f.length-1)return null;b=g+f[e].size-b;e++}else b=g-b;d+=b}for(;xd(a.doc,d)!=d;){if(e==(0>c?0:f.length-1))return null;d+=c*f[e-(0>c?1:0)].size;e+=c}return{index:e,lineN:d}}function ff(a){a=a.display.view;for(var b=0,d=0;d<a.length;d++){var c=a[d];c.hidden||c.node&&!c.changes||++b}return b}function Vb(a){a.display.input.showSelection(a.display.input.prepareSelection())}function gf(a,b){void 0===
b&&(b=!0);var d=a.doc,c={},e=c.cursors=document.createDocumentFragment(),f=c.selection=document.createDocumentFragment(),g=a.options.$customCursor;g&&(b=!0);for(var h=0;h<d.sel.ranges.length;h++)if(b||h!=d.sel.primIndex){var k=d.sel.ranges[h];if(!(k.from().line>=a.display.viewTo||k.to().line<a.display.viewFrom)){var l=k.empty();if(g){var m=g(a,k);m&&Od(a,m,e)}else(l||a.options.showCursorWhenSelecting)&&Od(a,k.head,e);l||Tg(a,k,f)}}return c}function Od(a,b,d){var c=Ba(a,b,"div",null,null,!a.options.singleCursorHeightPerLine),
e=d.appendChild(v("div","\u00a0","CodeMirror-cursor"));e.style.left=c.left+"px";e.style.top=c.top+"px";e.style.height=Math.max(0,c.bottom-c.top)*a.options.cursorHeight+"px";/\bcm-fat-cursor\b/.test(a.getWrapperElement().className)&&(b=Ic(a,b,"div",null,null),b=b.right-b.left,e.style.width=(0<b?b:a.defaultCharWidth())+"px");c.other&&(a=d.appendChild(v("div","\u00a0","CodeMirror-cursor CodeMirror-secondarycursor")),a.style.display="",a.style.left=c.other.left+"px",a.style.top=c.other.top+"px",a.style.height=
.85*(c.other.bottom-c.other.top)+"px")}function Kc(a,b){return a.top-b.top||a.left-b.left}function Tg(a,b,d){function c(q,r,u,A){0>r&&(r=0);r=Math.round(r);A=Math.round(A);h.appendChild(v("div",null,"CodeMirror-selected","position: absolute; left: "+q+"px;\n top: "+r+"px; width: "+(null==u?m-q:u)+"px;\n height: "+(A-r)+"px"))}function e(q,r,u){function A(F,R){return Ic(a,t(q,F),"div",x,R)}function Y(F,R,H){F=df(a,x,null,F);R="ltr"==R==("after"==
H)?"left":"right";H="after"==H?F.begin:F.end-(/\s/.test(x.text.charAt(F.end-1))?2:1);return A(H,R)[R]}var x=w(g,q),P=x.text.length,K,Q,S=Ja(x,g.direction);Bg(S,r||0,null==u?P:u,function(F,R,H,L){var ha="ltr"==H,na=A(F,ha?"left":"right"),ua=A(R-1,ha?"right":"left"),hb=null==r&&0==F,ib=null==u&&R==P,Pd=0==L;L=!S||L==S.length-1;3>=ua.top-na.top?(R=(n?hb:ib)&&Pd?l:(ha?na:ua).left,c(R,na.top,((n?ib:hb)&&L?m:(ha?ua:na).right)-R,na.bottom)):(ha?(ha=n&&hb&&Pd?l:na.left,hb=n?m:Y(F,H,"before"),F=n?l:Y(R,H,
"after"),ib=n&&ib&&L?m:ua.right):(ha=n?Y(F,H,"before"):l,hb=!n&&hb&&Pd?m:na.right,F=!n&&ib&&L?l:ua.left,ib=n?Y(R,H,"after"):m),c(ha,na.top,hb-ha,na.bottom),na.bottom<ua.top&&c(l,na.bottom,null,ua.top),c(F,ua.top,ib-F,ua.bottom));if(!K||0>Kc(na,K))K=na;0>Kc(ua,K)&&(K=ua);if(!Q||0>Kc(na,Q))Q=na;0>Kc(ua,Q)&&(Q=ua)});return{start:K,end:Q}}var f=a.display,g=a.doc,h=document.createDocumentFragment(),k=Te(a.display),l=k.left,m=Math.max(f.sizerWidth,cb(a)-f.sizer.offsetLeft)-k.right,n="ltr"==g.direction;
f=b.from();b=b.to();if(f.line==b.line)e(f.line,f.ch,b.ch);else{var p=w(g,f.line);k=w(g,b.line);k=za(p)==za(k);f=e(f.line,f.ch,k?p.text.length+1:null).end;b=e(b.line,k?0:null,b.ch).start;k&&(f.top<b.top-2?(c(f.right,f.top,null,f.bottom),c(l,b.top,b.left,b.bottom)):c(f.right,f.top,b.left-f.right,f.bottom));f.bottom<b.top&&c(l,f.bottom,null,b.top)}d.appendChild(h)}function Qd(a){if(a.state.focused){var b=a.display;clearInterval(b.blinker);var d=!0;b.cursorDiv.style.visibility="";0<a.options.cursorBlinkRate?
b.blinker=setInterval(function(){a.hasFocus()||wb(a);b.cursorDiv.style.visibility=(d=!d)?"":"hidden"},a.options.cursorBlinkRate):0>a.options.cursorBlinkRate&&(b.cursorDiv.style.visibility="hidden")}}function hf(a){a.hasFocus()||(a.display.input.focus(),a.state.focused||Rd(a))}function Sd(a){a.state.delayingBlurEvent=!0;setTimeout(function(){a.state.delayingBlurEvent&&(a.state.delayingBlurEvent=!1,a.state.focused&&wb(a))},100)}function Rd(a,b){a.state.delayingBlurEvent&&!a.state.draggingText&&(a.state.delayingBlurEvent=
!1);"nocursor"!=a.options.readOnly&&(a.state.focused||(W(a,"focus",a,b),a.state.focused=!0,Ya(a.display.wrapper,"CodeMirror-focused"),a.curOp||a.display.selForContextMenu==a.doc.sel||(a.display.input.reset(),fa&&setTimeout(function(){return a.display.input.reset(!0)},20)),a.display.input.receivedFocus()),Qd(a))}function wb(a,b){a.state.delayingBlurEvent||(a.state.focused&&(W(a,"blur",a,b),a.state.focused=!1,jb(a.display.wrapper,"CodeMirror-focused")),clearInterval(a.display.blinker),setTimeout(function(){a.state.focused||
(a.display.shift=!1)},150))}function Lc(a){for(var b=a.display,d=b.lineDiv.offsetTop,c=Math.max(0,b.scroller.getBoundingClientRect().top),e=b.lineDiv.getBoundingClientRect().top,f=0,g=0;g<b.view.length;g++){var h=b.view[g],k=a.options.lineWrapping,l=0;if(!h.hidden){e+=h.line.height;if(G&&8>T){k=h.node.offsetTop+h.node.offsetHeight;var m=k-d;d=k}else{var n=h.node.getBoundingClientRect();m=n.bottom-n.top;!k&&h.text.firstChild&&(l=h.text.firstChild.getBoundingClientRect().right-n.left-1)}k=h.line.height-
m;if(.005<k||-.005>k)if(e<c&&(f-=k),Ea(h.line,m),jf(h.line),h.rest)for(m=0;m<h.rest.length;m++)jf(h.rest[m]);l>a.display.sizerWidth&&(l=Math.ceil(l/ub(a.display)),l>a.display.maxLineLength&&(a.display.maxLineLength=l,a.display.maxLine=h.line,a.display.maxLineChanged=!0))}}2<Math.abs(f)&&(b.scroller.scrollTop+=f)}function jf(a){if(a.widgets)for(var b=0;b<a.widgets.length;++b){var d=a.widgets[b],c=d.node.parentNode;c&&(d.height=c.offsetHeight)}}function Mc(a,b,d){var c=d&&null!=d.top?Math.max(0,d.top):
a.scroller.scrollTop;c=Math.floor(c-a.lineSpace.offsetTop);var e=d&&null!=d.bottom?d.bottom:c+a.wrapper.clientHeight;c=bb(b,c);e=bb(b,e);if(d&&d.ensure){var f=d.ensure.from.line;d=d.ensure.to.line;f<c?(c=f,e=bb(b,Ga(w(b,f))+a.wrapper.clientHeight)):Math.min(d,b.lastLine())>=e&&(c=bb(b,Ga(w(b,d))-a.wrapper.clientHeight),e=d)}return{from:c,to:Math.max(e,c+1)}}function Td(a,b){var d=a.display,c=vb(a.display);0>b.top&&(b.top=0);var e=a.curOp&&null!=a.curOp.scrollTop?a.curOp.scrollTop:d.scroller.scrollTop,
f=Ed(a),g={};b.bottom-b.top>f&&(b.bottom=b.top+f);var h=a.doc.height+Dd(d),k=b.top<c;c=b.bottom>h-c;b.top<e?g.scrollTop=k?0:b.top:b.bottom>e+f&&(f=Math.min(b.top,(c?h:b.bottom)-f),f!=e&&(g.scrollTop=f));e=a.options.fixedGutter?0:d.gutters.offsetWidth;f=a.curOp&&null!=a.curOp.scrollLeft?a.curOp.scrollLeft:d.scroller.scrollLeft-e;a=cb(a)-d.gutters.offsetWidth;if(d=b.right-b.left>a)b.right=b.left+a;10>b.left?g.scrollLeft=0:b.left<f?g.scrollLeft=Math.max(0,b.left+e-(d?0:10)):b.right>a+f-3&&(g.scrollLeft=
b.right+(d?0:10)-a);return g}function Nc(a,b){null!=b&&(Oc(a),a.curOp.scrollTop=(null==a.curOp.scrollTop?a.doc.scrollTop:a.curOp.scrollTop)+b)}function xb(a){Oc(a);var b=a.getCursor();a.curOp.scrollToPos={from:b,to:b,margin:a.options.cursorScrollMargin}}function Wb(a,b,d){null==b&&null==d||Oc(a);null!=b&&(a.curOp.scrollLeft=b);null!=d&&(a.curOp.scrollTop=d)}function Oc(a){var b=a.curOp.scrollToPos;if(b){a.curOp.scrollToPos=null;var d=bf(a,b.from),c=bf(a,b.to);kf(a,d,c,b.margin)}}function kf(a,b,d,
c){b=Td(a,{left:Math.min(b.left,d.left),top:Math.min(b.top,d.top)-c,right:Math.max(b.right,d.right),bottom:Math.max(b.bottom,d.bottom)+c});Wb(a,b.scrollLeft,b.scrollTop)}function Xb(a,b){2>Math.abs(a.doc.scrollTop-b)||(Ma||Ud(a,{top:b}),lf(a,b,!0),Ma&&Ud(a),Yb(a,100))}function lf(a,b,d){b=Math.max(0,Math.min(a.display.scroller.scrollHeight-a.display.scroller.clientHeight,b));if(a.display.scroller.scrollTop!=b||d)a.doc.scrollTop=b,a.display.scrollbars.setScrollTop(b),a.display.scroller.scrollTop!=
b&&(a.display.scroller.scrollTop=b)}function kb(a,b,d,c){b=Math.max(0,Math.min(b,a.display.scroller.scrollWidth-a.display.scroller.clientWidth));(d?b==a.doc.scrollLeft:2>Math.abs(a.doc.scrollLeft-b))&&!c||(a.doc.scrollLeft=b,mf(a),a.display.scroller.scrollLeft!=b&&(a.display.scroller.scrollLeft=b),a.display.scrollbars.setScrollLeft(b))}function Zb(a){var b=a.display,d=b.gutters.offsetWidth,c=Math.round(a.doc.height+Dd(a.display));return{clientHeight:b.scroller.clientHeight,viewHeight:b.wrapper.clientHeight,
scrollWidth:b.scroller.scrollWidth,clientWidth:b.scroller.clientWidth,viewWidth:b.wrapper.clientWidth,barLeft:a.options.fixedGutter?d:0,docHeight:c,scrollHeight:c+Ha(a)+b.barHeight,nativeBarWidth:b.nativeBarWidth,gutterWidth:d}}function yb(a,b){b||(b=Zb(a));var d=a.display.barWidth,c=a.display.barHeight;nf(a,b);for(b=0;4>b&&d!=a.display.barWidth||c!=a.display.barHeight;b++)d!=a.display.barWidth&&a.options.lineWrapping&&Lc(a),nf(a,Zb(a)),d=a.display.barWidth,c=a.display.barHeight}function nf(a,b){var d=
a.display,c=d.scrollbars.update(b);d.sizer.style.paddingRight=(d.barWidth=c.right)+"px";d.sizer.style.paddingBottom=(d.barHeight=c.bottom)+"px";d.heightForcer.style.borderBottom=c.bottom+"px solid transparent";c.right&&c.bottom?(d.scrollbarFiller.style.display="block",d.scrollbarFiller.style.height=c.bottom+"px",d.scrollbarFiller.style.width=c.right+"px"):d.scrollbarFiller.style.display="";c.bottom&&a.options.coverGutterNextToScrollbar&&a.options.fixedGutter?(d.gutterFiller.style.display="block",
d.gutterFiller.style.height=c.bottom+"px",d.gutterFiller.style.width=b.gutterWidth+"px"):d.gutterFiller.style.display=""}function of(a){a.display.scrollbars&&(a.display.scrollbars.clear(),a.display.scrollbars.addClass&&jb(a.display.wrapper,a.display.scrollbars.addClass));a.display.scrollbars=new pf[a.options.scrollbarStyle](function(b){a.display.wrapper.insertBefore(b,a.display.scrollbarFiller);z(b,"mousedown",function(){a.state.focused&&setTimeout(function(){return a.display.input.focus()},0)});
b.setAttribute("cm-not-content","true")},function(b,d){"horizontal"==d?kb(a,b):Xb(a,b)},a);a.display.scrollbars.addClass&&Ya(a.display.wrapper,a.display.scrollbars.addClass)}function lb(a){a.curOp={cm:a,viewChanged:!1,startHeight:a.doc.height,forceUpdate:!1,updateInput:0,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++Ug,markArrays:null};a=a.curOp;tb?tb.ops.push(a):a.ownsGroup=
tb={ops:[a],delayedCallbacks:[]}}function mb(a){(a=a.curOp)&&Ng(a,function(b){for(var d=0;d<b.ops.length;d++)b.ops[d].cm.curOp=null;b=b.ops;for(d=0;d<b.length;d++){var c=b[d],e=c.cm,f=e.display,g=e.display;!g.scrollbarsClipped&&g.scroller.offsetWidth&&(g.nativeBarWidth=g.scroller.offsetWidth-g.scroller.clientWidth,g.heightForcer.style.height=Ha(e)+"px",g.sizer.style.marginBottom=-g.nativeBarWidth+"px",g.sizer.style.borderRightWidth=Ha(e)+"px",g.scrollbarsClipped=!0);c.updateMaxLine&&zd(e);c.mustUpdate=
c.viewChanged||c.forceUpdate||null!=c.scrollTop||c.scrollToPos&&(c.scrollToPos.from.line<f.viewFrom||c.scrollToPos.to.line>=f.viewTo)||f.maxLineChanged&&e.options.lineWrapping;c.update=c.mustUpdate&&new Pc(e,c.mustUpdate&&{top:c.scrollTop,ensure:c.scrollToPos},c.forceUpdate)}for(d=0;d<b.length;d++)c=b[d],c.updatedDisplay=c.mustUpdate&&Vd(c.cm,c.update);for(d=0;d<b.length;d++)if(c=b[d],e=c.cm,f=e.display,c.updatedDisplay&&Lc(e),c.barMeasure=Zb(e),f.maxLineChanged&&!e.options.lineWrapping&&(g=f.maxLine.text.length,
g=Aa(e,eb(e,f.maxLine),g,void 0),c.adjustWidthTo=g.left+3,e.display.sizerWidth=c.adjustWidthTo,c.barMeasure.scrollWidth=Math.max(f.scroller.clientWidth,f.sizer.offsetLeft+c.adjustWidthTo+Ha(e)+e.display.barWidth),c.maxScrollLeft=Math.max(0,f.sizer.offsetLeft+c.adjustWidthTo-cb(e))),c.updatedDisplay||c.selectionChanged)c.preparedSelection=f.input.prepareSelection();for(d=0;d<b.length;d++)c=b[d],e=c.cm,null!=c.adjustWidthTo&&(e.display.sizer.style.minWidth=c.adjustWidthTo+"px",c.maxScrollLeft<e.doc.scrollLeft&&
kb(e,Math.min(e.display.scroller.scrollLeft,c.maxScrollLeft),!0),e.display.maxLineChanged=!1),f=c.focus&&c.focus==ka(qa(e)),c.preparedSelection&&e.display.input.showSelection(c.preparedSelection,f),(c.updatedDisplay||c.startHeight!=e.doc.height)&&yb(e,c.barMeasure),c.updatedDisplay&&Wd(e,c.barMeasure),c.selectionChanged&&Qd(e),e.state.focused&&c.updateInput&&e.display.input.reset(c.typing),f&&hf(c.cm);for(d=0;d<b.length;d++){var h=void 0;c=b[d];e=c.cm;f=e.display;g=e.doc;c.updatedDisplay&&qf(e,c.update);
null==f.wheelStartX||null==c.scrollTop&&null==c.scrollLeft&&!c.scrollToPos||(f.wheelStartX=f.wheelStartY=null);null!=c.scrollTop&&lf(e,c.scrollTop,c.forceScroll);null!=c.scrollLeft&&kb(e,c.scrollLeft,!0,!0);if(c.scrollToPos){var k=C(g,c.scrollToPos.from);var l=C(g,c.scrollToPos.to);var m=c.scrollToPos.margin;null==m&&(m=0);e.options.lineWrapping||k!=l||(l="before"==k.sticky?t(k.line,k.ch+1,"before"):k,k=k.ch?t(k.line,"before"==k.sticky?k.ch-1:k.ch,"after"):k);for(var n=0;5>n;n++){var p=!1;h=Ba(e,
k);var q=l&&l!=k?Ba(e,l):h;h={left:Math.min(h.left,q.left),top:Math.min(h.top,q.top)-m,right:Math.max(h.left,q.left),bottom:Math.max(h.bottom,q.bottom)+m};q=Td(e,h);var r=e.doc.scrollTop,u=e.doc.scrollLeft;null!=q.scrollTop&&(Xb(e,q.scrollTop),1<Math.abs(e.doc.scrollTop-r)&&(p=!0));null!=q.scrollLeft&&(kb(e,q.scrollLeft),1<Math.abs(e.doc.scrollLeft-u)&&(p=!0));if(!p)break}l=h;Z(e,"scrollCursorIntoView")||(m=e.display,n=m.sizer.getBoundingClientRect(),k=null,p=m.wrapper.ownerDocument,0>l.top+n.top?
k=!0:l.bottom+n.top>(p.defaultView.innerHeight||p.documentElement.clientHeight)&&(k=!1),null==k||Vg||(l=v("div","\u200b",null,"position: absolute;\n top: "+(l.top-m.viewOffset-e.display.lineSpace.offsetTop)+"px;\n height: "+(l.bottom-l.top+Ha(e)+m.barHeight)+"px;\n left: "+l.left+"px; width: "+Math.max(2,l.right-l.left)+"px;"),e.display.lineSpace.appendChild(l),l.scrollIntoView(k),e.display.lineSpace.removeChild(l)))}l=c.maybeHiddenMarkers;
k=c.maybeUnhiddenMarkers;if(l)for(m=0;m<l.length;++m)l[m].lines.length||W(l[m],"hide");if(k)for(l=0;l<k.length;++l)k[l].lines.length&&W(k[l],"unhide");f.wrapper.offsetHeight&&(g.scrollTop=e.display.scroller.scrollTop);c.changeObjs&&W(e,"changes",e,c.changeObjs);c.update&&c.update.finish()}})}function ra(a,b){if(a.curOp)return b();lb(a);try{return b()}finally{mb(a)}}function ba(a,b){return function(){if(a.curOp)return b.apply(a,arguments);lb(a);try{return b.apply(a,arguments)}finally{mb(a)}}}function ia(a){return function(){if(this.curOp)return a.apply(this,
arguments);lb(this);try{return a.apply(this,arguments)}finally{mb(this)}}}function ca(a){return function(){var b=this.cm;if(!b||b.curOp)return a.apply(this,arguments);lb(b);try{return a.apply(this,arguments)}finally{mb(b)}}}function Yb(a,b){a.doc.highlightFrontier<a.display.viewTo&&a.state.highlight.set(b,gd(Wg,a))}function Wg(a){var b=a.doc;if(!(b.highlightFrontier>=a.display.viewTo)){var d=+new Date+a.options.workTime,c=Ob(a,b.highlightFrontier),e=[];b.iter(c.line,Math.min(b.first+b.size,a.display.viewTo+
500),function(f){if(c.line>=a.display.viewFrom){var g=f.styles,h=f.text.length>a.options.maxHighlightLength?$a(b.mode,c.state):null,k=ye(a,f,c,!0);h&&(c.state=h);f.styles=k.styles;h=f.styleClasses;(k=k.classes)?f.styleClasses=k:h&&(f.styleClasses=null);k=!g||g.length!=f.styles.length||h!=k&&(!h||!k||h.bgClass!=k.bgClass||h.textClass!=k.textClass);for(h=0;!k&&h<g.length;++h)k=g[h]!=f.styles[h];k&&e.push(c.line);f.stateAfter=c.save()}else f.text.length<=a.options.maxHighlightLength&&td(a,f.text,c),
f.stateAfter=0==c.line%5?c.save():null;c.nextLine();if(+new Date>d)return Yb(a,a.options.workDelay),!0});b.highlightFrontier=c.line;b.modeFrontier=Math.max(b.modeFrontier,c.line);e.length&&ra(a,function(){for(var f=0;f<e.length;f++)Sa(a,e[f],"text")})}}function Vd(a,b){var d=a.display,c=a.doc;if(b.editorIsHidden)return Ra(a),!1;if(!b.force&&b.visible.from>=d.viewFrom&&b.visible.to<=d.viewTo&&(null==d.updateLineNumbers||d.updateLineNumbers>=d.viewTo)&&d.renderedView==d.view&&0==ff(a))return!1;rf(a)&&
(Ra(a),b.dims=Gd(a));var e=c.first+c.size,f=Math.max(b.visible.from-a.options.viewportMargin,c.first),g=Math.min(e,b.visible.to+a.options.viewportMargin);d.viewFrom<f&&20>f-d.viewFrom&&(f=Math.max(c.first,d.viewFrom));d.viewTo>g&&20>d.viewTo-g&&(g=Math.min(e,d.viewTo));Ka&&(f=xd(a.doc,f),g=Je(a.doc,g));c=f!=d.viewFrom||g!=d.viewTo||d.lastWrapHeight!=b.wrapperHeight||d.lastWrapWidth!=b.wrapperWidth;e=a.display;0==e.view.length||f>=e.viewTo||g<=e.viewFrom?(e.view=Fc(a,f,g),e.viewFrom=f):(e.viewFrom>
f?e.view=Fc(a,f,e.viewFrom).concat(e.view):e.viewFrom<f&&(e.view=e.view.slice(db(a,f))),e.viewFrom=f,e.viewTo<g?e.view=e.view.concat(Fc(a,e.viewTo,g)):e.viewTo>g&&(e.view=e.view.slice(0,db(a,g))));e.viewTo=g;d.viewOffset=Ga(w(a.doc,d.viewFrom));a.display.mover.style.top=d.viewOffset+"px";g=ff(a);if(!c&&0==g&&!b.force&&d.renderedView==d.view&&(null==d.updateLineNumbers||d.updateLineNumbers>=d.viewTo))return!1;a.hasFocus()?f=null:(f=ka(qa(a)))&&ja(a.display.lineDiv,f)?(f={activeElt:f},window.getSelection&&
(e=qa(a).defaultView.getSelection(),e.anchorNode&&e.extend&&ja(a.display.lineDiv,e.anchorNode)&&(f.anchorNode=e.anchorNode,f.anchorOffset=e.anchorOffset,f.focusNode=e.focusNode,f.focusOffset=e.focusOffset))):f=null;4<g&&(d.lineDiv.style.display="none");Xg(a,d.updateLineNumbers,b.dims);4<g&&(d.lineDiv.style.display="");d.renderedView=d.view;(g=f)&&g.activeElt&&g.activeElt!=ka(g.activeElt.ownerDocument)&&(g.activeElt.focus(),!/^(INPUT|TEXTAREA)$/.test(g.activeElt.nodeName)&&g.anchorNode&&ja(document.body,
g.anchorNode)&&ja(document.body,g.focusNode)&&(e=g.activeElt.ownerDocument,f=e.defaultView.getSelection(),e=e.createRange(),e.setEnd(g.anchorNode,g.anchorOffset),e.collapse(!1),f.removeAllRanges(),f.addRange(e),f.extend(g.focusNode,g.focusOffset)));E(d.cursorDiv);E(d.selectionDiv);d.gutters.style.height=d.sizer.style.minHeight=0;c&&(d.lastWrapHeight=b.wrapperHeight,d.lastWrapWidth=b.wrapperWidth,Yb(a,400));d.updateLineNumbers=null;return!0}function qf(a,b){for(var d=b.viewport,c=!0;;c=!1){if(c&&a.options.lineWrapping&&
b.oldDisplayWidth!=cb(a))c&&(b.visible=Mc(a.display,a.doc,d));else if(d&&null!=d.top&&(d={top:Math.min(a.doc.height+Dd(a.display)-Ed(a),d.top)}),b.visible=Mc(a.display,a.doc,d),b.visible.from>=a.display.viewFrom&&b.visible.to<=a.display.viewTo)break;if(!Vd(a,b))break;Lc(a);c=Zb(a);Vb(a);yb(a,c);Wd(a,c);b.force=!1}b.signal(a,"update",a);if(a.display.viewFrom!=a.display.reportedViewFrom||a.display.viewTo!=a.display.reportedViewTo)b.signal(a,"viewportChange",a,a.display.viewFrom,a.display.viewTo),a.display.reportedViewFrom=
a.display.viewFrom,a.display.reportedViewTo=a.display.viewTo}function Ud(a,b){b=new Pc(a,b);if(Vd(a,b)){Lc(a);qf(a,b);var d=Zb(a);Vb(a);yb(a,d);Wd(a,d);b.finish()}}function Xg(a,b,d){function c(p){var q=p.nextSibling;fa&&ya&&a.display.currentWheelTarget==p?p.style.display="none":p.parentNode.removeChild(p);return q}var e=a.display,f=a.options.lineNumbers,g=e.lineDiv,h=g.firstChild,k=e.view;e=e.viewFrom;for(var l=0;l<k.length;l++){var m=k[l];if(!m.hidden)if(m.node&&m.node.parentNode==g){for(;h!=m.node;)h=
c(h);h=f&&null!=b&&b<=e&&m.lineNumber;m.changes&&(-1<ea(m.changes,"gutter")&&(h=!1),Oe(a,m,e,d));h&&(E(m.lineNumber),m.lineNumber.appendChild(document.createTextNode(qd(a.options,e))));h=m.node.nextSibling}else{var n=Pg(a,m,e,d);g.insertBefore(n,h)}e+=m.size}for(;h;)h=c(h)}function Xd(a){a.sizer.style.marginLeft=a.gutters.offsetWidth+"px";aa(a,"gutterChanged",a)}function Wd(a,b){a.display.sizer.style.minHeight=b.docHeight+"px";a.display.heightForcer.style.top=b.docHeight+"px";a.display.gutters.style.height=
b.docHeight+a.display.barHeight+Ha(a)+"px"}function mf(a){var b=a.display,d=b.view;if(b.alignWidgets||b.gutters.firstChild&&a.options.fixedGutter){for(var c=Md(b)-b.scroller.scrollLeft+a.doc.scrollLeft,e=b.gutters.offsetWidth,f=c+"px",g=0;g<d.length;g++)if(!d[g].hidden){a.options.fixedGutter&&(d[g].gutter&&(d[g].gutter.style.left=f),d[g].gutterBackground&&(d[g].gutterBackground.style.left=f));var h=d[g].alignable;if(h)for(var k=0;k<h.length;k++)h[k].style.left=f}a.options.fixedGutter&&(b.gutters.style.left=
c+e+"px")}}function rf(a){if(!a.options.lineNumbers)return!1;var b=a.doc;b=qd(a.options,b.first+b.size-1);var d=a.display;if(b.length!=d.lineNumChars){var c=d.measure.appendChild(v("div",[v("div",b)],"CodeMirror-linenumber CodeMirror-gutter-elt")),e=c.firstChild.offsetWidth;c=c.offsetWidth-e;d.lineGutter.style.width="";d.lineNumInnerWidth=Math.max(e,d.lineGutter.offsetWidth-c)+1;d.lineNumWidth=d.lineNumInnerWidth+c;d.lineNumChars=d.lineNumInnerWidth?b.length:-1;d.lineGutter.style.width=d.lineNumWidth+
"px";Xd(a.display);return!0}return!1}function Yd(a,b){for(var d=[],c=!1,e=0;e<a.length;e++){var f=a[e],g=null;"string"!=typeof f&&(g=f.style,f=f.className);if("CodeMirror-linenumbers"==f)if(b)c=!0;else continue;d.push({className:f,style:g})}b&&!c&&d.push({className:"CodeMirror-linenumbers",style:null});return d}function sf(a){var b=a.gutters,d=a.gutterSpecs;E(b);a.lineGutter=null;for(var c=0;c<d.length;++c){var e=d[c],f=e.className;e=e.style;var g=b.appendChild(v("div",null,"CodeMirror-gutter "+f));
e&&(g.style.cssText=e);"CodeMirror-linenumbers"==f&&(a.lineGutter=g,g.style.width=(a.lineNumWidth||1)+"px")}b.style.display=d.length?"":"none";Xd(a)}function $b(a){sf(a.display);ma(a);mf(a)}function Yg(a,b,d,c){this.input=d;this.scrollbarFiller=v("div",null,"CodeMirror-scrollbar-filler");this.scrollbarFiller.setAttribute("cm-not-content","true");this.gutterFiller=v("div",null,"CodeMirror-gutter-filler");this.gutterFiller.setAttribute("cm-not-content","true");this.lineDiv=M("div",null,"CodeMirror-code");
this.selectionDiv=v("div",null,null,"position: relative; z-index: 1");this.cursorDiv=v("div",null,"CodeMirror-cursors");this.measure=v("div",null,"CodeMirror-measure");this.lineMeasure=v("div",null,"CodeMirror-measure");this.lineSpace=M("div",[this.measure,this.lineMeasure,this.selectionDiv,this.cursorDiv,this.lineDiv],null,"position: relative; outline: none");var e=M("div",[this.lineSpace],"CodeMirror-lines");this.mover=v("div",[e],null,"position: relative");this.sizer=v("div",[this.mover],"CodeMirror-sizer");
this.sizerWidth=null;this.heightForcer=v("div",null,null,"position: absolute; height: 50px; width: 1px;");this.gutters=v("div",null,"CodeMirror-gutters");this.lineGutter=null;this.scroller=v("div",[this.sizer,this.heightForcer,this.gutters],"CodeMirror-scroll");this.scroller.setAttribute("tabIndex","-1");this.wrapper=v("div",[this.scrollbarFiller,this.gutterFiller,this.scroller],"CodeMirror");Qa&&105<=tf&&(this.wrapper.style.clipPath="inset(0px)");this.wrapper.setAttribute("translate","no");G&&8>
T&&(this.gutters.style.zIndex=-1,this.scroller.style.paddingRight=0);fa||Ma&&ac||(this.scroller.draggable=!0);a&&(a.appendChild?a.appendChild(this.wrapper):a(this.wrapper));this.reportedViewFrom=this.reportedViewTo=this.viewFrom=this.viewTo=b.first;this.view=[];this.externalMeasured=this.renderedView=null;this.lastWrapHeight=this.lastWrapWidth=this.viewOffset=0;this.updateLineNumbers=null;this.nativeBarWidth=this.barHeight=this.barWidth=0;this.scrollbarsClipped=!1;this.lineNumWidth=this.lineNumInnerWidth=
this.lineNumChars=null;this.alignWidgets=!1;this.maxLine=this.cachedCharWidth=this.cachedTextHeight=this.cachedPaddingH=null;this.maxLineLength=0;this.maxLineChanged=!1;this.wheelDX=this.wheelDY=this.wheelStartX=this.wheelStartY=null;this.shift=!1;this.activeTouch=this.selForContextMenu=null;this.gutterSpecs=Yd(c.gutters,c.lineNumbers);sf(this);d.init(this)}function uf(a){var b=a.wheelDeltaX,d=a.wheelDeltaY;null==b&&a.detail&&a.axis==a.HORIZONTAL_AXIS&&(b=a.detail);null==d&&a.detail&&a.axis==a.VERTICAL_AXIS?
d=a.detail:null==d&&(d=a.wheelDelta);return{x:b,y:d}}function Zg(a){a=uf(a);a.x*=Na;a.y*=Na;return a}function vf(a,b){Qa&&102==tf&&(null==a.display.chromeScrollHack?a.display.sizer.style.pointerEvents="none":clearTimeout(a.display.chromeScrollHack),a.display.chromeScrollHack=setTimeout(function(){a.display.chromeScrollHack=null;a.display.sizer.style.pointerEvents=""},100));var d=uf(b),c=d.x;d=d.y;var e=Na;0===b.deltaMode&&(c=b.deltaX,d=b.deltaY,e=1);var f=a.display,g=f.scroller,h=g.scrollWidth>g.clientWidth,
k=g.scrollHeight>g.clientHeight;if(c&&h||d&&k){if(d&&ya&&fa){h=b.target;var l=f.view;a:for(;h!=g;h=h.parentNode)for(var m=0;m<l.length;m++)if(l[m].node==h){a.display.currentWheelTarget=h;break a}}!c||Ma||Ca||null==e?(d&&null!=e&&(e*=d,k=a.doc.scrollTop,h=k+f.wrapper.clientHeight,0>e?k=Math.max(0,k+e-50):h=Math.min(a.doc.height,h+e+50),Ud(a,{top:k,bottom:h})),20>Qc&&0!==b.deltaMode&&(null==f.wheelStartX?(f.wheelStartX=g.scrollLeft,f.wheelStartY=g.scrollTop,f.wheelDX=c,f.wheelDY=d,setTimeout(function(){if(null!=
f.wheelStartX){var n=g.scrollLeft-f.wheelStartX,p=g.scrollTop-f.wheelStartY;n=p&&f.wheelDY&&p/f.wheelDY||n&&f.wheelDX&&n/f.wheelDX;f.wheelStartX=f.wheelStartY=null;n&&(Na=(Na*Qc+n)/(Qc+1),++Qc)}},200)):(f.wheelDX+=c,f.wheelDY+=d))):(d&&k&&Xb(a,Math.max(0,g.scrollTop+d*e)),kb(a,Math.max(0,g.scrollLeft+c*e)),(!d||d&&k)&&la(b),f.wheelStartX=null)}}function Da(a,b,d){a=a&&a.options.selectionsMayTouch;d=b[d];b.sort(function(k,l){return B(k.from(),l.from())});d=ea(b,d);for(var c=1;c<b.length;c++){var e=
b[c],f=b[c-1],g=B(f.to(),e.from());if(a&&!e.empty()?0<g:0<=g){g=Bc(f.from(),e.from());var h=Ac(f.to(),e.to());e=f.empty()?e.from()==e.head:f.from()==f.head;c<=d&&--d;b.splice(--c,2,new I(e?h:g,e?g:h))}}return new va(b,d)}function Oa(a,b){return new va([new I(a,b||a)],0)}function Ta(a){return a.text?t(a.from.line+a.text.length-1,J(a.text).length+(1==a.text.length?a.from.ch:0)):a.to}function wf(a,b){if(0>B(a,b.from))return a;if(0>=B(a,b.to))return Ta(b);var d=a.line+b.text.length-(b.to.line-b.from.line)-
1,c=a.ch;a.line==b.to.line&&(c+=Ta(b).ch-b.to.ch);return t(d,c)}function Zd(a,b){for(var d=[],c=0;c<a.sel.ranges.length;c++){var e=a.sel.ranges[c];d.push(new I(wf(e.anchor,b),wf(e.head,b)))}return Da(a.cm,d,a.sel.primIndex)}function xf(a,b,d){return a.line==b.line?t(d.line,a.ch-b.ch+d.ch):t(d.line+(a.line-b.line),a.ch)}function $d(a){a.doc.mode=nd(a.options,a.doc.modeOption);bc(a)}function bc(a){a.doc.iter(function(b){b.stateAfter&&(b.stateAfter=null);b.styles&&(b.styles=null)});a.doc.modeFrontier=
a.doc.highlightFrontier=a.doc.first;Yb(a,100);a.state.modeGen++;a.curOp&&ma(a)}function yf(a,b){return 0==b.from.ch&&0==b.to.ch&&""==J(b.text)&&(!a.cm||a.cm.options.wholeLineUpdateBefore)}function ae(a,b,d,c){function e(r,u,A){r.text=u;r.stateAfter&&(r.stateAfter=null);r.styles&&(r.styles=null);null!=r.order&&(r.order=null);Ge(r);He(r,A);u=c?c(r):1;u!=r.height&&Ea(r,u);aa(r,"change",r,b)}function f(r,u){for(var A=[];r<u;++r)A.push(new zb(k[r],d?d[r]:null,c));return A}var g=b.from,h=b.to,k=b.text,
l=w(a,g.line),m=w(a,h.line),n=J(k),p=d?d[k.length-1]:null,q=h.line-g.line;b.full?(a.insert(0,f(0,k.length)),a.remove(k.length,a.size-k.length)):yf(a,b)?(h=f(0,k.length-1),e(m,m.text,p),q&&a.remove(g.line,q),h.length&&a.insert(g.line,h)):l==m?1==k.length?e(l,l.text.slice(0,g.ch)+n+l.text.slice(h.ch),p):(q=f(1,k.length-1),q.push(new zb(n+l.text.slice(h.ch),p,c)),e(l,l.text.slice(0,g.ch)+k[0],d?d[0]:null),a.insert(g.line+1,q)):1==k.length?(e(l,l.text.slice(0,g.ch)+k[0]+m.text.slice(h.ch),d?d[0]:null),
a.remove(g.line+1,q)):(e(l,l.text.slice(0,g.ch)+k[0],d?d[0]:null),e(m,n+m.text.slice(h.ch),p),p=f(1,k.length-1),1<q&&a.remove(g.line+1,q-1),a.insert(g.line+1,p));aa(a,"change",a,b)}function Ua(a,b,d){function c(e,f,g){if(e.linked)for(var h=0;h<e.linked.length;++h){var k=e.linked[h];if(k.doc!=f){var l=g&&k.sharedHist;if(!d||l)b(k.doc,l),c(k.doc,e,l)}}}c(a,null,!0)}function zf(a,b){if(b.cm)throw Error("This document is already in use.");a.doc=b;b.cm=a;Nd(a);$d(a);Af(a);a.options.direction=b.direction;
a.options.lineWrapping||zd(a);a.options.mode=b.modeOption;ma(a)}function Af(a){("rtl"==a.doc.direction?Ya:jb)(a.display.lineDiv,"CodeMirror-rtl")}function $g(a){ra(a,function(){Af(a);ma(a)})}function Rc(a){this.done=[];this.undone=[];this.undoDepth=a?a.undoDepth:Infinity;this.lastModTime=this.lastSelTime=0;this.lastOrigin=this.lastSelOrigin=this.lastOp=this.lastSelOp=null;this.generation=this.maxGeneration=a?a.maxGeneration:1}function be(a,b){var d={from:sd(b.from),to:Ta(b),text:ab(a,b.from,b.to)};
Bf(a,d,b.from.line,b.to.line+1);Ua(a,function(c){return Bf(c,d,b.from.line,b.to.line+1)},!0);return d}function Cf(a){for(;a.length;)if(J(a).ranges)a.pop();else break}function Df(a,b,d,c){var e=a.history;e.undone.length=0;var f=+new Date,g;if(g=e.lastOp==c||e.lastOrigin==b.origin&&b.origin&&("+"==b.origin.charAt(0)&&e.lastModTime>f-(a.cm?a.cm.options.historyEventDelay:500)||"*"==b.origin.charAt(0))){if(e.lastOp==c){Cf(e.done);var h=J(e.done)}else e.done.length&&!J(e.done).ranges?h=J(e.done):1<e.done.length&&
!e.done[e.done.length-2].ranges?(e.done.pop(),h=J(e.done)):h=void 0;g=h}if(g){var k=J(h.changes);0==B(b.from,b.to)&&0==B(b.from,k.to)?k.to=Ta(b):h.changes.push(be(a,b))}else for((h=J(e.done))&&h.ranges||Sc(a.sel,e.done),h={changes:[be(a,b)],generation:e.generation},e.done.push(h);e.done.length>e.undoDepth;)e.done.shift(),e.done[0].ranges||e.done.shift();e.done.push(d);e.generation=++e.maxGeneration;e.lastModTime=e.lastSelTime=f;e.lastOp=e.lastSelOp=c;e.lastOrigin=e.lastSelOrigin=b.origin;k||W(a,"historyAdded")}
function Sc(a,b){var d=J(b);d&&d.ranges&&d.equals(a)||b.push(a)}function Bf(a,b,d,c){var e=b["spans_"+a.id],f=0;a.iter(Math.max(a.first,d),Math.min(a.first+a.size,c),function(g){g.markedSpans&&((e||(e=b["spans_"+a.id]={}))[f]=g.markedSpans);++f})}function Ef(a,b){var d;if(d=b["spans_"+a.id]){for(var c=[],e=0;e<b.text.length;++e){var f=c,g=f.push;var h=void 0;var k=d[e];if(k){for(var l=0;l<k.length;++l)k[l].marker.explicitlyCleared?h||(h=k.slice(0,l)):h&&h.push(k[l]);h=h?h.length?h:null:k}else h=null;
g.call(f,h)}d=c}else d=null;a=vd(a,b);if(!d)return a;if(!a)return d;for(b=0;b<d.length;++b)if(c=d[b],e=a[b],c&&e)a:for(f=0;f<e.length;++f){g=e[f];for(h=0;h<c.length;++h)if(c[h].marker==g.marker)continue a;c.push(g)}else e&&(d[b]=e);return d}function Ab(a,b,d){for(var c=[],e=0;e<a.length;++e){var f=a[e];if(f.ranges)c.push(d?va.prototype.deepCopy.call(f):f);else{f=f.changes;var g=[];c.push({changes:g});for(var h=0;h<f.length;++h){var k=f[h],l;g.push({from:k.from,to:k.to,text:k.text});if(b)for(var m in k)(l=
m.match(/^spans_(\d+)$/))&&-1<ea(b,Number(l[1]))&&(J(g)[m]=k[m],delete k[m])}}}return c}function ce(a,b,d,c){return c?(a=a.anchor,d&&(c=0>B(b,a),c!=0>B(d,a)?(a=b,b=d):c!=0>B(b,d)&&(b=d)),new I(a,b)):new I(d||b,b)}function Tc(a,b,d,c,e){null==e&&(e=a.cm&&(a.cm.display.shift||a.extend));da(a,new va([ce(a.sel.primary(),b,d,e)],0),c)}function Ff(a,b,d){for(var c=[],e=a.cm&&(a.cm.display.shift||a.extend),f=0;f<a.sel.ranges.length;f++)c[f]=ce(a.sel.ranges[f],b[f],null,e);b=Da(a.cm,c,a.sel.primIndex);da(a,
b,d)}function de(a,b,d,c){var e=a.sel.ranges.slice(0);e[b]=d;da(a,Da(a.cm,e,a.sel.primIndex),c)}function ah(a,b,d){d={ranges:b.ranges,update:function(c){this.ranges=[];for(var e=0;e<c.length;e++)this.ranges[e]=new I(C(a,c[e].anchor),C(a,c[e].head))},origin:d&&d.origin};W(a,"beforeSelectionChange",a,d);a.cm&&W(a.cm,"beforeSelectionChange",a.cm,d);return d.ranges!=b.ranges?Da(a.cm,d.ranges,d.ranges.length-1):b}function Gf(a,b,d){var c=a.history.done,e=J(c);e&&e.ranges?(c[c.length-1]=b,Uc(a,b,d)):da(a,
b,d)}function da(a,b,d){Uc(a,b,d);b=a.sel;var c=a.cm?a.cm.curOp.id:NaN,e=a.history,f=d&&d.origin,g;if(!(g=c==e.lastSelOp)&&(g=f&&e.lastSelOrigin==f)&&!(g=e.lastModTime==e.lastSelTime&&e.lastOrigin==f)){g=J(e.done);var h=f.charAt(0);g="*"==h||"+"==h&&g.ranges.length==b.ranges.length&&g.somethingSelected()==b.somethingSelected()&&new Date-a.history.lastSelTime<=(a.cm?a.cm.options.historyEventDelay:500)}g?e.done[e.done.length-1]=b:Sc(b,e.done);e.lastSelTime=+new Date;e.lastSelOrigin=f;e.lastSelOp=c;
d&&!1!==d.clearRedo&&Cf(e.undone)}function Uc(a,b,d){if(xa(a,"beforeSelectionChange")||a.cm&&xa(a.cm,"beforeSelectionChange"))b=ah(a,b,d);var c=d&&d.bias||(0>B(b.primary().head,a.sel.primary().head)?-1:1);Hf(a,If(a,b,c,!0));d&&!1===d.scroll||!a.cm||"nocursor"==a.cm.getOption("readOnly")||xb(a.cm)}function Hf(a,b){b.equals(a.sel)||(a.sel=b,a.cm&&(a.cm.curOp.updateInput=1,a.cm.curOp.selectionChanged=!0,te(a.cm)),aa(a,"cursorActivity",a))}function Jf(a){Hf(a,If(a,a.sel,null,!1))}function If(a,b,d,c){for(var e,
f=0;f<b.ranges.length;f++){var g=b.ranges[f],h=b.ranges.length==a.sel.ranges.length&&a.sel.ranges[f],k=Vc(a,g.anchor,h&&h.anchor,d,c);h=g.head==g.anchor?k:Vc(a,g.head,h&&h.head,d,c);if(e||k!=g.anchor||h!=g.head)e||(e=b.ranges.slice(0,f)),e[f]=new I(k,h)}return e?Da(a.cm,e,b.primIndex):b}function Bb(a,b,d,c,e){var f=w(a,b.line);if(f.markedSpans)for(var g=0;g<f.markedSpans.length;++g){var h=f.markedSpans[g],k=h.marker,l="selectLeft"in k?!k.selectLeft:k.inclusiveLeft,m="selectRight"in k?!k.selectRight:
k.inclusiveRight;if((null==h.from||(l?h.from<=b.ch:h.from<b.ch))&&(null==h.to||(m?h.to>=b.ch:h.to>b.ch))){if(e&&(W(k,"beforeCursorEnter"),k.explicitlyCleared))if(f.markedSpans){--g;continue}else break;if(k.atomic){if(d){g=k.find(0>c?1:-1);h=void 0;if(0>c?m:l)g=Kf(a,g,-c,g&&g.line==b.line?f:null);if(g&&g.line==b.line&&(h=B(g,d))&&(0>c?0>h:0<h))return Bb(a,g,b,c,e)}d=k.find(0>c?-1:1);if(0>c?l:m)d=Kf(a,d,c,d.line==b.line?f:null);return d?Bb(a,d,b,c,e):null}}}return b}function Vc(a,b,d,c,e){c=c||1;b=
Bb(a,b,d,c,e)||!e&&Bb(a,b,d,c,!0)||Bb(a,b,d,-c,e)||!e&&Bb(a,b,d,-c,!0);return b?b:(a.cantEdit=!0,t(a.first,0))}function Kf(a,b,d,c){return 0>d&&0==b.ch?b.line>a.first?C(a,t(b.line-1)):null:0<d&&b.ch==(c||w(a,b.line)).text.length?b.line<a.first+a.size-1?t(b.line+1,0):null:new t(b.line,b.ch+d)}function Lf(a){a.setSelection(t(a.firstLine(),0),t(a.lastLine()),Ia)}function Mf(a,b,d){var c={canceled:!1,from:b.from,to:b.to,text:b.text,origin:b.origin,cancel:function(){return c.canceled=!0}};d&&(c.update=
function(e,f,g,h){e&&(c.from=C(a,e));f&&(c.to=C(a,f));g&&(c.text=g);void 0!==h&&(c.origin=h)});W(a,"beforeChange",a,c);a.cm&&W(a.cm,"beforeChange",a.cm,c);return c.canceled?(a.cm&&(a.cm.curOp.updateInput=2),null):{from:c.from,to:c.to,text:c.text,origin:c.origin}}function Cb(a,b,d){if(a.cm){if(!a.cm.curOp)return ba(a.cm,Cb)(a,b,d);if(a.cm.state.suppressEdits)return}if(xa(a,"beforeChange")||a.cm&&xa(a.cm,"beforeChange"))if(b=Mf(a,b,!0),!b)return;if(d=Nf&&!d&&Hg(a,b.from,b.to))for(var c=d.length-1;0<=
c;--c)Of(a,{from:d[c].from,to:d[c].to,text:c?[""]:b.text,origin:b.origin});else Of(a,b)}function Of(a,b){if(1!=b.text.length||""!=b.text[0]||0!=B(b.from,b.to)){var d=Zd(a,b);Df(a,b,d,a.cm?a.cm.curOp.id:NaN);cc(a,b,d,vd(a,b));var c=[];Ua(a,function(e,f){f||-1!=ea(c,e.history)||(Pf(e.history,b),c.push(e.history));cc(e,b,null,vd(e,b))})}}function Wc(a,b,d){var c=a.cm&&a.cm.state.suppressEdits;if(!c||d){for(var e=a.history,f,g=a.sel,h="undo"==b?e.done:e.undone,k="undo"==b?e.undone:e.done,l=0;l<h.length&&
(f=h[l],d?!f.ranges||f.equals(a.sel):f.ranges);l++);if(l!=h.length){for(e.lastOrigin=e.lastSelOrigin=null;;)if(f=h.pop(),f.ranges){Sc(f,k);if(d&&!f.equals(a.sel)){da(a,f,{clearRedo:!1});return}g=f}else{if(c){h.push(f);return}break}var m=[];Sc(g,k);k.push({changes:m,generation:e.generation});e.generation=f.generation||++e.maxGeneration;var n=xa(a,"beforeChange")||a.cm&&xa(a.cm,"beforeChange");d=function(p){var q=f.changes[p];q.origin=b;if(n&&!Mf(a,q,!1))return h.length=0,{};m.push(be(a,q));var r=p?
Zd(a,q):J(h);cc(a,q,r,Ef(a,q));!p&&a.cm&&a.cm.scrollIntoView({from:q.from,to:Ta(q)});var u=[];Ua(a,function(A,Y){Y||-1!=ea(u,A.history)||(Pf(A.history,q),u.push(A.history));cc(A,q,null,Ef(A,q))})};for(c=f.changes.length-1;0<=c;--c)if(e=d(c))return e.v}}}function Qf(a,b){if(0!=b&&(a.first+=b,a.sel=new va(wc(a.sel.ranges,function(e){return new I(t(e.anchor.line+b,e.anchor.ch),t(e.head.line+b,e.head.ch))}),a.sel.primIndex),a.cm)){ma(a.cm,a.first,a.first-b,b);for(var d=a.cm.display,c=d.viewFrom;c<d.viewTo;c++)Sa(a.cm,
c,"gutter")}}function cc(a,b,d,c){if(a.cm&&!a.cm.curOp)return ba(a.cm,cc)(a,b,d,c);if(b.to.line<a.first)Qf(a,b.text.length-1-(b.to.line-b.from.line));else if(!(b.from.line>a.lastLine())){if(b.from.line<a.first){var e=b.text.length-1-(a.first-b.from.line);Qf(a,e);b={from:t(a.first,0),to:t(b.to.line+e,b.to.ch),text:[J(b.text)],origin:b.origin}}e=a.lastLine();b.to.line>e&&(b={from:b.from,to:t(e,w(a,e).text.length),text:[b.text[0]],origin:b.origin});b.removed=ab(a,b.from,b.to);d||(d=Zd(a,b));a.cm?bh(a.cm,
b,c):ae(a,b,c);Uc(a,d,Ia);a.cantEdit&&Vc(a,t(a.firstLine(),0))&&(a.cantEdit=!1)}}function bh(a,b,d){var c=a.doc,e=a.display,f=b.from,g=b.to,h=!1,k=f.line;a.options.lineWrapping||(k=N(za(w(c,f.line))),c.iter(k,g.line+1,function(l){if(l==e.maxLine)return h=!0}));-1<c.sel.contains(b.from,b.to)&&te(a);ae(c,b,d,ef(a));a.options.lineWrapping||(c.iter(k,f.line+b.text.length,function(l){var m=Ec(l);m>e.maxLineLength&&(e.maxLine=l,e.maxLineLength=m,e.maxLineChanged=!0,h=!1)}),h&&(a.curOp.updateMaxLine=!0));
Gg(c,f.line);Yb(a,400);d=b.text.length-(g.line-f.line)-1;b.full?ma(a):f.line!=g.line||1!=b.text.length||yf(a.doc,b)?ma(a,f.line,g.line+1,d):Sa(a,f.line,"text");d=xa(a,"changes");if((c=xa(a,"change"))||d)b={from:f,to:g,text:b.text,removed:b.removed,origin:b.origin},c&&aa(a,"change",a,b),d&&(a.curOp.changeObjs||(a.curOp.changeObjs=[])).push(b);a.display.selForContextMenu=null}function Db(a,b,d,c,e){c||(c=d);0>B(c,d)&&(c=[c,d],d=c[0],c=c[1]);"string"==typeof b&&(b=a.splitLines(b));Cb(a,{from:d,to:c,
text:b,origin:e})}function Rf(a,b,d,c){d<a.line?a.line+=c:b<a.line&&(a.line=b,a.ch=0)}function Sf(a,b,d,c){for(var e=0;e<a.length;++e){var f=a[e],g=!0;if(f.ranges)for(f.copied||(f=a[e]=f.deepCopy(),f.copied=!0),g=0;g<f.ranges.length;g++)Rf(f.ranges[g].anchor,b,d,c),Rf(f.ranges[g].head,b,d,c);else{for(var h=0;h<f.changes.length;++h){var k=f.changes[h];if(d<k.from.line)k.from=t(k.from.line+c,k.from.ch),k.to=t(k.to.line+c,k.to.ch);else if(b<=k.to.line){g=!1;break}}g||(a.splice(0,e+1),e=0)}}}function Pf(a,
b){var d=b.from.line,c=b.to.line;b=b.text.length-(c-d)-1;Sf(a.done,d,c,b);Sf(a.undone,d,c,b)}function dc(a,b,d,c){var e=b,f=b;"number"==typeof b?f=w(a,Math.max(a.first,Math.min(b,a.first+a.size-1))):e=N(b);if(null==e)return null;c(f,e)&&a.cm&&Sa(a.cm,e,d);return f}function ec(a){this.lines=a;this.parent=null;for(var b=0,d=0;d<a.length;++d)a[d].parent=this,b+=a[d].height;this.height=b}function fc(a){this.children=a;for(var b=0,d=0,c=0;c<a.length;++c){var e=a[c];b+=e.chunkSize();d+=e.height;e.parent=
this}this.size=b;this.height=d;this.parent=null}function ch(a,b,d,c){var e=new gc(a,d,c),f=a.cm;f&&e.noHScroll&&(f.display.alignWidgets=!0);dc(a,b,"widget",function(g){var h=g.widgets||(g.widgets=[]);null==e.insertAt?h.push(e):h.splice(Math.min(h.length,Math.max(0,e.insertAt)),0,e);e.line=g;f&&!Pa(a,g)&&(h=Ga(g)<a.scrollTop,Ea(g,g.height+Tb(e)),h&&Nc(f,e.height),f.curOp.forceUpdate=!0);return!0});f&&aa(f,"lineWidgetAdded",f,e,"number"==typeof b?b:N(b));return e}function Eb(a,b,d,c,e){if(c&&c.shared)return dh(a,
b,d,c,e);if(a.cm&&!a.cm.curOp)return ba(a.cm,Eb)(a,b,d,c,e);var f=new Va(a,e);e=B(b,d);c&&Za(c,f,!1);if(0<e||0==e&&!1!==f.clearWhenEmpty)return f;f.replacedWith&&(f.collapsed=!0,f.widgetNode=M("span",[f.replacedWith],"CodeMirror-widget"),c.handleMouseEvents||f.widgetNode.setAttribute("cm-ignore-events","true"),c.insertLeft&&(f.widgetNode.insertLeft=!0));if(f.collapsed){if(Ie(a,b.line,b,d,f)||b.line!=d.line&&Ie(a,d.line,b,d,f))throw Error("Inserting collapsed marker partially overlapping an existing one");
Ka=!0}f.addToHistory&&Df(a,{from:b,to:d,origin:"markText"},a.sel,NaN);var g=b.line,h=a.cm,k;a.iter(g,d.line+1,function(l){h&&f.collapsed&&!h.options.lineWrapping&&za(l)==h.display.maxLine&&(k=!0);f.collapsed&&g!=b.line&&Ea(l,0);var m=new Dc(f,g==b.line?b.ch:null,g==d.line?d.ch:null),n=a.cm&&a.cm.curOp;(n=n&&window.WeakSet&&(n.markedSpans||(n.markedSpans=new WeakSet)))&&l.markedSpans&&n.has(l.markedSpans)?l.markedSpans.push(m):(l.markedSpans=l.markedSpans?l.markedSpans.concat([m]):[m],n&&n.add(l.markedSpans));
m.marker.attachLine(l);++g});f.collapsed&&a.iter(b.line,d.line+1,function(l){Pa(a,l)&&Ea(l,0)});f.clearOnEnter&&z(f,"beforeCursorEnter",function(){return f.clear()});f.readOnly&&(Nf=!0,(a.history.done.length||a.history.undone.length)&&a.clearHistory());f.collapsed&&(f.id=++Tf,f.atomic=!0);if(h){k&&(h.curOp.updateMaxLine=!0);if(f.collapsed)ma(h,b.line,d.line+1);else if(f.className||f.startStyle||f.endStyle||f.css||f.attributes||f.title)for(c=b.line;c<=d.line;c++)Sa(h,c,"text");f.atomic&&Jf(h.doc);
aa(h,"markerAdded",h,f)}return f}function dh(a,b,d,c,e){c=Za(c);c.shared=!1;var f=[Eb(a,b,d,c,e)],g=f[0],h=c.widgetNode;Ua(a,function(k){h&&(c.widgetNode=h.cloneNode(!0));f.push(Eb(k,C(k,b),C(k,d),c,e));for(var l=0;l<k.linked.length;++l)if(k.linked[l].isParent)return;g=J(f)});return new hc(f,g)}function Uf(a){return a.findMarks(t(a.first,0),a.clipPos(t(a.lastLine())),function(b){return b.parent})}function eh(a){for(var b=function(c){c=a[c];var e=[c.primary.doc];Ua(c.primary.doc,function(h){return e.push(h)});
for(var f=0;f<c.markers.length;f++){var g=c.markers[f];-1==ea(e,g.doc)&&(g.parent=null,c.markers.splice(f--,1))}},d=0;d<a.length;d++)b(d)}function fh(a){var b=this;Vf(b);if(!Z(b,a)&&!La(b.display,a)){la(a);G&&(Wf=+new Date);var d=gb(b,a,!0),c=a.dataTransfer.files;if(d&&!b.isReadOnly())if(c&&c.length&&window.FileReader&&window.File)for(var e=c.length,f=Array(e),g=0,h=function(){++g==e&&ba(b,function(){d=C(b.doc,d);var m={from:d,to:d,text:b.doc.splitLines(f.filter(function(n){return null!=n}).join(b.doc.lineSeparator())),
origin:"paste"};Cb(b.doc,m);Gf(b.doc,Oa(C(b.doc,d),C(b.doc,Ta(m))))})()},k=function(m,n){if(b.options.allowDropFileTypes&&-1==ea(b.options.allowDropFileTypes,m.type))h();else{var p=new FileReader;p.onerror=function(){return h()};p.onload=function(){var q=p.result;/[\x00-\x08\x0e-\x1f]{2}/.test(q)||(f[n]=q);h()};p.readAsText(m)}},l=0;l<c.length;l++)k(c[l],l);else if(b.state.draggingText&&-1<b.doc.sel.contains(d))b.state.draggingText(a),setTimeout(function(){return b.display.input.focus()},20);else try{if(k=
a.dataTransfer.getData("Text")){b.state.draggingText&&!b.state.draggingText.copy&&(l=b.listSelections());Uc(b.doc,Oa(d,d));if(l)for(c=0;c<l.length;++c)Db(b.doc,"",l[c].anchor,l[c].head,"drag");b.replaceSelection(k,"around","paste");b.display.input.focus()}}catch(m){}}}function Vf(a){a.display.dragCursor&&(a.display.lineSpace.removeChild(a.display.dragCursor),a.display.dragCursor=null)}function Xf(a){if(document.getElementsByClassName){for(var b=document.getElementsByClassName("CodeMirror"),d=[],c=
0;c<b.length;c++){var e=b[c].CodeMirror;e&&d.push(e)}d.length&&d[0].operation(function(){for(var f=0;f<d.length;f++)a(d[f])})}}function gh(){var a;z(window,"resize",function(){null==a&&(a=setTimeout(function(){a=null;Xf(hh)},100))});z(window,"blur",function(){return Xf(wb)})}function hh(a){var b=a.display;b.cachedCharWidth=b.cachedTextHeight=b.cachedPaddingH=null;b.scrollbarsClipped=!1;a.setSize()}function ih(a){var b=a.split(/-(?!$)/);a=b[b.length-1];for(var d,c,e,f,g=0;g<b.length-1;g++){var h=b[g];
if(/^(cmd|meta|m)$/i.test(h))f=!0;else if(/^a(lt)?$/i.test(h))d=!0;else if(/^(c|ctrl|control)$/i.test(h))c=!0;else if(/^s(hift)?$/i.test(h))e=!0;else throw Error("Unrecognized modifier name: "+h);}d&&(a="Alt-"+a);c&&(a="Ctrl-"+a);f&&(a="Cmd-"+a);e&&(a="Shift-"+a);return a}function jh(a){var b={},d;for(d in a)if(a.hasOwnProperty(d)){var c=a[d];if(!/^(name|fallthrough|(de|at)tach)$/.test(d)){if("..."!=c)for(var e=wc(d.split(" "),ih),f=0;f<e.length;f++){if(f==e.length-1){var g=e.join(" ");var h=c}else g=
e.slice(0,f+1).join(" "),h="...";var k=b[g];if(!k)b[g]=h;else if(k!=h)throw Error("Inconsistent bindings for "+g);}delete a[d]}}for(var l in b)a[l]=b[l];return a}function Fb(a,b,d,c){b=Xc(b);var e=b.call?b.call(a,c):b[a];if(!1===e)return"nothing";if("..."===e)return"multi";if(null!=e&&d(e))return"handled";if(b.fallthrough){if("[object Array]"!=Object.prototype.toString.call(b.fallthrough))return Fb(a,b.fallthrough,d,c);for(e=0;e<b.fallthrough.length;e++){var f=Fb(a,b.fallthrough[e],d,c);if(f)return f}}}
function Yf(a){a="string"==typeof a?a:Wa[a.keyCode];return"Ctrl"==a||"Alt"==a||"Shift"==a||"Mod"==a}function Zf(a,b,d){var c=a;b.altKey&&"Alt"!=c&&(a="Alt-"+a);($f?b.metaKey:b.ctrlKey)&&"Ctrl"!=c&&(a="Ctrl-"+a);($f?b.ctrlKey:b.metaKey)&&"Mod"!=c&&(a="Cmd-"+a);!d&&b.shiftKey&&"Shift"!=c&&(a="Shift-"+a);return a}function ag(a,b){if(Ca&&34==a.keyCode&&a["char"])return!1;var d=Wa[a.keyCode];if(null==d||a.altGraphKey)return!1;3==a.keyCode&&a.code&&(d=a.code);return Zf(d,a,b)}function Xc(a){return"string"==
typeof a?ic[a]:a}function Gb(a,b){for(var d=a.doc.sel.ranges,c=[],e=0;e<d.length;e++){for(var f=b(d[e]);c.length&&0>=B(f.from,J(c).to);){var g=c.pop();if(0>B(g.from,f.from)){f.from=g.from;break}}c.push(f)}ra(a,function(){for(var h=c.length-1;0<=h;h--)Db(a.doc,"",c[h].from,c[h].to,"+delete");xb(a)})}function ee(a,b,d){b=se(a.text,b+d,d);return 0>b||b>a.text.length?null:b}function fe(a,b,d){a=ee(a,b.ch,d);return null==a?null:new t(b.line,a,0>d?"after":"before")}function ge(a,b,d,c,e){if(a&&("rtl"==
b.doc.direction&&(e=-e),a=Ja(d,b.doc.direction))){a=0>e?J(a):a[0];var f=0>e==(1==a.level)?"after":"before";if(0<a.level||"rtl"==b.doc.direction){var g=eb(b,d);var h=0>e?d.text.length-1:0;var k=Aa(b,g,h).top;h=Jb(function(l){return Aa(b,g,l).top==k},0>e==(1==a.level)?a.from:a.to-1,h);"before"==f&&(h=ee(d,h,1))}else h=0>e?a.to:a.from;return new t(c,h,f)}return new t(c,0>e?d.text.length:0,0>e?"before":"after")}function kh(a,b,d,c){var e=Ja(b,a.doc.direction);if(!e)return fe(b,d,c);d.ch>=b.text.length?
(d.ch=b.text.length,d.sticky="before"):0>=d.ch&&(d.ch=0,d.sticky="after");var f=Kb(e,d.ch,d.sticky),g=e[f];if("ltr"==a.doc.direction&&0==g.level%2&&(0<c?g.to>d.ch:g.from<d.ch))return fe(b,d,c);var h=function(q,r){return ee(b,q instanceof t?q.ch:q,r)},k,l=function(q){if(!a.options.lineWrapping)return{begin:0,end:b.text.length};k=k||eb(a,b);return df(a,b,k,q)},m=l("before"==d.sticky?h(d,-1):d.ch);if("rtl"==a.doc.direction||1==g.level){var n=1==g.level==0>c,p=h(d,n?1:-1);if(null!=p&&(n?p<=g.to&&p<=m.end:
p>=g.from&&p>=m.begin))return new t(d.line,p,n?"before":"after")}g=function(q,r,u){for(var A=function(K,Q){return Q?new t(d.line,h(K,1),"before"):new t(d.line,K,"after")};0<=q&&q<e.length;q+=r){var Y=e[q],x=0<r==(1!=Y.level),P=x?u.begin:h(u.end,-1);if(Y.from<=P&&P<Y.to)return A(P,x);P=x?Y.from:h(Y.to,-1);if(u.begin<=P&&P<u.end)return A(P,x)}};if(f=g(f+c,c,m))return f;m=0<c?m.end:h(m.begin,-1);return null==m||0<c&&m==b.text.length||!(f=g(0<c?0:e.length-1,c,l(m)))?null:f}function bg(a,b){var d=w(a.doc,
b),c=za(d);c!=d&&(b=N(c));return ge(!0,a,c,b,1)}function cg(a,b){var d=bg(a,b.line),c=w(a.doc,d.line);a=Ja(c,a.doc.direction);return a&&0!=a[0].level?d:(c=Math.max(d.ch,c.text.search(/\S/)),t(d.line,b.line==d.line&&b.ch<=c&&b.ch?0:c,d.sticky))}function Yc(a,b,d){if("string"==typeof b&&(b=jc[b],!b))return!1;a.display.input.ensurePolled();var c=a.display.shift,e=!1;try{a.isReadOnly()&&(a.state.suppressEdits=!0),d&&(a.display.shift=!1),e=b(a)!=Zc}finally{a.display.shift=c,a.state.suppressEdits=!1}return e}
function kc(a,b,d,c){var e=a.state.keySeq;if(e){if(Yf(b))return"handled";/'$/.test(b)?a.state.keySeq=null:lh.set(50,function(){a.state.keySeq==e&&(a.state.keySeq=null,a.display.input.reset())});if(dg(a,e+" "+b,d,c))return!0}return dg(a,b,d,c)}function dg(a,b,d,c){a:{for(var e=0;e<a.state.keyMaps.length;e++){var f=Fb(b,a.state.keyMaps[e],c,a);if(f){c=f;break a}}c=a.options.extraKeys&&Fb(b,a.options.extraKeys,c,a)||Fb(b,a.options.keyMap,c,a)}"multi"==c&&(a.state.keySeq=b);"handled"==c&&aa(a,"keyHandled",
a,b,d);if("handled"==c||"multi"==c)la(d),Qd(a);return!!c}function eg(a,b){var d=ag(b,!0);return d?b.shiftKey&&!a.state.keySeq?kc(a,"Shift-"+d,b,function(c){return Yc(a,c,!0)})||kc(a,d,b,function(c){if("string"==typeof c?/^go[A-Z]/.test(c):c.motion)return Yc(a,c)}):kc(a,d,b,function(c){return Yc(a,c)}):!1}function mh(a,b,d){return kc(a,"'"+d+"'",b,function(c){return Yc(a,c,!0)})}function fg(a){if(!a.target||a.target==this.display.input.getField())if(this.curOp.focus=ka(qa(this)),!Z(this,a)){G&&11>
T&&27==a.keyCode&&(a.returnValue=!1);var b=a.keyCode;this.display.shift=16==b||a.shiftKey;var d=eg(this,a);Ca&&(he=d?b:null,!d&&88==b&&!nh&&(ya?a.metaKey:a.ctrlKey)&&this.replaceSelection("",null,"cut"));Ma&&!ya&&!d&&46==b&&a.shiftKey&&!a.ctrlKey&&document.execCommand&&document.execCommand("cut");18!=b||/\bCodeMirror-crosshair\b/.test(this.display.lineDiv.className)||oh(this)}}function oh(a){function b(c){18!=c.keyCode&&c.altKey||(jb(d,"CodeMirror-crosshair"),ta(document,"keyup",b),ta(document,"mouseover",
b))}var d=a.display.lineDiv;Ya(d,"CodeMirror-crosshair");z(document,"keyup",b);z(document,"mouseover",b)}function gg(a){16==a.keyCode&&(this.doc.sel.shift=!1);Z(this,a)}function hg(a){if(!(a.target&&a.target!=this.display.input.getField()||La(this.display,a)||Z(this,a)||a.ctrlKey&&!a.altKey||ya&&a.metaKey)){var b=a.keyCode,d=a.charCode;if(Ca&&b==he)he=null,la(a);else if(!Ca||a.which&&!(10>a.which)||!eg(this,a))if(b=String.fromCharCode(null==d?b:d),"\b"!=b&&!mh(this,a,b))this.display.input.onKeyPress(a)}}
function ph(a,b){var d=+new Date;if(lc&&lc.compare(d,a,b))return mc=lc=null,"triple";if(mc&&mc.compare(d,a,b))return lc=new ie(d,a,b),mc=null,"double";mc=new ie(d,a,b);lc=null;return"single"}function ig(a){var b=this.display;if(!(Z(this,a)||b.activeTouch&&b.input.supportsTouch()))if(b.input.ensurePolled(),b.shift=a.shiftKey,La(b,a))fa||(b.scroller.draggable=!1,setTimeout(function(){return b.scroller.draggable=!0},100));else if(!$c(this,a,"gutterClick",!0)){var d=gb(this,a),c=ve(a),e=d?ph(d,c):"single";
qa(this).defaultView.focus();1==c&&this.state.selectingText&&this.state.selectingText(a);if(!d||!qh(this,c,d,e,a))if(1==c)d?rh(this,d,e,a):(a.target||a.srcElement)==b.scroller&&la(a);else if(2==c)d&&Tc(this.doc,d),setTimeout(function(){return b.input.focus()},20);else if(3==c)if(je)this.display.input.onContextMenu(a);else Sd(this)}}function qh(a,b,d,c,e){var f="Click";"double"==c?f="Double"+f:"triple"==c&&(f="Triple"+f);return kc(a,Zf((1==b?"Left":2==b?"Middle":"Right")+f,e),e,function(g){"string"==
typeof g&&(g=jc[g]);if(!g)return!1;var h=!1;try{a.isReadOnly()&&(a.state.suppressEdits=!0),h=g(a,d)!=Zc}finally{a.state.suppressEdits=!1}return h})}function rh(a,b,d,c){G?setTimeout(gd(hf,a),0):a.curOp.focus=ka(qa(a));var e=a.getOption("configureMouse");e=e?e(a,d,c):{};null==e.unit&&(e.unit=(sh?c.shiftKey&&c.metaKey:c.altKey)?"rectangle":"single"==d?"char":"double"==d?"word":"line");if(null==e.extend||a.doc.extend)e.extend=a.doc.extend||c.shiftKey;null==e.addNew&&(e.addNew=ya?c.metaKey:c.ctrlKey);
null==e.moveOnDrag&&(e.moveOnDrag=!(ya?c.altKey:c.ctrlKey));var f=a.doc.sel,g;a.options.dragDrop&&th&&!a.isReadOnly()&&"single"==d&&-1<(g=f.contains(b))&&(0>B((g=f.ranges[g]).from(),b)||0<b.xRel)&&(0<B(g.to(),b)||0>b.xRel)?uh(a,c,b,e):vh(a,c,b,e)}function uh(a,b,d,c){var e=a.display,f=!1,g=ba(a,function(l){fa&&(e.scroller.draggable=!1);a.state.draggingText=!1;a.state.delayingBlurEvent&&(a.hasFocus()?a.state.delayingBlurEvent=!1:Sd(a));ta(e.wrapper.ownerDocument,"mouseup",g);ta(e.wrapper.ownerDocument,
"mousemove",h);ta(e.scroller,"dragstart",k);ta(e.scroller,"drop",g);f||(la(l),c.addNew||Tc(a.doc,d,null,null,c.extend),fa&&!ad||G&&9==T?setTimeout(function(){e.wrapper.ownerDocument.body.focus({preventScroll:!0});e.input.focus()},20):e.input.focus())}),h=function(l){f=f||10<=Math.abs(b.clientX-l.clientX)+Math.abs(b.clientY-l.clientY)},k=function(){return f=!0};fa&&(e.scroller.draggable=!0);a.state.draggingText=g;g.copy=!c.moveOnDrag;z(e.wrapper.ownerDocument,"mouseup",g);z(e.wrapper.ownerDocument,
"mousemove",h);z(e.scroller,"dragstart",k);z(e.scroller,"drop",g);a.state.delayingBlurEvent=!0;setTimeout(function(){return e.input.focus()},20);e.scroller.dragDrop&&e.scroller.dragDrop()}function jg(a,b,d){if("char"==d)return new I(b,b);if("word"==d)return a.findWordAt(b);if("line"==d)return new I(t(b.line,0),C(a.doc,t(b.line+1,0)));a=d(a,b);return new I(a.from,a.to)}function vh(a,b,d,c){function e(x){if(0!=B(q,x))if(q=x,"rectangle"==c.unit){var P=[],K=a.options.tabSize,Q=wa(w(k,d.line).text,d.ch,
K),S=wa(w(k,x.line).text,x.ch,K),F=Math.min(Q,S);Q=Math.max(Q,S);S=Math.min(d.line,x.line);for(var R=Math.min(a.lastLine(),Math.max(d.line,x.line));S<=R;S++){var H=w(k,S).text,L=hd(H,F,K);F==Q?P.push(new I(t(S,L),t(S,L))):H.length>L&&P.push(new I(t(S,L),t(S,hd(H,Q,K))))}P.length||P.push(new I(d,d));da(k,Da(a,l.ranges.slice(0,n).concat(P),n),{origin:"*mouse",scroll:!1});a.scrollIntoView(x)}else P=p,F=jg(a,x,c.unit),x=P.anchor,0<B(F.anchor,x)?(K=F.head,x=Bc(P.from(),F.anchor)):(K=F.anchor,x=Ac(P.to(),
F.head)),P=l.ranges.slice(0),P[n]=wh(a,new I(C(k,x),K)),da(k,Da(a,P,n),ke)}function f(x){var P=++u,K=gb(a,x,!0,"rectangle"==c.unit);if(K)if(0!=B(K,q)){a.curOp.focus=ka(qa(a));e(K);var Q=Mc(h,k);(K.line>=Q.to||K.line<Q.from)&&setTimeout(ba(a,function(){u==P&&f(x)}),150)}else{var S=x.clientY<r.top?-20:x.clientY>r.bottom?20:0;S&&setTimeout(ba(a,function(){u==P&&(h.scroller.scrollTop+=S,f(x))}),50)}}function g(x){a.state.selectingText=!1;u=Infinity;x&&(la(x),h.input.focus());ta(h.wrapper.ownerDocument,
"mousemove",A);ta(h.wrapper.ownerDocument,"mouseup",Y);k.history.lastSelOrigin=null}G&&Sd(a);var h=a.display,k=a.doc;la(b);var l=k.sel,m=l.ranges;if(c.addNew&&!c.extend){var n=k.sel.contains(d);var p=-1<n?m[n]:new I(d,d)}else p=k.sel.primary(),n=k.sel.primIndex;"rectangle"==c.unit?(c.addNew||(p=new I(d,d)),d=gb(a,b,!0,!0),n=-1):(b=jg(a,d,c.unit),p=c.extend?ce(p,b.anchor,b.head,c.extend):b);c.addNew?-1==n?(n=m.length,da(k,Da(a,m.concat([p]),n),{scroll:!1,origin:"*mouse"})):1<m.length&&m[n].empty()&&
"char"==c.unit&&!c.extend?(da(k,Da(a,m.slice(0,n).concat(m.slice(n+1)),0),{scroll:!1,origin:"*mouse"}),l=k.sel):de(k,n,p,ke):(n=0,da(k,new va([p],0),ke),l=k.sel);var q=d,r=h.wrapper.getBoundingClientRect(),u=0,A=ba(a,function(x){0!==x.buttons&&ve(x)?f(x):g(x)}),Y=ba(a,g);a.state.selectingText=Y;z(h.wrapper.ownerDocument,"mousemove",A);z(h.wrapper.ownerDocument,"mouseup",Y)}function wh(a,b){var d=b.anchor,c=b.head,e=w(a.doc,d.line);if(0==B(d,c)&&d.sticky==c.sticky)return b;e=Ja(e);if(!e)return b;var f=
Kb(e,d.ch,d.sticky),g=e[f];if(g.from!=d.ch&&g.to!=d.ch)return b;var h=f+(g.from==d.ch==(1!=g.level)?0:1);if(0==h||h==e.length)return b;c.line!=d.line?a=0<(c.line-d.line)*("ltr"==a.doc.direction?1:-1):(a=Kb(e,c.ch,c.sticky),f=a-f||(c.ch-d.ch)*(1==g.level?-1:1),a=a==h-1||a==h?0>f:0<f);e=e[h+(a?-1:0)];e=(h=a==(1==e.level))?e.from:e.to;h=h?"after":"before";return d.ch==e&&d.sticky==h?b:new I(new t(d.line,e,h),c)}function $c(a,b,d,c){if(b.touches){var e=b.touches[0].clientX;var f=b.touches[0].clientY}else try{e=
b.clientX,f=b.clientY}catch(k){return!1}if(e>=Math.floor(a.display.gutters.getBoundingClientRect().right))return!1;c&&la(b);c=a.display;var g=c.lineDiv.getBoundingClientRect();if(f>g.bottom||!xa(a,d))return ld(b);f-=g.top-c.viewOffset;for(g=0;g<a.display.gutterSpecs.length;++g){var h=c.gutters.childNodes[g];if(h&&h.getBoundingClientRect().right>=e)return e=bb(a.doc,f),W(a,d,a,e,a.display.gutterSpecs[g].className,b),ld(b)}}function kg(a,b){var d;(d=La(a.display,b))||(d=xa(a,"gutterContextMenu")?$c(a,
b,"gutterContextMenu",!1):!1);if(!d&&!Z(a,b,"contextmenu")&&!je)a.display.input.onContextMenu(b)}function lg(a){a.display.wrapper.className=a.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+a.options.theme.replace(/(^|\s)\s*/g," cm-s-");Ub(a)}function xh(a,b,d){!b!=!(d&&d!=Hb)&&(d=a.display.dragFunctions,b=b?z:ta,b(a.display.scroller,"dragstart",d.start),b(a.display.scroller,"dragenter",d.enter),b(a.display.scroller,"dragover",d.over),b(a.display.scroller,"dragleave",d.leave),b(a.display.scroller,
"drop",d.drop))}function yh(a){a.options.lineWrapping?(Ya(a.display.wrapper,"CodeMirror-wrap"),a.display.sizer.style.minWidth="",a.display.sizerWidth=null):(jb(a.display.wrapper,"CodeMirror-wrap"),zd(a));Nd(a);ma(a);Ub(a);setTimeout(function(){return yb(a)},100)}function U(a,b){var d=this;if(!(this instanceof U))return new U(a,b);this.options=b=b?Za(b):{};Za(mg,b,!1);var c=b.value;"string"==typeof c?c=new oa(c,b.mode,null,b.lineSeparator,b.direction):b.mode&&(c.modeOption=b.mode);this.doc=c;var e=
new U.inputStyles[b.inputStyle](this);a=this.display=new Yg(a,c,e,b);a.wrapper.CodeMirror=this;lg(this);b.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap");of(this);this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:-1,cutIncoming:-1,selectingText:!1,draggingText:!1,highlight:new Xa,keySeq:null,specialChars:null};b.autofocus&&!ac&&a.input.focus();G&&11>T&&setTimeout(function(){return d.display.input.reset(!0)},
20);zh(this);ng||(gh(),ng=!0);lb(this);this.curOp.forceUpdate=!0;zf(this,c);b.autofocus&&!ac||this.hasFocus()?setTimeout(function(){d.hasFocus()&&!d.state.focused&&Rd(d)},20):wb(this);for(var f in bd)if(bd.hasOwnProperty(f))bd[f](this,b[f],Hb);rf(this);b.finishInit&&b.finishInit(this);for(c=0;c<le.length;++c)le[c](this);mb(this);fa&&b.lineWrapping&&"optimizelegibility"==getComputedStyle(a.lineDiv).textRendering&&(a.lineDiv.style.textRendering="auto")}function zh(a){function b(){c.activeTouch&&(e=
setTimeout(function(){return c.activeTouch=null},1E3),f=c.activeTouch,f.end=+new Date)}function d(h,k){if(null==k.left)return!0;var l=k.left-h.left;h=k.top-h.top;return 400<l*l+h*h}var c=a.display;z(c.scroller,"mousedown",ba(a,ig));G&&11>T?z(c.scroller,"dblclick",ba(a,function(h){if(!Z(a,h)){var k=gb(a,h);!k||$c(a,h,"gutterClick",!0)||La(a.display,h)||(la(h),h=a.findWordAt(k),Tc(a.doc,h.anchor,h.head))}})):z(c.scroller,"dblclick",function(h){return Z(a,h)||la(h)});z(c.scroller,"contextmenu",function(h){return kg(a,
h)});z(c.input.getField(),"contextmenu",function(h){c.scroller.contains(h.target)||kg(a,h)});var e,f={end:0};z(c.scroller,"touchstart",function(h){var k;if(k=!Z(a,h))1!=h.touches.length?k=!1:(k=h.touches[0],k=1>=k.radiusX&&1>=k.radiusY),k=!k;k&&!$c(a,h,"gutterClick",!0)&&(c.input.ensurePolled(),clearTimeout(e),k=+new Date,c.activeTouch={start:k,moved:!1,prev:300>=k-f.end?f:null},1==h.touches.length&&(c.activeTouch.left=h.touches[0].pageX,c.activeTouch.top=h.touches[0].pageY))});z(c.scroller,"touchmove",
function(){c.activeTouch&&(c.activeTouch.moved=!0)});z(c.scroller,"touchend",function(h){var k=c.activeTouch;if(k&&!La(c,h)&&null!=k.left&&!k.moved&&300>new Date-k.start){var l=a.coordsChar(c.activeTouch,"page");k=!k.prev||d(k,k.prev)?new I(l,l):!k.prev.prev||d(k,k.prev.prev)?a.findWordAt(l):new I(t(l.line,0),C(a.doc,t(l.line+1,0)));a.setSelection(k.anchor,k.head);a.focus();la(h)}b()});z(c.scroller,"touchcancel",b);z(c.scroller,"scroll",function(){c.scroller.clientHeight&&(Xb(a,c.scroller.scrollTop),
kb(a,c.scroller.scrollLeft,!0),W(a,"scroll",a))});z(c.scroller,"mousewheel",function(h){return vf(a,h)});z(c.scroller,"DOMMouseScroll",function(h){return vf(a,h)});z(c.wrapper,"scroll",function(){return c.wrapper.scrollTop=c.wrapper.scrollLeft=0});c.dragFunctions={enter:function(h){Z(a,h)||Mb(h)},over:function(h){if(!Z(a,h)){var k=gb(a,h);if(k){var l=document.createDocumentFragment();Od(a,k,l);a.display.dragCursor||(a.display.dragCursor=v("div",null,"CodeMirror-cursors CodeMirror-dragcursors"),a.display.lineSpace.insertBefore(a.display.dragCursor,
a.display.cursorDiv));D(a.display.dragCursor,l)}Mb(h)}},start:function(h){if(G&&(!a.state.draggingText||100>+new Date-Wf))Mb(h);else if(!Z(a,h)&&!La(a.display,h)&&(h.dataTransfer.setData("Text",a.getSelection()),h.dataTransfer.effectAllowed="copyMove",h.dataTransfer.setDragImage&&!ad)){var k=v("img",null,null,"position: fixed; left: 0; top: 0;");k.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";Ca&&(k.width=k.height=1,a.display.wrapper.appendChild(k),k._top=k.offsetTop);
h.dataTransfer.setDragImage(k,0,0);Ca&&k.parentNode.removeChild(k)}},drop:ba(a,fh),leave:function(h){Z(a,h)||Vf(a)}};var g=c.input.getField();z(g,"keyup",function(h){return gg.call(a,h)});z(g,"keydown",ba(a,fg));z(g,"keypress",ba(a,hg));z(g,"focus",function(h){return Rd(a,h)});z(g,"blur",function(h){return wb(a,h)})}function nc(a,b,d,c){var e=a.doc,f;null==d&&(d="add");"smart"==d&&(e.mode.indent?f=Ob(a,b).state:d="prev");var g=a.options.tabSize,h=w(e,b),k=wa(h.text,null,g);h.stateAfter&&(h.stateAfter=
null);var l=h.text.match(/^\s*/)[0];if(!c&&!/\S/.test(h.text)){var m=0;d="not"}else if("smart"==d&&(m=e.mode.indent(f,h.text.slice(l.length),h.text),m==Zc||150<m)){if(!c)return;d="prev"}"prev"==d?m=b>e.first?wa(w(e,b-1).text,null,g):0:"add"==d?m=k+a.options.indentUnit:"subtract"==d?m=k-a.options.indentUnit:"number"==typeof d&&(m=k+d);m=Math.max(0,m);d="";c=0;if(a.options.indentWithTabs)for(a=Math.floor(m/g);a;--a)c+=g,d+="\t";c<m&&(d+=id(m-c));if(d!=l)return Db(e,d,t(b,0),t(b,l.length),"+input"),
h.stateAfter=null,!0;for(g=0;g<e.sel.ranges.length;g++)if(h=e.sel.ranges[g],h.head.line==b&&h.head.ch<l.length){b=t(b,l.length);de(e,g,new I(b,b));break}}function me(a,b,d,c,e){var f=a.doc;a.display.shift=!1;c||(c=f.sel);var g=+new Date-200,h="paste"==e||a.state.pasteIncoming>g,k=ne(b),l=null;if(h&&1<c.ranges.length)if(sa&&sa.text.join("\n")==b){if(0==c.ranges.length%sa.text.length){l=[];for(var m=0;m<sa.text.length;m++)l.push(f.splitLines(sa.text[m]))}}else k.length==c.ranges.length&&a.options.pasteLinesPerSelection&&
(l=wc(k,function(u){return[u]}));m=a.curOp.updateInput;for(var n=c.ranges.length-1;0<=n;n--){var p=c.ranges[n],q=p.from(),r=p.to();p.empty()&&(d&&0<d?q=t(q.line,q.ch-d):a.state.overwrite&&!h?r=t(r.line,Math.min(w(f,r.line).text.length,r.ch+J(k).length)):h&&sa&&sa.lineWise&&sa.text.join("\n")==k.join("\n")&&(q=r=t(q.line,0)));p={from:q,to:r,text:l?l[n%l.length]:k,origin:e||(h?"paste":a.state.cutIncoming>g?"cut":"+input")};Cb(a.doc,p);aa(a,"inputRead",a,p)}b&&!h&&og(a,b);xb(a);2>a.curOp.updateInput&&
(a.curOp.updateInput=m);a.curOp.typing=!0;a.state.pasteIncoming=a.state.cutIncoming=-1}function pg(a,b){var d=a.clipboardData&&a.clipboardData.getData("Text");if(d)return a.preventDefault(),b.isReadOnly()||b.options.disableInput||!b.hasFocus()||ra(b,function(){return me(b,d,0,null,"paste")}),!0}function og(a,b){if(a.options.electricChars&&a.options.smartIndent)for(var d=a.doc.sel,c=d.ranges.length-1;0<=c;c--){var e=d.ranges[c];if(!(100<e.head.ch||c&&d.ranges[c-1].head.line==e.head.line)){var f=a.getModeAt(e.head),
g=!1;if(f.electricChars)for(var h=0;h<f.electricChars.length;h++){if(-1<b.indexOf(f.electricChars.charAt(h))){g=nc(a,e.head.line,"smart");break}}else f.electricInput&&f.electricInput.test(w(a.doc,e.head.line).text.slice(0,e.head.ch))&&(g=nc(a,e.head.line,"smart"));g&&aa(a,"electricInput",a,e.head.line)}}}function qg(a){for(var b=[],d=[],c=0;c<a.doc.sel.ranges.length;c++){var e=a.doc.sel.ranges[c].head.line;e={anchor:t(e,0),head:t(e+1,0)};d.push(e);b.push(a.getRange(e.anchor,e.head))}return{text:b,
ranges:d}}function rg(a,b,d,c){a.setAttribute("autocorrect",d?"":"off");a.setAttribute("autocapitalize",c?"":"off");a.setAttribute("spellcheck",!!b)}function sg(){var a=v("textarea",null,null,"position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none"),b=v("div",[a],null,"overflow: hidden; position: relative; width: 3px; height: 0px;");fa?a.style.width="1000px":a.setAttribute("wrap","off");oc&&(a.style.border="1px solid black");rg(a);return b}function oe(a,
b,d,c,e){function f(u){if("codepoint"==c){var A=k.text.charCodeAt(b.ch+(0<d?0:-1));A=isNaN(A)?null:new t(b.line,Math.max(0,Math.min(k.text.length,b.ch+d*((0<d?55296<=A&&56320>A:56320<=A&&57343>A)?2:1))),-d)}else A=e?kh(a.cm,k,b,d):fe(k,b,d);if(null==A){if(u=!u)u=b.line+l,u<a.first||u>=a.first+a.size?u=!1:(b=new t(u,b.ch,b.sticky),u=k=w(a,u));if(u)b=ge(e,a.cm,k,b.line,l);else return!1}else b=A;return!0}var g=b,h=d,k=w(a,b.line),l=e&&"rtl"==a.direction?-d:d;if("char"==c||"codepoint"==c)f();else if("column"==
c)f(!0);else if("word"==c||"group"==c)for(var m=null,n="group"==c,p=a.cm&&a.cm.getHelper(b,"wordChars"),q=!0;!(0>d)||f(!q);q=!1){var r=k.text.charAt(b.ch)||"\n";r=xc(r,p)?"w":n&&"\n"==r?"n":!n||/\s/.test(r)?null:"p";!n||q||r||(r="s");if(m&&m!=r){0>d&&(d=1,f(),b.sticky="after");break}r&&(m=r);if(0<d&&!f(!q))break}h=Vc(a,b,g,h,!0);rd(g,h)&&(h.hitSide=!0);return h}function tg(a,b,d,c){var e=a.doc,f=b.left;if("page"==c){var g=Math.min(a.display.wrapper.clientHeight,qa(a).defaultView.innerHeight||e(a).documentElement.clientHeight);
g=Math.max(g-.5*vb(a.display),3);g=(0<d?b.bottom:b.top)+d*g}else"line"==c&&(g=0<d?b.bottom+3:b.top-3);for(;;){b=Kd(a,f,g);if(!b.outside)break;if(0>d?0>=g:g>=e.height){b.hitSide=!0;break}g+=5*d}return b}function ug(a,b){var d=Fd(a,b.line);if(!d||d.hidden)return null;var c=w(a.doc,b.line);d=Ue(d,c,b.line);a=Ja(c,a.doc.direction);c="left";a&&(c=Kb(a,b.ch)%2?"right":"left");b=Ve(d.map,b.ch,c);b.offset="right"==b.collapse?b.end:b.start;return b}function Ah(a){for(;a;a=a.parentNode)if(/CodeMirror-gutter-wrapper/.test(a.className))return!0;
return!1}function Ib(a,b){b&&(a.bad=!0);return a}function Bh(a,b,d,c,e){function f(q){return function(r){return r.id==q}}function g(){m&&(l+=n,p&&(l+=n),m=p=!1)}function h(q){q&&(g(),l+=q)}function k(q){if(1==q.nodeType){var r=q.getAttribute("cm-text");if(r)h(r);else{r=q.getAttribute("cm-marker");var u;if(r)q=a.findMarks(t(c,0),t(e+1,0),f(+r)),q.length&&(u=q[0].find(0))&&h(ab(a.doc,u.from,u.to).join(n));else if("false"!=q.getAttribute("contenteditable")&&(u=/^(pre|div|p|li|table|br)$/i.test(q.nodeName),
/^br$/i.test(q.nodeName)||0!=q.textContent.length)){u&&g();for(r=0;r<q.childNodes.length;r++)k(q.childNodes[r]);/^(pre|p)$/i.test(q.nodeName)&&(p=!0);u&&(m=!0)}}}else 3==q.nodeType&&h(q.nodeValue.replace(/\u200b/g,"").replace(/\u00a0/g," "))}for(var l="",m=!1,n=a.doc.lineSeparator(),p=!1;;){k(b);if(b==d)break;b=b.nextSibling;p=!1}return l}function cd(a,b,d){if(b==a.display.lineDiv){var c=a.display.lineDiv.childNodes[d];if(!c)return Ib(a.clipPos(t(a.display.viewTo-1)),!0);b=null;d=0}else for(c=b;;c=
c.parentNode){if(!c||c==a.display.lineDiv)return null;if(c.parentNode&&c.parentNode==a.display.lineDiv)break}for(var e=0;e<a.display.view.length;e++){var f=a.display.view[e];if(f.node==c)return Ch(f,b,d)}}function Ch(a,b,d){function c(m,n,p){for(var q=-1;q<(l?l.length:0);q++)for(var r=0>q?k.map:l[q],u=0;u<r.length;u+=3){var A=r[u+2];if(A==m||A==n){n=N(0>q?a.line:a.rest[q]);q=r[u]+p;if(0>p||A!=m)q=r[u+(p?1:0)];return t(n,q)}}}var e=a.text.firstChild,f=!1;if(!b||!ja(e,b))return Ib(t(N(a.line),0),!0);
if(b==e&&(f=!0,b=e.childNodes[d],d=0,!b))return d=a.rest?J(a.rest):a.line,Ib(t(N(d),d.text.length),f);var g=3==b.nodeType?b:null,h=b;g||1!=b.childNodes.length||3!=b.firstChild.nodeType||(g=b.firstChild,d&&(d=g.nodeValue.length));for(;h.parentNode!=e;)h=h.parentNode;var k=a.measure,l=k.maps;if(b=c(g,h,d))return Ib(b,f);e=h.nextSibling;for(g=g?g.nodeValue.length-d:0;e;e=e.nextSibling){if(b=c(e,e.firstChild,0))return Ib(t(b.line,b.ch-g),f);g+=e.textContent.length}for(h=h.previousSibling;h;h=h.previousSibling){if(b=
c(h,h.firstChild,-1))return Ib(t(b.line,b.ch+d),f);d+=h.textContent.length}}var pa=navigator.userAgent,vg=navigator.platform,Ma=/gecko\/\d/i.test(pa),wg=/MSIE \d/.test(pa),xg=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(pa),dd=/Edge\/(\d+)/.exec(pa),G=wg||xg||dd,T=G&&(wg?document.documentMode||6:+(dd||xg)[1]),fa=!dd&&/WebKit\//.test(pa),Dh=fa&&/Qt\/\d+\.\d+/.test(pa),Qa=!dd&&/Chrome\/(\d+)/.exec(pa),tf=Qa&&+Qa[1],Ca=/Opera\//.test(pa),ad=/Apple Computer/.test(navigator.vendor),Eh=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(pa),
Vg=/PhantomJS/.test(pa),oc=ad&&(/Mobile\/\w+/.test(pa)||2<navigator.maxTouchPoints),Gc=/Android/.test(pa),ac=oc||Gc||/webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(pa),ya=oc||/Mac/.test(vg),sh=/\bCrOS\b/.test(pa),Fh=/win/i.test(vg),nb=Ca&&pa.match(/Version\/(\d*\.\d*)/);nb&&(nb=Number(nb[1]));nb&&15<=nb&&(Ca=!1,fa=!0);var $f=ya&&(Dh||Ca&&(null==nb||12.11>nb)),je=Ma||G&&9<=T,jb=function(a,b){var d=a.className;if(b=y(b).exec(d)){var c=d.slice(b.index+b[0].length);a.className=d.slice(0,b.index)+
(c?b[1]+c:"")}};var Qb=document.createRange?function(a,b,d,c){var e=document.createRange();e.setEnd(c||a,d);e.setStart(a,b);return e}:function(a,b,d){var c=document.body.createTextRange();try{c.moveToElementText(a.parentNode)}catch(e){return c}c.collapse(!0);c.moveEnd("character",d);c.moveStart("character",b);return c};var pc=function(a){a.select()};oc?pc=function(a){a.selectionStart=0;a.selectionEnd=a.value.length}:G&&(pc=function(a){try{a.select()}catch(b){}});var Xa=function(){this.f=this.id=null;
this.time=0;this.handler=gd(this.onTimeout,this)};Xa.prototype.onTimeout=function(a){a.id=0;a.time<=+new Date?a.f():setTimeout(a.handler,a.time-+new Date)};Xa.prototype.set=function(a,b){this.f=b;b=+new Date+a;if(!this.id||b<this.time)clearTimeout(this.id),this.id=setTimeout(this.handler,a),this.time=b};var Zc={toString:function(){return"CodeMirror.Pass"}},Ia={scroll:!1},ke={origin:"*mouse"},qc={origin:"+move"},vc=[""],zg=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,
Ag=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/,
Lb=null,Cg=function(){function a(g,h,k){this.level=g;this.from=h;this.to=k}var b=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,d=/[stwN]/,c=/[LRr]/,e=/[Lb1n]/,f=/[1n]/;return function(g,h){var k="ltr"==h?"L":"R";if(0==g.length||"ltr"==h&&!b.test(g))return!1;for(var l=g.length,m=[],n=0;n<l;++n){var p=m,q=p.push;var r=g.charCodeAt(n);r=247>=r?"bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN".charAt(r):
1424<=r&&1524>=r?"R":1536<=r&&1785>=r?"nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111".charAt(r-1536):1774<=r&&2220>=r?"r":8192<=r&&8203>=r?"w":8204==r?"b":"L";q.call(p,r)}n=0;for(p=k;n<l;++n)q=m[n],"m"==q?m[n]=p:p=q;n=0;for(p=k;n<l;++n)q=m[n],"1"==q&&"r"==p?m[n]="n":c.test(q)&&(p=q,"r"==q&&(m[n]=
"R"));n=1;for(p=m[0];n<l-1;++n)q=m[n],"+"==q&&"1"==p&&"1"==m[n+1]?m[n]="1":","!=q||p!=m[n+1]||"1"!=p&&"n"!=p||(m[n]=p),p=q;for(n=0;n<l;++n)if(p=m[n],","==p)m[n]="N";else if("%"==p){for(p=n+1;p<l&&"%"==m[p];++p);for(q=n&&"!"==m[n-1]||p<l&&"1"==m[p]?"1":"N";n<p;++n)m[n]=q;n=p-1}n=0;for(p=k;n<l;++n)q=m[n],"L"==p&&"1"==q?m[n]="L":c.test(q)&&(p=q);for(p=0;p<l;++p)if(d.test(m[p])){for(n=p+1;n<l&&d.test(m[n]);++n);q="L"==(p?m[p-1]:k);for(q=q==("L"==(n<l?m[n]:k))?q?"L":"R":k;p<n;++p)m[p]=q;p=n-1}k=[];var u;
for(n=0;n<l;)if(e.test(m[n])){p=n;for(++n;n<l&&e.test(m[n]);++n);k.push(new a(0,p,n))}else{var A=n;p=k.length;q="rtl"==h?1:0;for(++n;n<l&&"L"!=m[n];++n);for(r=A;r<n;)if(f.test(m[r])){A<r&&(k.splice(p,0,new a(1,A,r)),p+=q);A=r;for(++r;r<n&&f.test(m[r]);++r);k.splice(p,0,new a(2,A,r));p+=q;A=r}else++r;A<n&&k.splice(p,0,new a(1,A,n))}"ltr"==h&&(1==k[0].level&&(u=g.match(/^\s+/))&&(k[0].from=u[0].length,k.unshift(new a(0,0,u[0].length))),1==J(k).level&&(u=g.match(/\s+$/))&&(J(k).to-=u[0].length,k.push(new a(0,
l-u[0].length,l))));return"rtl"==h?k.reverse():k}}(),yc=[],z=function(a,b,d){a.addEventListener?a.addEventListener(b,d,!1):a.attachEvent?a.attachEvent("on"+b,d):(a=a._handlers||(a._handlers={}),a[b]=(a[b]||yc).concat(d))},th=function(){if(G&&9>T)return!1;var a=v("div");return"draggable"in a||"dragDrop"in a}(),Bd,Ad,ne=3!="\n\nb".split(/\n/).length?function(a){for(var b=0,d=[],c=a.length;b<=c;){var e=a.indexOf("\n",b);-1==e&&(e=a.length);var f=a.slice(b,"\r"==a.charAt(e-1)?e-1:e),g=f.indexOf("\r");
-1!=g?(d.push(f.slice(0,g)),b+=g+1):(d.push(f),b=e+1)}return d}:function(a){return a.split(/\r\n?|\n/)},Gh=window.getSelection?function(a){try{return a.selectionStart!=a.selectionEnd}catch(b){return!1}}:function(a){try{var b=a.ownerDocument.selection.createRange()}catch(d){}return b&&b.parentElement()==a?0!=b.compareEndPoints("StartToEnd",b):!1},nh=function(){var a=v("div");if("oncopy"in a)return!0;a.setAttribute("oncopy","return;");return"function"==typeof a.oncopy}(),Hd=null,md={},qb={},rb={},X=
function(a,b,d){this.pos=this.start=0;this.string=a;this.tabSize=b||8;this.lineStart=this.lastColumnPos=this.lastColumnValue=0;this.lineOracle=d};X.prototype.eol=function(){return this.pos>=this.string.length};X.prototype.sol=function(){return this.pos==this.lineStart};X.prototype.peek=function(){return this.string.charAt(this.pos)||void 0};X.prototype.next=function(){if(this.pos<this.string.length)return this.string.charAt(this.pos++)};X.prototype.eat=function(a){var b=this.string.charAt(this.pos);
if("string"==typeof a?b==a:b&&(a.test?a.test(b):a(b)))return++this.pos,b};X.prototype.eatWhile=function(a){for(var b=this.pos;this.eat(a););return this.pos>b};X.prototype.eatSpace=function(){for(var a=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>a};X.prototype.skipToEnd=function(){this.pos=this.string.length};X.prototype.skipTo=function(a){a=this.string.indexOf(a,this.pos);if(-1<a)return this.pos=a,!0};X.prototype.backUp=function(a){this.pos-=a};X.prototype.column=
function(){this.lastColumnPos<this.start&&(this.lastColumnValue=wa(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue),this.lastColumnPos=this.start);return this.lastColumnValue-(this.lineStart?wa(this.string,this.lineStart,this.tabSize):0)};X.prototype.indentation=function(){return wa(this.string,null,this.tabSize)-(this.lineStart?wa(this.string,this.lineStart,this.tabSize):0)};X.prototype.match=function(a,b,d){if("string"==typeof a){var c=function(f){return d?f.toLowerCase():
f},e=this.string.substr(this.pos,a.length);if(c(e)==c(a))return!1!==b&&(this.pos+=a.length),!0}else{if((a=this.string.slice(this.pos).match(a))&&0<a.index)return null;a&&!1!==b&&(this.pos+=a[0].length);return a}};X.prototype.current=function(){return this.string.slice(this.start,this.pos)};X.prototype.hideFirstChars=function(a,b){this.lineStart+=a;try{return b()}finally{this.lineStart-=a}};X.prototype.lookAhead=function(a){var b=this.lineOracle;return b&&b.lookAhead(a)};X.prototype.baseToken=function(){var a=
this.lineOracle;return a&&a.baseToken(this.pos)};var Cc=function(a,b){this.state=a;this.lookAhead=b},Fa=function(a,b,d,c){this.state=b;this.doc=a;this.line=d;this.maxLookAhead=c||0;this.baseTokens=null;this.baseTokenPos=1};Fa.prototype.lookAhead=function(a){var b=this.doc.getLine(this.line+a);null!=b&&a>this.maxLookAhead&&(this.maxLookAhead=a);return b};Fa.prototype.baseToken=function(a){if(!this.baseTokens)return null;for(;this.baseTokens[this.baseTokenPos]<=a;)this.baseTokenPos+=2;var b=this.baseTokens[this.baseTokenPos+
1];return{type:b&&b.replace(/( |^)overlay .*/,""),size:this.baseTokens[this.baseTokenPos]-a}};Fa.prototype.nextLine=function(){this.line++;0<this.maxLookAhead&&this.maxLookAhead--};Fa.fromSaved=function(a,b,d){return b instanceof Cc?new Fa(a,$a(a.mode,b.state),d,b.lookAhead):new Fa(a,$a(a.mode,b),d)};Fa.prototype.save=function(a){a=!1!==a?$a(this.doc.mode,this.state):this.state;return 0<this.maxLookAhead?new Cc(a,this.maxLookAhead):a};var De=function(a,b,d){this.start=a.start;this.end=a.pos;this.string=
a.current();this.type=b||null;this.state=d},Nf=!1,Ka=!1,zb=function(a,b,d){this.text=a;He(this,b);this.height=d?d(this):1};zb.prototype.lineNo=function(){return N(this)};pb(zb);var Jg={},Ig={},tb=null,Rb=null,We={left:0,right:0,top:0,bottom:0},fb,ob=function(a,b,d){this.cm=d;var c=this.vert=v("div",[v("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),e=this.horiz=v("div",[v("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");c.tabIndex=e.tabIndex=-1;a(c);a(e);z(c,
"scroll",function(){c.clientHeight&&b(c.scrollTop,"vertical")});z(e,"scroll",function(){e.clientWidth&&b(e.scrollLeft,"horizontal")});this.checkedZeroWidth=!1;G&&8>T&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")};ob.prototype.update=function(a){var b=a.scrollWidth>a.clientWidth+1,d=a.scrollHeight>a.clientHeight+1,c=a.nativeBarWidth;d?(this.vert.style.display="block",this.vert.style.bottom=b?c+"px":"0",this.vert.firstChild.style.height=Math.max(0,a.scrollHeight-a.clientHeight+(a.viewHeight-
(b?c:0)))+"px"):(this.vert.scrollTop=0,this.vert.style.display="",this.vert.firstChild.style.height="0");b?(this.horiz.style.display="block",this.horiz.style.right=d?c+"px":"0",this.horiz.style.left=a.barLeft+"px",this.horiz.firstChild.style.width=Math.max(0,a.scrollWidth-a.clientWidth+(a.viewWidth-a.barLeft-(d?c:0)))+"px"):(this.horiz.style.display="",this.horiz.firstChild.style.width="0");!this.checkedZeroWidth&&0<a.clientHeight&&(0==c&&this.zeroWidthHack(),this.checkedZeroWidth=!0);return{right:d?
c:0,bottom:b?c:0}};ob.prototype.setScrollLeft=function(a){this.horiz.scrollLeft!=a&&(this.horiz.scrollLeft=a);this.disableHoriz&&this.enableZeroWidthBar(this.horiz,this.disableHoriz,"horiz")};ob.prototype.setScrollTop=function(a){this.vert.scrollTop!=a&&(this.vert.scrollTop=a);this.disableVert&&this.enableZeroWidthBar(this.vert,this.disableVert,"vert")};ob.prototype.zeroWidthHack=function(){this.horiz.style.height=this.vert.style.width=ya&&!Eh?"12px":"18px";this.horiz.style.visibility=this.vert.style.visibility=
"hidden";this.disableHoriz=new Xa;this.disableVert=new Xa};ob.prototype.enableZeroWidthBar=function(a,b,d){function c(){var e=a.getBoundingClientRect();("vert"==d?document.elementFromPoint(e.right-1,(e.top+e.bottom)/2):document.elementFromPoint((e.right+e.left)/2,e.bottom-1))!=a?a.style.visibility="hidden":b.set(1E3,c)}a.style.visibility="";b.set(1E3,c)};ob.prototype.clear=function(){var a=this.horiz.parentNode;a.removeChild(this.horiz);a.removeChild(this.vert)};var rc=function(){};rc.prototype.update=
function(){return{bottom:0,right:0}};rc.prototype.setScrollLeft=function(){};rc.prototype.setScrollTop=function(){};rc.prototype.clear=function(){};var pf={"native":ob,"null":rc},Ug=0,Pc=function(a,b,d){var c=a.display;this.viewport=b;this.visible=Mc(c,a.doc,b);this.editorIsHidden=!c.wrapper.offsetWidth;this.wrapperHeight=c.wrapper.clientHeight;this.wrapperWidth=c.wrapper.clientWidth;this.oldDisplayWidth=cb(a);this.force=d;this.dims=Gd(a);this.events=[]};Pc.prototype.signal=function(a,b){xa(a,b)&&
this.events.push(arguments)};Pc.prototype.finish=function(){for(var a=0;a<this.events.length;a++)W.apply(null,this.events[a])};var Qc=0,Na=null;G?Na=-.53:Ma?Na=15:Qa?Na=-.7:ad&&(Na=-1/3);var va=function(a,b){this.ranges=a;this.primIndex=b};va.prototype.primary=function(){return this.ranges[this.primIndex]};va.prototype.equals=function(a){if(a==this)return!0;if(a.primIndex!=this.primIndex||a.ranges.length!=this.ranges.length)return!1;for(var b=0;b<this.ranges.length;b++){var d=this.ranges[b],c=a.ranges[b];
if(!rd(d.anchor,c.anchor)||!rd(d.head,c.head))return!1}return!0};va.prototype.deepCopy=function(){for(var a=[],b=0;b<this.ranges.length;b++)a[b]=new I(sd(this.ranges[b].anchor),sd(this.ranges[b].head));return new va(a,this.primIndex)};va.prototype.somethingSelected=function(){for(var a=0;a<this.ranges.length;a++)if(!this.ranges[a].empty())return!0;return!1};va.prototype.contains=function(a,b){b||(b=a);for(var d=0;d<this.ranges.length;d++){var c=this.ranges[d];if(0<=B(b,c.from())&&0>=B(a,c.to()))return d}return-1};
var I=function(a,b){this.anchor=a;this.head=b};I.prototype.from=function(){return Bc(this.anchor,this.head)};I.prototype.to=function(){return Ac(this.anchor,this.head)};I.prototype.empty=function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch};ec.prototype={chunkSize:function(){return this.lines.length},removeInner:function(a,b){for(var d=a,c=a+b;d<c;++d){var e=this.lines[d];this.height-=e.height;var f=e;f.parent=null;Ge(f);aa(e,"delete")}this.lines.splice(a,b)},collapse:function(a){a.push.apply(a,
this.lines)},insertInner:function(a,b,d){this.height+=d;this.lines=this.lines.slice(0,a).concat(b).concat(this.lines.slice(a));for(a=0;a<b.length;++a)b[a].parent=this},iterN:function(a,b,d){for(b=a+b;a<b;++a)if(d(this.lines[a]))return!0}};fc.prototype={chunkSize:function(){return this.size},removeInner:function(a,b){this.size-=b;for(var d=0;d<this.children.length;++d){var c=this.children[d],e=c.chunkSize();if(a<e){var f=Math.min(b,e-a),g=c.height;c.removeInner(a,f);this.height-=g-c.height;e==f&&(this.children.splice(d--,
1),c.parent=null);if(0==(b-=f))break;a=0}else a-=e}25>this.size-b&&(1<this.children.length||!(this.children[0]instanceof ec))&&(a=[],this.collapse(a),this.children=[new ec(a)],this.children[0].parent=this)},collapse:function(a){for(var b=0;b<this.children.length;++b)this.children[b].collapse(a)},insertInner:function(a,b,d){this.size+=b.length;this.height+=d;for(var c=0;c<this.children.length;++c){var e=this.children[c],f=e.chunkSize();if(a<=f){e.insertInner(a,b,d);if(e.lines&&50<e.lines.length){for(b=
a=e.lines.length%25+25;b<e.lines.length;)d=new ec(e.lines.slice(b,b+=25)),e.height-=d.height,this.children.splice(++c,0,d),d.parent=this;e.lines=e.lines.slice(0,a);this.maybeSpill()}break}a-=f}},maybeSpill:function(){if(!(10>=this.children.length)){var a=this;do{var b=a.children.splice(a.children.length-5,5);b=new fc(b);if(a.parent){a.size-=b.size;a.height-=b.height;var d=ea(a.parent.children,a);a.parent.children.splice(d+1,0,b)}else d=new fc(a.children),d.parent=a,a.children=[d,b],a=d;b.parent=a.parent}while(10<
a.children.length);a.parent.maybeSpill()}},iterN:function(a,b,d){for(var c=0;c<this.children.length;++c){var e=this.children[c],f=e.chunkSize();if(a<f){f=Math.min(b,f-a);if(e.iterN(a,f,d))return!0;if(0==(b-=f))break;a=0}else a-=f}}};var gc=function(a,b,d){if(d)for(var c in d)d.hasOwnProperty(c)&&(this[c]=d[c]);this.doc=a;this.node=b};gc.prototype.clear=function(){var a=this.doc.cm,b=this.line.widgets,d=this.line,c=N(d);if(null!=c&&b){for(var e=0;e<b.length;++e)b[e]==this&&b.splice(e--,1);b.length||
(d.widgets=null);var f=Tb(this);Ea(d,Math.max(0,d.height-f));a&&(ra(a,function(){var g=-f;Ga(d)<(a.curOp&&a.curOp.scrollTop||a.doc.scrollTop)&&Nc(a,g);Sa(a,c,"widget")}),aa(a,"lineWidgetCleared",a,this,c))}};gc.prototype.changed=function(){var a=this,b=this.height,d=this.doc.cm,c=this.line;this.height=null;var e=Tb(this)-b;e&&(Pa(this.doc,c)||Ea(c,c.height+e),d&&ra(d,function(){d.curOp.forceUpdate=!0;Ga(c)<(d.curOp&&d.curOp.scrollTop||d.doc.scrollTop)&&Nc(d,e);aa(d,"lineWidgetChanged",d,a,N(c))}))};
pb(gc);var Tf=0,Va=function(a,b){this.lines=[];this.type=b;this.doc=a;this.id=++Tf};Va.prototype.clear=function(){if(!this.explicitlyCleared){var a=this.doc.cm,b=a&&!a.curOp;b&&lb(a);if(xa(this,"clear")){var d=this.find();d&&aa(this,"clear",d.from,d.to)}for(var c=d=null,e=0;e<this.lines.length;++e){var f=this.lines[e],g=Pb(f.markedSpans,this);a&&!this.collapsed?Sa(a,N(f),"text"):a&&(null!=g.to&&(c=N(f)),null!=g.from&&(d=N(f)));for(var h=f,k=void 0,l=f.markedSpans,m=g,n=0;n<l.length;++n)l[n]!=m&&(k||
(k=[])).push(l[n]);h.markedSpans=k;null==g.from&&this.collapsed&&!Pa(this.doc,f)&&a&&Ea(f,vb(a.display))}if(a&&this.collapsed&&!a.options.lineWrapping)for(e=0;e<this.lines.length;++e)f=za(this.lines[e]),g=Ec(f),g>a.display.maxLineLength&&(a.display.maxLine=f,a.display.maxLineLength=g,a.display.maxLineChanged=!0);null!=d&&a&&this.collapsed&&ma(a,d,c+1);this.lines.length=0;this.explicitlyCleared=!0;this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,a&&Jf(a.doc));a&&aa(a,"markerCleared",a,this,d,
c);b&&mb(a);this.parent&&this.parent.clear()}};Va.prototype.find=function(a,b){null==a&&"bookmark"==this.type&&(a=1);for(var d,c,e=0;e<this.lines.length;++e){var f=this.lines[e],g=Pb(f.markedSpans,this);if(null!=g.from&&(d=t(b?f:N(f),g.from),-1==a))return d;if(null!=g.to&&(c=t(b?f:N(f),g.to),1==a))return c}return d&&{from:d,to:c}};Va.prototype.changed=function(){var a=this,b=this.find(-1,!0),d=this,c=this.doc.cm;b&&c&&ra(c,function(){var e=b.line,f=N(b.line);if(f=Fd(c,f))Xe(f),c.curOp.selectionChanged=
c.curOp.forceUpdate=!0;c.curOp.updateMaxLine=!0;Pa(d.doc,e)||null==d.height||(f=d.height,d.height=null,(f=Tb(d)-f)&&Ea(e,e.height+f));aa(c,"markerChanged",c,a)})};Va.prototype.attachLine=function(a){if(!this.lines.length&&this.doc.cm){var b=this.doc.cm.curOp;b.maybeHiddenMarkers&&-1!=ea(b.maybeHiddenMarkers,this)||(b.maybeUnhiddenMarkers||(b.maybeUnhiddenMarkers=[])).push(this)}this.lines.push(a)};Va.prototype.detachLine=function(a){this.lines.splice(ea(this.lines,a),1);!this.lines.length&&this.doc.cm&&
(a=this.doc.cm.curOp,(a.maybeHiddenMarkers||(a.maybeHiddenMarkers=[])).push(this))};pb(Va);var hc=function(a,b){this.markers=a;this.primary=b;for(b=0;b<a.length;++b)a[b].parent=this};hc.prototype.clear=function(){if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var a=0;a<this.markers.length;++a)this.markers[a].clear();aa(this,"clear")}};hc.prototype.find=function(a,b){return this.primary.find(a,b)};pb(hc);var Hh=0,oa=function(a,b,d,c,e){if(!(this instanceof oa))return new oa(a,b,d,c,e);null==
d&&(d=0);fc.call(this,[new ec([new zb("",null)])]);this.first=d;this.scrollTop=this.scrollLeft=0;this.cantEdit=!1;this.cleanGeneration=1;this.modeFrontier=this.highlightFrontier=d;d=t(d,0);this.sel=Oa(d);this.history=new Rc(null);this.id=++Hh;this.modeOption=b;this.lineSep=c;this.direction="rtl"==e?"rtl":"ltr";this.extend=!1;"string"==typeof a&&(a=this.splitLines(a));ae(this,{from:d,to:d,text:a});da(this,Oa(d),Ia)};oa.prototype=qe(fc.prototype,{constructor:oa,iter:function(a,b,d){d?this.iterN(a-this.first,
b-a,d):this.iterN(this.first,this.first+this.size,a)},insert:function(a,b){for(var d=0,c=0;c<b.length;++c)d+=b[c].height;this.insertInner(a-this.first,b,d)},remove:function(a,b){this.removeInner(a-this.first,b)},getValue:function(a){var b=pd(this,this.first,this.first+this.size);return!1===a?b:b.join(a||this.lineSeparator())},setValue:ca(function(a){var b=t(this.first,0),d=this.first+this.size-1;Cb(this,{from:b,to:t(d,w(this,d).text.length),text:this.splitLines(a),origin:"setValue",full:!0},!0);this.cm&&
Wb(this.cm,0,0);da(this,Oa(b),Ia)}),replaceRange:function(a,b,d,c){b=C(this,b);d=d?C(this,d):b;Db(this,a,b,d,c)},getRange:function(a,b,d){a=ab(this,C(this,a),C(this,b));return!1===d?a:""===d?a.join(""):a.join(d||this.lineSeparator())},getLine:function(a){return(a=this.getLineHandle(a))&&a.text},getLineHandle:function(a){if(Nb(this,a))return w(this,a)},getLineNumber:function(a){return N(a)},getLineHandleVisualStart:function(a){"number"==typeof a&&(a=w(this,a));return za(a)},lineCount:function(){return this.size},
firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(a){return C(this,a)},getCursor:function(a){var b=this.sel.primary();return null==a||"head"==a?b.head:"anchor"==a?b.anchor:"end"==a||"to"==a||!1===a?b.to():b.from()},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:ca(function(a,b,d){a=C(this,"number"==typeof a?t(a,b||0):a);da(this,Oa(a,null),d)}),setSelection:ca(function(a,
b,d){var c=C(this,a);a=C(this,b||a);da(this,Oa(c,a),d)}),extendSelection:ca(function(a,b,d){Tc(this,C(this,a),b&&C(this,b),d)}),extendSelections:ca(function(a,b){Ff(this,xe(this,a),b)}),extendSelectionsBy:ca(function(a,b){a=wc(this.sel.ranges,a);Ff(this,xe(this,a),b)}),setSelections:ca(function(a,b,d){if(a.length){for(var c=[],e=0;e<a.length;e++)c[e]=new I(C(this,a[e].anchor),C(this,a[e].head||a[e].anchor));null==b&&(b=Math.min(a.length-1,this.sel.primIndex));da(this,Da(this.cm,c,b),d)}}),addSelection:ca(function(a,
b,d){var c=this.sel.ranges.slice(0);c.push(new I(C(this,a),C(this,b||a)));da(this,Da(this.cm,c,c.length-1),d)}),getSelection:function(a){for(var b=this.sel.ranges,d,c=0;c<b.length;c++){var e=ab(this,b[c].from(),b[c].to());d=d?d.concat(e):e}return!1===a?d:d.join(a||this.lineSeparator())},getSelections:function(a){for(var b=[],d=this.sel.ranges,c=0;c<d.length;c++){var e=ab(this,d[c].from(),d[c].to());!1!==a&&(e=e.join(a||this.lineSeparator()));b[c]=e}return b},replaceSelection:function(a,b,d){for(var c=
[],e=0;e<this.sel.ranges.length;e++)c[e]=a;this.replaceSelections(c,b,d||"+input")},replaceSelections:ca(function(a,b,d){for(var c=[],e=this.sel,f=0;f<e.ranges.length;f++){var g=e.ranges[f];c[f]={from:g.from(),to:g.to(),text:this.splitLines(a[f]),origin:d}}if(a=b&&"end"!=b){a=[];e=d=t(this.first,0);for(f=0;f<c.length;f++){var h=c[f];g=xf(h.from,d,e);var k=xf(Ta(h),d,e);d=h.to;e=k;"around"==b?(h=this.sel.ranges[f],h=0>B(h.head,h.anchor),a[f]=new I(h?k:g,h?g:k)):a[f]=new I(g,g)}a=new va(a,this.sel.primIndex)}b=
a;for(a=c.length-1;0<=a;a--)Cb(this,c[a]);b?Gf(this,b):this.cm&&xb(this.cm)}),undo:ca(function(){Wc(this,"undo")}),redo:ca(function(){Wc(this,"redo")}),undoSelection:ca(function(){Wc(this,"undo",!0)}),redoSelection:ca(function(){Wc(this,"redo",!0)}),setExtending:function(a){this.extend=a},getExtending:function(){return this.extend},historySize:function(){for(var a=this.history,b=0,d=0,c=0;c<a.done.length;c++)a.done[c].ranges||++b;for(c=0;c<a.undone.length;c++)a.undone[c].ranges||++d;return{undo:b,
redo:d}},clearHistory:function(){var a=this;this.history=new Rc(this.history);Ua(this,function(b){return b.history=a.history},!0)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(a){a&&(this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null);return this.history.generation},isClean:function(a){return this.history.generation==(a||this.cleanGeneration)},getHistory:function(){return{done:Ab(this.history.done),undone:Ab(this.history.undone)}},
setHistory:function(a){var b=this.history=new Rc(this.history);b.done=Ab(a.done.slice(0),null,!0);b.undone=Ab(a.undone.slice(0),null,!0)},setGutterMarker:ca(function(a,b,d){return dc(this,a,"gutter",function(c){var e=c.gutterMarkers||(c.gutterMarkers={});e[b]=d;!d&&re(e)&&(c.gutterMarkers=null);return!0})}),clearGutter:ca(function(a){var b=this;this.iter(function(d){d.gutterMarkers&&d.gutterMarkers[a]&&dc(b,d,"gutter",function(){d.gutterMarkers[a]=null;re(d.gutterMarkers)&&(d.gutterMarkers=null);
return!0})})}),lineInfo:function(a){if("number"==typeof a){if(!Nb(this,a))return null;var b=a;a=w(this,a);if(!a)return null}else if(b=N(a),null==b)return null;return{line:b,handle:a,text:a.text,gutterMarkers:a.gutterMarkers,textClass:a.textClass,bgClass:a.bgClass,wrapClass:a.wrapClass,widgets:a.widgets}},addLineClass:ca(function(a,b,d){return dc(this,a,"gutter"==b?"gutter":"class",function(c){var e="text"==b?"textClass":"background"==b?"bgClass":"gutter"==b?"gutterClass":"wrapClass";if(c[e]){if(y(d).test(c[e]))return!1;
c[e]+=" "+d}else c[e]=d;return!0})}),removeLineClass:ca(function(a,b,d){return dc(this,a,"gutter"==b?"gutter":"class",function(c){var e="text"==b?"textClass":"background"==b?"bgClass":"gutter"==b?"gutterClass":"wrapClass",f=c[e];if(f)if(null==d)c[e]=null;else{var g=f.match(y(d));if(!g)return!1;var h=g.index+g[0].length;c[e]=f.slice(0,g.index)+(g.index&&h!=f.length?" ":"")+f.slice(h)||null}else return!1;return!0})}),addLineWidget:ca(function(a,b,d){return ch(this,a,b,d)}),removeLineWidget:function(a){a.clear()},
markText:function(a,b,d){return Eb(this,C(this,a),C(this,b),d,d&&d.type||"range")},setBookmark:function(a,b){b={replacedWith:b&&(null==b.nodeType?b.widget:b),insertLeft:b&&b.insertLeft,clearWhenEmpty:!1,shared:b&&b.shared,handleMouseEvents:b&&b.handleMouseEvents};a=C(this,a);return Eb(this,a,a,b,"bookmark")},findMarksAt:function(a){a=C(this,a);var b=[],d=w(this,a.line).markedSpans;if(d)for(var c=0;c<d.length;++c){var e=d[c];(null==e.from||e.from<=a.ch)&&(null==e.to||e.to>=a.ch)&&b.push(e.marker.parent||
e.marker)}return b},findMarks:function(a,b,d){a=C(this,a);b=C(this,b);var c=[],e=a.line;this.iter(a.line,b.line+1,function(f){if(f=f.markedSpans)for(var g=0;g<f.length;g++){var h=f[g];null!=h.to&&e==a.line&&a.ch>=h.to||null==h.from&&e!=a.line||null!=h.from&&e==b.line&&h.from>=b.ch||d&&!d(h.marker)||c.push(h.marker.parent||h.marker)}++e});return c},getAllMarks:function(){var a=[];this.iter(function(b){if(b=b.markedSpans)for(var d=0;d<b.length;++d)null!=b[d].from&&a.push(b[d].marker)});return a},posFromIndex:function(a){var b,
d=this.first,c=this.lineSeparator().length;this.iter(function(e){e=e.text.length+c;if(e>a)return b=a,!0;a-=e;++d});return C(this,t(d,b))},indexFromPos:function(a){a=C(this,a);var b=a.ch;if(a.line<this.first||0>a.ch)return 0;var d=this.lineSeparator().length;this.iter(this.first,a.line,function(c){b+=c.text.length+d});return b},copy:function(a){var b=new oa(pd(this,this.first,this.first+this.size),this.modeOption,this.first,this.lineSep,this.direction);b.scrollTop=this.scrollTop;b.scrollLeft=this.scrollLeft;
b.sel=this.sel;b.extend=!1;a&&(b.history.undoDepth=this.history.undoDepth,b.setHistory(this.getHistory()));return b},linkedDoc:function(a){a||(a={});var b=this.first,d=this.first+this.size;null!=a.from&&a.from>b&&(b=a.from);null!=a.to&&a.to<d&&(d=a.to);b=new oa(pd(this,b,d),a.mode||this.modeOption,b,this.lineSep,this.direction);a.sharedHist&&(b.history=this.history);(this.linked||(this.linked=[])).push({doc:b,sharedHist:a.sharedHist});b.linked=[{doc:this,isParent:!0,sharedHist:a.sharedHist}];a=Uf(this);
for(d=0;d<a.length;d++){var c=a[d],e=c.find(),f=b.clipPos(e.from);e=b.clipPos(e.to);B(f,e)&&(f=Eb(b,f,e,c.primary,c.primary.type),c.markers.push(f),f.parent=c)}return b},unlinkDoc:function(a){a instanceof U&&(a=a.doc);if(this.linked)for(var b=0;b<this.linked.length;++b)if(this.linked[b].doc==a){this.linked.splice(b,1);a.unlinkDoc(this);eh(Uf(this));break}if(a.history==this.history){var d=[a.id];Ua(a,function(c){return d.push(c.id)},!0);a.history=new Rc(null);a.history.done=Ab(this.history.done,d);
a.history.undone=Ab(this.history.undone,d)}},iterLinkedDocs:function(a){Ua(this,a)},getMode:function(){return this.mode},getEditor:function(){return this.cm},splitLines:function(a){return this.lineSep?a.split(this.lineSep):ne(a)},lineSeparator:function(){return this.lineSep||"\n"},setDirection:ca(function(a){"rtl"!=a&&(a="ltr");a!=this.direction&&(this.direction=a,this.iter(function(b){return b.order=null}),this.cm&&$g(this.cm))})});oa.prototype.eachLine=oa.prototype.iter;for(var Wf=0,ng=!1,Wa={3:"Pause",
8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",106:"*",107:"=",109:"-",110:".",111:"/",145:"ScrollLock",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",224:"Mod",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",
63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"},sc=0;10>sc;sc++)Wa[sc+48]=Wa[sc+96]=String(sc);for(var ed=65;90>=ed;ed++)Wa[ed]=String.fromCharCode(ed);for(var tc=1;12>=tc;tc++)Wa[tc+111]=Wa[tc+63235]="F"+tc;var ic={basic:{Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",
Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},pcDefault:{"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev",
"Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},emacsy:{"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars",
"Ctrl-O":"openLine"},macDefault:{"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace",
"Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]}};ic["default"]=ya?ic.macDefault:ic.pcDefault;var jc={selectAll:Lf,singleSelection:function(a){return a.setSelection(a.getCursor("anchor"),a.getCursor("head"),Ia)},killLine:function(a){return Gb(a,function(b){if(b.empty()){var d=
w(a.doc,b.head.line).text.length;return b.head.ch==d&&b.head.line<a.lastLine()?{from:b.head,to:t(b.head.line+1,0)}:{from:b.head,to:t(b.head.line,d)}}return{from:b.from(),to:b.to()}})},deleteLine:function(a){return Gb(a,function(b){return{from:t(b.from().line,0),to:C(a.doc,t(b.to().line+1,0))}})},delLineLeft:function(a){return Gb(a,function(b){return{from:t(b.from().line,0),to:b.from()}})},delWrappedLineLeft:function(a){return Gb(a,function(b){var d=a.charCoords(b.head,"div").top+5;return{from:a.coordsChar({left:0,
top:d},"div"),to:b.from()}})},delWrappedLineRight:function(a){return Gb(a,function(b){var d=a.charCoords(b.head,"div").top+5;d=a.coordsChar({left:a.display.lineDiv.offsetWidth+100,top:d},"div");return{from:b.from(),to:d}})},undo:function(a){return a.undo()},redo:function(a){return a.redo()},undoSelection:function(a){return a.undoSelection()},redoSelection:function(a){return a.redoSelection()},goDocStart:function(a){return a.extendSelection(t(a.firstLine(),0))},goDocEnd:function(a){return a.extendSelection(t(a.lastLine()))},
goLineStart:function(a){return a.extendSelectionsBy(function(b){return bg(a,b.head.line)},{origin:"+move",bias:1})},goLineStartSmart:function(a){return a.extendSelectionsBy(function(b){return cg(a,b.head)},{origin:"+move",bias:1})},goLineEnd:function(a){return a.extendSelectionsBy(function(b){b=b.head.line;var d=w(a.doc,b);var c=d;for(var e;e=sb(c,!1);)c=e.find(1,!0).line;c!=d&&(b=N(c));return ge(!0,a,d,b,-1)},{origin:"+move",bias:-1})},goLineRight:function(a){return a.extendSelectionsBy(function(b){b=
a.cursorCoords(b.head,"div").top+5;return a.coordsChar({left:a.display.lineDiv.offsetWidth+100,top:b},"div")},qc)},goLineLeft:function(a){return a.extendSelectionsBy(function(b){b=a.cursorCoords(b.head,"div").top+5;return a.coordsChar({left:0,top:b},"div")},qc)},goLineLeftSmart:function(a){return a.extendSelectionsBy(function(b){var d=a.cursorCoords(b.head,"div").top+5;d=a.coordsChar({left:0,top:d},"div");return d.ch<a.getLine(d.line).search(/\S/)?cg(a,b.head):d},qc)},goLineUp:function(a){return a.moveV(-1,
"line")},goLineDown:function(a){return a.moveV(1,"line")},goPageUp:function(a){return a.moveV(-1,"page")},goPageDown:function(a){return a.moveV(1,"page")},goCharLeft:function(a){return a.moveH(-1,"char")},goCharRight:function(a){return a.moveH(1,"char")},goColumnLeft:function(a){return a.moveH(-1,"column")},goColumnRight:function(a){return a.moveH(1,"column")},goWordLeft:function(a){return a.moveH(-1,"word")},goGroupRight:function(a){return a.moveH(1,"group")},goGroupLeft:function(a){return a.moveH(-1,
"group")},goWordRight:function(a){return a.moveH(1,"word")},delCharBefore:function(a){return a.deleteH(-1,"codepoint")},delCharAfter:function(a){return a.deleteH(1,"char")},delWordBefore:function(a){return a.deleteH(-1,"word")},delWordAfter:function(a){return a.deleteH(1,"word")},delGroupBefore:function(a){return a.deleteH(-1,"group")},delGroupAfter:function(a){return a.deleteH(1,"group")},indentAuto:function(a){return a.indentSelection("smart")},indentMore:function(a){return a.indentSelection("add")},
indentLess:function(a){return a.indentSelection("subtract")},insertTab:function(a){return a.replaceSelection("\t")},insertSoftTab:function(a){for(var b=[],d=a.listSelections(),c=a.options.tabSize,e=0;e<d.length;e++){var f=d[e].from();f=wa(a.getLine(f.line),f.ch,c);b.push(id(c-f%c))}a.replaceSelections(b)},defaultTab:function(a){a.somethingSelected()?a.indentSelection("add"):a.execCommand("insertTab")},transposeChars:function(a){return ra(a,function(){for(var b=a.listSelections(),d=[],c=0;c<b.length;c++)if(b[c].empty()){var e=
b[c].head,f=w(a.doc,e.line).text;if(f)if(e.ch==f.length&&(e=new t(e.line,e.ch-1)),0<e.ch)e=new t(e.line,e.ch+1),a.replaceRange(f.charAt(e.ch-1)+f.charAt(e.ch-2),t(e.line,e.ch-2),e,"+transpose");else if(e.line>a.doc.first){var g=w(a.doc,e.line-1).text;g&&(e=new t(e.line,1),a.replaceRange(f.charAt(0)+a.doc.lineSeparator()+g.charAt(g.length-1),t(e.line-1,g.length-1),e,"+transpose"))}d.push(new I(e,e))}a.setSelections(d)})},newlineAndIndent:function(a){return ra(a,function(){for(var b=a.listSelections(),
d=b.length-1;0<=d;d--)a.replaceRange(a.doc.lineSeparator(),b[d].anchor,b[d].head,"+input");b=a.listSelections();for(d=0;d<b.length;d++)a.indentLine(b[d].from().line,null,!0);xb(a)})},openLine:function(a){return a.replaceSelection("\n","start")},toggleOverwrite:function(a){return a.toggleOverwrite()}},lh=new Xa,he=null,ie=function(a,b,d){this.time=a;this.pos=b;this.button=d};ie.prototype.compare=function(a,b,d){return this.time+400>a&&0==B(b,this.pos)&&d==this.button};var mc,lc,Hb={toString:function(){return"CodeMirror.Init"}},
mg={},bd={};U.defaults=mg;U.optionHandlers=bd;var le=[];U.defineInitHook=function(a){return le.push(a)};var sa=null,O=function(a){this.cm=a;this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null;this.polling=new Xa;this.composing=null;this.gracePeriod=!1;this.readDOMTimeout=null};O.prototype.init=function(a){function b(h){for(h=h.target;h;h=h.parentNode){if(h==g)return!0;if(/\bCodeMirror-(?:line)?widget\b/.test(h.className))break}return!1}function d(h){if(b(h)&&!Z(f,
h)){if(f.somethingSelected())sa={lineWise:!1,text:f.getSelections()},"cut"==h.type&&f.replaceSelection("",null,"cut");else if(f.options.lineWiseCopyCut){var k=qg(f);sa={lineWise:!0,text:k.text};"cut"==h.type&&f.operation(function(){f.setSelections(k.ranges,0,Ia);f.replaceSelection("",null,"cut")})}else return;if(h.clipboardData){h.clipboardData.clearData();var l=sa.text.join("\n");h.clipboardData.setData("Text",l);if(h.clipboardData.getData("Text")==l){h.preventDefault();return}}var m=sg();h=m.firstChild;
f.display.lineSpace.insertBefore(m,f.display.lineSpace.firstChild);h.value=sa.text.join("\n");var n=ka(g.ownerDocument);pc(h);setTimeout(function(){f.display.lineSpace.removeChild(m);n.focus();n==g&&e.showPrimarySelection()},50)}}var c=this,e=this,f=e.cm,g=e.div=a.lineDiv;g.contentEditable=!0;rg(g,f.options.spellcheck,f.options.autocorrect,f.options.autocapitalize);z(g,"paste",function(h){!b(h)||Z(f,h)||pg(h,f)||11>=T&&setTimeout(ba(f,function(){return c.updateFromDOM()}),20)});z(g,"compositionstart",
function(h){c.composing={data:h.data,done:!1}});z(g,"compositionupdate",function(h){c.composing||(c.composing={data:h.data,done:!1})});z(g,"compositionend",function(h){c.composing&&(h.data!=c.composing.data&&c.readFromDOMSoon(),c.composing.done=!0)});z(g,"touchstart",function(){return e.forceCompositionEnd()});z(g,"input",function(){c.composing||c.readFromDOMSoon()});z(g,"copy",d);z(g,"cut",d)};O.prototype.screenReaderLabelChanged=function(a){a?this.div.setAttribute("aria-label",a):this.div.removeAttribute("aria-label")};
O.prototype.prepareSelection=function(){var a=gf(this.cm,!1);a.focus=ka(this.div.ownerDocument)==this.div;return a};O.prototype.showSelection=function(a,b){a&&this.cm.display.view.length&&((a.focus||b)&&this.showPrimarySelection(),this.showMultipleSelections(a))};O.prototype.getSelection=function(){return this.cm.display.wrapper.ownerDocument.getSelection()};O.prototype.showPrimarySelection=function(){var a=this.getSelection(),b=this.cm,d=b.doc.sel.primary(),c=d.from();d=d.to();if(b.display.viewTo==
b.display.viewFrom||c.line>=b.display.viewTo||d.line<b.display.viewFrom)a.removeAllRanges();else{var e=cd(b,a.anchorNode,a.anchorOffset),f=cd(b,a.focusNode,a.focusOffset);if(!e||e.bad||!f||f.bad||0!=B(Bc(e,f),c)||0!=B(Ac(e,f),d))if(e=b.display.view,c=c.line>=b.display.viewFrom&&ug(b,c)||{node:e[0].measure.map[2],offset:0},d=d.line<b.display.viewTo&&ug(b,d),d||(d=e[e.length-1].measure,d=d.maps?d.maps[d.maps.length-1]:d.map,d={node:d[d.length-1],offset:d[d.length-2]-d[d.length-3]}),c&&d){e=a.rangeCount&&
a.getRangeAt(0);try{var g=Qb(c.node,c.offset,d.offset,d.node)}catch(h){}g&&(!Ma&&b.state.focused?(a.collapse(c.node,c.offset),g.collapsed||(a.removeAllRanges(),a.addRange(g))):(a.removeAllRanges(),a.addRange(g)),e&&null==a.anchorNode?a.addRange(e):Ma&&this.startGracePeriod());this.rememberSelection()}else a.removeAllRanges()}};O.prototype.startGracePeriod=function(){var a=this;clearTimeout(this.gracePeriod);this.gracePeriod=setTimeout(function(){a.gracePeriod=!1;a.selectionChanged()&&a.cm.operation(function(){return a.cm.curOp.selectionChanged=
!0})},20)};O.prototype.showMultipleSelections=function(a){D(this.cm.display.cursorDiv,a.cursors);D(this.cm.display.selectionDiv,a.selection)};O.prototype.rememberSelection=function(){var a=this.getSelection();this.lastAnchorNode=a.anchorNode;this.lastAnchorOffset=a.anchorOffset;this.lastFocusNode=a.focusNode;this.lastFocusOffset=a.focusOffset};O.prototype.selectionInEditor=function(){var a=this.getSelection();if(!a.rangeCount)return!1;a=a.getRangeAt(0).commonAncestorContainer;return ja(this.div,a)};
O.prototype.focus=function(){"nocursor"!=this.cm.options.readOnly&&(this.selectionInEditor()&&ka(this.div.ownerDocument)==this.div||this.showSelection(this.prepareSelection(),!0),this.div.focus())};O.prototype.blur=function(){this.div.blur()};O.prototype.getField=function(){return this.div};O.prototype.supportsTouch=function(){return!0};O.prototype.receivedFocus=function(){function a(){d.cm.state.focused&&(d.pollSelection(),d.polling.set(d.cm.options.pollInterval,a))}var b=this,d=this;this.selectionInEditor()?
setTimeout(function(){return b.pollSelection()},20):ra(this.cm,function(){return d.cm.curOp.selectionChanged=!0});this.polling.set(this.cm.options.pollInterval,a)};O.prototype.selectionChanged=function(){var a=this.getSelection();return a.anchorNode!=this.lastAnchorNode||a.anchorOffset!=this.lastAnchorOffset||a.focusNode!=this.lastFocusNode||a.focusOffset!=this.lastFocusOffset};O.prototype.pollSelection=function(){if(null==this.readDOMTimeout&&!this.gracePeriod&&this.selectionChanged()){var a=this.getSelection(),
b=this.cm;if(Gc&&Qa&&this.cm.display.gutterSpecs.length&&Ah(a.anchorNode))this.cm.triggerOnKeyDown({type:"keydown",keyCode:8,preventDefault:Math.abs}),this.blur(),this.focus();else if(!this.composing){this.rememberSelection();var d=cd(b,a.anchorNode,a.anchorOffset),c=cd(b,a.focusNode,a.focusOffset);d&&c&&ra(b,function(){da(b.doc,Oa(d,c),Ia);if(d.bad||c.bad)b.curOp.selectionChanged=!0})}}};O.prototype.pollContent=function(){null!=this.readDOMTimeout&&(clearTimeout(this.readDOMTimeout),this.readDOMTimeout=
null);var a=this.cm,b=a.display,d=a.doc.sel.primary(),c=d.from(),e=d.to();0==c.ch&&c.line>a.firstLine()&&(c=t(c.line-1,w(a.doc,c.line-1).length));e.ch==w(a.doc,e.line).text.length&&e.line<a.lastLine()&&(e=t(e.line+1,0));if(c.line<b.viewFrom||e.line>b.viewTo-1)return!1;var f;c.line==b.viewFrom||0==(f=db(a,c.line))?(d=N(b.view[0].line),f=b.view[0].node):(d=N(b.view[f].line),f=b.view[f-1].node.nextSibling);var g=db(a,e.line);g==b.view.length-1?(e=b.viewTo-1,b=b.lineDiv.lastChild):(e=N(b.view[g+1].line)-
1,b=b.view[g+1].node.previousSibling);if(!f)return!1;b=a.doc.splitLines(Bh(a,f,b,d,e));for(f=ab(a.doc,t(d,0),t(e,w(a.doc,e).text.length));1<b.length&&1<f.length;)if(J(b)==J(f))b.pop(),f.pop(),e--;else if(b[0]==f[0])b.shift(),f.shift(),d++;else break;var h=0;g=0;for(var k=b[0],l=f[0],m=Math.min(k.length,l.length);h<m&&k.charCodeAt(h)==l.charCodeAt(h);)++h;k=J(b);l=J(f);for(m=Math.min(k.length-(1==b.length?h:0),l.length-(1==f.length?h:0));g<m&&k.charCodeAt(k.length-g-1)==l.charCodeAt(l.length-g-1);)++g;
if(1==b.length&&1==f.length&&d==c.line)for(;h&&h>c.ch&&k.charCodeAt(k.length-g-1)==l.charCodeAt(l.length-g-1);)h--,g++;b[b.length-1]=k.slice(0,k.length-g).replace(/^\u200b+/,"");b[0]=b[0].slice(h).replace(/\u200b+$/,"");c=t(d,h);d=t(e,f.length?J(f).length-g:0);if(1<b.length||b[0]||B(c,d))return Db(a.doc,b,c,d,"+input"),!0};O.prototype.ensurePolled=function(){this.forceCompositionEnd()};O.prototype.reset=function(){this.forceCompositionEnd()};O.prototype.forceCompositionEnd=function(){this.composing&&
(clearTimeout(this.readDOMTimeout),this.composing=null,this.updateFromDOM(),this.div.blur(),this.div.focus())};O.prototype.readFromDOMSoon=function(){var a=this;null==this.readDOMTimeout&&(this.readDOMTimeout=setTimeout(function(){a.readDOMTimeout=null;if(a.composing)if(a.composing.done)a.composing=null;else return;a.updateFromDOM()},80))};O.prototype.updateFromDOM=function(){var a=this;!this.cm.isReadOnly()&&this.pollContent()||ra(this.cm,function(){return ma(a.cm)})};O.prototype.setUneditable=function(a){a.contentEditable=
"false"};O.prototype.onKeyPress=function(a){0==a.charCode||this.composing||(a.preventDefault(),this.cm.isReadOnly()||ba(this.cm,me)(this.cm,String.fromCharCode(null==a.charCode?a.keyCode:a.charCode),0))};O.prototype.readOnlyChanged=function(a){this.div.contentEditable=String("nocursor"!=a)};O.prototype.onContextMenu=function(){};O.prototype.resetPosition=function(){};O.prototype.needsContentAttribute=!0;var V=function(a){this.cm=a;this.prevInput="";this.pollingFast=!1;this.polling=new Xa;this.hasSelection=
!1;this.composing=null;this.resetting=!1};V.prototype.init=function(a){function b(g){if(!Z(e,g)){if(e.somethingSelected())sa={lineWise:!1,text:e.getSelections()};else if(e.options.lineWiseCopyCut){var h=qg(e);sa={lineWise:!0,text:h.text};"cut"==g.type?e.setSelections(h.ranges,null,Ia):(c.prevInput="",f.value=h.text.join("\n"),pc(f))}else return;"cut"==g.type&&(e.state.cutIncoming=+new Date)}}var d=this,c=this,e=this.cm;this.createField(a);var f=this.textarea;a.wrapper.insertBefore(this.wrapper,a.wrapper.firstChild);
oc&&(f.style.width="0px");z(f,"input",function(){G&&9<=T&&d.hasSelection&&(d.hasSelection=null);c.poll()});z(f,"paste",function(g){Z(e,g)||pg(g,e)||(e.state.pasteIncoming=+new Date,c.fastPoll())});z(f,"cut",b);z(f,"copy",b);z(a.scroller,"paste",function(g){if(!La(a,g)&&!Z(e,g))if(f.dispatchEvent){var h=new Event("paste");h.clipboardData=g.clipboardData;f.dispatchEvent(h)}else e.state.pasteIncoming=+new Date,c.focus()});z(a.lineSpace,"selectstart",function(g){La(a,g)||la(g)});z(f,"compositionstart",
function(){var g=e.getCursor("from");c.composing&&c.composing.range.clear();c.composing={start:g,range:e.markText(g,e.getCursor("to"),{className:"CodeMirror-composing"})}});z(f,"compositionend",function(){c.composing&&(c.poll(),c.composing.range.clear(),c.composing=null)})};V.prototype.createField=function(a){this.wrapper=sg();this.textarea=this.wrapper.firstChild};V.prototype.screenReaderLabelChanged=function(a){a?this.textarea.setAttribute("aria-label",a):this.textarea.removeAttribute("aria-label")};
V.prototype.prepareSelection=function(){var a=this.cm,b=a.display,d=a.doc,c=gf(a);if(a.options.moveInputWithCursor){a=Ba(a,d.sel.primary().head,"div");d=b.wrapper.getBoundingClientRect();var e=b.lineDiv.getBoundingClientRect();c.teTop=Math.max(0,Math.min(b.wrapper.clientHeight-10,a.top+e.top-d.top));c.teLeft=Math.max(0,Math.min(b.wrapper.clientWidth-10,a.left+e.left-d.left))}return c};V.prototype.showSelection=function(a){var b=this.cm.display;D(b.cursorDiv,a.cursors);D(b.selectionDiv,a.selection);
null!=a.teTop&&(this.wrapper.style.top=a.teTop+"px",this.wrapper.style.left=a.teLeft+"px")};V.prototype.reset=function(a){if(!(this.contextMenuPending||this.composing&&a)){var b=this.cm;this.resetting=!0;b.somethingSelected()?(this.prevInput="",a=b.getSelection(),this.textarea.value=a,b.state.focused&&pc(this.textarea),G&&9<=T&&(this.hasSelection=a)):a||(this.prevInput=this.textarea.value="",G&&9<=T&&(this.hasSelection=null));this.resetting=!1}};V.prototype.getField=function(){return this.textarea};
V.prototype.supportsTouch=function(){return!1};V.prototype.focus=function(){if("nocursor"!=this.cm.options.readOnly&&(!ac||ka(this.textarea.ownerDocument)!=this.textarea))try{this.textarea.focus()}catch(a){}};V.prototype.blur=function(){this.textarea.blur()};V.prototype.resetPosition=function(){this.wrapper.style.top=this.wrapper.style.left=0};V.prototype.receivedFocus=function(){this.slowPoll()};V.prototype.slowPoll=function(){var a=this;this.pollingFast||this.polling.set(this.cm.options.pollInterval,
function(){a.poll();a.cm.state.focused&&a.slowPoll()})};V.prototype.fastPoll=function(){function a(){d.poll()||b?(d.pollingFast=!1,d.slowPoll()):(b=!0,d.polling.set(60,a))}var b=!1,d=this;d.pollingFast=!0;d.polling.set(20,a)};V.prototype.poll=function(){var a=this,b=this.cm,d=this.textarea,c=this.prevInput;if(this.contextMenuPending||this.resetting||!b.state.focused||Gh(d)&&!c&&!this.composing||b.isReadOnly()||b.options.disableInput||b.state.keySeq)return!1;var e=d.value;if(e==c&&!b.somethingSelected())return!1;
if(G&&9<=T&&this.hasSelection===e||ya&&/[\uf700-\uf7ff]/.test(e))return b.display.input.reset(),!1;if(b.doc.sel==b.display.selForContextMenu){var f=e.charCodeAt(0);8203!=f||c||(c="\u200b");if(8666==f)return this.reset(),this.cm.execCommand("undo")}var g=0;for(f=Math.min(c.length,e.length);g<f&&c.charCodeAt(g)==e.charCodeAt(g);)++g;ra(b,function(){me(b,e.slice(g),c.length-g,null,a.composing?"*compose":null);1E3<e.length||-1<e.indexOf("\n")?d.value=a.prevInput="":a.prevInput=e;a.composing&&(a.composing.range.clear(),
a.composing.range=b.markText(a.composing.start,b.getCursor("to"),{className:"CodeMirror-composing"}))});return!0};V.prototype.ensurePolled=function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1)};V.prototype.onKeyPress=function(){G&&9<=T&&(this.hasSelection=null);this.fastPoll()};V.prototype.onContextMenu=function(a){function b(){if(null!=g.selectionStart){var q=e.somethingSelected(),r="\u200b"+(q?g.value:"");g.value="\u21da";g.value=r;c.prevInput=q?"":"\u200b";g.selectionStart=1;g.selectionEnd=
r.length;f.selForContextMenu=e.doc.sel}}function d(){if(c.contextMenuPending==d&&(c.contextMenuPending=!1,c.wrapper.style.cssText=m,g.style.cssText=l,G&&9>T&&f.scrollbars.setScrollTop(f.scroller.scrollTop=k),null!=g.selectionStart)){(!G||G&&9>T)&&b();var q=0,r=function(){f.selForContextMenu==e.doc.sel&&0==g.selectionStart&&0<g.selectionEnd&&"\u200b"==c.prevInput?ba(e,Lf)(e):10>q++?f.detectingSelectAll=setTimeout(r,500):(f.selForContextMenu=null,f.input.reset())};f.detectingSelectAll=setTimeout(r,
200)}}var c=this,e=c.cm,f=e.display,g=c.textarea;c.contextMenuPending&&c.contextMenuPending();var h=gb(e,a),k=f.scroller.scrollTop;if(h&&!Ca){e.options.resetSelectionOnContextMenu&&-1==e.doc.sel.contains(h)&&ba(e,da)(e.doc,Oa(h),Ia);var l=g.style.cssText,m=c.wrapper.style.cssText;h=c.wrapper.offsetParent.getBoundingClientRect();c.wrapper.style.cssText="position: static";g.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(a.clientY-h.top-5)+"px; left: "+(a.clientX-h.left-
5)+"px;\n z-index: 1000; background: "+(G?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";if(fa)var n=g.ownerDocument.defaultView.scrollY;f.input.focus();fa&&g.ownerDocument.defaultView.scrollTo(null,n);f.input.reset();e.somethingSelected()||(g.value=c.prevInput=" ");c.contextMenuPending=d;f.selForContextMenu=e.doc.sel;clearTimeout(f.detectingSelectAll);G&&9<=T&&b();if(je){Mb(a);var p=
function(){ta(window,"mouseup",p);setTimeout(d,20)};z(window,"mouseup",p)}else setTimeout(d,50)}};V.prototype.readOnlyChanged=function(a){a||this.reset();this.textarea.disabled="nocursor"==a;this.textarea.readOnly=!!a};V.prototype.setUneditable=function(){};V.prototype.needsContentAttribute=!1;(function(a){function b(c,e,f,g){a.defaults[c]=e;f&&(d[c]=g?function(h,k,l){l!=Hb&&f(h,k,l)}:f)}var d=a.optionHandlers;a.defineOption=b;a.Init=Hb;b("value","",function(c,e){return c.setValue(e)},!0);b("mode",
null,function(c,e){c.doc.modeOption=e;$d(c)},!0);b("indentUnit",2,$d,!0);b("indentWithTabs",!1);b("smartIndent",!0);b("tabSize",4,function(c){bc(c);Ub(c);ma(c)},!0);b("lineSeparator",null,function(c,e){if(c.doc.lineSep=e){var f=[],g=c.doc.first;c.doc.iter(function(k){for(var l=0;;){var m=k.text.indexOf(e,l);if(-1==m)break;l=m+e.length;f.push(t(g,m))}g++});for(var h=f.length-1;0<=h;h--)Db(c.doc,e,f[h],t(f[h].line,f[h].ch+e.length))}});b("specialChars",/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\u202d\u202e\u2066\u2067\u2069\ufeff\ufff9-\ufffc]/g,
function(c,e,f){c.state.specialChars=new RegExp(e.source+(e.test("\t")?"":"|\t"),"g");f!=Hb&&c.refresh()});b("specialCharPlaceholder",Mg,function(c){return c.refresh()},!0);b("electricChars",!0);b("inputStyle",ac?"contenteditable":"textarea",function(){throw Error("inputStyle can not (yet) be changed in a running editor");},!0);b("spellcheck",!1,function(c,e){return c.getInputField().spellcheck=e},!0);b("autocorrect",!1,function(c,e){return c.getInputField().autocorrect=e},!0);b("autocapitalize",
!1,function(c,e){return c.getInputField().autocapitalize=e},!0);b("rtlMoveVisually",!Fh);b("wholeLineUpdateBefore",!0);b("theme","default",function(c){lg(c);$b(c)},!0);b("keyMap","default",function(c,e,f){e=Xc(e);(f=f!=Hb&&Xc(f))&&f.detach&&f.detach(c,e);e.attach&&e.attach(c,f||null)});b("extraKeys",null);b("configureMouse",null);b("lineWrapping",!1,yh,!0);b("gutters",[],function(c,e){c.display.gutterSpecs=Yd(e,c.options.lineNumbers);$b(c)},!0);b("fixedGutter",!0,function(c,e){c.display.gutters.style.left=
e?Md(c.display)+"px":"0";c.refresh()},!0);b("coverGutterNextToScrollbar",!1,function(c){return yb(c)},!0);b("scrollbarStyle","native",function(c){of(c);yb(c);c.display.scrollbars.setScrollTop(c.doc.scrollTop);c.display.scrollbars.setScrollLeft(c.doc.scrollLeft)},!0);b("lineNumbers",!1,function(c,e){c.display.gutterSpecs=Yd(c.options.gutters,e);$b(c)},!0);b("firstLineNumber",1,$b,!0);b("lineNumberFormatter",function(c){return c},$b,!0);b("showCursorWhenSelecting",!1,Vb,!0);b("resetSelectionOnContextMenu",
!0);b("lineWiseCopyCut",!0);b("pasteLinesPerSelection",!0);b("selectionsMayTouch",!1);b("readOnly",!1,function(c,e){"nocursor"==e&&(wb(c),c.display.input.blur());c.display.input.readOnlyChanged(e)});b("screenReaderLabel",null,function(c,e){c.display.input.screenReaderLabelChanged(""===e?null:e)});b("disableInput",!1,function(c,e){e||c.display.input.reset()},!0);b("dragDrop",!0,xh);b("allowDropFileTypes",null);b("cursorBlinkRate",530);b("cursorScrollMargin",0);b("cursorHeight",1,Vb,!0);b("singleCursorHeightPerLine",
!0,Vb,!0);b("workTime",100);b("workDelay",100);b("flattenSpans",!0,bc,!0);b("addModeClass",!1,bc,!0);b("pollInterval",100);b("undoDepth",200,function(c,e){return c.doc.history.undoDepth=e});b("historyEventDelay",1250);b("viewportMargin",10,function(c){return c.refresh()},!0);b("maxHighlightLength",1E4,bc,!0);b("moveInputWithCursor",!0,function(c,e){e||c.display.input.resetPosition()});b("tabindex",null,function(c,e){return c.display.input.getField().tabIndex=e||""});b("autofocus",null);b("direction",
"ltr",function(c,e){return c.doc.setDirection(e)},!0);b("phrases",null)})(U);(function(a){var b=a.optionHandlers,d=a.helpers={};a.prototype={constructor:a,focus:function(){qa(this).defaultView.focus();this.display.input.focus()},setOption:function(c,e){var f=this.options,g=f[c];if(f[c]!=e||"mode"==c)f[c]=e,b.hasOwnProperty(c)&&ba(this,b[c])(this,e,g),W(this,"optionChange",this,c)},getOption:function(c){return this.options[c]},getDoc:function(){return this.doc},addKeyMap:function(c,e){this.state.keyMaps[e?
"push":"unshift"](Xc(c))},removeKeyMap:function(c){for(var e=this.state.keyMaps,f=0;f<e.length;++f)if(e[f]==c||e[f].name==c)return e.splice(f,1),!0},addOverlay:ia(function(c,e){var f=c.token?c:a.getMode(this.options,c);if(f.startState)throw Error("Overlays may not be stateful.");yg(this.state.overlays,{mode:f,modeSpec:c,opaque:e&&e.opaque,priority:e&&e.priority||0},function(g){return g.priority});this.state.modeGen++;ma(this)}),removeOverlay:ia(function(c){for(var e=this.state.overlays,f=0;f<e.length;++f){var g=
e[f].modeSpec;if(g==c||"string"==typeof c&&g.name==c){e.splice(f,1);this.state.modeGen++;ma(this);break}}}),indentLine:ia(function(c,e,f){"string"!=typeof e&&"number"!=typeof e&&(e=null==e?this.options.smartIndent?"smart":"prev":e?"add":"subtract");Nb(this.doc,c)&&nc(this,c,e,f)}),indentSelection:ia(function(c){for(var e=this.doc.sel.ranges,f=-1,g=0;g<e.length;g++){var h=e[g];if(h.empty())h.head.line>f&&(nc(this,h.head.line,c,!0),f=h.head.line,g==this.doc.sel.primIndex&&xb(this));else{var k=h.from();
h=h.to();var l=Math.max(f,k.line);f=Math.min(this.lastLine(),h.line-(h.ch?0:1))+1;for(h=l;h<f;++h)nc(this,h,c);h=this.doc.sel.ranges;0==k.ch&&e.length==h.length&&0<h[g].from().ch&&de(this.doc,g,new I(k,h[g].to()),Ia)}}}),getTokenAt:function(c,e){return Ce(this,c,e)},getLineTokens:function(c,e){return Ce(this,t(c),e,!0)},getTokenTypeAt:function(c){c=C(this.doc,c);var e=Ae(this,w(this.doc,c.line)),f=0,g=(e.length-1)/2;c=c.ch;if(0==c)e=e[2];else for(;;){var h=f+g>>1;if((h?e[2*h-1]:0)>=c)g=h;else if(e[2*
h+1]<c)f=h+1;else{e=e[2*h+2];break}}f=e?e.indexOf("overlay "):-1;return 0>f?e:0==f?null:e.slice(0,f-1)},getModeAt:function(c){var e=this.doc.mode;return e.innerMode?a.innerMode(e,this.getTokenAt(c).state).mode:e},getHelper:function(c,e){return this.getHelpers(c,e)[0]},getHelpers:function(c,e){var f=[];if(!d.hasOwnProperty(e))return f;var g=d[e];c=this.getModeAt(c);if("string"==typeof c[e])g[c[e]]&&f.push(g[c[e]]);else if(c[e])for(var h=0;h<c[e].length;h++){var k=g[c[e][h]];k&&f.push(k)}else c.helperType&&
g[c.helperType]?f.push(g[c.helperType]):g[c.name]&&f.push(g[c.name]);for(e=0;e<g._global.length;e++)h=g._global[e],h.pred(c,this)&&-1==ea(f,h.val)&&f.push(h.val);return f},getStateAfter:function(c,e){var f=this.doc;c=Math.max(f.first,Math.min(null==c?f.first+f.size-1:c,f.first+f.size-1));return Ob(this,c+1,e).state},cursorCoords:function(c,e){var f=this.doc.sel.primary();c=null==c?f.head:"object"==typeof c?C(this.doc,c):c?f.from():f.to();return Ba(this,c,e||"page")},charCoords:function(c,e){return Ic(this,
C(this.doc,c),e||"page")},coordsChar:function(c,e){c=af(this,c,e||"page");return Kd(this,c.left,c.top)},lineAtHeight:function(c,e){c=af(this,{top:c,left:0},e||"page").top;return bb(this.doc,c+this.display.viewOffset)},heightAtLine:function(c,e,f){var g=!1;if("number"==typeof c){var h=this.doc.first+this.doc.size-1;c<this.doc.first?c=this.doc.first:c>h&&(c=h,g=!0);c=w(this.doc,c)}return Hc(this,c,{top:0,left:0},e||"page",f||g).top+(g?this.doc.height-Ga(c):0)},defaultTextHeight:function(){return vb(this.display)},
defaultCharWidth:function(){return ub(this.display)},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(c,e,f,g,h){var k=this.display;c=Ba(this,C(this.doc,c));var l=c.bottom,m=c.left;e.style.position="absolute";e.setAttribute("cm-ignore-events","true");this.display.input.setUneditable(e);k.sizer.appendChild(e);if("over"==g)l=c.top;else if("above"==g||"near"==g){var n=Math.max(k.wrapper.clientHeight,this.doc.height),p=Math.max(k.sizer.clientWidth,k.lineSpace.clientWidth);
("above"==g||c.bottom+e.offsetHeight>n)&&c.top>e.offsetHeight?l=c.top-e.offsetHeight:c.bottom+e.offsetHeight<=n&&(l=c.bottom);m+e.offsetWidth>p&&(m=p-e.offsetWidth)}e.style.top=l+"px";e.style.left=e.style.right="";"right"==h?(m=k.sizer.clientWidth-e.offsetWidth,e.style.right="0px"):("left"==h?m=0:"middle"==h&&(m=(k.sizer.clientWidth-e.offsetWidth)/2),e.style.left=m+"px");f&&(c=Td(this,{left:m,top:l,right:m+e.offsetWidth,bottom:l+e.offsetHeight}),null!=c.scrollTop&&Xb(this,c.scrollTop),null!=c.scrollLeft&&
kb(this,c.scrollLeft))},triggerOnKeyDown:ia(fg),triggerOnKeyPress:ia(hg),triggerOnKeyUp:gg,triggerOnMouseDown:ia(ig),execCommand:function(c){if(jc.hasOwnProperty(c))return jc[c].call(null,this)},triggerElectric:ia(function(c){og(this,c)}),findPosH:function(c,e,f,g){var h=1;0>e&&(h=-1,e=-e);c=C(this.doc,c);for(var k=0;k<e&&(c=oe(this.doc,c,h,f,g),!c.hitSide);++k);return c},moveH:ia(function(c,e){var f=this;this.extendSelectionsBy(function(g){return f.display.shift||f.doc.extend||g.empty()?oe(f.doc,
g.head,c,e,f.options.rtlMoveVisually):0>c?g.from():g.to()},qc)}),deleteH:ia(function(c,e){var f=this.doc;this.doc.sel.somethingSelected()?f.replaceSelection("",null,"+delete"):Gb(this,function(g){var h=oe(f,g.head,c,e,!1);return 0>c?{from:h,to:g.head}:{from:g.head,to:h}})}),findPosV:function(c,e,f,g){var h=1;0>e&&(h=-1,e=-e);var k=C(this.doc,c);for(c=0;c<e&&(k=Ba(this,k,"div"),null==g?g=k.left:k.left=g,k=tg(this,k,h,f),!k.hitSide);++c);return k},moveV:ia(function(c,e){var f=this,g=this.doc,h=[],k=
!this.display.shift&&!g.extend&&g.sel.somethingSelected();g.extendSelectionsBy(function(m){if(k)return 0>c?m.from():m.to();var n=Ba(f,m.head,"div");null!=m.goalColumn&&(n.left=m.goalColumn);h.push(n.left);var p=tg(f,n,c,e);"page"==e&&m==g.sel.primary()&&Nc(f,Ic(f,p,"div").top-n.top);return p},qc);if(h.length)for(var l=0;l<g.sel.ranges.length;l++)g.sel.ranges[l].goalColumn=h[l]}),findWordAt:function(c){var e=w(this.doc,c.line).text,f=c.ch,g=c.ch;if(e){var h=this.getHelper(c,"wordChars");"before"!=
c.sticky&&g!=e.length||!f?++g:--f;var k=e.charAt(f);for(k=xc(k,h)?function(l){return xc(l,h)}:/\s/.test(k)?function(l){return/\s/.test(l)}:function(l){return!/\s/.test(l)&&!xc(l)};0<f&&k(e.charAt(f-1));)--f;for(;g<e.length&&k(e.charAt(g));)++g}return new I(t(c.line,f),t(c.line,g))},toggleOverwrite:function(c){if(null==c||c!=this.state.overwrite)(this.state.overwrite=!this.state.overwrite)?Ya(this.display.cursorDiv,"CodeMirror-overwrite"):jb(this.display.cursorDiv,"CodeMirror-overwrite"),W(this,"overwriteToggle",
this,this.state.overwrite)},hasFocus:function(){return this.display.input.getField()==ka(qa(this))},isReadOnly:function(){return!(!this.options.readOnly&&!this.doc.cantEdit)},scrollTo:ia(function(c,e){Wb(this,c,e)}),getScrollInfo:function(){var c=this.display.scroller;return{left:c.scrollLeft,top:c.scrollTop,height:c.scrollHeight-Ha(this)-this.display.barHeight,width:c.scrollWidth-Ha(this)-this.display.barWidth,clientHeight:Ed(this),clientWidth:cb(this)}},scrollIntoView:ia(function(c,e){null==c?(c=
{from:this.doc.sel.primary().head,to:null},null==e&&(e=this.options.cursorScrollMargin)):"number"==typeof c?c={from:t(c,0),to:null}:null==c.from&&(c={from:c,to:null});c.to||(c.to=c.from);c.margin=e||0;null!=c.from.line?(Oc(this),this.curOp.scrollToPos=c):kf(this,c.from,c.to,c.margin)}),setSize:ia(function(c,e){var f=this,g=function(k){return"number"==typeof k||/^\d+$/.test(String(k))?k+"px":k};null!=c&&(this.display.wrapper.style.width=g(c));null!=e&&(this.display.wrapper.style.height=g(e));this.options.lineWrapping&&
Ye(this);var h=this.display.viewFrom;this.doc.iter(h,this.display.viewTo,function(k){if(k.widgets)for(var l=0;l<k.widgets.length;l++)if(k.widgets[l].noHScroll){Sa(f,h,"widget");break}++h});this.curOp.forceUpdate=!0;W(this,"refresh",this)}),operation:function(c){return ra(this,c)},startOperation:function(){return lb(this)},endOperation:function(){return mb(this)},refresh:ia(function(){var c=this.display.cachedTextHeight;ma(this);this.curOp.forceUpdate=!0;Ub(this);Wb(this,this.doc.scrollLeft,this.doc.scrollTop);
Xd(this.display);(null==c||.5<Math.abs(c-vb(this.display))||this.options.lineWrapping)&&Nd(this);W(this,"refresh",this)}),swapDoc:ia(function(c){var e=this.doc;e.cm=null;this.state.selectingText&&this.state.selectingText();zf(this,c);Ub(this);this.display.input.reset();Wb(this,c.scrollLeft,c.scrollTop);this.curOp.forceScroll=!0;aa(this,"swapDoc",this,e);return e}),phrase:function(c){var e=this.options.phrases;return e&&Object.prototype.hasOwnProperty.call(e,c)?e[c]:c},getInputField:function(){return this.display.input.getField()},
getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}};pb(a);a.registerHelper=function(c,e,f){d.hasOwnProperty(c)||(d[c]=a[c]={_global:[]});d[c][e]=f};a.registerGlobalHelper=function(c,e,f,g){a.registerHelper(c,e,g);d[c]._global.push({pred:f,val:g})}})(U);var Ih="iter insert remove copy getEditor constructor".split(" "),uc;for(uc in oa.prototype)oa.prototype.hasOwnProperty(uc)&&
0>ea(Ih,uc)&&(U.prototype[uc]=function(a){return function(){return a.apply(this.doc,arguments)}}(oa.prototype[uc]));pb(oa);U.inputStyles={textarea:V,contenteditable:O};U.defineMode=function(a){U.defaults.mode||"null"==a||(U.defaults.mode=a);Dg.apply(this,arguments)};U.defineMIME=function(a,b){qb[a]=b};U.defineMode("null",function(){return{token:function(a){return a.skipToEnd()}}});U.defineMIME("text/plain","null");U.defineExtension=function(a,b){U.prototype[a]=b};U.defineDocExtension=function(a,b){oa.prototype[a]=
b};U.fromTextArea=function(a,b){function d(){a.value=h.getValue()}b=b?Za(b):{};b.value=a.value;!b.tabindex&&a.tabIndex&&(b.tabindex=a.tabIndex);!b.placeholder&&a.placeholder&&(b.placeholder=a.placeholder);if(null==b.autofocus){var c=ka(a.ownerDocument);b.autofocus=c==a||null!=a.getAttribute("autofocus")&&c==document.body}if(a.form&&(z(a.form,"submit",d),!b.leaveSubmitMethodAlone)){var e=a.form;var f=e.submit;try{var g=e.submit=function(){d();e.submit=f;e.submit();e.submit=g}}catch(k){}}b.finishInit=
function(k){k.save=d;k.getTextArea=function(){return a};k.toTextArea=function(){k.toTextArea=isNaN;d();a.parentNode.removeChild(k.getWrapperElement());a.style.display="";a.form&&(ta(a.form,"submit",d),b.leaveSubmitMethodAlone||"function"!=typeof a.form.submit||(a.form.submit=f))}};a.style.display="none";var h=U(function(k){return a.parentNode.insertBefore(k,a.nextSibling)},b);return h};(function(a){a.off=ta;a.on=z;a.wheelEventPixels=Zg;a.Doc=oa;a.splitLines=ne;a.countColumn=wa;a.findColumn=hd;a.isWordChar=
jd;a.Pass=Zc;a.signal=W;a.Line=zb;a.changeEnd=Ta;a.scrollbarModel=pf;a.Pos=t;a.cmpPos=B;a.modes=md;a.mimeModes=qb;a.resolveMode=zc;a.getMode=nd;a.modeExtensions=rb;a.extendMode=Eg;a.copyState=$a;a.startState=we;a.innerMode=od;a.commands=jc;a.keyMap=ic;a.keyName=ag;a.isModifierKey=Yf;a.lookupKey=Fb;a.normalizeKeyMap=jh;a.StringStream=X;a.SharedTextMarker=hc;a.TextMarker=Va;a.LineWidget=gc;a.e_preventDefault=la;a.e_stopPropagation=ue;a.e_stop=Mb;a.addClass=Ya;a.contains=ja;a.rmClass=jb;a.keyNames=Wa})(U);
U.version="5.65.9";return U});
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],59:[function(require,module,exports){
(function(v){"object"==typeof exports&&"object"==typeof module?v(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],v):v(CodeMirror)})(function(v){v.defineMode("javascript",function(Ua,A){var p,w,f;function u(a,b,d){V=a;ca=d;return b}function I(a,b){var d=a.next();if('"'==d||"'"==d)return b.tokenize=Va(d),b.tokenize(a,b);if("."==d&&a.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/))return u("number","number");if("."==d&&a.match(".."))return u("spread","meta");
if(/[\[\]{}\(\),;:\.]/.test(d))return u(d);if("="==d&&a.eat(">"))return u("=>","operator");if("0"==d&&a.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/))return u("number","number");if(/\d/.test(d))return a.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/),u("number","number");if("/"==d){if(a.eat("*"))return b.tokenize=da,da(a,b);if(a.eat("/"))return a.skipToEnd(),u("comment","comment");if(Aa(a,b,1)){a:for(var e=b=!1;null!=(d=a.next());){if(!b){if("/"==d&&!e)break a;"["==d?e=!0:e&&"]"==d&&(e=
!1)}b=!b&&"\\"==d}a.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/);return u("regexp","string-2")}a.eat("=");return u("operator","operator",a.current())}if("`"==d)return b.tokenize=W,W(a,b);if("#"==d&&"!"==a.peek())return a.skipToEnd(),u("meta","meta");if("#"==d&&a.eatWhile(ea))return u("variable","property");if("<"==d&&a.match("!--")||"-"==d&&a.match("->")&&!/\S/.test(a.string.slice(0,a.start)))return a.skipToEnd(),u("comment","comment");if(Ba.test(d))return">"==d&&b.lexical&&">"==b.lexical.type||(a.eat("=")?
"!"!=d&&"="!=d||a.eat("="):/[<>*+\-|&?]/.test(d)&&(a.eat(d),">"==d&&a.eat(d))),"?"==d&&a.eat(".")?u("."):u("operator","operator",a.current());if(ea.test(d)){a.eatWhile(ea);d=a.current();if("."!=b.lastType){if(Ca.propertyIsEnumerable(d))return a=Ca[d],u(a.type,a.style,d);if("async"==d&&a.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/,!1))return u("async","keyword",d)}return u("variable","variable",d)}}function Va(a){return function(b,d){var e=!1,h;if(fa&&"@"==b.peek()&&b.match(Wa))return d.tokenize=
I,u("jsonld-keyword","meta");for(;null!=(h=b.next())&&(h!=a||e);)e=!e&&"\\"==h;e||(d.tokenize=I);return u("string","string")}}function da(a,b){for(var d=!1,e;e=a.next();){if("/"==e&&d){b.tokenize=I;break}d="*"==e}return u("comment","comment")}function W(a,b){for(var d=!1,e;null!=(e=a.next());){if(!d&&("`"==e||"$"==e&&a.eat("{"))){b.tokenize=I;break}d=!d&&"\\"==e}return u("quasi","string-2",a.current())}function qa(a,b){b.fatArrowAt&&(b.fatArrowAt=null);var d=a.string.indexOf("=>",a.start);if(!(0>
d)){if(r){var e=/:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(a.string.slice(a.start,d));e&&(d=e.index)}e=0;var h=!1;for(--d;0<=d;--d){var m=a.string.charAt(d),y="([{}])".indexOf(m);if(0<=y&&3>y){if(!e){++d;break}if(0==--e){"("==m&&(h=!0);break}}else if(3<=y&&6>y)++e;else if(ea.test(m))h=!0;else if(/["'\/`]/.test(m))for(;;--d){if(0==d)return;if(a.string.charAt(d-1)==m&&"\\"!=a.string.charAt(d-2)){d--;break}}else if(h&&!e){++d;break}}h&&!e&&(b.fatArrowAt=d)}}function Da(a,b,d,e,h,m){this.indented=
a;this.column=b;this.type=d;this.prev=h;this.info=m;null!=e&&(this.align=e)}function Ea(a,b,d,e,h){var m=a.cc;p=a;w=h;f=null;ra=m;X=b;a.lexical.hasOwnProperty("align")||(a.lexical.align=!0);for(;;)if((m.length?m.pop():J?t:x)(d,e)){for(;m.length&&m[m.length-1].lex;)m.pop()();if(f)return f;if(d="variable"==d)a:if(Fa){for(d=a.localVars;d;d=d.next)if(d.name==e){d=!0;break a}for(a=a.context;a;a=a.prev)for(d=a.vars;d;d=d.next)if(d.name==e){d=!0;break a}d=void 0}else d=!1;return d?"variable-2":b}}function k(){for(var a=
arguments.length-1;0<=a;a--)ra.push(arguments[a])}function c(){k.apply(null,arguments);return!0}function sa(a,b){for(;b;b=b.next)if(b.name==a)return!0;return!1}function O(a){var b=p;f="def";if(Fa){if(b.context)if("var"==b.lexical.info&&b.context&&b.context.block){var d=Ga(a,b.context);if(null!=d){b.context=d;return}}else if(!sa(a,b.localVars)){b.localVars=new Y(a,b.localVars);return}A.globalVars&&!sa(a,b.globalVars)&&(b.globalVars=new Y(a,b.globalVars))}}function Ga(a,b){return b?b.block?(a=Ga(a,
b.prev))?a==b.prev?b:new Z(a,b.vars,!0):null:sa(a,b.vars)?b:new Z(b.prev,new Y(a,b.vars),!1):null}function ha(a){return"public"==a||"private"==a||"protected"==a||"abstract"==a||"readonly"==a}function Z(a,b,d){this.prev=a;this.vars=b;this.block=d}function Y(a,b){this.name=a;this.next=b}function K(){p.context=new Z(p.context,p.localVars,!1);p.localVars=Xa}function ia(){p.context=new Z(p.context,p.localVars,!0);p.localVars=null}function C(){p.localVars=p.context.vars;p.context=p.context.prev}function l(a,
b){var d=function(){var e=p,h=e.indented;if("stat"==e.lexical.type)h=e.lexical.indented;else for(var m=e.lexical;m&&")"==m.type&&m.align;m=m.prev)h=m.indented;e.lexical=new Da(h,w.column(),a,null,e.lexical,b)};d.lex=!0;return d}function g(){var a=p;a.lexical.prev&&(")"==a.lexical.type&&(a.indented=a.lexical.indented),a.lexical=a.lexical.prev)}function n(a){function b(d){return d==a?c():";"==a||"}"==d||")"==d||"]"==d?k():c(b)}return b}function x(a,b){return"var"==a?c(l("vardef",b),ta,n(";"),g):"keyword a"==
a?c(l("form"),ua,x,g):"keyword b"==a?c(l("form"),x,g):"keyword d"==a?w.match(/^\s*$/,!1)?c():c(l("stat"),P,n(";"),g):"debugger"==a?c(n(";")):"{"==a?c(l("}"),ia,ja,g,C):";"==a?c():"if"==a?("else"==p.lexical.info&&p.cc[p.cc.length-1]==g&&p.cc.pop()(),c(l("form"),ua,x,g,Ha)):"function"==a?c(G):"for"==a?c(l("form"),ia,Ia,x,C,g):"class"==a||r&&"interface"==b?(f="keyword",c(l("form","class"==a?a:b),Ja,g)):"variable"==a?r&&"declare"==b?(f="keyword",c(x)):r&&("module"==b||"enum"==b||"type"==b)&&w.match(/^\s*\w/,
!1)?(f="keyword","enum"==b?c(Ka):"type"==b?c(La,n("operator"),q,n(";")):c(l("form"),D,n("{"),l("}"),ja,g,g)):r&&"namespace"==b?(f="keyword",c(l("form"),t,x,g)):r&&"abstract"==b?(f="keyword",c(x)):c(l("stat"),Ya):"switch"==a?c(l("form"),ua,n("{"),l("}","switch"),ia,ja,g,g,C):"case"==a?c(t,n(":")):"default"==a?c(n(":")):"catch"==a?c(l("form"),K,Za,x,g,C):"export"==a?c(l("stat"),$a,g):"import"==a?c(l("stat"),ab,g):"async"==a?c(x):"@"==b?c(t,x):k(l("stat"),t,n(";"),g)}function Za(a){if("("==a)return c(L,
n(")"))}function t(a,b){return Ma(a,b,!1)}function B(a,b){return Ma(a,b,!0)}function ua(a){return"("!=a?k():c(l(")"),P,n(")"),g)}function Ma(a,b,d){if(p.fatArrowAt==w.start){var e=d?Na:Oa;if("("==a)return c(K,l(")"),z(L,")"),g,n("=>"),e,C);if("variable"==a)return k(K,D,n("=>"),e,C)}e=d?Q:M;return bb.hasOwnProperty(a)?c(e):"function"==a?c(G,e):"class"==a||r&&"interface"==b?(f="keyword",c(l("form"),cb,g)):"keyword c"==a||"async"==a?c(d?B:t):"("==a?c(l(")"),P,n(")"),g,e):"operator"==a||"spread"==a?c(d?
B:t):"["==a?c(l("]"),db,g,e):"{"==a?aa(ka,"}",null,e):"quasi"==a?k(la,e):"new"==a?c(eb(d)):c()}function P(a){return a.match(/[;\}\)\],]/)?k():k(t)}function M(a,b){return","==a?c(P):Q(a,b,!1)}function Q(a,b,d){var e=0==d?M:Q,h=0==d?t:B;if("=>"==a)return c(K,d?Na:Oa,C);if("operator"==a)return/\+\+|--/.test(b)||r&&"!"==b?c(e):r&&"<"==b&&w.match(/^([^<>]|<[^<>]*>)*>\s*\(/,!1)?c(l(">"),z(q,">"),g,e):"?"==b?c(t,n(":"),h):c(h);if("quasi"==a)return k(la,e);if(";"!=a){if("("==a)return aa(B,")","call",e);if("."==
a)return c(fb,e);if("["==a)return c(l("]"),P,n("]"),g,e);if(r&&"as"==b)return f="keyword",c(q,e);if("regexp"==a)return p.lastType=f="operator",w.backUp(w.pos-w.start-1),c(h)}}function la(a,b){return"quasi"!=a?k():"${"!=b.slice(b.length-2)?c(la):c(P,gb)}function gb(a){if("}"==a)return f="string-2",p.tokenize=W,c(la)}function Oa(a){qa(w,p);return k("{"==a?x:t)}function Na(a){qa(w,p);return k("{"==a?x:B)}function eb(a){return function(b){return"."==b?c(a?hb:ib):"variable"==b&&r?c(jb,a?Q:M):k(a?B:t)}}
function ib(a,b){if("target"==b)return f="keyword",c(M)}function hb(a,b){if("target"==b)return f="keyword",c(Q)}function Ya(a){return":"==a?c(g,x):k(M,n(";"),g)}function fb(a){if("variable"==a)return f="property",c()}function ka(a,b){if("async"==a)return f="property",c(ka);if("variable"==a||"keyword"==X){f="property";if("get"==b||"set"==b)return c(kb);var d;r&&p.fatArrowAt==w.start&&(d=w.match(/^\s*:\s*/,!1))&&(p.fatArrowAt=w.pos+d[0].length);return c(N)}if("number"==a||"string"==a)return f=fa?"property":
X+" property",c(N);if("jsonld-keyword"==a)return c(N);if(r&&ha(b))return f="keyword",c(ka);if("["==a)return c(t,R,n("]"),N);if("spread"==a)return c(B,N);if("*"==b)return f="keyword",c(ka);if(":"==a)return k(N)}function kb(a){if("variable"!=a)return k(N);f="property";return c(G)}function N(a){if(":"==a)return c(B);if("("==a)return k(G)}function z(a,b,d){function e(h,m){return(d?-1<d.indexOf(h):","==h)?(h=p.lexical,"call"==h.info&&(h.pos=(h.pos||0)+1),c(function(y,va){return y==b||va==b?k():k(a)},e)):
h==b||m==b?c():d&&-1<d.indexOf(";")?k(a):c(n(b))}return function(h,m){return h==b||m==b?c():k(a,e)}}function aa(a,b,d){for(var e=3;e<arguments.length;e++)ra.push(arguments[e]);return c(l(b,d),z(a,b),g)}function ja(a){return"}"==a?c():k(x,ja)}function R(a,b){if(r){if(":"==a)return c(q);if("?"==b)return c(R)}}function lb(a,b){if(r&&(":"==a||"in"==b))return c(q)}function Pa(a){if(r&&":"==a)return w.match(/^\s*\w+\s+is\b/,!1)?c(t,mb,q):c(q)}function mb(a,b){if("is"==b)return f="keyword",c()}function q(a,
b){if("keyof"==b||"typeof"==b||"infer"==b||"readonly"==b)return f="keyword",c("typeof"==b?B:q);if("variable"==a||"void"==b)return f="type",c(E);if("|"==b||"&"==b)return c(q);if("string"==a||"number"==a||"atom"==a)return c(E);if("["==a)return c(l("]"),z(q,"]",","),g,E);if("{"==a)return c(l("}"),wa,g,E);if("("==a)return c(z(xa,")"),nb,E);if("<"==a)return c(z(q,">"),q);if("quasi"==a)return k(ya,E)}function nb(a){if("=>"==a)return c(q)}function wa(a){return a.match(/[\}\)\]]/)?c():","==a||";"==a?c(wa):
k(ba,wa)}function ba(a,b){if("variable"==a||"keyword"==X)return f="property",c(ba);if("?"==b||"number"==a||"string"==a)return c(ba);if(":"==a)return c(q);if("["==a)return c(n("variable"),lb,n("]"),ba);if("("==a)return k(S,ba);if(!a.match(/[;\}\)\],]/))return c()}function ya(a,b){return"quasi"!=a?k():"${"!=b.slice(b.length-2)?c(ya):c(q,ob)}function ob(a){if("}"==a)return f="string-2",p.tokenize=W,c(ya)}function xa(a,b){return"variable"==a&&w.match(/^\s*[?:]/,!1)||"?"==b?c(xa):":"==a?c(q):"spread"==
a?c(xa):k(q)}function E(a,b){if("<"==b)return c(l(">"),z(q,">"),g,E);if("|"==b||"."==a||"&"==b)return c(q);if("["==a)return c(q,n("]"),E);if("extends"==b||"implements"==b)return f="keyword",c(q);if("?"==b)return c(q,n(":"),q)}function jb(a,b){if("<"==b)return c(l(">"),z(q,">"),g,E)}function ma(){return k(q,pb)}function pb(a,b){if("="==b)return c(q)}function ta(a,b){return"enum"==b?(f="keyword",c(Ka)):k(D,R,H,qb)}function D(a,b){if(r&&ha(b))return f="keyword",c(D);if("variable"==a)return O(b),c();
if("spread"==a)return c(D);if("["==a)return aa(rb,"]");if("{"==a)return aa(Qa,"}")}function Qa(a,b){if("variable"==a&&!w.match(/^\s*:/,!1))return O(b),c(H);"variable"==a&&(f="property");return"spread"==a?c(D):"}"==a?k():"["==a?c(t,n("]"),n(":"),Qa):c(n(":"),D,H)}function rb(){return k(D,H)}function H(a,b){if("="==b)return c(B)}function qb(a){if(","==a)return c(ta)}function Ha(a,b){if("keyword b"==a&&"else"==b)return c(l("form","else"),x,g)}function Ia(a,b){if("await"==b)return c(Ia);if("("==a)return c(l(")"),
sb,g)}function sb(a){return"var"==a?c(ta,T):"variable"==a?c(T):k(T)}function T(a,b){return")"==a?c():";"==a?c(T):"in"==b||"of"==b?(f="keyword",c(t,T)):k(t,T)}function G(a,b){if("*"==b)return f="keyword",c(G);if("variable"==a)return O(b),c(G);if("("==a)return c(K,l(")"),z(L,")"),g,Pa,x,C);if(r&&"<"==b)return c(l(">"),z(ma,">"),g,G)}function S(a,b){if("*"==b)return f="keyword",c(S);if("variable"==a)return O(b),c(S);if("("==a)return c(K,l(")"),z(L,")"),g,Pa,C);if(r&&"<"==b)return c(l(">"),z(ma,">"),
g,S)}function La(a,b){if("keyword"==a||"variable"==a)return f="type",c(La);if("<"==b)return c(l(">"),z(ma,">"),g)}function L(a,b){"@"==b&&c(t,L);return"spread"==a?c(L):r&&ha(b)?(f="keyword",c(L)):r&&"this"==a?c(R,H):k(D,R,H)}function cb(a,b){return"variable"==a?Ja(a,b):na(a,b)}function Ja(a,b){if("variable"==a)return O(b),c(na)}function na(a,b){if("<"==b)return c(l(">"),z(ma,">"),g,na);if("extends"==b||"implements"==b||r&&","==a)return"implements"==b&&(f="keyword"),c(r?q:t,na);if("{"==a)return c(l("}"),
F,g)}function F(a,b){if("async"==a||"variable"==a&&("static"==b||"get"==b||"set"==b||r&&ha(b))&&w.match(/^\s+[\w$\xa1-\uffff]/,!1))return f="keyword",c(F);if("variable"==a||"keyword"==X)return f="property",c(oa,F);if("number"==a||"string"==a)return c(oa,F);if("["==a)return c(t,R,n("]"),oa,F);if("*"==b)return f="keyword",c(F);if(r&&"("==a)return k(S,F);if(";"==a||","==a)return c(F);if("}"==a)return c();if("@"==b)return c(t,F)}function oa(a,b){if("!"==b||"?"==b)return c(oa);if(":"==a)return c(q,H);
if("="==b)return c(B);a=p.lexical.prev;return k(a&&"interface"==a.info?S:G)}function $a(a,b){return"*"==b?(f="keyword",c(za,n(";"))):"default"==b?(f="keyword",c(t,n(";"))):"{"==a?c(z(Ra,"}"),za,n(";")):k(x)}function Ra(a,b){if("as"==b)return f="keyword",c(n("variable"));if("variable"==a)return k(B,Ra)}function ab(a){return"string"==a?c():"("==a?k(t):"."==a?k(M):k(pa,Sa,za)}function pa(a,b){if("{"==a)return aa(pa,"}");"variable"==a&&O(b);"*"==b&&(f="keyword");return c(tb)}function Sa(a){if(","==a)return c(pa,
Sa)}function tb(a,b){if("as"==b)return f="keyword",c(pa)}function za(a,b){if("from"==b)return f="keyword",c(t)}function db(a){return"]"==a?c():k(z(B,"]"))}function Ka(){return k(l("form"),D,n("{"),l("}"),z(ub,"}"),g,g)}function ub(){return k(D,H)}function Aa(a,b,d){return b.tokenize==I&&/^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(b.lastType)||"quasi"==b.lastType&&/\{\s*$/.test(a.string.slice(0,a.pos-(d||0)))}var U=Ua.indentUnit,Ta=A.statementIndent,fa=A.jsonld,
J=A.json||fa,Fa=!1!==A.trackScope,r=A.typescript,ea=A.wordCharacters||/[\w$\xa1-\uffff]/,Ca=function(){function a(va){return{type:va,style:"keyword"}}var b=a("keyword a"),d=a("keyword b"),e=a("keyword c"),h=a("keyword d"),m=a("operator"),y={type:"atom",style:"atom"};return{"if":a("if"),"while":b,"with":b,"else":d,"do":d,"try":d,"finally":d,"return":h,"break":h,"continue":h,"new":a("new"),"delete":e,"void":e,"throw":e,"debugger":a("debugger"),"var":a("var"),"const":a("var"),let:a("var"),"function":a("function"),
"catch":a("catch"),"for":a("for"),"switch":a("switch"),"case":a("case"),"default":a("default"),"in":m,"typeof":m,"instanceof":m,"true":y,"false":y,"null":y,undefined:y,NaN:y,Infinity:y,"this":a("this"),"class":a("class"),"super":a("atom"),yield:e,"export":a("export"),"import":a("import"),"extends":e,await:e}}(),Ba=/[+\-*&%=<>!?|~^@]/,Wa=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/,V,ca,bb={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,"this":!0,"import":!0,
"jsonld-keyword":!0};var ra=f=p=null;var X=w=void 0;var Xa=new Y("this",new Y("arguments",null));K.lex=ia.lex=!0;C.lex=!0;g.lex=!0;return{startState:function(a){a={tokenize:I,lastType:"sof",cc:[],lexical:new Da((a||0)-U,0,"block",!1),localVars:A.localVars,context:A.localVars&&new Z(null,null,!1),indented:a||0};A.globalVars&&"object"==typeof A.globalVars&&(a.globalVars=A.globalVars);return a},token:function(a,b){a.sol()&&(b.lexical.hasOwnProperty("align")||(b.lexical.align=!1),b.indented=a.indentation(),
qa(a,b));if(b.tokenize!=da&&a.eatSpace())return null;var d=b.tokenize(a,b);if("comment"==V)return d;b.lastType="operator"!=V||"++"!=ca&&"--"!=ca?V:"incdec";return Ea(b,d,V,ca,a)},indent:function(a,b){if(a.tokenize==da||a.tokenize==W)return v.Pass;if(a.tokenize!=I)return 0;var d=b&&b.charAt(0),e=a.lexical,h;if(!/^\s*else\b/.test(b))for(var m=a.cc.length-1;0<=m;--m){var y=a.cc[m];if(y==g)e=e.prev;else if(y!=Ha&&y!=C)break}for(;!("stat"!=e.type&&"form"!=e.type||"}"!=d&&(!(h=a.cc[a.cc.length-1])||h!=
M&&h!=Q||/^[,\.=+\-*:?[\(]/.test(b)));)e=e.prev;Ta&&")"==e.type&&"stat"==e.prev.type&&(e=e.prev);h=e.type;m=d==h;return"vardef"==h?e.indented+("operator"==a.lastType||","==a.lastType?e.info.length+1:0):"form"==h&&"{"==d?e.indented:"form"==h?e.indented+U:"stat"==h?(d=e.indented,a="operator"==a.lastType||","==a.lastType||Ba.test(b.charAt(0))||/[,.]/.test(b.charAt(0)),d+(a?Ta||U:0)):"switch"!=e.info||m||0==A.doubleIndentSwitch?e.align?e.column+(m?0:1):e.indented+(m?0:U):e.indented+(/^(?:case|default)\b/.test(b)?
U:2*U)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:J?null:"/*",blockCommentEnd:J?null:"*/",blockCommentContinue:J?null:" * ",lineComment:J?null:"//",fold:"brace",closeBrackets:"()[]{}''\"\"``",helperType:J?"json":"javascript",jsonldMode:fa,jsonMode:J,expressionAllowed:Aa,skipExpression:function(a){Ea(a,"atom","atom","true",new v.StringStream("",2,null))}}});v.registerHelper("wordChars","javascript",/[\w$]/);v.defineMIME("text/javascript","javascript");v.defineMIME("text/ecmascript",
"javascript");v.defineMIME("application/javascript","javascript");v.defineMIME("application/x-javascript","javascript");v.defineMIME("application/ecmascript","javascript");v.defineMIME("application/json",{name:"javascript",json:!0});v.defineMIME("application/x-json",{name:"javascript",json:!0});v.defineMIME("application/manifest+json",{name:"javascript",json:!0});v.defineMIME("application/ld+json",{name:"javascript",jsonld:!0});v.defineMIME("text/typescript",{name:"javascript",typescript:!0});v.defineMIME("application/typescript",
{name:"javascript",typescript:!0})});
},{"../../lib/codemirror":58}],60:[function(require,module,exports){
/**
* Slice reference.
*/
var slice = [].slice;
/**
* Bind `obj` to `fn`.
*
* @param {Object} obj
* @param {Function|String} fn or string
* @return {Function}
* @api public
*/
module.exports = function(obj, fn){
if ('string' == typeof fn) fn = obj[fn];
if ('function' != typeof fn) throw new Error('bind() requires a function');
var args = slice.call(arguments, 2);
return function(){
return fn.apply(obj, args.concat(slice.call(arguments)));
}
};
},{}],61:[function(require,module,exports){
/**
* Expose `Emitter`.
*/
if (typeof module !== 'undefined') {
module.exports = Emitter;
}
/**
* Initialize a new `Emitter`.
*
* @api public
*/
function Emitter(obj) {
if (obj) return mixin(obj);
};
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
(this._callbacks['$' + event] = this._callbacks['$' + event] || [])
.push(fn);
return this;
};
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function(event, fn){
function on() {
this.off(event, on);
fn.apply(this, arguments);
}
on.fn = fn;
this.on(event, on);
return this;
};
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
// all
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
// specific event
var callbacks = this._callbacks['$' + event];
if (!callbacks) return this;
// remove all handlers
if (1 == arguments.length) {
delete this._callbacks['$' + event];
return this;
}
// remove specific handler
var cb;
for (var i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
// Remove event specific arrays for event types that no
// one is subscribed for to avoid memory leak.
if (callbacks.length === 0) {
delete this._callbacks['$' + event];
}
return this;
};
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function(event){
this._callbacks = this._callbacks || {};
var args = new Array(arguments.length - 1)
, callbacks = this._callbacks['$' + event];
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function(event){
this._callbacks = this._callbacks || {};
return this._callbacks['$' + event] || [];
};
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function(event){
return !! this.listeners(event).length;
};
},{}],62:[function(require,module,exports){
module.exports = function(a, b){
var fn = function(){};
fn.prototype = b.prototype;
a.prototype = new fn;
a.prototype.constructor = a;
};
},{}],63:[function(require,module,exports){
'use strict'
module.exports = ready
function ready (callback) {
if (typeof document === 'undefined') {
throw new Error('document-ready only runs in the browser')
}
var state = document.readyState
if (state === 'complete' || state === 'interactive') {
return setTimeout(callback, 0)
}
document.addEventListener('DOMContentLoaded', function onLoad () {
callback()
})
}
},{}],64:[function(require,module,exports){
module.exports = (function () {
if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')(); // eslint-disable-line no-new-func
}
})();
},{}],65:[function(require,module,exports){
module.exports = require('./socket');
/**
* Exports parser
*
* @api public
*
*/
module.exports.parser = require('engine.io-parser');
},{"./socket":66,"engine.io-parser":77}],66:[function(require,module,exports){
/**
* Module dependencies.
*/
var transports = require('./transports/index');
var Emitter = require('component-emitter');
var debug = require('debug')('engine.io-client:socket');
var index = require('indexof');
var parser = require('engine.io-parser');
var parseuri = require('parseuri');
var parseqs = require('parseqs');
/**
* Module exports.
*/
module.exports = Socket;
/**
* Socket constructor.
*
* @param {String|Object} uri or options
* @param {Object} options
* @api public
*/
function Socket (uri, opts) {
if (!(this instanceof Socket)) return new Socket(uri, opts);
opts = opts || {};
if (uri && 'object' === typeof uri) {
opts = uri;
uri = null;
}
if (uri) {
uri = parseuri(uri);
opts.hostname = uri.host;
opts.secure = uri.protocol === 'https' || uri.protocol === 'wss';
opts.port = uri.port;
if (uri.query) opts.query = uri.query;
} else if (opts.host) {
opts.hostname = parseuri(opts.host).host;
}
this.secure = null != opts.secure ? opts.secure
: (typeof location !== 'undefined' && 'https:' === location.protocol);
if (opts.hostname && !opts.port) {
// if no port is specified manually, use the protocol default
opts.port = this.secure ? '443' : '80';
}
this.agent = opts.agent || false;
this.hostname = opts.hostname ||
(typeof location !== 'undefined' ? location.hostname : 'localhost');
this.port = opts.port || (typeof location !== 'undefined' && location.port
? location.port
: (this.secure ? 443 : 80));
this.query = opts.query || {};
if ('string' === typeof this.query) this.query = parseqs.decode(this.query);
this.upgrade = false !== opts.upgrade;
this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
this.forceJSONP = !!opts.forceJSONP;
this.jsonp = false !== opts.jsonp;
this.forceBase64 = !!opts.forceBase64;
this.enablesXDR = !!opts.enablesXDR;
this.withCredentials = false !== opts.withCredentials;
this.timestampParam = opts.timestampParam || 't';
this.timestampRequests = opts.timestampRequests;
this.transports = opts.transports || ['polling', 'websocket'];
this.transportOptions = opts.transportOptions || {};
this.readyState = '';
this.writeBuffer = [];
this.prevBufferLen = 0;
this.policyPort = opts.policyPort || 843;
this.rememberUpgrade = opts.rememberUpgrade || false;
this.binaryType = null;
this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false;
if (true === this.perMessageDeflate) this.perMessageDeflate = {};
if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) {
this.perMessageDeflate.threshold = 1024;
}
// SSL options for Node.js client
this.pfx = opts.pfx || undefined;
this.key = opts.key || undefined;
this.passphrase = opts.passphrase || undefined;
this.cert = opts.cert || undefined;
this.ca = opts.ca || undefined;
this.ciphers = opts.ciphers || undefined;
this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? true : opts.rejectUnauthorized;
this.forceNode = !!opts.forceNode;
// detect ReactNative environment
this.isReactNative = (typeof navigator !== 'undefined' && typeof navigator.product === 'string' && navigator.product.toLowerCase() === 'reactnative');
// other options for Node.js or ReactNative client
if (typeof self === 'undefined' || this.isReactNative) {
if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) {
this.extraHeaders = opts.extraHeaders;
}
if (opts.localAddress) {
this.localAddress = opts.localAddress;
}
}
// set on handshake
this.id = null;
this.upgrades = null;
this.pingInterval = null;
this.pingTimeout = null;
// set on heartbeat
this.pingIntervalTimer = null;
this.pingTimeoutTimer = null;
this.open();
}
Socket.priorWebsocketSuccess = false;
/**
* Mix in `Emitter`.
*/
Emitter(Socket.prototype);
/**
* Protocol version.
*
* @api public
*/
Socket.protocol = parser.protocol; // this is an int
/**
* Expose deps for legacy compatibility
* and standalone browser access.
*/
Socket.Socket = Socket;
Socket.Transport = require('./transport');
Socket.transports = require('./transports/index');
Socket.parser = require('engine.io-parser');
/**
* Creates transport of the given type.
*
* @param {String} transport name
* @return {Transport}
* @api private
*/
Socket.prototype.createTransport = function (name) {
debug('creating transport "%s"', name);
var query = clone(this.query);
// append engine.io protocol identifier
query.EIO = parser.protocol;
// transport name
query.transport = name;
// per-transport options
var options = this.transportOptions[name] || {};
// session id if we already have one
if (this.id) query.sid = this.id;
var transport = new transports[name]({
query: query,
socket: this,
agent: options.agent || this.agent,
hostname: options.hostname || this.hostname,
port: options.port || this.port,
secure: options.secure || this.secure,
path: options.path || this.path,
forceJSONP: options.forceJSONP || this.forceJSONP,
jsonp: options.jsonp || this.jsonp,
forceBase64: options.forceBase64 || this.forceBase64,
enablesXDR: options.enablesXDR || this.enablesXDR,
withCredentials: options.withCredentials || this.withCredentials,
timestampRequests: options.timestampRequests || this.timestampRequests,
timestampParam: options.timestampParam || this.timestampParam,
policyPort: options.policyPort || this.policyPort,
pfx: options.pfx || this.pfx,
key: options.key || this.key,
passphrase: options.passphrase || this.passphrase,
cert: options.cert || this.cert,
ca: options.ca || this.ca,
ciphers: options.ciphers || this.ciphers,
rejectUnauthorized: options.rejectUnauthorized || this.rejectUnauthorized,
perMessageDeflate: options.perMessageDeflate || this.perMessageDeflate,
extraHeaders: options.extraHeaders || this.extraHeaders,
forceNode: options.forceNode || this.forceNode,
localAddress: options.localAddress || this.localAddress,
requestTimeout: options.requestTimeout || this.requestTimeout,
protocols: options.protocols || void (0),
isReactNative: this.isReactNative
});
return transport;
};
function clone (obj) {
var o = {};
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
o[i] = obj[i];
}
}
return o;
}
/**
* Initializes transport to use and starts probe.
*
* @api private
*/
Socket.prototype.open = function () {
var transport;
if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) {
transport = 'websocket';
} else if (0 === this.transports.length) {
// Emit error on next tick so it can be listened to
var self = this;
setTimeout(function () {
self.emit('error', 'No transports available');
}, 0);
return;
} else {
transport = this.transports[0];
}
this.readyState = 'opening';
// Retry with the next transport if the transport is disabled (jsonp: false)
try {
transport = this.createTransport(transport);
} catch (e) {
this.transports.shift();
this.open();
return;
}
transport.open();
this.setTransport(transport);
};
/**
* Sets the current transport. Disables the existing one (if any).
*
* @api private
*/
Socket.prototype.setTransport = function (transport) {
debug('setting transport %s', transport.name);
var self = this;
if (this.transport) {
debug('clearing existing transport %s', this.transport.name);
this.transport.removeAllListeners();
}
// set up transport
this.transport = transport;
// set up transport listeners
transport
.on('drain', function () {
self.onDrain();
})
.on('packet', function (packet) {
self.onPacket(packet);
})
.on('error', function (e) {
self.onError(e);
})
.on('close', function () {
self.onClose('transport close');
});
};
/**
* Probes a transport.
*
* @param {String} transport name
* @api private
*/
Socket.prototype.probe = function (name) {
debug('probing transport "%s"', name);
var transport = this.createTransport(name, { probe: 1 });
var failed = false;
var self = this;
Socket.priorWebsocketSuccess = false;
function onTransportOpen () {
if (self.onlyBinaryUpgrades) {
var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
failed = failed || upgradeLosesBinary;
}
if (failed) return;
debug('probe transport "%s" opened', name);
transport.send([{ type: 'ping', data: 'probe' }]);
transport.once('packet', function (msg) {
if (failed) return;
if ('pong' === msg.type && 'probe' === msg.data) {
debug('probe transport "%s" pong', name);
self.upgrading = true;
self.emit('upgrading', transport);
if (!transport) return;
Socket.priorWebsocketSuccess = 'websocket' === transport.name;
debug('pausing current transport "%s"', self.transport.name);
self.transport.pause(function () {
if (failed) return;
if ('closed' === self.readyState) return;
debug('changing transport and sending upgrade packet');
cleanup();
self.setTransport(transport);
transport.send([{ type: 'upgrade' }]);
self.emit('upgrade', transport);
transport = null;
self.upgrading = false;
self.flush();
});
} else {
debug('probe transport "%s" failed', name);
var err = new Error('probe error');
err.transport = transport.name;
self.emit('upgradeError', err);
}
});
}
function freezeTransport () {
if (failed) return;
// Any callback called by transport should be ignored since now
failed = true;
cleanup();
transport.close();
transport = null;
}
// Handle any error that happens while probing
function onerror (err) {
var error = new Error('probe error: ' + err);
error.transport = transport.name;
freezeTransport();
debug('probe transport "%s" failed because of error: %s', name, err);
self.emit('upgradeError', error);
}
function onTransportClose () {
onerror('transport closed');
}
// When the socket is closed while we're probing
function onclose () {
onerror('socket closed');
}
// When the socket is upgraded while we're probing
function onupgrade (to) {
if (transport && to.name !== transport.name) {
debug('"%s" works - aborting "%s"', to.name, transport.name);
freezeTransport();
}
}
// Remove all listeners on the transport and on self
function cleanup () {
transport.removeListener('open', onTransportOpen);
transport.removeListener('error', onerror);
transport.removeListener('close', onTransportClose);
self.removeListener('close', onclose);
self.removeListener('upgrading', onupgrade);
}
transport.once('open', onTransportOpen);
transport.once('error', onerror);
transport.once('close', onTransportClose);
this.once('close', onclose);
this.once('upgrading', onupgrade);
transport.open();
};
/**
* Called when connection is deemed open.
*
* @api public
*/
Socket.prototype.onOpen = function () {
debug('socket open');
this.readyState = 'open';
Socket.priorWebsocketSuccess = 'websocket' === this.transport.name;
this.emit('open');
this.flush();
// we check for `readyState` in case an `open`
// listener already closed the socket
if ('open' === this.readyState && this.upgrade && this.transport.pause) {
debug('starting upgrade probes');
for (var i = 0, l = this.upgrades.length; i < l; i++) {
this.probe(this.upgrades[i]);
}
}
};
/**
* Handles a packet.
*
* @api private
*/
Socket.prototype.onPacket = function (packet) {
if ('opening' === this.readyState || 'open' === this.readyState ||
'closing' === this.readyState) {
debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
this.emit('packet', packet);
// Socket is live - any packet counts
this.emit('heartbeat');
switch (packet.type) {
case 'open':
this.onHandshake(JSON.parse(packet.data));
break;
case 'pong':
this.setPing();
this.emit('pong');
break;
case 'error':
var err = new Error('server error');
err.code = packet.data;
this.onError(err);
break;
case 'message':
this.emit('data', packet.data);
this.emit('message', packet.data);
break;
}
} else {
debug('packet received with socket readyState "%s"', this.readyState);
}
};
/**
* Called upon handshake completion.
*
* @param {Object} handshake obj
* @api private
*/
Socket.prototype.onHandshake = function (data) {
this.emit('handshake', data);
this.id = data.sid;
this.transport.query.sid = data.sid;
this.upgrades = this.filterUpgrades(data.upgrades);
this.pingInterval = data.pingInterval;
this.pingTimeout = data.pingTimeout;
this.onOpen();
// In case open handler closes socket
if ('closed' === this.readyState) return;
this.setPing();
// Prolong liveness of socket on heartbeat
this.removeListener('heartbeat', this.onHeartbeat);
this.on('heartbeat', this.onHeartbeat);
};
/**
* Resets ping timeout.
*
* @api private
*/
Socket.prototype.onHeartbeat = function (timeout) {
clearTimeout(this.pingTimeoutTimer);
var self = this;
self.pingTimeoutTimer = setTimeout(function () {
if ('closed' === self.readyState) return;
self.onClose('ping timeout');
}, timeout || (self.pingInterval + self.pingTimeout));
};
/**
* Pings server every `this.pingInterval` and expects response
* within `this.pingTimeout` or closes connection.
*
* @api private
*/
Socket.prototype.setPing = function () {
var self = this;
clearTimeout(self.pingIntervalTimer);
self.pingIntervalTimer = setTimeout(function () {
debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
self.ping();
self.onHeartbeat(self.pingTimeout);
}, self.pingInterval);
};
/**
* Sends a ping packet.
*
* @api private
*/
Socket.prototype.ping = function () {
var self = this;
this.sendPacket('ping', function () {
self.emit('ping');
});
};
/**
* Called on `drain` event
*
* @api private
*/
Socket.prototype.onDrain = function () {
this.writeBuffer.splice(0, this.prevBufferLen);
// setting prevBufferLen = 0 is very important
// for example, when upgrading, upgrade packet is sent over,
// and a nonzero prevBufferLen could cause problems on `drain`
this.prevBufferLen = 0;
if (0 === this.writeBuffer.length) {
this.emit('drain');
} else {
this.flush();
}
};
/**
* Flush write buffers.
*
* @api private
*/
Socket.prototype.flush = function () {
if ('closed' !== this.readyState && this.transport.writable &&
!this.upgrading && this.writeBuffer.length) {
debug('flushing %d packets in socket', this.writeBuffer.length);
this.transport.send(this.writeBuffer);
// keep track of current length of writeBuffer
// splice writeBuffer and callbackBuffer on `drain`
this.prevBufferLen = this.writeBuffer.length;
this.emit('flush');
}
};
/**
* Sends a message.
*
* @param {String} message.
* @param {Function} callback function.
* @param {Object} options.
* @return {Socket} for chaining.
* @api public
*/
Socket.prototype.write =
Socket.prototype.send = function (msg, options, fn) {
this.sendPacket('message', msg, options, fn);
return this;
};
/**
* Sends a packet.
*
* @param {String} packet type.
* @param {String} data.
* @param {Object} options.
* @param {Function} callback function.
* @api private
*/
Socket.prototype.sendPacket = function (type, data, options, fn) {
if ('function' === typeof data) {
fn = data;
data = undefined;
}
if ('function' === typeof options) {
fn = options;
options = null;
}
if ('closing' === this.readyState || 'closed' === this.readyState) {
return;
}
options = options || {};
options.compress = false !== options.compress;
var packet = {
type: type,
data: data,
options: options
};
this.emit('packetCreate', packet);
this.writeBuffer.push(packet);
if (fn) this.once('flush', fn);
this.flush();
};
/**
* Closes the connection.
*
* @api private
*/
Socket.prototype.close = function () {
if ('opening' === this.readyState || 'open' === this.readyState) {
this.readyState = 'closing';
var self = this;
if (this.writeBuffer.length) {
this.once('drain', function () {
if (this.upgrading) {
waitForUpgrade();
} else {
close();
}
});
} else if (this.upgrading) {
waitForUpgrade();
} else {
close();
}
}
function close () {
self.onClose('forced close');
debug('socket closing - telling transport to close');
self.transport.close();
}
function cleanupAndClose () {
self.removeListener('upgrade', cleanupAndClose);
self.removeListener('upgradeError', cleanupAndClose);
close();
}
function waitForUpgrade () {
// wait for upgrade to finish since we can't send packets while pausing a transport
self.once('upgrade', cleanupAndClose);
self.once('upgradeError', cleanupAndClose);
}
return this;
};
/**
* Called upon transport error
*
* @api private
*/
Socket.prototype.onError = function (err) {
debug('socket error %j', err);
Socket.priorWebsocketSuccess = false;
this.emit('error', err);
this.onClose('transport error', err);
};
/**
* Called upon transport close.
*
* @api private
*/
Socket.prototype.onClose = function (reason, desc) {
if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) {
debug('socket close with reason: "%s"', reason);
var self = this;
// clear timers
clearTimeout(this.pingIntervalTimer);
clearTimeout(this.pingTimeoutTimer);
// stop event from firing again for transport
this.transport.removeAllListeners('close');
// ensure transport won't stay open
this.transport.close();
// ignore further transport communication
this.transport.removeAllListeners();
// set ready state
this.readyState = 'closed';
// clear session id
this.id = null;
// emit close event
this.emit('close', reason, desc);
// clean buffers after, so users can still
// grab the buffers on `close` event
self.writeBuffer = [];
self.prevBufferLen = 0;
}
};
/**
* Filters upgrades, returning only those matching client transports.
*
* @param {Array} server upgrades
* @api private
*
*/
Socket.prototype.filterUpgrades = function (upgrades) {
var filteredUpgrades = [];
for (var i = 0, j = upgrades.length; i < j; i++) {
if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
}
return filteredUpgrades;
};
},{"./transport":67,"./transports/index":68,"component-emitter":61,"debug":74,"engine.io-parser":77,"indexof":101,"parseqs":156,"parseuri":157}],67:[function(require,module,exports){
/**
* Module dependencies.
*/
var parser = require('engine.io-parser');
var Emitter = require('component-emitter');
/**
* Module exports.
*/
module.exports = Transport;
/**
* Transport abstract constructor.
*
* @param {Object} options.
* @api private
*/
function Transport (opts) {
this.path = opts.path;
this.hostname = opts.hostname;
this.port = opts.port;
this.secure = opts.secure;
this.query = opts.query;
this.timestampParam = opts.timestampParam;
this.timestampRequests = opts.timestampRequests;
this.readyState = '';
this.agent = opts.agent || false;
this.socket = opts.socket;
this.enablesXDR = opts.enablesXDR;
this.withCredentials = opts.withCredentials;
// SSL options for Node.js client
this.pfx = opts.pfx;
this.key = opts.key;
this.passphrase = opts.passphrase;
this.cert = opts.cert;
this.ca = opts.ca;
this.ciphers = opts.ciphers;
this.rejectUnauthorized = opts.rejectUnauthorized;
this.forceNode = opts.forceNode;
// results of ReactNative environment detection
this.isReactNative = opts.isReactNative;
// other options for Node.js client
this.extraHeaders = opts.extraHeaders;
this.localAddress = opts.localAddress;
}
/**
* Mix in `Emitter`.
*/
Emitter(Transport.prototype);
/**
* Emits an error.
*
* @param {String} str
* @return {Transport} for chaining
* @api public
*/
Transport.prototype.onError = function (msg, desc) {
var err = new Error(msg);
err.type = 'TransportError';
err.description = desc;
this.emit('error', err);
return this;
};
/**
* Opens the transport.
*
* @api public
*/
Transport.prototype.open = function () {
if ('closed' === this.readyState || '' === this.readyState) {
this.readyState = 'opening';
this.doOpen();
}
return this;
};
/**
* Closes the transport.
*
* @api private
*/
Transport.prototype.close = function () {
if ('opening' === this.readyState || 'open' === this.readyState) {
this.doClose();
this.onClose();
}
return this;
};
/**
* Sends multiple packets.
*
* @param {Array} packets
* @api private
*/
Transport.prototype.send = function (packets) {
if ('open' === this.readyState) {
this.write(packets);
} else {
throw new Error('Transport not open');
}
};
/**
* Called upon open
*
* @api private
*/
Transport.prototype.onOpen = function () {
this.readyState = 'open';
this.writable = true;
this.emit('open');
};
/**
* Called with data.
*
* @param {String} data
* @api private
*/
Transport.prototype.onData = function (data) {
var packet = parser.decodePacket(data, this.socket.binaryType);
this.onPacket(packet);
};
/**
* Called with a decoded packet.
*/
Transport.prototype.onPacket = function (packet) {
this.emit('packet', packet);
};
/**
* Called upon close.
*
* @api private
*/
Transport.prototype.onClose = function () {
this.readyState = 'closed';
this.emit('close');
};
},{"component-emitter":61,"engine.io-parser":77}],68:[function(require,module,exports){
/**
* Module dependencies
*/
var XMLHttpRequest = require('./xmlhttprequest');
var XHR = require('./polling-xhr');
var JSONP = require('./polling-jsonp');
var websocket = require('./websocket');
/**
* Export transports.
*/
exports.polling = polling;
exports.websocket = websocket;
/**
* Polling transport polymorphic constructor.
* Decides on xhr vs jsonp based on feature detection.
*
* @api private
*/
function polling (opts) {
var xhr;
var xd = false;
var xs = false;
var jsonp = false !== opts.jsonp;
if (typeof location !== 'undefined') {
var isSSL = 'https:' === location.protocol;
var port = location.port;
// some user agents have empty `location.port`
if (!port) {
port = isSSL ? 443 : 80;
}
xd = opts.hostname !== location.hostname || port !== opts.port;
xs = opts.secure !== isSSL;
}
opts.xdomain = xd;
opts.xscheme = xs;
xhr = new XMLHttpRequest(opts);
if ('open' in xhr && !opts.forceJSONP) {
return new XHR(opts);
} else {
if (!jsonp) throw new Error('JSONP disabled');
return new JSONP(opts);
}
}
},{"./polling-jsonp":69,"./polling-xhr":70,"./websocket":72,"./xmlhttprequest":73}],69:[function(require,module,exports){
/**
* Module requirements.
*/
var Polling = require('./polling');
var inherit = require('component-inherit');
var globalThis = require('../globalThis');
/**
* Module exports.
*/
module.exports = JSONPPolling;
/**
* Cached regular expressions.
*/
var rNewline = /\n/g;
var rEscapedNewline = /\\n/g;
/**
* Global JSONP callbacks.
*/
var callbacks;
/**
* Noop.
*/
function empty () { }
/**
* JSONP Polling constructor.
*
* @param {Object} opts.
* @api public
*/
function JSONPPolling (opts) {
Polling.call(this, opts);
this.query = this.query || {};
// define global callbacks array if not present
// we do this here (lazily) to avoid unneeded global pollution
if (!callbacks) {
// we need to consider multiple engines in the same page
callbacks = globalThis.___eio = (globalThis.___eio || []);
}
// callback identifier
this.index = callbacks.length;
// add callback to jsonp global
var self = this;
callbacks.push(function (msg) {
self.onData(msg);
});
// append to query string
this.query.j = this.index;
// prevent spurious errors from being emitted when the window is unloaded
if (typeof addEventListener === 'function') {
addEventListener('beforeunload', function () {
if (self.script) self.script.onerror = empty;
}, false);
}
}
/**
* Inherits from Polling.
*/
inherit(JSONPPolling, Polling);
/*
* JSONP only supports binary as base64 encoded strings
*/
JSONPPolling.prototype.supportsBinary = false;
/**
* Closes the socket.
*
* @api private
*/
JSONPPolling.prototype.doClose = function () {
if (this.script) {
this.script.parentNode.removeChild(this.script);
this.script = null;
}
if (this.form) {
this.form.parentNode.removeChild(this.form);
this.form = null;
this.iframe = null;
}
Polling.prototype.doClose.call(this);
};
/**
* Starts a poll cycle.
*
* @api private
*/
JSONPPolling.prototype.doPoll = function () {
var self = this;
var script = document.createElement('script');
if (this.script) {
this.script.parentNode.removeChild(this.script);
this.script = null;
}
script.async = true;
script.src = this.uri();
script.onerror = function (e) {
self.onError('jsonp poll error', e);
};
var insertAt = document.getElementsByTagName('script')[0];
if (insertAt) {
insertAt.parentNode.insertBefore(script, insertAt);
} else {
(document.head || document.body).appendChild(script);
}
this.script = script;
var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent);
if (isUAgecko) {
setTimeout(function () {
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
document.body.removeChild(iframe);
}, 100);
}
};
/**
* Writes with a hidden iframe.
*
* @param {String} data to send
* @param {Function} called upon flush.
* @api private
*/
JSONPPolling.prototype.doWrite = function (data, fn) {
var self = this;
if (!this.form) {
var form = document.createElement('form');
var area = document.createElement('textarea');
var id = this.iframeId = 'eio_iframe_' + this.index;
var iframe;
form.className = 'socketio';
form.style.position = 'absolute';
form.style.top = '-1000px';
form.style.left = '-1000px';
form.target = id;
form.method = 'POST';
form.setAttribute('accept-charset', 'utf-8');
area.name = 'd';
form.appendChild(area);
document.body.appendChild(form);
this.form = form;
this.area = area;
}
this.form.action = this.uri();
function complete () {
initIframe();
fn();
}
function initIframe () {
if (self.iframe) {
try {
self.form.removeChild(self.iframe);
} catch (e) {
self.onError('jsonp polling iframe removal error', e);
}
}
try {
// ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
var html = '<iframe src="javascript:0" name="' + self.iframeId + '">';
iframe = document.createElement(html);
} catch (e) {
iframe = document.createElement('iframe');
iframe.name = self.iframeId;
iframe.src = 'javascript:0';
}
iframe.id = self.iframeId;
self.form.appendChild(iframe);
self.iframe = iframe;
}
initIframe();
// escape \n to prevent it from being converted into \r\n by some UAs
// double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
data = data.replace(rEscapedNewline, '\\\n');
this.area.value = data.replace(rNewline, '\\n');
try {
this.form.submit();
} catch (e) {}
if (this.iframe.attachEvent) {
this.iframe.onreadystatechange = function () {
if (self.iframe.readyState === 'complete') {
complete();
}
};
} else {
this.iframe.onload = complete;
}
};
},{"../globalThis":64,"./polling":71,"component-inherit":62}],70:[function(require,module,exports){
/* global attachEvent */
/**
* Module requirements.
*/
var XMLHttpRequest = require('./xmlhttprequest');
var Polling = require('./polling');
var Emitter = require('component-emitter');
var inherit = require('component-inherit');
var debug = require('debug')('engine.io-client:polling-xhr');
var globalThis = require('../globalThis');
/**
* Module exports.
*/
module.exports = XHR;
module.exports.Request = Request;
/**
* Empty function
*/
function empty () {}
/**
* XHR Polling constructor.
*
* @param {Object} opts
* @api public
*/
function XHR (opts) {
Polling.call(this, opts);
this.requestTimeout = opts.requestTimeout;
this.extraHeaders = opts.extraHeaders;
if (typeof location !== 'undefined') {
var isSSL = 'https:' === location.protocol;
var port = location.port;
// some user agents have empty `location.port`
if (!port) {
port = isSSL ? 443 : 80;
}
this.xd = (typeof location !== 'undefined' && opts.hostname !== location.hostname) ||
port !== opts.port;
this.xs = opts.secure !== isSSL;
}
}
/**
* Inherits from Polling.
*/
inherit(XHR, Polling);
/**
* XHR supports binary
*/
XHR.prototype.supportsBinary = true;
/**
* Creates a request.
*
* @param {String} method
* @api private
*/
XHR.prototype.request = function (opts) {
opts = opts || {};
opts.uri = this.uri();
opts.xd = this.xd;
opts.xs = this.xs;
opts.agent = this.agent || false;
opts.supportsBinary = this.supportsBinary;
opts.enablesXDR = this.enablesXDR;
opts.withCredentials = this.withCredentials;
// SSL options for Node.js client
opts.pfx = this.pfx;
opts.key = this.key;
opts.passphrase = this.passphrase;
opts.cert = this.cert;
opts.ca = this.ca;
opts.ciphers = this.ciphers;
opts.rejectUnauthorized = this.rejectUnauthorized;
opts.requestTimeout = this.requestTimeout;
// other options for Node.js client
opts.extraHeaders = this.extraHeaders;
return new Request(opts);
};
/**
* Sends data.
*
* @param {String} data to send.
* @param {Function} called upon flush.
* @api private
*/
XHR.prototype.doWrite = function (data, fn) {
var isBinary = typeof data !== 'string' && data !== undefined;
var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
var self = this;
req.on('success', fn);
req.on('error', function (err) {
self.onError('xhr post error', err);
});
this.sendXhr = req;
};
/**
* Starts a poll cycle.
*
* @api private
*/
XHR.prototype.doPoll = function () {
debug('xhr poll');
var req = this.request();
var self = this;
req.on('data', function (data) {
self.onData(data);
});
req.on('error', function (err) {
self.onError('xhr poll error', err);
});
this.pollXhr = req;
};
/**
* Request constructor
*
* @param {Object} options
* @api public
*/
function Request (opts) {
this.method = opts.method || 'GET';
this.uri = opts.uri;
this.xd = !!opts.xd;
this.xs = !!opts.xs;
this.async = false !== opts.async;
this.data = undefined !== opts.data ? opts.data : null;
this.agent = opts.agent;
this.isBinary = opts.isBinary;
this.supportsBinary = opts.supportsBinary;
this.enablesXDR = opts.enablesXDR;
this.withCredentials = opts.withCredentials;
this.requestTimeout = opts.requestTimeout;
// SSL options for Node.js client
this.pfx = opts.pfx;
this.key = opts.key;
this.passphrase = opts.passphrase;
this.cert = opts.cert;
this.ca = opts.ca;
this.ciphers = opts.ciphers;
this.rejectUnauthorized = opts.rejectUnauthorized;
// other options for Node.js client
this.extraHeaders = opts.extraHeaders;
this.create();
}
/**
* Mix in `Emitter`.
*/
Emitter(Request.prototype);
/**
* Creates the XHR object and sends the request.
*
* @api private
*/
Request.prototype.create = function () {
var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
// SSL options for Node.js client
opts.pfx = this.pfx;
opts.key = this.key;
opts.passphrase = this.passphrase;
opts.cert = this.cert;
opts.ca = this.ca;
opts.ciphers = this.ciphers;
opts.rejectUnauthorized = this.rejectUnauthorized;
var xhr = this.xhr = new XMLHttpRequest(opts);
var self = this;
try {
debug('xhr open %s: %s', this.method, this.uri);
xhr.open(this.method, this.uri, this.async);
try {
if (this.extraHeaders) {
xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
for (var i in this.extraHeaders) {
if (this.extraHeaders.hasOwnProperty(i)) {
xhr.setRequestHeader(i, this.extraHeaders[i]);
}
}
}
} catch (e) {}
if ('POST' === this.method) {
try {
if (this.isBinary) {
xhr.setRequestHeader('Content-type', 'application/octet-stream');
} else {
xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
}
} catch (e) {}
}
try {
xhr.setRequestHeader('Accept', '*/*');
} catch (e) {}
// ie6 check
if ('withCredentials' in xhr) {
xhr.withCredentials = this.withCredentials;
}
if (this.requestTimeout) {
xhr.timeout = this.requestTimeout;
}
if (this.hasXDR()) {
xhr.onload = function () {
self.onLoad();
};
xhr.onerror = function () {
self.onError(xhr.responseText);
};
} else {
xhr.onreadystatechange = function () {
if (xhr.readyState === 2) {
try {
var contentType = xhr.getResponseHeader('Content-Type');
if (self.supportsBinary && contentType === 'application/octet-stream' || contentType === 'application/octet-stream; charset=UTF-8') {
xhr.responseType = 'arraybuffer';
}
} catch (e) {}
}
if (4 !== xhr.readyState) return;
if (200 === xhr.status || 1223 === xhr.status) {
self.onLoad();
} else {
// make sure the `error` event handler that's user-set
// does not throw in the same tick and gets caught here
setTimeout(function () {
self.onError(typeof xhr.status === 'number' ? xhr.status : 0);
}, 0);
}
};
}
debug('xhr data %s', this.data);
xhr.send(this.data);
} catch (e) {
// Need to defer since .create() is called directly fhrom the constructor
// and thus the 'error' event can only be only bound *after* this exception
// occurs. Therefore, also, we cannot throw here at all.
setTimeout(function () {
self.onError(e);
}, 0);
return;
}
if (typeof document !== 'undefined') {
this.index = Request.requestsCount++;
Request.requests[this.index] = this;
}
};
/**
* Called upon successful response.
*
* @api private
*/
Request.prototype.onSuccess = function () {
this.emit('success');
this.cleanup();
};
/**
* Called if we have data.
*
* @api private
*/
Request.prototype.onData = function (data) {
this.emit('data', data);
this.onSuccess();
};
/**
* Called upon error.
*
* @api private
*/
Request.prototype.onError = function (err) {
this.emit('error', err);
this.cleanup(true);
};
/**
* Cleans up house.
*
* @api private
*/
Request.prototype.cleanup = function (fromError) {
if ('undefined' === typeof this.xhr || null === this.xhr) {
return;
}
// xmlhttprequest
if (this.hasXDR()) {
this.xhr.onload = this.xhr.onerror = empty;
} else {
this.xhr.onreadystatechange = empty;
}
if (fromError) {
try {
this.xhr.abort();
} catch (e) {}
}
if (typeof document !== 'undefined') {
delete Request.requests[this.index];
}
this.xhr = null;
};
/**
* Called upon load.
*
* @api private
*/
Request.prototype.onLoad = function () {
var data;
try {
var contentType;
try {
contentType = this.xhr.getResponseHeader('Content-Type');
} catch (e) {}
if (contentType === 'application/octet-stream' || contentType === 'application/octet-stream; charset=UTF-8') {
data = this.xhr.response || this.xhr.responseText;
} else {
data = this.xhr.responseText;
}
} catch (e) {
this.onError(e);
}
if (null != data) {
this.onData(data);
}
};
/**
* Check if it has XDomainRequest.
*
* @api private
*/
Request.prototype.hasXDR = function () {
return typeof XDomainRequest !== 'undefined' && !this.xs && this.enablesXDR;
};
/**
* Aborts the request.
*
* @api public
*/
Request.prototype.abort = function () {
this.cleanup();
};
/**
* Aborts pending requests when unloading the window. This is needed to prevent
* memory leaks (e.g. when using IE) and to ensure that no spurious error is
* emitted.
*/
Request.requestsCount = 0;
Request.requests = {};
if (typeof document !== 'undefined') {
if (typeof attachEvent === 'function') {
attachEvent('onunload', unloadHandler);
} else if (typeof addEventListener === 'function') {
var terminationEvent = 'onpagehide' in globalThis ? 'pagehide' : 'unload';
addEventListener(terminationEvent, unloadHandler, false);
}
}
function unloadHandler () {
for (var i in Request.requests) {
if (Request.requests.hasOwnProperty(i)) {
Request.requests[i].abort();
}
}
}
},{"../globalThis":64,"./polling":71,"./xmlhttprequest":73,"component-emitter":61,"component-inherit":62,"debug":74}],71:[function(require,module,exports){
/**
* Module dependencies.
*/
var Transport = require('../transport');
var parseqs = require('parseqs');
var parser = require('engine.io-parser');
var inherit = require('component-inherit');
var yeast = require('yeast');
var debug = require('debug')('engine.io-client:polling');
/**
* Module exports.
*/
module.exports = Polling;
/**
* Is XHR2 supported?
*/
var hasXHR2 = (function () {
var XMLHttpRequest = require('./xmlhttprequest');
var xhr = new XMLHttpRequest({ xdomain: false });
return null != xhr.responseType;
})();
/**
* Polling interface.
*
* @param {Object} opts
* @api private
*/
function Polling (opts) {
var forceBase64 = (opts && opts.forceBase64);
if (!hasXHR2 || forceBase64) {
this.supportsBinary = false;
}
Transport.call(this, opts);
}
/**
* Inherits from Transport.
*/
inherit(Polling, Transport);
/**
* Transport name.
*/
Polling.prototype.name = 'polling';
/**
* Opens the socket (triggers polling). We write a PING message to determine
* when the transport is open.
*
* @api private
*/
Polling.prototype.doOpen = function () {
this.poll();
};
/**
* Pauses polling.
*
* @param {Function} callback upon buffers are flushed and transport is paused
* @api private
*/
Polling.prototype.pause = function (onPause) {
var self = this;
this.readyState = 'pausing';
function pause () {
debug('paused');
self.readyState = 'paused';
onPause();
}
if (this.polling || !this.writable) {
var total = 0;
if (this.polling) {
debug('we are currently polling - waiting to pause');
total++;
this.once('pollComplete', function () {
debug('pre-pause polling complete');
--total || pause();
});
}
if (!this.writable) {
debug('we are currently writing - waiting to pause');
total++;
this.once('drain', function () {
debug('pre-pause writing complete');
--total || pause();
});
}
} else {
pause();
}
};
/**
* Starts polling cycle.
*
* @api public
*/
Polling.prototype.poll = function () {
debug('polling');
this.polling = true;
this.doPoll();
this.emit('poll');
};
/**
* Overloads onData to detect payloads.
*
* @api private
*/
Polling.prototype.onData = function (data) {
var self = this;
debug('polling got data %s', data);
var callback = function (packet, index, total) {
// if its the first message we consider the transport open
if ('opening' === self.readyState && packet.type === 'open') {
self.onOpen();
}
// if its a close packet, we close the ongoing requests
if ('close' === packet.type) {
self.onClose();
return false;
}
// otherwise bypass onData and handle the message
self.onPacket(packet);
};
// decode payload
parser.decodePayload(data, this.socket.binaryType, callback);
// if an event did not trigger closing
if ('closed' !== this.readyState) {
// if we got data we're not polling
this.polling = false;
this.emit('pollComplete');
if ('open' === this.readyState) {
this.poll();
} else {
debug('ignoring poll - transport state "%s"', this.readyState);
}
}
};
/**
* For polling, send a close packet.
*
* @api private
*/
Polling.prototype.doClose = function () {
var self = this;
function close () {
debug('writing close packet');
self.write([{ type: 'close' }]);
}
if ('open' === this.readyState) {
debug('transport open - closing');
close();
} else {
// in case we're trying to close while
// handshaking is in progress (GH-164)
debug('transport not open - deferring close');
this.once('open', close);
}
};
/**
* Writes a packets payload.
*
* @param {Array} data packets
* @param {Function} drain callback
* @api private
*/
Polling.prototype.write = function (packets) {
var self = this;
this.writable = false;
var callbackfn = function () {
self.writable = true;
self.emit('drain');
};
parser.encodePayload(packets, this.supportsBinary, function (data) {
self.doWrite(data, callbackfn);
});
};
/**
* Generates uri for connection.
*
* @api private
*/
Polling.prototype.uri = function () {
var query = this.query || {};
var schema = this.secure ? 'https' : 'http';
var port = '';
// cache busting is forced
if (false !== this.timestampRequests) {
query[this.timestampParam] = yeast();
}
if (!this.supportsBinary && !query.sid) {
query.b64 = 1;
}
query = parseqs.encode(query);
// avoid port if default for schema
if (this.port && (('https' === schema && Number(this.port) !== 443) ||
('http' === schema && Number(this.port) !== 80))) {
port = ':' + this.port;
}
// prepend ? to query
if (query.length) {
query = '?' + query;
}
var ipv6 = this.hostname.indexOf(':') !== -1;
return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
};
},{"../transport":67,"./xmlhttprequest":73,"component-inherit":62,"debug":74,"engine.io-parser":77,"parseqs":156,"yeast":227}],72:[function(require,module,exports){
(function (Buffer){(function (){
/**
* Module dependencies.
*/
var Transport = require('../transport');
var parser = require('engine.io-parser');
var parseqs = require('parseqs');
var inherit = require('component-inherit');
var yeast = require('yeast');
var debug = require('debug')('engine.io-client:websocket');
var BrowserWebSocket, NodeWebSocket;
if (typeof WebSocket !== 'undefined') {
BrowserWebSocket = WebSocket;
} else if (typeof self !== 'undefined') {
BrowserWebSocket = self.WebSocket || self.MozWebSocket;
}
if (typeof window === 'undefined') {
try {
NodeWebSocket = require('ws');
} catch (e) { }
}
/**
* Get either the `WebSocket` or `MozWebSocket` globals
* in the browser or try to resolve WebSocket-compatible
* interface exposed by `ws` for Node-like environment.
*/
var WebSocketImpl = BrowserWebSocket || NodeWebSocket;
/**
* Module exports.
*/
module.exports = WS;
/**
* WebSocket transport constructor.
*
* @api {Object} connection options
* @api public
*/
function WS (opts) {
var forceBase64 = (opts && opts.forceBase64);
if (forceBase64) {
this.supportsBinary = false;
}
this.perMessageDeflate = opts.perMessageDeflate;
this.usingBrowserWebSocket = BrowserWebSocket && !opts.forceNode;
this.protocols = opts.protocols;
if (!this.usingBrowserWebSocket) {
WebSocketImpl = NodeWebSocket;
}
Transport.call(this, opts);
}
/**
* Inherits from Transport.
*/
inherit(WS, Transport);
/**
* Transport name.
*
* @api public
*/
WS.prototype.name = 'websocket';
/*
* WebSockets support binary
*/
WS.prototype.supportsBinary = true;
/**
* Opens socket.
*
* @api private
*/
WS.prototype.doOpen = function () {
if (!this.check()) {
// let probe timeout
return;
}
var uri = this.uri();
var protocols = this.protocols;
var opts = {};
if (!this.isReactNative) {
opts.agent = this.agent;
opts.perMessageDeflate = this.perMessageDeflate;
// SSL options for Node.js client
opts.pfx = this.pfx;
opts.key = this.key;
opts.passphrase = this.passphrase;
opts.cert = this.cert;
opts.ca = this.ca;
opts.ciphers = this.ciphers;
opts.rejectUnauthorized = this.rejectUnauthorized;
}
if (this.extraHeaders) {
opts.headers = this.extraHeaders;
}
if (this.localAddress) {
opts.localAddress = this.localAddress;
}
try {
this.ws =
this.usingBrowserWebSocket && !this.isReactNative
? protocols
? new WebSocketImpl(uri, protocols)
: new WebSocketImpl(uri)
: new WebSocketImpl(uri, protocols, opts);
} catch (err) {
return this.emit('error', err);
}
if (this.ws.binaryType === undefined) {
this.supportsBinary = false;
}
if (this.ws.supports && this.ws.supports.binary) {
this.supportsBinary = true;
this.ws.binaryType = 'nodebuffer';
} else {
this.ws.binaryType = 'arraybuffer';
}
this.addEventListeners();
};
/**
* Adds event listeners to the socket
*
* @api private
*/
WS.prototype.addEventListeners = function () {
var self = this;
this.ws.onopen = function () {
self.onOpen();
};
this.ws.onclose = function () {
self.onClose();
};
this.ws.onmessage = function (ev) {
self.onData(ev.data);
};
this.ws.onerror = function (e) {
self.onError('websocket error', e);
};
};
/**
* Writes data to socket.
*
* @param {Array} array of packets.
* @api private
*/
WS.prototype.write = function (packets) {
var self = this;
this.writable = false;
// encodePacket efficient as it uses WS framing
// no need for encodePayload
var total = packets.length;
for (var i = 0, l = total; i < l; i++) {
(function (packet) {
parser.encodePacket(packet, self.supportsBinary, function (data) {
if (!self.usingBrowserWebSocket) {
// always create a new object (GH-437)
var opts = {};
if (packet.options) {
opts.compress = packet.options.compress;
}
if (self.perMessageDeflate) {
var len = 'string' === typeof data ? Buffer.byteLength(data) : data.length;
if (len < self.perMessageDeflate.threshold) {
opts.compress = false;
}
}
}
// Sometimes the websocket has already been closed but the browser didn't
// have a chance of informing us about it yet, in that case send will
// throw an error
try {
if (self.usingBrowserWebSocket) {
// TypeError is thrown when passing the second argument on Safari
self.ws.send(data);
} else {
self.ws.send(data, opts);
}
} catch (e) {
debug('websocket closed before onclose event');
}
--total || done();
});
})(packets[i]);
}
function done () {
self.emit('flush');
// fake drain
// defer to next tick to allow Socket to clear writeBuffer
setTimeout(function () {
self.writable = true;
self.emit('drain');
}, 0);
}
};
/**
* Called upon close
*
* @api private
*/
WS.prototype.onClose = function () {
Transport.prototype.onClose.call(this);
};
/**
* Closes socket.
*
* @api private
*/
WS.prototype.doClose = function () {
if (typeof this.ws !== 'undefined') {
this.ws.close();
}
};
/**
* Generates uri for connection.
*
* @api private
*/
WS.prototype.uri = function () {
var query = this.query || {};
var schema = this.secure ? 'wss' : 'ws';
var port = '';
// avoid port if default for schema
if (this.port && (('wss' === schema && Number(this.port) !== 443) ||
('ws' === schema && Number(this.port) !== 80))) {
port = ':' + this.port;
}
// append timestamp to URI
if (this.timestampRequests) {
query[this.timestampParam] = yeast();
}
// communicate binary support capabilities
if (!this.supportsBinary) {
query.b64 = 1;
}
query = parseqs.encode(query);
// prepend ? to query
if (query.length) {
query = '?' + query;
}
var ipv6 = this.hostname.indexOf(':') !== -1;
return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
};
/**
* Feature detection for WebSocket.
*
* @return {Boolean} whether this transport is available.
* @api public
*/
WS.prototype.check = function () {
return !!WebSocketImpl && !('__initialize' in WebSocketImpl && this.name === WS.prototype.name);
};
}).call(this)}).call(this,require("buffer").Buffer)
},{"../transport":67,"buffer":35,"component-inherit":62,"debug":74,"engine.io-parser":77,"parseqs":156,"ws":34,"yeast":227}],73:[function(require,module,exports){
// browser shim for xmlhttprequest module
var hasCORS = require('has-cors');
var globalThis = require('../globalThis');
module.exports = function (opts) {
var xdomain = opts.xdomain;
// scheme must be same when usign XDomainRequest
// http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
var xscheme = opts.xscheme;
// XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
// https://github.com/Automattic/engine.io-client/pull/217
var enablesXDR = opts.enablesXDR;
// XMLHttpRequest can be disabled on IE
try {
if ('undefined' !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
return new XMLHttpRequest();
}
} catch (e) { }
// Use XDomainRequest for IE8 if enablesXDR is true
// because loading bar keeps flashing when using jsonp-polling
// https://github.com/yujiosaka/socke.io-ie8-loading-example
try {
if ('undefined' !== typeof XDomainRequest && !xscheme && enablesXDR) {
return new XDomainRequest();
}
} catch (e) { }
if (!xdomain) {
try {
return new globalThis[['Active'].concat('Object').join('X')]('Microsoft.XMLHTTP');
} catch (e) { }
}
};
},{"../globalThis":64,"has-cors":91}],74:[function(require,module,exports){
(function (process){(function (){
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC',
'#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF',
'#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC',
'#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF',
'#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC',
'#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033',
'#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366',
'#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933',
'#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC',
'#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF',
'#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
return true;
}
// Internet Explorer and Edge do not support colors.
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (err) {
return '[UnexpectedJSONParseError]: ' + err.message;
}
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return;
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit')
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.debug;
} catch(e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
return window.localStorage;
} catch (e) {}
}
}).call(this)}).call(this,require('_process'))
},{"./debug":75,"_process":160}],75:[function(require,module,exports){
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require('ms');
/**
* Active `debug` instances.
*/
exports.instances = [];
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
exports.formatters = {};
/**
* Select a color.
* @param {String} namespace
* @return {Number}
* @api private
*/
function selectColor(namespace) {
var hash = 0, i;
for (i in namespace) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return exports.colors[Math.abs(hash) % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
var prevTime;
function debug() {
// disabled?
if (!debug.enabled) return;
var self = debug;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// turn the `arguments` into a proper Array
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %O
args.unshift('%O');
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// apply env-specific formatting (colors, etc.)
exports.formatArgs.call(self, args);
var logFn = debug.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = exports.enabled(namespace);
debug.useColors = exports.useColors();
debug.color = selectColor(namespace);
debug.destroy = destroy;
// env-specific initialization logic for debug instances
if ('function' === typeof exports.init) {
exports.init(debug);
}
exports.instances.push(debug);
return debug;
}
function destroy () {
var index = exports.instances.indexOf(this);
if (index !== -1) {
exports.instances.splice(index, 1);
return true;
} else {
return false;
}
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
exports.names = [];
exports.skips = [];
var i;
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
var len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
for (i = 0; i < exports.instances.length; i++) {
var instance = exports.instances[i];
instance.enabled = exports.enabled(instance.namespace);
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
if (name[name.length - 1] === '*') {
return true;
}
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
},{"ms":76}],76:[function(require,module,exports){
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isNaN(val) === false) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
if (ms >= d) {
return Math.round(ms / d) + 'd';
}
if (ms >= h) {
return Math.round(ms / h) + 'h';
}
if (ms >= m) {
return Math.round(ms / m) + 'm';
}
if (ms >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
return plural(ms, d, 'day') ||
plural(ms, h, 'hour') ||
plural(ms, m, 'minute') ||
plural(ms, s, 'second') ||
ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) {
return;
}
if (ms < n * 1.5) {
return Math.floor(ms / n) + ' ' + name;
}
return Math.ceil(ms / n) + ' ' + name + 's';
}
},{}],77:[function(require,module,exports){
/**
* Module dependencies.
*/
var keys = require('./keys');
var hasBinary = require('has-binary2');
var sliceBuffer = require('arraybuffer.slice');
var after = require('after');
var utf8 = require('./utf8');
var base64encoder;
if (typeof ArrayBuffer !== 'undefined') {
base64encoder = require('base64-arraybuffer');
}
/**
* Check if we are running an android browser. That requires us to use
* ArrayBuffer with polling transports...
*
* http://ghinda.net/jpeg-blob-ajax-android/
*/
var isAndroid = typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent);
/**
* Check if we are running in PhantomJS.
* Uploading a Blob with PhantomJS does not work correctly, as reported here:
* https://github.com/ariya/phantomjs/issues/11395
* @type boolean
*/
var isPhantomJS = typeof navigator !== 'undefined' && /PhantomJS/i.test(navigator.userAgent);
/**
* When true, avoids using Blobs to encode payloads.
* @type boolean
*/
var dontSendBlobs = isAndroid || isPhantomJS;
/**
* Current protocol version.
*/
exports.protocol = 3;
/**
* Packet types.
*/
var packets = exports.packets = {
open: 0 // non-ws
, close: 1 // non-ws
, ping: 2
, pong: 3
, message: 4
, upgrade: 5
, noop: 6
};
var packetslist = keys(packets);
/**
* Premade error packet.
*/
var err = { type: 'error', data: 'parser error' };
/**
* Create a blob api even for blob builder when vendor prefixes exist
*/
var Blob = require('blob');
/**
* Encodes a packet.
*
* <packet type id> [ <data> ]
*
* Example:
*
* 5hello world
* 3
* 4
*
* Binary is encoded in an identical principle
*
* @api private
*/
exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
if (typeof supportsBinary === 'function') {
callback = supportsBinary;
supportsBinary = false;
}
if (typeof utf8encode === 'function') {
callback = utf8encode;
utf8encode = null;
}
var data = (packet.data === undefined)
? undefined
: packet.data.buffer || packet.data;
if (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer) {
return encodeArrayBuffer(packet, supportsBinary, callback);
} else if (typeof Blob !== 'undefined' && data instanceof Blob) {
return encodeBlob(packet, supportsBinary, callback);
}
// might be an object with { base64: true, data: dataAsBase64String }
if (data && data.base64) {
return encodeBase64Object(packet, callback);
}
// Sending data as a utf-8 string
var encoded = packets[packet.type];
// data fragment is optional
if (undefined !== packet.data) {
encoded += utf8encode ? utf8.encode(String(packet.data), { strict: false }) : String(packet.data);
}
return callback('' + encoded);
};
function encodeBase64Object(packet, callback) {
// packet data is an object { base64: true, data: dataAsBase64String }
var message = 'b' + exports.packets[packet.type] + packet.data.data;
return callback(message);
}
/**
* Encode packet helpers for binary types
*/
function encodeArrayBuffer(packet, supportsBinary, callback) {
if (!supportsBinary) {
return exports.encodeBase64Packet(packet, callback);
}
var data = packet.data;
var contentArray = new Uint8Array(data);
var resultBuffer = new Uint8Array(1 + data.byteLength);
resultBuffer[0] = packets[packet.type];
for (var i = 0; i < contentArray.length; i++) {
resultBuffer[i+1] = contentArray[i];
}
return callback(resultBuffer.buffer);
}
function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
if (!supportsBinary) {
return exports.encodeBase64Packet(packet, callback);
}
var fr = new FileReader();
fr.onload = function() {
exports.encodePacket({ type: packet.type, data: fr.result }, supportsBinary, true, callback);
};
return fr.readAsArrayBuffer(packet.data);
}
function encodeBlob(packet, supportsBinary, callback) {
if (!supportsBinary) {
return exports.encodeBase64Packet(packet, callback);
}
if (dontSendBlobs) {
return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
}
var length = new Uint8Array(1);
length[0] = packets[packet.type];
var blob = new Blob([length.buffer, packet.data]);
return callback(blob);
}
/**
* Encodes a packet with binary data in a base64 string
*
* @param {Object} packet, has `type` and `data`
* @return {String} base64 encoded message
*/
exports.encodeBase64Packet = function(packet, callback) {
var message = 'b' + exports.packets[packet.type];
if (typeof Blob !== 'undefined' && packet.data instanceof Blob) {
var fr = new FileReader();
fr.onload = function() {
var b64 = fr.result.split(',')[1];
callback(message + b64);
};
return fr.readAsDataURL(packet.data);
}
var b64data;
try {
b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
} catch (e) {
// iPhone Safari doesn't let you apply with typed arrays
var typed = new Uint8Array(packet.data);
var basic = new Array(typed.length);
for (var i = 0; i < typed.length; i++) {
basic[i] = typed[i];
}
b64data = String.fromCharCode.apply(null, basic);
}
message += btoa(b64data);
return callback(message);
};
/**
* Decodes a packet. Changes format to Blob if requested.
*
* @return {Object} with `type` and `data` (if any)
* @api private
*/
exports.decodePacket = function (data, binaryType, utf8decode) {
if (data === undefined) {
return err;
}
// String data
if (typeof data === 'string') {
if (data.charAt(0) === 'b') {
return exports.decodeBase64Packet(data.substr(1), binaryType);
}
if (utf8decode) {
data = tryDecode(data);
if (data === false) {
return err;
}
}
var type = data.charAt(0);
if (Number(type) != type || !packetslist[type]) {
return err;
}
if (data.length > 1) {
return { type: packetslist[type], data: data.substring(1) };
} else {
return { type: packetslist[type] };
}
}
var asArray = new Uint8Array(data);
var type = asArray[0];
var rest = sliceBuffer(data, 1);
if (Blob && binaryType === 'blob') {
rest = new Blob([rest]);
}
return { type: packetslist[type], data: rest };
};
function tryDecode(data) {
try {
data = utf8.decode(data, { strict: false });
} catch (e) {
return false;
}
return data;
}
/**
* Decodes a packet encoded in a base64 string
*
* @param {String} base64 encoded message
* @return {Object} with `type` and `data` (if any)
*/
exports.decodeBase64Packet = function(msg, binaryType) {
var type = packetslist[msg.charAt(0)];
if (!base64encoder) {
return { type: type, data: { base64: true, data: msg.substr(1) } };
}
var data = base64encoder.decode(msg.substr(1));
if (binaryType === 'blob' && Blob) {
data = new Blob([data]);
}
return { type: type, data: data };
};
/**
* Encodes multiple messages (payload).
*
* <length>:data
*
* Example:
*
* 11:hello world2:hi
*
* If any contents are binary, they will be encoded as base64 strings. Base64
* encoded strings are marked with a b before the length specifier
*
* @param {Array} packets
* @api private
*/
exports.encodePayload = function (packets, supportsBinary, callback) {
if (typeof supportsBinary === 'function') {
callback = supportsBinary;
supportsBinary = null;
}
var isBinary = hasBinary(packets);
if (supportsBinary && isBinary) {
if (Blob && !dontSendBlobs) {
return exports.encodePayloadAsBlob(packets, callback);
}
return exports.encodePayloadAsArrayBuffer(packets, callback);
}
if (!packets.length) {
return callback('0:');
}
function setLengthHeader(message) {
return message.length + ':' + message;
}
function encodeOne(packet, doneCallback) {
exports.encodePacket(packet, !isBinary ? false : supportsBinary, false, function(message) {
doneCallback(null, setLengthHeader(message));
});
}
map(packets, encodeOne, function(err, results) {
return callback(results.join(''));
});
};
/**
* Async array map using after
*/
function map(ary, each, done) {
var result = new Array(ary.length);
var next = after(ary.length, done);
var eachWithIndex = function(i, el, cb) {
each(el, function(error, msg) {
result[i] = msg;
cb(error, result);
});
};
for (var i = 0; i < ary.length; i++) {
eachWithIndex(i, ary[i], next);
}
}
/*
* Decodes data when a payload is maybe expected. Possible binary contents are
* decoded from their base64 representation
*
* @param {String} data, callback method
* @api public
*/
exports.decodePayload = function (data, binaryType, callback) {
if (typeof data !== 'string') {
return exports.decodePayloadAsBinary(data, binaryType, callback);
}
if (typeof binaryType === 'function') {
callback = binaryType;
binaryType = null;
}
var packet;
if (data === '') {
// parser error - ignoring payload
return callback(err, 0, 1);
}
var length = '', n, msg;
for (var i = 0, l = data.length; i < l; i++) {
var chr = data.charAt(i);
if (chr !== ':') {
length += chr;
continue;
}
if (length === '' || (length != (n = Number(length)))) {
// parser error - ignoring payload
return callback(err, 0, 1);
}
msg = data.substr(i + 1, n);
if (length != msg.length) {
// parser error - ignoring payload
return callback(err, 0, 1);
}
if (msg.length) {
packet = exports.decodePacket(msg, binaryType, false);
if (err.type === packet.type && err.data === packet.data) {
// parser error in individual packet - ignoring payload
return callback(err, 0, 1);
}
var ret = callback(packet, i + n, l);
if (false === ret) return;
}
// advance cursor
i += n;
length = '';
}
if (length !== '') {
// parser error - ignoring payload
return callback(err, 0, 1);
}
};
/**
* Encodes multiple messages (payload) as binary.
*
* <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
* 255><data>
*
* Example:
* 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
*
* @param {Array} packets
* @return {ArrayBuffer} encoded payload
* @api private
*/
exports.encodePayloadAsArrayBuffer = function(packets, callback) {
if (!packets.length) {
return callback(new ArrayBuffer(0));
}
function encodeOne(packet, doneCallback) {
exports.encodePacket(packet, true, true, function(data) {
return doneCallback(null, data);
});
}
map(packets, encodeOne, function(err, encodedPackets) {
var totalLength = encodedPackets.reduce(function(acc, p) {
var len;
if (typeof p === 'string'){
len = p.length;
} else {
len = p.byteLength;
}
return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
}, 0);
var resultArray = new Uint8Array(totalLength);
var bufferIndex = 0;
encodedPackets.forEach(function(p) {
var isString = typeof p === 'string';
var ab = p;
if (isString) {
var view = new Uint8Array(p.length);
for (var i = 0; i < p.length; i++) {
view[i] = p.charCodeAt(i);
}
ab = view.buffer;
}
if (isString) { // not true binary
resultArray[bufferIndex++] = 0;
} else { // true binary
resultArray[bufferIndex++] = 1;
}
var lenStr = ab.byteLength.toString();
for (var i = 0; i < lenStr.length; i++) {
resultArray[bufferIndex++] = parseInt(lenStr[i]);
}
resultArray[bufferIndex++] = 255;
var view = new Uint8Array(ab);
for (var i = 0; i < view.length; i++) {
resultArray[bufferIndex++] = view[i];
}
});
return callback(resultArray.buffer);
});
};
/**
* Encode as Blob
*/
exports.encodePayloadAsBlob = function(packets, callback) {
function encodeOne(packet, doneCallback) {
exports.encodePacket(packet, true, true, function(encoded) {
var binaryIdentifier = new Uint8Array(1);
binaryIdentifier[0] = 1;
if (typeof encoded === 'string') {
var view = new Uint8Array(encoded.length);
for (var i = 0; i < encoded.length; i++) {
view[i] = encoded.charCodeAt(i);
}
encoded = view.buffer;
binaryIdentifier[0] = 0;
}
var len = (encoded instanceof ArrayBuffer)
? encoded.byteLength
: encoded.size;
var lenStr = len.toString();
var lengthAry = new Uint8Array(lenStr.length + 1);
for (var i = 0; i < lenStr.length; i++) {
lengthAry[i] = parseInt(lenStr[i]);
}
lengthAry[lenStr.length] = 255;
if (Blob) {
var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
doneCallback(null, blob);
}
});
}
map(packets, encodeOne, function(err, results) {
return callback(new Blob(results));
});
};
/*
* Decodes data when a payload is maybe expected. Strings are decoded by
* interpreting each byte as a key code for entries marked to start with 0. See
* description of encodePayloadAsBinary
*
* @param {ArrayBuffer} data, callback method
* @api public
*/
exports.decodePayloadAsBinary = function (data, binaryType, callback) {
if (typeof binaryType === 'function') {
callback = binaryType;
binaryType = null;
}
var bufferTail = data;
var buffers = [];
while (bufferTail.byteLength > 0) {
var tailArray = new Uint8Array(bufferTail);
var isString = tailArray[0] === 0;
var msgLength = '';
for (var i = 1; ; i++) {
if (tailArray[i] === 255) break;
// 310 = char length of Number.MAX_VALUE
if (msgLength.length > 310) {
return callback(err, 0, 1);
}
msgLength += tailArray[i];
}
bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
msgLength = parseInt(msgLength);
var msg = sliceBuffer(bufferTail, 0, msgLength);
if (isString) {
try {
msg = String.fromCharCode.apply(null, new Uint8Array(msg));
} catch (e) {
// iPhone Safari doesn't let you apply to typed arrays
var typed = new Uint8Array(msg);
msg = '';
for (var i = 0; i < typed.length; i++) {
msg += String.fromCharCode(typed[i]);
}
}
}
buffers.push(msg);
bufferTail = sliceBuffer(bufferTail, msgLength);
}
var total = buffers.length;
buffers.forEach(function(buffer, i) {
callback(exports.decodePacket(buffer, binaryType, true), i, total);
});
};
},{"./keys":78,"./utf8":79,"after":20,"arraybuffer.slice":21,"base64-arraybuffer":31,"blob":33,"has-binary2":89}],78:[function(require,module,exports){
/**
* Gets the keys for an object.
*
* @return {Array} keys
* @api private
*/
module.exports = Object.keys || function keys (obj){
var arr = [];
var has = Object.prototype.hasOwnProperty;
for (var i in obj) {
if (has.call(obj, i)) {
arr.push(i);
}
}
return arr;
};
},{}],79:[function(require,module,exports){
/*! https://mths.be/utf8js v2.1.2 by @mathias */
var stringFromCharCode = String.fromCharCode;
// Taken from https://mths.be/punycode
function ucs2decode(string) {
var output = [];
var counter = 0;
var length = string.length;
var value;
var extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
// Taken from https://mths.be/punycode
function ucs2encode(array) {
var length = array.length;
var index = -1;
var value;
var output = '';
while (++index < length) {
value = array[index];
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
}
return output;
}
function checkScalarValue(codePoint, strict) {
if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
if (strict) {
throw Error(
'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
' is not a scalar value'
);
}
return false;
}
return true;
}
/*--------------------------------------------------------------------------*/
function createByte(codePoint, shift) {
return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
}
function encodeCodePoint(codePoint, strict) {
if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
return stringFromCharCode(codePoint);
}
var symbol = '';
if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
}
else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
if (!checkScalarValue(codePoint, strict)) {
codePoint = 0xFFFD;
}
symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
symbol += createByte(codePoint, 6);
}
else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
symbol += createByte(codePoint, 12);
symbol += createByte(codePoint, 6);
}
symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
return symbol;
}
function utf8encode(string, opts) {
opts = opts || {};
var strict = false !== opts.strict;
var codePoints = ucs2decode(string);
var length = codePoints.length;
var index = -1;
var codePoint;
var byteString = '';
while (++index < length) {
codePoint = codePoints[index];
byteString += encodeCodePoint(codePoint, strict);
}
return byteString;
}
/*--------------------------------------------------------------------------*/
function readContinuationByte() {
if (byteIndex >= byteCount) {
throw Error('Invalid byte index');
}
var continuationByte = byteArray[byteIndex] & 0xFF;
byteIndex++;
if ((continuationByte & 0xC0) == 0x80) {
return continuationByte & 0x3F;
}
// If we end up here, its not a continuation byte
throw Error('Invalid continuation byte');
}
function decodeSymbol(strict) {
var byte1;
var byte2;
var byte3;
var byte4;
var codePoint;
if (byteIndex > byteCount) {
throw Error('Invalid byte index');
}
if (byteIndex == byteCount) {
return false;
}
// Read first byte
byte1 = byteArray[byteIndex] & 0xFF;
byteIndex++;
// 1-byte sequence (no continuation bytes)
if ((byte1 & 0x80) == 0) {
return byte1;
}
// 2-byte sequence
if ((byte1 & 0xE0) == 0xC0) {
byte2 = readContinuationByte();
codePoint = ((byte1 & 0x1F) << 6) | byte2;
if (codePoint >= 0x80) {
return codePoint;
} else {
throw Error('Invalid continuation byte');
}
}
// 3-byte sequence (may include unpaired surrogates)
if ((byte1 & 0xF0) == 0xE0) {
byte2 = readContinuationByte();
byte3 = readContinuationByte();
codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
if (codePoint >= 0x0800) {
return checkScalarValue(codePoint, strict) ? codePoint : 0xFFFD;
} else {
throw Error('Invalid continuation byte');
}
}
// 4-byte sequence
if ((byte1 & 0xF8) == 0xF0) {
byte2 = readContinuationByte();
byte3 = readContinuationByte();
byte4 = readContinuationByte();
codePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) |
(byte3 << 0x06) | byte4;
if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
return codePoint;
}
}
throw Error('Invalid UTF-8 detected');
}
var byteArray;
var byteCount;
var byteIndex;
function utf8decode(byteString, opts) {
opts = opts || {};
var strict = false !== opts.strict;
byteArray = ucs2decode(byteString);
byteCount = byteArray.length;
byteIndex = 0;
var codePoints = [];
var tmp;
while ((tmp = decodeSymbol(strict)) !== false) {
codePoints.push(tmp);
}
return ucs2encode(codePoints);
}
module.exports = {
version: '2.1.2',
encode: utf8encode,
decode: utf8decode
};
},{}],80:[function(require,module,exports){
'use strict';
/**
* @typedef {{ [key: string]: any }} Extensions
* @typedef {Error} Err
* @property {string} message
*/
/**
*
* @param {Error} obj
* @param {Extensions} props
* @returns {Error & Extensions}
*/
function assign(obj, props) {
for (const key in props) {
Object.defineProperty(obj, key, {
value: props[key],
enumerable: true,
configurable: true,
});
}
return obj;
}
/**
*
* @param {any} err - An Error
* @param {string|Extensions} code - A string code or props to set on the error
* @param {Extensions} [props] - Props to set on the error
* @returns {Error & Extensions}
*/
function createError(err, code, props) {
if (!err || typeof err === 'string') {
throw new TypeError('Please pass an Error to err-code');
}
if (!props) {
props = {};
}
if (typeof code === 'object') {
props = code;
code = '';
}
if (code) {
props.code = code;
}
try {
return assign(err, props);
} catch (_) {
props.message = err.message;
props.stack = err.stack;
const ErrClass = function () {};
ErrClass.prototype = Object.create(Object.getPrototypeOf(err));
// @ts-ignore
const output = assign(new ErrClass(), props);
return output;
}
}
module.exports = createError;
},{}],81:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
}
var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
}
function EventEmitter() {
EventEmitter.init.call(this);
}
module.exports = EventEmitter;
module.exports.once = once;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function() {
if (this._events === undefined ||
this._events === Object.getPrototypeOf(this)._events) {
this._events = Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
// If there is no 'error' event listener then throw.
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
// Note: The comments on the `throw` lines are intentional, they show
// up in Node's output if this results in an unhandled exception.
throw er; // Unhandled 'error' event
}
// At least give some kind of context to the user
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
err.context = er;
throw err; // Unhandled 'error' event
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
// Re-assign `events` because a newListener handler could have caused the
// this._events to be assigned to a new object
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
// Optimize the case of one listener. Don't need the extra array object.
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
// If we've already got an array, just append.
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
// No error code for this since it is a Warning
// eslint-disable-next-line no-restricted-syntax
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
// not listening for removeListener, no need to emit
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (events !== undefined) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener !== undefined) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
function once(emitter, name) {
return new Promise(function (resolve, reject) {
function errorListener(err) {
emitter.removeListener(name, resolver);
reject(err);
}
function resolver() {
if (typeof emitter.removeListener === 'function') {
emitter.removeListener('error', errorListener);
}
resolve([].slice.call(arguments));
};
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
if (name !== 'error') {
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
}
});
}
function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
if (typeof emitter.on === 'function') {
eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
}
}
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
if (typeof emitter.on === 'function') {
if (flags.once) {
emitter.once(name, listener);
} else {
emitter.on(name, listener);
}
} else if (typeof emitter.addEventListener === 'function') {
// EventTarget does not have `error` event semantics like Node
// EventEmitters, we do not listen for `error` events here.
emitter.addEventListener(name, function wrapListener(arg) {
// IE does not have builtin `{ once: true }` support so we
// have to do it manually.
if (flags.once) {
emitter.removeEventListener(name, wrapListener);
}
listener(arg);
});
} else {
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
}
}
},{}],82:[function(require,module,exports){
module.exports = stringify
stringify.default = stringify
stringify.stable = deterministicStringify
stringify.stableStringify = deterministicStringify
var LIMIT_REPLACE_NODE = '[...]'
var CIRCULAR_REPLACE_NODE = '[Circular]'
var arr = []
var replacerStack = []
function defaultOptions () {
return {
depthLimit: Number.MAX_SAFE_INTEGER,
edgesLimit: Number.MAX_SAFE_INTEGER
}
}
// Regular stringify
function stringify (obj, replacer, spacer, options) {
if (typeof options === 'undefined') {
options = defaultOptions()
}
decirc(obj, '', 0, [], undefined, 0, options)
var res
try {
if (replacerStack.length === 0) {
res = JSON.stringify(obj, replacer, spacer)
} else {
res = JSON.stringify(obj, replaceGetterValues(replacer), spacer)
}
} catch (_) {
return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]')
} finally {
while (arr.length !== 0) {
var part = arr.pop()
if (part.length === 4) {
Object.defineProperty(part[0], part[1], part[3])
} else {
part[0][part[1]] = part[2]
}
}
}
return res
}
function setReplace (replace, val, k, parent) {
var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k)
if (propertyDescriptor.get !== undefined) {
if (propertyDescriptor.configurable) {
Object.defineProperty(parent, k, { value: replace })
arr.push([parent, k, val, propertyDescriptor])
} else {
replacerStack.push([val, k, replace])
}
} else {
parent[k] = replace
arr.push([parent, k, val])
}
}
function decirc (val, k, edgeIndex, stack, parent, depth, options) {
depth += 1
var i
if (typeof val === 'object' && val !== null) {
for (i = 0; i < stack.length; i++) {
if (stack[i] === val) {
setReplace(CIRCULAR_REPLACE_NODE, val, k, parent)
return
}
}
if (
typeof options.depthLimit !== 'undefined' &&
depth > options.depthLimit
) {
setReplace(LIMIT_REPLACE_NODE, val, k, parent)
return
}
if (
typeof options.edgesLimit !== 'undefined' &&
edgeIndex + 1 > options.edgesLimit
) {
setReplace(LIMIT_REPLACE_NODE, val, k, parent)
return
}
stack.push(val)
// Optimize for Arrays. Big arrays could kill the performance otherwise!
if (Array.isArray(val)) {
for (i = 0; i < val.length; i++) {
decirc(val[i], i, i, stack, val, depth, options)
}
} else {
var keys = Object.keys(val)
for (i = 0; i < keys.length; i++) {
var key = keys[i]
decirc(val[key], key, i, stack, val, depth, options)
}
}
stack.pop()
}
}
// Stable-stringify
function compareFunction (a, b) {
if (a < b) {
return -1
}
if (a > b) {
return 1
}
return 0
}
function deterministicStringify (obj, replacer, spacer, options) {
if (typeof options === 'undefined') {
options = defaultOptions()
}
var tmp = deterministicDecirc(obj, '', 0, [], undefined, 0, options) || obj
var res
try {
if (replacerStack.length === 0) {
res = JSON.stringify(tmp, replacer, spacer)
} else {
res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer)
}
} catch (_) {
return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]')
} finally {
// Ensure that we restore the object as it was.
while (arr.length !== 0) {
var part = arr.pop()
if (part.length === 4) {
Object.defineProperty(part[0], part[1], part[3])
} else {
part[0][part[1]] = part[2]
}
}
}
return res
}
function deterministicDecirc (val, k, edgeIndex, stack, parent, depth, options) {
depth += 1
var i
if (typeof val === 'object' && val !== null) {
for (i = 0; i < stack.length; i++) {
if (stack[i] === val) {
setReplace(CIRCULAR_REPLACE_NODE, val, k, parent)
return
}
}
try {
if (typeof val.toJSON === 'function') {
return
}
} catch (_) {
return
}
if (
typeof options.depthLimit !== 'undefined' &&
depth > options.depthLimit
) {
setReplace(LIMIT_REPLACE_NODE, val, k, parent)
return
}
if (
typeof options.edgesLimit !== 'undefined' &&
edgeIndex + 1 > options.edgesLimit
) {
setReplace(LIMIT_REPLACE_NODE, val, k, parent)
return
}
stack.push(val)
// Optimize for Arrays. Big arrays could kill the performance otherwise!
if (Array.isArray(val)) {
for (i = 0; i < val.length; i++) {
deterministicDecirc(val[i], i, i, stack, val, depth, options)
}
} else {
// Create a temporary object in the required way
var tmp = {}
var keys = Object.keys(val).sort(compareFunction)
for (i = 0; i < keys.length; i++) {
var key = keys[i]
deterministicDecirc(val[key], key, i, stack, val, depth, options)
tmp[key] = val[key]
}
if (typeof parent !== 'undefined') {
arr.push([parent, k, val])
parent[k] = tmp
} else {
return tmp
}
}
stack.pop()
}
}
// wraps replacer function to handle values we couldn't replace
// and mark them as replaced value
function replaceGetterValues (replacer) {
replacer =
typeof replacer !== 'undefined'
? replacer
: function (k, v) {
return v
}
return function (key, val) {
if (replacerStack.length > 0) {
for (var i = 0; i < replacerStack.length; i++) {
var part = replacerStack[i]
if (part[1] === key && part[0] === val) {
val = part[2]
replacerStack.splice(i, 1)
break
}
}
}
return replacer.call(this, key, val)
}
}
},{}],83:[function(require,module,exports){
'use strict';
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var slice = Array.prototype.slice;
var toStr = Object.prototype.toString;
var funcType = '[object Function]';
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.call(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slice.call(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
args.concat(slice.call(arguments))
);
if (Object(result) === result) {
return result;
}
return this;
} else {
return target.apply(
that,
args.concat(slice.call(arguments))
);
}
};
var boundLength = Math.max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs.push('$' + i);
}
bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
},{}],84:[function(require,module,exports){
'use strict';
var implementation = require('./implementation');
module.exports = Function.prototype.bind || implementation;
},{"./implementation":83}],85:[function(require,module,exports){
// originally pulled out of simple-peer
module.exports = function getBrowserRTC () {
if (typeof globalThis === 'undefined') return null
var wrtc = {
RTCPeerConnection: globalThis.RTCPeerConnection || globalThis.mozRTCPeerConnection ||
globalThis.webkitRTCPeerConnection,
RTCSessionDescription: globalThis.RTCSessionDescription ||
globalThis.mozRTCSessionDescription || globalThis.webkitRTCSessionDescription,
RTCIceCandidate: globalThis.RTCIceCandidate || globalThis.mozRTCIceCandidate ||
globalThis.webkitRTCIceCandidate
}
if (!wrtc.RTCPeerConnection) return null
return wrtc
}
},{}],86:[function(require,module,exports){
'use strict';
var undefined;
var $SyntaxError = SyntaxError;
var $Function = Function;
var $TypeError = TypeError;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols = require('has-symbols')();
var hasProto = require('has-proto')();
var getProto = Object.getPrototypeOf || (
hasProto
? function (x) { return x.__proto__; } // eslint-disable-line no-proto
: null
);
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);
var INTRINSICS = {
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,
'%AsyncFromSyncIteratorPrototype%': undefined,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'%RangeError%': RangeError,
'%ReferenceError%': ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,
'%Symbol%': hasSymbols ? Symbol : undefined,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'%URIError%': URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};
if (getProto) {
try {
null.error; // eslint-disable-line no-unused-expressions
} catch (e) {
// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
var errorProto = getProto(getProto(e));
INTRINSICS['%Error.prototype%'] = errorProto;
}
}
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen && getProto) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind = require('function-bind');
var hasOwn = require('has');
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
var $exec = bind.call(Function.call, RegExp.prototype.exec);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
if ($exec(/^%?[^%]*%?$/, name) === null) {
throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
},{"function-bind":84,"has":95,"has-proto":92,"has-symbols":93}],87:[function(require,module,exports){
(function (global){(function (){
var topLevel = typeof global !== 'undefined' ? global :
typeof window !== 'undefined' ? window : {}
var minDoc = require('min-document');
var doccy;
if (typeof document !== 'undefined') {
doccy = document;
} else {
doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
if (!doccy) {
doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
}
}
module.exports = doccy;
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"min-document":34}],88:[function(require,module,exports){
(function (global){(function (){
var win;
if (typeof window !== "undefined") {
win = window;
} else if (typeof global !== "undefined") {
win = global;
} else if (typeof self !== "undefined"){
win = self;
} else {
win = {};
}
module.exports = win;
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],89:[function(require,module,exports){
(function (Buffer){(function (){
/* global Blob File */
/*
* Module requirements.
*/
var isArray = require('isarray');
var toString = Object.prototype.toString;
var withNativeBlob = typeof Blob === 'function' ||
typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]';
var withNativeFile = typeof File === 'function' ||
typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]';
/**
* Module exports.
*/
module.exports = hasBinary;
/**
* Checks for binary data.
*
* Supports Buffer, ArrayBuffer, Blob and File.
*
* @param {Object} anything
* @api public
*/
function hasBinary (obj) {
if (!obj || typeof obj !== 'object') {
return false;
}
if (isArray(obj)) {
for (var i = 0, l = obj.length; i < l; i++) {
if (hasBinary(obj[i])) {
return true;
}
}
return false;
}
if ((typeof Buffer === 'function' && Buffer.isBuffer && Buffer.isBuffer(obj)) ||
(typeof ArrayBuffer === 'function' && obj instanceof ArrayBuffer) ||
(withNativeBlob && obj instanceof Blob) ||
(withNativeFile && obj instanceof File)
) {
return true;
}
// see: https://github.com/Automattic/has-binary/pull/4
if (obj.toJSON && typeof obj.toJSON === 'function' && arguments.length === 1) {
return hasBinary(obj.toJSON(), true);
}
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
return true;
}
}
return false;
}
}).call(this)}).call(this,require("buffer").Buffer)
},{"buffer":35,"isarray":90}],90:[function(require,module,exports){
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
},{}],91:[function(require,module,exports){
/**
* Module exports.
*
* Logic borrowed from Modernizr:
*
* - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
*/
try {
module.exports = typeof XMLHttpRequest !== 'undefined' &&
'withCredentials' in new XMLHttpRequest();
} catch (err) {
// if XMLHttp support is disabled in IE then it will throw
// when trying to create
module.exports = false;
}
},{}],92:[function(require,module,exports){
'use strict';
var test = {
foo: {}
};
var $Object = Object;
module.exports = function hasProto() {
return { __proto__: test }.foo === test.foo && !({ __proto__: null } instanceof $Object);
};
},{}],93:[function(require,module,exports){
'use strict';
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = require('./shams');
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
},{"./shams":94}],94:[function(require,module,exports){
'use strict';
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
},{}],95:[function(require,module,exports){
'use strict';
var bind = require('function-bind');
module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);
},{"function-bind":84}],96:[function(require,module,exports){
module.exports = attributeToProperty
var transform = {
'class': 'className',
'for': 'htmlFor',
'http-equiv': 'httpEquiv'
}
function attributeToProperty (h) {
return function (tagName, attrs, children) {
for (var attr in attrs) {
if (attr in transform) {
attrs[transform[attr]] = attrs[attr]
delete attrs[attr]
}
}
return h(tagName, attrs, children)
}
}
},{}],97:[function(require,module,exports){
var attrToProp = require('hyperscript-attribute-to-property')
var VAR = 0, TEXT = 1, OPEN = 2, CLOSE = 3, ATTR = 4
var ATTR_KEY = 5, ATTR_KEY_W = 6
var ATTR_VALUE_W = 7, ATTR_VALUE = 8
var ATTR_VALUE_SQ = 9, ATTR_VALUE_DQ = 10
var ATTR_EQ = 11, ATTR_BREAK = 12
var COMMENT = 13
module.exports = function (h, opts) {
if (!opts) opts = {}
var concat = opts.concat || function (a, b) {
return String(a) + String(b)
}
if (opts.attrToProp !== false) {
h = attrToProp(h)
}
return function (strings) {
var state = TEXT, reg = ''
var arglen = arguments.length
var parts = []
for (var i = 0; i < strings.length; i++) {
if (i < arglen - 1) {
var arg = arguments[i+1]
var p = parse(strings[i])
var xstate = state
if (xstate === ATTR_VALUE_DQ) xstate = ATTR_VALUE
if (xstate === ATTR_VALUE_SQ) xstate = ATTR_VALUE
if (xstate === ATTR_VALUE_W) xstate = ATTR_VALUE
if (xstate === ATTR) xstate = ATTR_KEY
if (xstate === OPEN) {
if (reg === '/') {
p.push([ OPEN, '/', arg ])
reg = ''
} else {
p.push([ OPEN, arg ])
}
} else if (xstate === COMMENT && opts.comments) {
reg += String(arg)
} else if (xstate !== COMMENT) {
p.push([ VAR, xstate, arg ])
}
parts.push.apply(parts, p)
} else parts.push.apply(parts, parse(strings[i]))
}
var tree = [null,{},[]]
var stack = [[tree,-1]]
for (var i = 0; i < parts.length; i++) {
var cur = stack[stack.length-1][0]
var p = parts[i], s = p[0]
if (s === OPEN && /^\//.test(p[1])) {
var ix = stack[stack.length-1][1]
if (stack.length > 1) {
stack.pop()
stack[stack.length-1][0][2][ix] = h(
cur[0], cur[1], cur[2].length ? cur[2] : undefined
)
}
} else if (s === OPEN) {
var c = [p[1],{},[]]
cur[2].push(c)
stack.push([c,cur[2].length-1])
} else if (s === ATTR_KEY || (s === VAR && p[1] === ATTR_KEY)) {
var key = ''
var copyKey
for (; i < parts.length; i++) {
if (parts[i][0] === ATTR_KEY) {
key = concat(key, parts[i][1])
} else if (parts[i][0] === VAR && parts[i][1] === ATTR_KEY) {
if (typeof parts[i][2] === 'object' && !key) {
for (copyKey in parts[i][2]) {
if (parts[i][2].hasOwnProperty(copyKey) && !cur[1][copyKey]) {
cur[1][copyKey] = parts[i][2][copyKey]
}
}
} else {
key = concat(key, parts[i][2])
}
} else break
}
if (parts[i][0] === ATTR_EQ) i++
var j = i
for (; i < parts.length; i++) {
if (parts[i][0] === ATTR_VALUE || parts[i][0] === ATTR_KEY) {
if (!cur[1][key]) cur[1][key] = strfn(parts[i][1])
else parts[i][1]==="" || (cur[1][key] = concat(cur[1][key], parts[i][1]));
} else if (parts[i][0] === VAR
&& (parts[i][1] === ATTR_VALUE || parts[i][1] === ATTR_KEY)) {
if (!cur[1][key]) cur[1][key] = strfn(parts[i][2])
else parts[i][2]==="" || (cur[1][key] = concat(cur[1][key], parts[i][2]));
} else {
if (key.length && !cur[1][key] && i === j
&& (parts[i][0] === CLOSE || parts[i][0] === ATTR_BREAK)) {
// https://html.spec.whatwg.org/multipage/infrastructure.html#boolean-attributes
// empty string is falsy, not well behaved value in browser
cur[1][key] = key.toLowerCase()
}
if (parts[i][0] === CLOSE) {
i--
}
break
}
}
} else if (s === ATTR_KEY) {
cur[1][p[1]] = true
} else if (s === VAR && p[1] === ATTR_KEY) {
cur[1][p[2]] = true
} else if (s === CLOSE) {
if (selfClosing(cur[0]) && stack.length) {
var ix = stack[stack.length-1][1]
stack.pop()
stack[stack.length-1][0][2][ix] = h(
cur[0], cur[1], cur[2].length ? cur[2] : undefined
)
}
} else if (s === VAR && p[1] === TEXT) {
if (p[2] === undefined || p[2] === null) p[2] = ''
else if (!p[2]) p[2] = concat('', p[2])
if (Array.isArray(p[2][0])) {
cur[2].push.apply(cur[2], p[2])
} else {
cur[2].push(p[2])
}
} else if (s === TEXT) {
cur[2].push(p[1])
} else if (s === ATTR_EQ || s === ATTR_BREAK) {
// no-op
} else {
throw new Error('unhandled: ' + s)
}
}
if (tree[2].length > 1 && /^\s*$/.test(tree[2][0])) {
tree[2].shift()
}
if (tree[2].length > 2
|| (tree[2].length === 2 && /\S/.test(tree[2][1]))) {
if (opts.createFragment) return opts.createFragment(tree[2])
throw new Error(
'multiple root elements must be wrapped in an enclosing tag'
)
}
if (Array.isArray(tree[2][0]) && typeof tree[2][0][0] === 'string'
&& Array.isArray(tree[2][0][2])) {
tree[2][0] = h(tree[2][0][0], tree[2][0][1], tree[2][0][2])
}
return tree[2][0]
function parse (str) {
var res = []
if (state === ATTR_VALUE_W) state = ATTR
for (var i = 0; i < str.length; i++) {
var c = str.charAt(i)
if (state === TEXT && c === '<') {
if (reg.length) res.push([TEXT, reg])
reg = ''
state = OPEN
} else if (c === '>' && !quot(state) && state !== COMMENT) {
if (state === OPEN && reg.length) {
res.push([OPEN,reg])
} else if (state === ATTR_KEY) {
res.push([ATTR_KEY,reg])
} else if (state === ATTR_VALUE && reg.length) {
res.push([ATTR_VALUE,reg])
}
res.push([CLOSE])
reg = ''
state = TEXT
} else if (state === COMMENT && /-$/.test(reg) && c === '-') {
if (opts.comments) {
res.push([ATTR_VALUE,reg.substr(0, reg.length - 1)])
}
reg = ''
state = TEXT
} else if (state === OPEN && /^!--$/.test(reg)) {
if (opts.comments) {
res.push([OPEN, reg],[ATTR_KEY,'comment'],[ATTR_EQ])
}
reg = c
state = COMMENT
} else if (state === TEXT || state === COMMENT) {
reg += c
} else if (state === OPEN && c === '/' && reg.length) {
// no-op, self closing tag without a space <br/>
} else if (state === OPEN && /\s/.test(c)) {
if (reg.length) {
res.push([OPEN, reg])
}
reg = ''
state = ATTR
} else if (state === OPEN) {
reg += c
} else if (state === ATTR && /[^\s"'=/]/.test(c)) {
state = ATTR_KEY
reg = c
} else if (state === ATTR && /\s/.test(c)) {
if (reg.length) res.push([ATTR_KEY,reg])
res.push([ATTR_BREAK])
} else if (state === ATTR_KEY && /\s/.test(c)) {
res.push([ATTR_KEY,reg])
reg = ''
state = ATTR_KEY_W
} else if (state === ATTR_KEY && c === '=') {
res.push([ATTR_KEY,reg],[ATTR_EQ])
reg = ''
state = ATTR_VALUE_W
} else if (state === ATTR_KEY) {
reg += c
} else if ((state === ATTR_KEY_W || state === ATTR) && c === '=') {
res.push([ATTR_EQ])
state = ATTR_VALUE_W
} else if ((state === ATTR_KEY_W || state === ATTR) && !/\s/.test(c)) {
res.push([ATTR_BREAK])
if (/[\w-]/.test(c)) {
reg += c
state = ATTR_KEY
} else state = ATTR
} else if (state === ATTR_VALUE_W && c === '"') {
state = ATTR_VALUE_DQ
} else if (state === ATTR_VALUE_W && c === "'") {
state = ATTR_VALUE_SQ
} else if (state === ATTR_VALUE_DQ && c === '"') {
res.push([ATTR_VALUE,reg],[ATTR_BREAK])
reg = ''
state = ATTR
} else if (state === ATTR_VALUE_SQ && c === "'") {
res.push([ATTR_VALUE,reg],[ATTR_BREAK])
reg = ''
state = ATTR
} else if (state === ATTR_VALUE_W && !/\s/.test(c)) {
state = ATTR_VALUE
i--
} else if (state === ATTR_VALUE && /\s/.test(c)) {
res.push([ATTR_VALUE,reg],[ATTR_BREAK])
reg = ''
state = ATTR
} else if (state === ATTR_VALUE || state === ATTR_VALUE_SQ
|| state === ATTR_VALUE_DQ) {
reg += c
}
}
if (state === TEXT && reg.length) {
res.push([TEXT,reg])
reg = ''
} else if (state === ATTR_VALUE && reg.length) {
res.push([ATTR_VALUE,reg])
reg = ''
} else if (state === ATTR_VALUE_DQ && reg.length) {
res.push([ATTR_VALUE,reg])
reg = ''
} else if (state === ATTR_VALUE_SQ && reg.length) {
res.push([ATTR_VALUE,reg])
reg = ''
} else if (state === ATTR_KEY) {
res.push([ATTR_KEY,reg])
reg = ''
}
return res
}
}
function strfn (x) {
if (typeof x === 'function') return x
else if (typeof x === 'string') return x
else if (x && typeof x === 'object') return x
else if (x === null || x === undefined) return x
else return concat('', x)
}
}
function quot (state) {
return state === ATTR_VALUE_SQ || state === ATTR_VALUE_DQ
}
var closeRE = RegExp('^(' + [
'area', 'base', 'basefont', 'bgsound', 'br', 'col', 'command', 'embed',
'frame', 'hr', 'img', 'input', 'isindex', 'keygen', 'link', 'meta', 'param',
'source', 'track', 'wbr', '!--',
// SVG TAGS
'animate', 'animateTransform', 'circle', 'cursor', 'desc', 'ellipse',
'feBlend', 'feColorMatrix', 'feComposite',
'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap',
'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR',
'feGaussianBlur', 'feImage', 'feMergeNode', 'feMorphology',
'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile',
'feTurbulence', 'font-face-format', 'font-face-name', 'font-face-uri',
'glyph', 'glyphRef', 'hkern', 'image', 'line', 'missing-glyph', 'mpath',
'path', 'polygon', 'polyline', 'rect', 'set', 'stop', 'tref', 'use', 'view',
'vkern'
].join('|') + ')(?:[\.#][a-zA-Z0-9\u007F-\uFFFF_:-]+)*$')
function selfClosing (tag) { return closeRE.test(tag) }
},{"hyperscript-attribute-to-property":96}],98:[function(require,module,exports){
'use strict';
var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
var _createClass = require('@babel/runtime/helpers/createClass');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck);
var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass);
var arr = [];
var each = arr.forEach;
var slice = arr.slice;
function defaults(obj) {
each.call(slice.call(arguments, 1), function (source) {
if (source) {
for (var prop in source) {
if (obj[prop] === undefined) obj[prop] = source[prop];
}
}
});
return obj;
}
// eslint-disable-next-line no-control-regex
var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
var serializeCookie = function serializeCookie(name, val, options) {
var opt = options || {};
opt.path = opt.path || '/';
var value = encodeURIComponent(val);
var str = "".concat(name, "=").concat(value);
if (opt.maxAge > 0) {
var maxAge = opt.maxAge - 0;
if (Number.isNaN(maxAge)) throw new Error('maxAge should be a Number');
str += "; Max-Age=".concat(Math.floor(maxAge));
}
if (opt.domain) {
if (!fieldContentRegExp.test(opt.domain)) {
throw new TypeError('option domain is invalid');
}
str += "; Domain=".concat(opt.domain);
}
if (opt.path) {
if (!fieldContentRegExp.test(opt.path)) {
throw new TypeError('option path is invalid');
}
str += "; Path=".concat(opt.path);
}
if (opt.expires) {
if (typeof opt.expires.toUTCString !== 'function') {
throw new TypeError('option expires is invalid');
}
str += "; Expires=".concat(opt.expires.toUTCString());
}
if (opt.httpOnly) str += '; HttpOnly';
if (opt.secure) str += '; Secure';
if (opt.sameSite) {
var sameSite = typeof opt.sameSite === 'string' ? opt.sameSite.toLowerCase() : opt.sameSite;
switch (sameSite) {
case true:
str += '; SameSite=Strict';
break;
case 'lax':
str += '; SameSite=Lax';
break;
case 'strict':
str += '; SameSite=Strict';
break;
case 'none':
str += '; SameSite=None';
break;
default:
throw new TypeError('option sameSite is invalid');
}
}
return str;
};
var cookie = {
create: function create(name, value, minutes, domain) {
var cookieOptions = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
path: '/',
sameSite: 'strict'
};
if (minutes) {
cookieOptions.expires = new Date();
cookieOptions.expires.setTime(cookieOptions.expires.getTime() + minutes * 60 * 1000);
}
if (domain) cookieOptions.domain = domain;
document.cookie = serializeCookie(name, encodeURIComponent(value), cookieOptions);
},
read: function read(name) {
var nameEQ = "".concat(name, "=");
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
},
remove: function remove(name) {
this.create(name, '', -1);
}
};
var cookie$1 = {
name: 'cookie',
lookup: function lookup(options) {
var found;
if (options.lookupCookie && typeof document !== 'undefined') {
var c = cookie.read(options.lookupCookie);
if (c) found = c;
}
return found;
},
cacheUserLanguage: function cacheUserLanguage(lng, options) {
if (options.lookupCookie && typeof document !== 'undefined') {
cookie.create(options.lookupCookie, lng, options.cookieMinutes, options.cookieDomain, options.cookieOptions);
}
}
};
var querystring = {
name: 'querystring',
lookup: function lookup(options) {
var found;
if (typeof window !== 'undefined') {
var search = window.location.search;
if (!window.location.search && window.location.hash && window.location.hash.indexOf('?') > -1) {
search = window.location.hash.substring(window.location.hash.indexOf('?'));
}
var query = search.substring(1);
var params = query.split('&');
for (var i = 0; i < params.length; i++) {
var pos = params[i].indexOf('=');
if (pos > 0) {
var key = params[i].substring(0, pos);
if (key === options.lookupQuerystring) {
found = params[i].substring(pos + 1);
}
}
}
}
return found;
}
};
var hasLocalStorageSupport = null;
var localStorageAvailable = function localStorageAvailable() {
if (hasLocalStorageSupport !== null) return hasLocalStorageSupport;
try {
hasLocalStorageSupport = window !== 'undefined' && window.localStorage !== null;
var testKey = 'i18next.translate.boo';
window.localStorage.setItem(testKey, 'foo');
window.localStorage.removeItem(testKey);
} catch (e) {
hasLocalStorageSupport = false;
}
return hasLocalStorageSupport;
};
var localStorage = {
name: 'localStorage',
lookup: function lookup(options) {
var found;
if (options.lookupLocalStorage && localStorageAvailable()) {
var lng = window.localStorage.getItem(options.lookupLocalStorage);
if (lng) found = lng;
}
return found;
},
cacheUserLanguage: function cacheUserLanguage(lng, options) {
if (options.lookupLocalStorage && localStorageAvailable()) {
window.localStorage.setItem(options.lookupLocalStorage, lng);
}
}
};
var hasSessionStorageSupport = null;
var sessionStorageAvailable = function sessionStorageAvailable() {
if (hasSessionStorageSupport !== null) return hasSessionStorageSupport;
try {
hasSessionStorageSupport = window !== 'undefined' && window.sessionStorage !== null;
var testKey = 'i18next.translate.boo';
window.sessionStorage.setItem(testKey, 'foo');
window.sessionStorage.removeItem(testKey);
} catch (e) {
hasSessionStorageSupport = false;
}
return hasSessionStorageSupport;
};
var sessionStorage = {
name: 'sessionStorage',
lookup: function lookup(options) {
var found;
if (options.lookupSessionStorage && sessionStorageAvailable()) {
var lng = window.sessionStorage.getItem(options.lookupSessionStorage);
if (lng) found = lng;
}
return found;
},
cacheUserLanguage: function cacheUserLanguage(lng, options) {
if (options.lookupSessionStorage && sessionStorageAvailable()) {
window.sessionStorage.setItem(options.lookupSessionStorage, lng);
}
}
};
var navigator$1 = {
name: 'navigator',
lookup: function lookup(options) {
var found = [];
if (typeof navigator !== 'undefined') {
if (navigator.languages) {
// chrome only; not an array, so can't use .push.apply instead of iterating
for (var i = 0; i < navigator.languages.length; i++) {
found.push(navigator.languages[i]);
}
}
if (navigator.userLanguage) {
found.push(navigator.userLanguage);
}
if (navigator.language) {
found.push(navigator.language);
}
}
return found.length > 0 ? found : undefined;
}
};
var htmlTag = {
name: 'htmlTag',
lookup: function lookup(options) {
var found;
var htmlTag = options.htmlTag || (typeof document !== 'undefined' ? document.documentElement : null);
if (htmlTag && typeof htmlTag.getAttribute === 'function') {
found = htmlTag.getAttribute('lang');
}
return found;
}
};
var path = {
name: 'path',
lookup: function lookup(options) {
var found;
if (typeof window !== 'undefined') {
var language = window.location.pathname.match(/\/([a-zA-Z-]*)/g);
if (language instanceof Array) {
if (typeof options.lookupFromPathIndex === 'number') {
if (typeof language[options.lookupFromPathIndex] !== 'string') {
return undefined;
}
found = language[options.lookupFromPathIndex].replace('/', '');
} else {
found = language[0].replace('/', '');
}
}
}
return found;
}
};
var subdomain = {
name: 'subdomain',
lookup: function lookup(options) {
// If given get the subdomain index else 1
var lookupFromSubdomainIndex = typeof options.lookupFromSubdomainIndex === 'number' ? options.lookupFromSubdomainIndex + 1 : 1; // get all matches if window.location. is existing
// first item of match is the match itself and the second is the first group macht which sould be the first subdomain match
// is the hostname no public domain get the or option of localhost
var language = typeof window !== 'undefined' && window.location && window.location.hostname && window.location.hostname.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i); // if there is no match (null) return undefined
if (!language) return undefined; // return the given group match
return language[lookupFromSubdomainIndex];
}
};
function getDefaults() {
return {
order: ['querystring', 'cookie', 'localStorage', 'sessionStorage', 'navigator', 'htmlTag'],
lookupQuerystring: 'lng',
lookupCookie: 'i18next',
lookupLocalStorage: 'i18nextLng',
lookupSessionStorage: 'i18nextLng',
// cache user language
caches: ['localStorage'],
excludeCacheFor: ['cimode'] // cookieMinutes: 10,
// cookieDomain: 'myDomain'
};
}
var Browser = /*#__PURE__*/function () {
function Browser(services) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck__default["default"](this, Browser);
this.type = 'languageDetector';
this.detectors = {};
this.init(services, options);
}
_createClass__default["default"](Browser, [{
key: "init",
value: function init(services) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var i18nOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
this.services = services;
this.options = defaults(options, this.options || {}, getDefaults()); // backwards compatibility
if (this.options.lookupFromUrlIndex) this.options.lookupFromPathIndex = this.options.lookupFromUrlIndex;
this.i18nOptions = i18nOptions;
this.addDetector(cookie$1);
this.addDetector(querystring);
this.addDetector(localStorage);
this.addDetector(sessionStorage);
this.addDetector(navigator$1);
this.addDetector(htmlTag);
this.addDetector(path);
this.addDetector(subdomain);
}
}, {
key: "addDetector",
value: function addDetector(detector) {
this.detectors[detector.name] = detector;
}
}, {
key: "detect",
value: function detect(detectionOrder) {
var _this = this;
if (!detectionOrder) detectionOrder = this.options.order;
var detected = [];
detectionOrder.forEach(function (detectorName) {
if (_this.detectors[detectorName]) {
var lookup = _this.detectors[detectorName].lookup(_this.options);
if (lookup && typeof lookup === 'string') lookup = [lookup];
if (lookup) detected = detected.concat(lookup);
}
});
if (this.services.languageUtils.getBestMatchFromCodes) return detected; // new i18next v19.5.0
return detected.length > 0 ? detected[0] : null; // a little backward compatibility
}
}, {
key: "cacheUserLanguage",
value: function cacheUserLanguage(lng, caches) {
var _this2 = this;
if (!caches) caches = this.options.caches;
if (!caches) return;
if (this.options.excludeCacheFor && this.options.excludeCacheFor.indexOf(lng) > -1) return;
caches.forEach(function (cacheName) {
if (_this2.detectors[cacheName]) _this2.detectors[cacheName].cacheUserLanguage(lng, _this2.options);
});
}
}]);
return Browser;
}();
Browser.type = 'languageDetector';
module.exports = Browser;
},{"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6}],99:[function(require,module,exports){
'use strict';
var _typeof = require('@babel/runtime/helpers/typeof');
var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
var _createClass = require('@babel/runtime/helpers/createClass');
var _assertThisInitialized = require('@babel/runtime/helpers/assertThisInitialized');
var _inherits = require('@babel/runtime/helpers/inherits');
var _possibleConstructorReturn = require('@babel/runtime/helpers/possibleConstructorReturn');
var _getPrototypeOf = require('@babel/runtime/helpers/getPrototypeOf');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _toArray = require('@babel/runtime/helpers/toArray');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var _typeof__default = /*#__PURE__*/_interopDefaultLegacy(_typeof);
var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck);
var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass);
var _assertThisInitialized__default = /*#__PURE__*/_interopDefaultLegacy(_assertThisInitialized);
var _inherits__default = /*#__PURE__*/_interopDefaultLegacy(_inherits);
var _possibleConstructorReturn__default = /*#__PURE__*/_interopDefaultLegacy(_possibleConstructorReturn);
var _getPrototypeOf__default = /*#__PURE__*/_interopDefaultLegacy(_getPrototypeOf);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var _toArray__default = /*#__PURE__*/_interopDefaultLegacy(_toArray);
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var consoleLogger = {
type: 'logger',
log: function log(args) {
this.output('log', args);
},
warn: function warn(args) {
this.output('warn', args);
},
error: function error(args) {
this.output('error', args);
},
output: function output(type, args) {
if (console && console[type]) console[type].apply(console, args);
}
};
var Logger = function () {
function Logger(concreteLogger) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck__default['default'](this, Logger);
this.init(concreteLogger, options);
}
_createClass__default['default'](Logger, [{
key: "init",
value: function init(concreteLogger) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
this.prefix = options.prefix || 'i18next:';
this.logger = concreteLogger || consoleLogger;
this.options = options;
this.debug = options.debug;
}
}, {
key: "setDebug",
value: function setDebug(bool) {
this.debug = bool;
}
}, {
key: "log",
value: function log() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return this.forward(args, 'log', '', true);
}
}, {
key: "warn",
value: function warn() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return this.forward(args, 'warn', '', true);
}
}, {
key: "error",
value: function error() {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
return this.forward(args, 'error', '');
}
}, {
key: "deprecate",
value: function deprecate() {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
}
}, {
key: "forward",
value: function forward(args, lvl, prefix, debugOnly) {
if (debugOnly && !this.debug) return null;
if (typeof args[0] === 'string') args[0] = "".concat(prefix).concat(this.prefix, " ").concat(args[0]);
return this.logger[lvl](args);
}
}, {
key: "create",
value: function create(moduleName) {
return new Logger(this.logger, _objectSpread(_objectSpread({}, {
prefix: "".concat(this.prefix, ":").concat(moduleName, ":")
}), this.options));
}
}, {
key: "clone",
value: function clone(options) {
options = options || this.options;
options.prefix = options.prefix || this.prefix;
return new Logger(this.logger, options);
}
}]);
return Logger;
}();
var baseLogger = new Logger();
var EventEmitter = function () {
function EventEmitter() {
_classCallCheck__default['default'](this, EventEmitter);
this.observers = {};
}
_createClass__default['default'](EventEmitter, [{
key: "on",
value: function on(events, listener) {
var _this = this;
events.split(' ').forEach(function (event) {
_this.observers[event] = _this.observers[event] || [];
_this.observers[event].push(listener);
});
return this;
}
}, {
key: "off",
value: function off(event, listener) {
if (!this.observers[event]) return;
if (!listener) {
delete this.observers[event];
return;
}
this.observers[event] = this.observers[event].filter(function (l) {
return l !== listener;
});
}
}, {
key: "emit",
value: function emit(event) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (this.observers[event]) {
var cloned = [].concat(this.observers[event]);
cloned.forEach(function (observer) {
observer.apply(void 0, args);
});
}
if (this.observers['*']) {
var _cloned = [].concat(this.observers['*']);
_cloned.forEach(function (observer) {
observer.apply(observer, [event].concat(args));
});
}
}
}]);
return EventEmitter;
}();
function defer() {
var res;
var rej;
var promise = new Promise(function (resolve, reject) {
res = resolve;
rej = reject;
});
promise.resolve = res;
promise.reject = rej;
return promise;
}
function makeString(object) {
if (object == null) return '';
return '' + object;
}
function copy(a, s, t) {
a.forEach(function (m) {
if (s[m]) t[m] = s[m];
});
}
function getLastOfPath(object, path, Empty) {
function cleanKey(key) {
return key && key.indexOf('###') > -1 ? key.replace(/###/g, '.') : key;
}
function canNotTraverseDeeper() {
return !object || typeof object === 'string';
}
var stack = typeof path !== 'string' ? [].concat(path) : path.split('.');
while (stack.length > 1) {
if (canNotTraverseDeeper()) return {};
var key = cleanKey(stack.shift());
if (!object[key] && Empty) object[key] = new Empty();
if (Object.prototype.hasOwnProperty.call(object, key)) {
object = object[key];
} else {
object = {};
}
}
if (canNotTraverseDeeper()) return {};
return {
obj: object,
k: cleanKey(stack.shift())
};
}
function setPath(object, path, newValue) {
var _getLastOfPath = getLastOfPath(object, path, Object),
obj = _getLastOfPath.obj,
k = _getLastOfPath.k;
obj[k] = newValue;
}
function pushPath(object, path, newValue, concat) {
var _getLastOfPath2 = getLastOfPath(object, path, Object),
obj = _getLastOfPath2.obj,
k = _getLastOfPath2.k;
obj[k] = obj[k] || [];
if (concat) obj[k] = obj[k].concat(newValue);
if (!concat) obj[k].push(newValue);
}
function getPath(object, path) {
var _getLastOfPath3 = getLastOfPath(object, path),
obj = _getLastOfPath3.obj,
k = _getLastOfPath3.k;
if (!obj) return undefined;
return obj[k];
}
function getPathWithDefaults(data, defaultData, key) {
var value = getPath(data, key);
if (value !== undefined) {
return value;
}
return getPath(defaultData, key);
}
function deepExtend(target, source, overwrite) {
for (var prop in source) {
if (prop !== '__proto__' && prop !== 'constructor') {
if (prop in target) {
if (typeof target[prop] === 'string' || target[prop] instanceof String || typeof source[prop] === 'string' || source[prop] instanceof String) {
if (overwrite) target[prop] = source[prop];
} else {
deepExtend(target[prop], source[prop], overwrite);
}
} else {
target[prop] = source[prop];
}
}
}
return target;
}
function regexEscape(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}
var _entityMap = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;',
'/': '&#x2F;'
};
function escape(data) {
if (typeof data === 'string') {
return data.replace(/[&<>"'\/]/g, function (s) {
return _entityMap[s];
});
}
return data;
}
var isIE10 = typeof window !== 'undefined' && window.navigator && typeof window.navigator.userAgentData === 'undefined' && window.navigator.userAgent && window.navigator.userAgent.indexOf('MSIE') > -1;
var chars = [' ', ',', '?', '!', ';'];
function looksLikeObjectPath(key, nsSeparator, keySeparator) {
nsSeparator = nsSeparator || '';
keySeparator = keySeparator || '';
var possibleChars = chars.filter(function (c) {
return nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0;
});
if (possibleChars.length === 0) return true;
var r = new RegExp("(".concat(possibleChars.map(function (c) {
return c === '?' ? '\\?' : c;
}).join('|'), ")"));
var matched = !r.test(key);
if (!matched) {
var ki = key.indexOf(keySeparator);
if (ki > 0 && !r.test(key.substring(0, ki))) {
matched = true;
}
}
return matched;
}
function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function deepFind(obj, path) {
var keySeparator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '.';
if (!obj) return undefined;
if (obj[path]) return obj[path];
var paths = path.split(keySeparator);
var current = obj;
for (var i = 0; i < paths.length; ++i) {
if (!current) return undefined;
if (typeof current[paths[i]] === 'string' && i + 1 < paths.length) {
return undefined;
}
if (current[paths[i]] === undefined) {
var j = 2;
var p = paths.slice(i, i + j).join(keySeparator);
var mix = current[p];
while (mix === undefined && paths.length > i + j) {
j++;
p = paths.slice(i, i + j).join(keySeparator);
mix = current[p];
}
if (mix === undefined) return undefined;
if (mix === null) return null;
if (path.endsWith(p)) {
if (typeof mix === 'string') return mix;
if (p && typeof mix[p] === 'string') return mix[p];
}
var joinedPath = paths.slice(i + j).join(keySeparator);
if (joinedPath) return deepFind(mix, joinedPath, keySeparator);
return undefined;
}
current = current[paths[i]];
}
return current;
}
var ResourceStore = function (_EventEmitter) {
_inherits__default['default'](ResourceStore, _EventEmitter);
var _super = _createSuper(ResourceStore);
function ResourceStore(data) {
var _this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
ns: ['translation'],
defaultNS: 'translation'
};
_classCallCheck__default['default'](this, ResourceStore);
_this = _super.call(this);
if (isIE10) {
EventEmitter.call(_assertThisInitialized__default['default'](_this));
}
_this.data = data || {};
_this.options = options;
if (_this.options.keySeparator === undefined) {
_this.options.keySeparator = '.';
}
if (_this.options.ignoreJSONStructure === undefined) {
_this.options.ignoreJSONStructure = true;
}
return _this;
}
_createClass__default['default'](ResourceStore, [{
key: "addNamespaces",
value: function addNamespaces(ns) {
if (this.options.ns.indexOf(ns) < 0) {
this.options.ns.push(ns);
}
}
}, {
key: "removeNamespaces",
value: function removeNamespaces(ns) {
var index = this.options.ns.indexOf(ns);
if (index > -1) {
this.options.ns.splice(index, 1);
}
}
}, {
key: "getResource",
value: function getResource(lng, ns, key) {
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
var ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
var path = [lng, ns];
if (key && typeof key !== 'string') path = path.concat(key);
if (key && typeof key === 'string') path = path.concat(keySeparator ? key.split(keySeparator) : key);
if (lng.indexOf('.') > -1) {
path = lng.split('.');
}
var result = getPath(this.data, path);
if (result || !ignoreJSONStructure || typeof key !== 'string') return result;
return deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator);
}
}, {
key: "addResource",
value: function addResource(lng, ns, key, value) {
var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
silent: false
};
var keySeparator = this.options.keySeparator;
if (keySeparator === undefined) keySeparator = '.';
var path = [lng, ns];
if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
if (lng.indexOf('.') > -1) {
path = lng.split('.');
value = ns;
ns = path[1];
}
this.addNamespaces(ns);
setPath(this.data, path, value);
if (!options.silent) this.emit('added', lng, ns, key, value);
}
}, {
key: "addResources",
value: function addResources(lng, ns, resources) {
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
silent: false
};
for (var m in resources) {
if (typeof resources[m] === 'string' || Object.prototype.toString.apply(resources[m]) === '[object Array]') this.addResource(lng, ns, m, resources[m], {
silent: true
});
}
if (!options.silent) this.emit('added', lng, ns, resources);
}
}, {
key: "addResourceBundle",
value: function addResourceBundle(lng, ns, resources, deep, overwrite) {
var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {
silent: false
};
var path = [lng, ns];
if (lng.indexOf('.') > -1) {
path = lng.split('.');
deep = resources;
resources = ns;
ns = path[1];
}
this.addNamespaces(ns);
var pack = getPath(this.data, path) || {};
if (deep) {
deepExtend(pack, resources, overwrite);
} else {
pack = _objectSpread$1(_objectSpread$1({}, pack), resources);
}
setPath(this.data, path, pack);
if (!options.silent) this.emit('added', lng, ns, resources);
}
}, {
key: "removeResourceBundle",
value: function removeResourceBundle(lng, ns) {
if (this.hasResourceBundle(lng, ns)) {
delete this.data[lng][ns];
}
this.removeNamespaces(ns);
this.emit('removed', lng, ns);
}
}, {
key: "hasResourceBundle",
value: function hasResourceBundle(lng, ns) {
return this.getResource(lng, ns) !== undefined;
}
}, {
key: "getResourceBundle",
value: function getResourceBundle(lng, ns) {
if (!ns) ns = this.options.defaultNS;
if (this.options.compatibilityAPI === 'v1') return _objectSpread$1(_objectSpread$1({}, {}), this.getResource(lng, ns));
return this.getResource(lng, ns);
}
}, {
key: "getDataByLanguage",
value: function getDataByLanguage(lng) {
return this.data[lng];
}
}, {
key: "hasLanguageSomeTranslations",
value: function hasLanguageSomeTranslations(lng) {
var data = this.getDataByLanguage(lng);
var n = data && Object.keys(data) || [];
return !!n.find(function (v) {
return data[v] && Object.keys(data[v]).length > 0;
});
}
}, {
key: "toJSON",
value: function toJSON() {
return this.data;
}
}]);
return ResourceStore;
}(EventEmitter);
var postProcessor = {
processors: {},
addPostProcessor: function addPostProcessor(module) {
this.processors[module.name] = module;
},
handle: function handle(processors, value, key, options, translator) {
var _this = this;
processors.forEach(function (processor) {
if (_this.processors[processor]) value = _this.processors[processor].process(value, key, options, translator);
});
return value;
}
};
function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; }
function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var checkedLoadedFor = {};
var Translator = function (_EventEmitter) {
_inherits__default['default'](Translator, _EventEmitter);
var _super = _createSuper$1(Translator);
function Translator(services) {
var _this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck__default['default'](this, Translator);
_this = _super.call(this);
if (isIE10) {
EventEmitter.call(_assertThisInitialized__default['default'](_this));
}
copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, _assertThisInitialized__default['default'](_this));
_this.options = options;
if (_this.options.keySeparator === undefined) {
_this.options.keySeparator = '.';
}
_this.logger = baseLogger.create('translator');
return _this;
}
_createClass__default['default'](Translator, [{
key: "changeLanguage",
value: function changeLanguage(lng) {
if (lng) this.language = lng;
}
}, {
key: "exists",
value: function exists(key) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
interpolation: {}
};
if (key === undefined || key === null) {
return false;
}
var resolved = this.resolve(key, options);
return resolved && resolved.res !== undefined;
}
}, {
key: "extractFromKey",
value: function extractFromKey(key, options) {
var nsSeparator = options.nsSeparator !== undefined ? options.nsSeparator : this.options.nsSeparator;
if (nsSeparator === undefined) nsSeparator = ':';
var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
var namespaces = options.ns || this.options.defaultNS || [];
var wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
var seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
var m = key.match(this.interpolator.nestingRegexp);
if (m && m.length > 0) {
return {
key: key,
namespaces: namespaces
};
}
var parts = key.split(nsSeparator);
if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
key = parts.join(keySeparator);
}
if (typeof namespaces === 'string') namespaces = [namespaces];
return {
key: key,
namespaces: namespaces
};
}
}, {
key: "translate",
value: function translate(keys, options, lastKey) {
var _this2 = this;
if (_typeof__default['default'](options) !== 'object' && this.options.overloadTranslationOptionHandler) {
options = this.options.overloadTranslationOptionHandler(arguments);
}
if (!options) options = {};
if (keys === undefined || keys === null) return '';
if (!Array.isArray(keys)) keys = [String(keys)];
var returnDetails = options.returnDetails !== undefined ? options.returnDetails : this.options.returnDetails;
var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
var _this$extractFromKey = this.extractFromKey(keys[keys.length - 1], options),
key = _this$extractFromKey.key,
namespaces = _this$extractFromKey.namespaces;
var namespace = namespaces[namespaces.length - 1];
var lng = options.lng || this.language;
var appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
if (lng && lng.toLowerCase() === 'cimode') {
if (appendNamespaceToCIMode) {
var nsSeparator = options.nsSeparator || this.options.nsSeparator;
if (returnDetails) {
resolved.res = "".concat(namespace).concat(nsSeparator).concat(key);
return resolved;
}
return "".concat(namespace).concat(nsSeparator).concat(key);
}
if (returnDetails) {
resolved.res = key;
return resolved;
}
return key;
}
var resolved = this.resolve(keys, options);
var res = resolved && resolved.res;
var resUsedKey = resolved && resolved.usedKey || key;
var resExactUsedKey = resolved && resolved.exactUsedKey || key;
var resType = Object.prototype.toString.apply(res);
var noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
var joinArrays = options.joinArrays !== undefined ? options.joinArrays : this.options.joinArrays;
var handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
var handleAsObject = typeof res !== 'string' && typeof res !== 'boolean' && typeof res !== 'number';
if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(typeof joinArrays === 'string' && resType === '[object Array]')) {
if (!options.returnObjects && !this.options.returnObjects) {
if (!this.options.returnedObjectHandler) {
this.logger.warn('accessing an object - but returnObjects options is not enabled!');
}
var r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, _objectSpread$2(_objectSpread$2({}, options), {}, {
ns: namespaces
})) : "key '".concat(key, " (").concat(this.language, ")' returned an object instead of string.");
if (returnDetails) {
resolved.res = r;
return resolved;
}
return r;
}
if (keySeparator) {
var resTypeIsArray = resType === '[object Array]';
var copy = resTypeIsArray ? [] : {};
var newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
for (var m in res) {
if (Object.prototype.hasOwnProperty.call(res, m)) {
var deepKey = "".concat(newKeyToUse).concat(keySeparator).concat(m);
copy[m] = this.translate(deepKey, _objectSpread$2(_objectSpread$2({}, options), {
joinArrays: false,
ns: namespaces
}));
if (copy[m] === deepKey) copy[m] = res[m];
}
}
res = copy;
}
} else if (handleAsObjectInI18nFormat && typeof joinArrays === 'string' && resType === '[object Array]') {
res = res.join(joinArrays);
if (res) res = this.extendTranslation(res, keys, options, lastKey);
} else {
var usedDefault = false;
var usedKey = false;
var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
var hasDefaultValue = Translator.hasDefaultValue(options);
var defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : '';
var defaultValue = options["defaultValue".concat(defaultValueSuffix)] || options.defaultValue;
if (!this.isValidLookup(res) && hasDefaultValue) {
usedDefault = true;
res = defaultValue;
}
if (!this.isValidLookup(res)) {
usedKey = true;
res = key;
}
var missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
var resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
var updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
if (usedKey || usedDefault || updateMissing) {
this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);
if (keySeparator) {
var fk = this.resolve(key, _objectSpread$2(_objectSpread$2({}, options), {}, {
keySeparator: false
}));
if (fk && fk.res) this.logger.warn('Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.');
}
var lngs = [];
var fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);
if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
for (var i = 0; i < fallbackLngs.length; i++) {
lngs.push(fallbackLngs[i]);
}
} else if (this.options.saveMissingTo === 'all') {
lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);
} else {
lngs.push(options.lng || this.language);
}
var send = function send(l, k, specificDefaultValue) {
var defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
if (_this2.options.missingKeyHandler) {
_this2.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, options);
} else if (_this2.backendConnector && _this2.backendConnector.saveMissing) {
_this2.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, options);
}
_this2.emit('missingKey', l, namespace, k, res);
};
if (this.options.saveMissing) {
if (this.options.saveMissingPlurals && needsPluralHandling) {
lngs.forEach(function (language) {
_this2.pluralResolver.getSuffixes(language, options).forEach(function (suffix) {
send([language], key + suffix, options["defaultValue".concat(suffix)] || defaultValue);
});
});
} else {
send(lngs, key, defaultValue);
}
}
}
res = this.extendTranslation(res, keys, options, resolved, lastKey);
if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = "".concat(namespace, ":").concat(key);
if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
if (this.options.compatibilityAPI !== 'v1') {
res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? "".concat(namespace, ":").concat(key) : key, usedDefault ? res : undefined);
} else {
res = this.options.parseMissingKeyHandler(res);
}
}
}
if (returnDetails) {
resolved.res = res;
return resolved;
}
return res;
}
}, {
key: "extendTranslation",
value: function extendTranslation(res, key, options, resolved, lastKey) {
var _this3 = this;
if (this.i18nFormat && this.i18nFormat.parse) {
res = this.i18nFormat.parse(res, _objectSpread$2(_objectSpread$2({}, this.options.interpolation.defaultVariables), options), resolved.usedLng, resolved.usedNS, resolved.usedKey, {
resolved: resolved
});
} else if (!options.skipInterpolation) {
if (options.interpolation) this.interpolator.init(_objectSpread$2(_objectSpread$2({}, options), {
interpolation: _objectSpread$2(_objectSpread$2({}, this.options.interpolation), options.interpolation)
}));
var skipOnVariables = typeof res === 'string' && (options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
var nestBef;
if (skipOnVariables) {
var nb = res.match(this.interpolator.nestingRegexp);
nestBef = nb && nb.length;
}
var data = options.replace && typeof options.replace !== 'string' ? options.replace : options;
if (this.options.interpolation.defaultVariables) data = _objectSpread$2(_objectSpread$2({}, this.options.interpolation.defaultVariables), data);
res = this.interpolator.interpolate(res, data, options.lng || this.language, options);
if (skipOnVariables) {
var na = res.match(this.interpolator.nestingRegexp);
var nestAft = na && na.length;
if (nestBef < nestAft) options.nest = false;
}
if (options.nest !== false) res = this.interpolator.nest(res, function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (lastKey && lastKey[0] === args[0] && !options.context) {
_this3.logger.warn("It seems you are nesting recursively key: ".concat(args[0], " in key: ").concat(key[0]));
return null;
}
return _this3.translate.apply(_this3, args.concat([key]));
}, options);
if (options.interpolation) this.interpolator.reset();
}
var postProcess = options.postProcess || this.options.postProcess;
var postProcessorNames = typeof postProcess === 'string' ? [postProcess] : postProcess;
if (res !== undefined && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) {
res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? _objectSpread$2({
i18nResolved: resolved
}, options) : options, this);
}
return res;
}
}, {
key: "resolve",
value: function resolve(keys) {
var _this4 = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var found;
var usedKey;
var exactUsedKey;
var usedLng;
var usedNS;
if (typeof keys === 'string') keys = [keys];
keys.forEach(function (k) {
if (_this4.isValidLookup(found)) return;
var extracted = _this4.extractFromKey(k, options);
var key = extracted.key;
usedKey = key;
var namespaces = extracted.namespaces;
if (_this4.options.fallbackNS) namespaces = namespaces.concat(_this4.options.fallbackNS);
var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
var needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && _this4.pluralResolver.shouldUseIntlApi();
var needsContextHandling = options.context !== undefined && (typeof options.context === 'string' || typeof options.context === 'number') && options.context !== '';
var codes = options.lngs ? options.lngs : _this4.languageUtils.toResolveHierarchy(options.lng || _this4.language, options.fallbackLng);
namespaces.forEach(function (ns) {
if (_this4.isValidLookup(found)) return;
usedNS = ns;
if (!checkedLoadedFor["".concat(codes[0], "-").concat(ns)] && _this4.utils && _this4.utils.hasLoadedNamespace && !_this4.utils.hasLoadedNamespace(usedNS)) {
checkedLoadedFor["".concat(codes[0], "-").concat(ns)] = true;
_this4.logger.warn("key \"".concat(usedKey, "\" for languages \"").concat(codes.join(', '), "\" won't get resolved as namespace \"").concat(usedNS, "\" was not yet loaded"), 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
}
codes.forEach(function (code) {
if (_this4.isValidLookup(found)) return;
usedLng = code;
var finalKeys = [key];
if (_this4.i18nFormat && _this4.i18nFormat.addLookupKeys) {
_this4.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);
} else {
var pluralSuffix;
if (needsPluralHandling) pluralSuffix = _this4.pluralResolver.getSuffix(code, options.count, options);
var zeroSuffix = "".concat(_this4.options.pluralSeparator, "zero");
if (needsPluralHandling) {
finalKeys.push(key + pluralSuffix);
if (needsZeroSuffixLookup) {
finalKeys.push(key + zeroSuffix);
}
}
if (needsContextHandling) {
var contextKey = "".concat(key).concat(_this4.options.contextSeparator).concat(options.context);
finalKeys.push(contextKey);
if (needsPluralHandling) {
finalKeys.push(contextKey + pluralSuffix);
if (needsZeroSuffixLookup) {
finalKeys.push(contextKey + zeroSuffix);
}
}
}
}
var possibleKey;
while (possibleKey = finalKeys.pop()) {
if (!_this4.isValidLookup(found)) {
exactUsedKey = possibleKey;
found = _this4.getResource(code, ns, possibleKey, options);
}
}
});
});
});
return {
res: found,
usedKey: usedKey,
exactUsedKey: exactUsedKey,
usedLng: usedLng,
usedNS: usedNS
};
}
}, {
key: "isValidLookup",
value: function isValidLookup(res) {
return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
}
}, {
key: "getResource",
value: function getResource(code, ns, key) {
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
if (this.i18nFormat && this.i18nFormat.getResource) return this.i18nFormat.getResource(code, ns, key, options);
return this.resourceStore.getResource(code, ns, key, options);
}
}], [{
key: "hasDefaultValue",
value: function hasDefaultValue(options) {
var prefix = 'defaultValue';
for (var option in options) {
if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {
return true;
}
}
return false;
}
}]);
return Translator;
}(EventEmitter);
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
var LanguageUtil = function () {
function LanguageUtil(options) {
_classCallCheck__default['default'](this, LanguageUtil);
this.options = options;
this.supportedLngs = this.options.supportedLngs || false;
this.logger = baseLogger.create('languageUtils');
}
_createClass__default['default'](LanguageUtil, [{
key: "getScriptPartFromCode",
value: function getScriptPartFromCode(code) {
if (!code || code.indexOf('-') < 0) return null;
var p = code.split('-');
if (p.length === 2) return null;
p.pop();
if (p[p.length - 1].toLowerCase() === 'x') return null;
return this.formatLanguageCode(p.join('-'));
}
}, {
key: "getLanguagePartFromCode",
value: function getLanguagePartFromCode(code) {
if (!code || code.indexOf('-') < 0) return code;
var p = code.split('-');
return this.formatLanguageCode(p[0]);
}
}, {
key: "formatLanguageCode",
value: function formatLanguageCode(code) {
if (typeof code === 'string' && code.indexOf('-') > -1) {
var specialCases = ['hans', 'hant', 'latn', 'cyrl', 'cans', 'mong', 'arab'];
var p = code.split('-');
if (this.options.lowerCaseLng) {
p = p.map(function (part) {
return part.toLowerCase();
});
} else if (p.length === 2) {
p[0] = p[0].toLowerCase();
p[1] = p[1].toUpperCase();
if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
} else if (p.length === 3) {
p[0] = p[0].toLowerCase();
if (p[1].length === 2) p[1] = p[1].toUpperCase();
if (p[0] !== 'sgn' && p[2].length === 2) p[2] = p[2].toUpperCase();
if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
if (specialCases.indexOf(p[2].toLowerCase()) > -1) p[2] = capitalize(p[2].toLowerCase());
}
return p.join('-');
}
return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
}
}, {
key: "isSupportedCode",
value: function isSupportedCode(code) {
if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {
code = this.getLanguagePartFromCode(code);
}
return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
}
}, {
key: "getBestMatchFromCodes",
value: function getBestMatchFromCodes(codes) {
var _this = this;
if (!codes) return null;
var found;
codes.forEach(function (code) {
if (found) return;
var cleanedLng = _this.formatLanguageCode(code);
if (!_this.options.supportedLngs || _this.isSupportedCode(cleanedLng)) found = cleanedLng;
});
if (!found && this.options.supportedLngs) {
codes.forEach(function (code) {
if (found) return;
var lngOnly = _this.getLanguagePartFromCode(code);
if (_this.isSupportedCode(lngOnly)) return found = lngOnly;
found = _this.options.supportedLngs.find(function (supportedLng) {
if (supportedLng.indexOf(lngOnly) === 0) return supportedLng;
});
});
}
if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
return found;
}
}, {
key: "getFallbackCodes",
value: function getFallbackCodes(fallbacks, code) {
if (!fallbacks) return [];
if (typeof fallbacks === 'function') fallbacks = fallbacks(code);
if (typeof fallbacks === 'string') fallbacks = [fallbacks];
if (Object.prototype.toString.apply(fallbacks) === '[object Array]') return fallbacks;
if (!code) return fallbacks["default"] || [];
var found = fallbacks[code];
if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
if (!found) found = fallbacks[this.formatLanguageCode(code)];
if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
if (!found) found = fallbacks["default"];
return found || [];
}
}, {
key: "toResolveHierarchy",
value: function toResolveHierarchy(code, fallbackCode) {
var _this2 = this;
var fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);
var codes = [];
var addCode = function addCode(c) {
if (!c) return;
if (_this2.isSupportedCode(c)) {
codes.push(c);
} else {
_this2.logger.warn("rejecting language code not found in supportedLngs: ".concat(c));
}
};
if (typeof code === 'string' && code.indexOf('-') > -1) {
if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
} else if (typeof code === 'string') {
addCode(this.formatLanguageCode(code));
}
fallbackCodes.forEach(function (fc) {
if (codes.indexOf(fc) < 0) addCode(_this2.formatLanguageCode(fc));
});
return codes;
}
}]);
return LanguageUtil;
}();
var sets = [{
lngs: ['ach', 'ak', 'am', 'arn', 'br', 'fil', 'gun', 'ln', 'mfe', 'mg', 'mi', 'oc', 'pt', 'pt-BR', 'tg', 'tl', 'ti', 'tr', 'uz', 'wa'],
nr: [1, 2],
fc: 1
}, {
lngs: ['af', 'an', 'ast', 'az', 'bg', 'bn', 'ca', 'da', 'de', 'dev', 'el', 'en', 'eo', 'es', 'et', 'eu', 'fi', 'fo', 'fur', 'fy', 'gl', 'gu', 'ha', 'hi', 'hu', 'hy', 'ia', 'it', 'kk', 'kn', 'ku', 'lb', 'mai', 'ml', 'mn', 'mr', 'nah', 'nap', 'nb', 'ne', 'nl', 'nn', 'no', 'nso', 'pa', 'pap', 'pms', 'ps', 'pt-PT', 'rm', 'sco', 'se', 'si', 'so', 'son', 'sq', 'sv', 'sw', 'ta', 'te', 'tk', 'ur', 'yo'],
nr: [1, 2],
fc: 2
}, {
lngs: ['ay', 'bo', 'cgg', 'fa', 'ht', 'id', 'ja', 'jbo', 'ka', 'km', 'ko', 'ky', 'lo', 'ms', 'sah', 'su', 'th', 'tt', 'ug', 'vi', 'wo', 'zh'],
nr: [1],
fc: 3
}, {
lngs: ['be', 'bs', 'cnr', 'dz', 'hr', 'ru', 'sr', 'uk'],
nr: [1, 2, 5],
fc: 4
}, {
lngs: ['ar'],
nr: [0, 1, 2, 3, 11, 100],
fc: 5
}, {
lngs: ['cs', 'sk'],
nr: [1, 2, 5],
fc: 6
}, {
lngs: ['csb', 'pl'],
nr: [1, 2, 5],
fc: 7
}, {
lngs: ['cy'],
nr: [1, 2, 3, 8],
fc: 8
}, {
lngs: ['fr'],
nr: [1, 2],
fc: 9
}, {
lngs: ['ga'],
nr: [1, 2, 3, 7, 11],
fc: 10
}, {
lngs: ['gd'],
nr: [1, 2, 3, 20],
fc: 11
}, {
lngs: ['is'],
nr: [1, 2],
fc: 12
}, {
lngs: ['jv'],
nr: [0, 1],
fc: 13
}, {
lngs: ['kw'],
nr: [1, 2, 3, 4],
fc: 14
}, {
lngs: ['lt'],
nr: [1, 2, 10],
fc: 15
}, {
lngs: ['lv'],
nr: [1, 2, 0],
fc: 16
}, {
lngs: ['mk'],
nr: [1, 2],
fc: 17
}, {
lngs: ['mnk'],
nr: [0, 1, 2],
fc: 18
}, {
lngs: ['mt'],
nr: [1, 2, 11, 20],
fc: 19
}, {
lngs: ['or'],
nr: [2, 1],
fc: 2
}, {
lngs: ['ro'],
nr: [1, 2, 20],
fc: 20
}, {
lngs: ['sl'],
nr: [5, 1, 2, 3],
fc: 21
}, {
lngs: ['he', 'iw'],
nr: [1, 2, 20, 21],
fc: 22
}];
var _rulesPluralsTypes = {
1: function _(n) {
return Number(n > 1);
},
2: function _(n) {
return Number(n != 1);
},
3: function _(n) {
return 0;
},
4: function _(n) {
return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
},
5: function _(n) {
return Number(n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5);
},
6: function _(n) {
return Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2);
},
7: function _(n) {
return Number(n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
},
8: function _(n) {
return Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3);
},
9: function _(n) {
return Number(n >= 2);
},
10: function _(n) {
return Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4);
},
11: function _(n) {
return Number(n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3);
},
12: function _(n) {
return Number(n % 10 != 1 || n % 100 == 11);
},
13: function _(n) {
return Number(n !== 0);
},
14: function _(n) {
return Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3);
},
15: function _(n) {
return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
},
16: function _(n) {
return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2);
},
17: function _(n) {
return Number(n == 1 || n % 10 == 1 && n % 100 != 11 ? 0 : 1);
},
18: function _(n) {
return Number(n == 0 ? 0 : n == 1 ? 1 : 2);
},
19: function _(n) {
return Number(n == 1 ? 0 : n == 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3);
},
20: function _(n) {
return Number(n == 1 ? 0 : n == 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2);
},
21: function _(n) {
return Number(n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0);
},
22: function _(n) {
return Number(n == 1 ? 0 : n == 2 ? 1 : (n < 0 || n > 10) && n % 10 == 0 ? 2 : 3);
}
};
var deprecatedJsonVersions = ['v1', 'v2', 'v3'];
var suffixesOrder = {
zero: 0,
one: 1,
two: 2,
few: 3,
many: 4,
other: 5
};
function createRules() {
var rules = {};
sets.forEach(function (set) {
set.lngs.forEach(function (l) {
rules[l] = {
numbers: set.nr,
plurals: _rulesPluralsTypes[set.fc]
};
});
});
return rules;
}
var PluralResolver = function () {
function PluralResolver(languageUtils) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck__default['default'](this, PluralResolver);
this.languageUtils = languageUtils;
this.options = options;
this.logger = baseLogger.create('pluralResolver');
if ((!this.options.compatibilityJSON || this.options.compatibilityJSON === 'v4') && (typeof Intl === 'undefined' || !Intl.PluralRules)) {
this.options.compatibilityJSON = 'v3';
this.logger.error('Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.');
}
this.rules = createRules();
}
_createClass__default['default'](PluralResolver, [{
key: "addRule",
value: function addRule(lng, obj) {
this.rules[lng] = obj;
}
}, {
key: "getRule",
value: function getRule(code) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (this.shouldUseIntlApi()) {
try {
return new Intl.PluralRules(code, {
type: options.ordinal ? 'ordinal' : 'cardinal'
});
} catch (_unused) {
return;
}
}
return this.rules[code] || this.rules[this.languageUtils.getLanguagePartFromCode(code)];
}
}, {
key: "needsPlural",
value: function needsPlural(code) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var rule = this.getRule(code, options);
if (this.shouldUseIntlApi()) {
return rule && rule.resolvedOptions().pluralCategories.length > 1;
}
return rule && rule.numbers.length > 1;
}
}, {
key: "getPluralFormsOfKey",
value: function getPluralFormsOfKey(code, key) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
return this.getSuffixes(code, options).map(function (suffix) {
return "".concat(key).concat(suffix);
});
}
}, {
key: "getSuffixes",
value: function getSuffixes(code) {
var _this = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var rule = this.getRule(code, options);
if (!rule) {
return [];
}
if (this.shouldUseIntlApi()) {
return rule.resolvedOptions().pluralCategories.sort(function (pluralCategory1, pluralCategory2) {
return suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2];
}).map(function (pluralCategory) {
return "".concat(_this.options.prepend).concat(pluralCategory);
});
}
return rule.numbers.map(function (number) {
return _this.getSuffix(code, number, options);
});
}
}, {
key: "getSuffix",
value: function getSuffix(code, count) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var rule = this.getRule(code, options);
if (rule) {
if (this.shouldUseIntlApi()) {
return "".concat(this.options.prepend).concat(rule.select(count));
}
return this.getSuffixRetroCompatible(rule, count);
}
this.logger.warn("no plural rule found for: ".concat(code));
return '';
}
}, {
key: "getSuffixRetroCompatible",
value: function getSuffixRetroCompatible(rule, count) {
var _this2 = this;
var idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count));
var suffix = rule.numbers[idx];
if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
if (suffix === 2) {
suffix = 'plural';
} else if (suffix === 1) {
suffix = '';
}
}
var returnSuffix = function returnSuffix() {
return _this2.options.prepend && suffix.toString() ? _this2.options.prepend + suffix.toString() : suffix.toString();
};
if (this.options.compatibilityJSON === 'v1') {
if (suffix === 1) return '';
if (typeof suffix === 'number') return "_plural_".concat(suffix.toString());
return returnSuffix();
} else if (this.options.compatibilityJSON === 'v2') {
return returnSuffix();
} else if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
return returnSuffix();
}
return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString();
}
}, {
key: "shouldUseIntlApi",
value: function shouldUseIntlApi() {
return !deprecatedJsonVersions.includes(this.options.compatibilityJSON);
}
}]);
return PluralResolver;
}();
function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$3(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var Interpolator = function () {
function Interpolator() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck__default['default'](this, Interpolator);
this.logger = baseLogger.create('interpolator');
this.options = options;
this.format = options.interpolation && options.interpolation.format || function (value) {
return value;
};
this.init(options);
}
_createClass__default['default'](Interpolator, [{
key: "init",
value: function init() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (!options.interpolation) options.interpolation = {
escapeValue: true
};
var iOpts = options.interpolation;
this.escape = iOpts.escape !== undefined ? iOpts.escape : escape;
this.escapeValue = iOpts.escapeValue !== undefined ? iOpts.escapeValue : true;
this.useRawValueToEscape = iOpts.useRawValueToEscape !== undefined ? iOpts.useRawValueToEscape : false;
this.prefix = iOpts.prefix ? regexEscape(iOpts.prefix) : iOpts.prefixEscaped || '{{';
this.suffix = iOpts.suffix ? regexEscape(iOpts.suffix) : iOpts.suffixEscaped || '}}';
this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
this.unescapePrefix = iOpts.unescapeSuffix ? '' : iOpts.unescapePrefix || '-';
this.unescapeSuffix = this.unescapePrefix ? '' : iOpts.unescapeSuffix || '';
this.nestingPrefix = iOpts.nestingPrefix ? regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || regexEscape('$t(');
this.nestingSuffix = iOpts.nestingSuffix ? regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || regexEscape(')');
this.nestingOptionsSeparator = iOpts.nestingOptionsSeparator ? iOpts.nestingOptionsSeparator : iOpts.nestingOptionsSeparator || ',';
this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1000;
this.alwaysFormat = iOpts.alwaysFormat !== undefined ? iOpts.alwaysFormat : false;
this.resetRegExp();
}
}, {
key: "reset",
value: function reset() {
if (this.options) this.init(this.options);
}
}, {
key: "resetRegExp",
value: function resetRegExp() {
var regexpStr = "".concat(this.prefix, "(.+?)").concat(this.suffix);
this.regexp = new RegExp(regexpStr, 'g');
var regexpUnescapeStr = "".concat(this.prefix).concat(this.unescapePrefix, "(.+?)").concat(this.unescapeSuffix).concat(this.suffix);
this.regexpUnescape = new RegExp(regexpUnescapeStr, 'g');
var nestingRegexpStr = "".concat(this.nestingPrefix, "(.+?)").concat(this.nestingSuffix);
this.nestingRegexp = new RegExp(nestingRegexpStr, 'g');
}
}, {
key: "interpolate",
value: function interpolate(str, data, lng, options) {
var _this = this;
var match;
var value;
var replaces;
var defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
function regexSafe(val) {
return val.replace(/\$/g, '$$$$');
}
var handleFormat = function handleFormat(key) {
if (key.indexOf(_this.formatSeparator) < 0) {
var path = getPathWithDefaults(data, defaultData, key);
return _this.alwaysFormat ? _this.format(path, undefined, lng, _objectSpread$3(_objectSpread$3(_objectSpread$3({}, options), data), {}, {
interpolationkey: key
})) : path;
}
var p = key.split(_this.formatSeparator);
var k = p.shift().trim();
var f = p.join(_this.formatSeparator).trim();
return _this.format(getPathWithDefaults(data, defaultData, k), f, lng, _objectSpread$3(_objectSpread$3(_objectSpread$3({}, options), data), {}, {
interpolationkey: k
}));
};
this.resetRegExp();
var missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler;
var skipOnVariables = options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
var todos = [{
regex: this.regexpUnescape,
safeValue: function safeValue(val) {
return regexSafe(val);
}
}, {
regex: this.regexp,
safeValue: function safeValue(val) {
return _this.escapeValue ? regexSafe(_this.escape(val)) : regexSafe(val);
}
}];
todos.forEach(function (todo) {
replaces = 0;
while (match = todo.regex.exec(str)) {
var matchedVar = match[1].trim();
value = handleFormat(matchedVar);
if (value === undefined) {
if (typeof missingInterpolationHandler === 'function') {
var temp = missingInterpolationHandler(str, match, options);
value = typeof temp === 'string' ? temp : '';
} else if (options && options.hasOwnProperty(matchedVar)) {
value = '';
} else if (skipOnVariables) {
value = match[0];
continue;
} else {
_this.logger.warn("missed to pass in variable ".concat(matchedVar, " for interpolating ").concat(str));
value = '';
}
} else if (typeof value !== 'string' && !_this.useRawValueToEscape) {
value = makeString(value);
}
var safeValue = todo.safeValue(value);
str = str.replace(match[0], safeValue);
if (skipOnVariables) {
todo.regex.lastIndex += value.length;
todo.regex.lastIndex -= match[0].length;
} else {
todo.regex.lastIndex = 0;
}
replaces++;
if (replaces >= _this.maxReplaces) {
break;
}
}
});
return str;
}
}, {
key: "nest",
value: function nest(str, fc) {
var _this2 = this;
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var match;
var value;
var clonedOptions = _objectSpread$3({}, options);
clonedOptions.applyPostProcessor = false;
delete clonedOptions.defaultValue;
function handleHasOptions(key, inheritedOptions) {
var sep = this.nestingOptionsSeparator;
if (key.indexOf(sep) < 0) return key;
var c = key.split(new RegExp("".concat(sep, "[ ]*{")));
var optionsString = "{".concat(c[1]);
key = c[0];
optionsString = this.interpolate(optionsString, clonedOptions);
var matchedSingleQuotes = optionsString.match(/'/g);
var matchedDoubleQuotes = optionsString.match(/"/g);
if (matchedSingleQuotes && matchedSingleQuotes.length % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
optionsString = optionsString.replace(/'/g, '"');
}
try {
clonedOptions = JSON.parse(optionsString);
if (inheritedOptions) clonedOptions = _objectSpread$3(_objectSpread$3({}, inheritedOptions), clonedOptions);
} catch (e) {
this.logger.warn("failed parsing options string in nesting for key ".concat(key), e);
return "".concat(key).concat(sep).concat(optionsString);
}
delete clonedOptions.defaultValue;
return key;
}
while (match = this.nestingRegexp.exec(str)) {
var formatters = [];
var doReduce = false;
if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) {
var r = match[1].split(this.formatSeparator).map(function (elem) {
return elem.trim();
});
match[1] = r.shift();
formatters = r;
doReduce = true;
}
value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
if (value && match[0] === str && typeof value !== 'string') return value;
if (typeof value !== 'string') value = makeString(value);
if (!value) {
this.logger.warn("missed to resolve ".concat(match[1], " for nesting ").concat(str));
value = '';
}
if (doReduce) {
value = formatters.reduce(function (v, f) {
return _this2.format(v, f, options.lng, _objectSpread$3(_objectSpread$3({}, options), {}, {
interpolationkey: match[1].trim()
}));
}, value.trim());
}
str = str.replace(match[0], value);
this.regexp.lastIndex = 0;
}
return str;
}
}]);
return Interpolator;
}();
function ownKeys$4(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$4(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$4(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function parseFormatStr(formatStr) {
var formatName = formatStr.toLowerCase().trim();
var formatOptions = {};
if (formatStr.indexOf('(') > -1) {
var p = formatStr.split('(');
formatName = p[0].toLowerCase().trim();
var optStr = p[1].substring(0, p[1].length - 1);
if (formatName === 'currency' && optStr.indexOf(':') < 0) {
if (!formatOptions.currency) formatOptions.currency = optStr.trim();
} else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {
if (!formatOptions.range) formatOptions.range = optStr.trim();
} else {
var opts = optStr.split(';');
opts.forEach(function (opt) {
if (!opt) return;
var _opt$split = opt.split(':'),
_opt$split2 = _toArray__default['default'](_opt$split),
key = _opt$split2[0],
rest = _opt$split2.slice(1);
var val = rest.join(':').trim().replace(/^'+|'+$/g, '');
if (!formatOptions[key.trim()]) formatOptions[key.trim()] = val;
if (val === 'false') formatOptions[key.trim()] = false;
if (val === 'true') formatOptions[key.trim()] = true;
if (!isNaN(val)) formatOptions[key.trim()] = parseInt(val, 10);
});
}
}
return {
formatName: formatName,
formatOptions: formatOptions
};
}
function createCachedFormatter(fn) {
var cache = {};
return function invokeFormatter(val, lng, options) {
var key = lng + JSON.stringify(options);
var formatter = cache[key];
if (!formatter) {
formatter = fn(lng, options);
cache[key] = formatter;
}
return formatter(val);
};
}
var Formatter = function () {
function Formatter() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck__default['default'](this, Formatter);
this.logger = baseLogger.create('formatter');
this.options = options;
this.formats = {
number: createCachedFormatter(function (lng, options) {
var formatter = new Intl.NumberFormat(lng, options);
return function (val) {
return formatter.format(val);
};
}),
currency: createCachedFormatter(function (lng, options) {
var formatter = new Intl.NumberFormat(lng, _objectSpread$4(_objectSpread$4({}, options), {}, {
style: 'currency'
}));
return function (val) {
return formatter.format(val);
};
}),
datetime: createCachedFormatter(function (lng, options) {
var formatter = new Intl.DateTimeFormat(lng, _objectSpread$4({}, options));
return function (val) {
return formatter.format(val);
};
}),
relativetime: createCachedFormatter(function (lng, options) {
var formatter = new Intl.RelativeTimeFormat(lng, _objectSpread$4({}, options));
return function (val) {
return formatter.format(val, options.range || 'day');
};
}),
list: createCachedFormatter(function (lng, options) {
var formatter = new Intl.ListFormat(lng, _objectSpread$4({}, options));
return function (val) {
return formatter.format(val);
};
})
};
this.init(options);
}
_createClass__default['default'](Formatter, [{
key: "init",
value: function init(services) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
interpolation: {}
};
var iOpts = options.interpolation;
this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
}
}, {
key: "add",
value: function add(name, fc) {
this.formats[name.toLowerCase().trim()] = fc;
}
}, {
key: "addCached",
value: function addCached(name, fc) {
this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
}
}, {
key: "format",
value: function format(value, _format, lng, options) {
var _this = this;
var formats = _format.split(this.formatSeparator);
var result = formats.reduce(function (mem, f) {
var _parseFormatStr = parseFormatStr(f),
formatName = _parseFormatStr.formatName,
formatOptions = _parseFormatStr.formatOptions;
if (_this.formats[formatName]) {
var formatted = mem;
try {
var valOptions = options && options.formatParams && options.formatParams[options.interpolationkey] || {};
var l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
formatted = _this.formats[formatName](mem, l, _objectSpread$4(_objectSpread$4(_objectSpread$4({}, formatOptions), options), valOptions));
} catch (error) {
_this.logger.warn(error);
}
return formatted;
} else {
_this.logger.warn("there was no format function for ".concat(formatName));
}
return mem;
}, value);
return result;
}
}]);
return Formatter;
}();
function ownKeys$5(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$5(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$5(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$5(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; }
function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function removePending(q, name) {
if (q.pending[name] !== undefined) {
delete q.pending[name];
q.pendingCount--;
}
}
var Connector = function (_EventEmitter) {
_inherits__default['default'](Connector, _EventEmitter);
var _super = _createSuper$2(Connector);
function Connector(backend, store, services) {
var _this;
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
_classCallCheck__default['default'](this, Connector);
_this = _super.call(this);
if (isIE10) {
EventEmitter.call(_assertThisInitialized__default['default'](_this));
}
_this.backend = backend;
_this.store = store;
_this.services = services;
_this.languageUtils = services.languageUtils;
_this.options = options;
_this.logger = baseLogger.create('backendConnector');
_this.waitingReads = [];
_this.maxParallelReads = options.maxParallelReads || 10;
_this.readingCalls = 0;
_this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
_this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
_this.state = {};
_this.queue = [];
if (_this.backend && _this.backend.init) {
_this.backend.init(services, options.backend, options);
}
return _this;
}
_createClass__default['default'](Connector, [{
key: "queueLoad",
value: function queueLoad(languages, namespaces, options, callback) {
var _this2 = this;
var toLoad = {};
var pending = {};
var toLoadLanguages = {};
var toLoadNamespaces = {};
languages.forEach(function (lng) {
var hasAllNamespaces = true;
namespaces.forEach(function (ns) {
var name = "".concat(lng, "|").concat(ns);
if (!options.reload && _this2.store.hasResourceBundle(lng, ns)) {
_this2.state[name] = 2;
} else if (_this2.state[name] < 0) ; else if (_this2.state[name] === 1) {
if (pending[name] === undefined) pending[name] = true;
} else {
_this2.state[name] = 1;
hasAllNamespaces = false;
if (pending[name] === undefined) pending[name] = true;
if (toLoad[name] === undefined) toLoad[name] = true;
if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;
}
});
if (!hasAllNamespaces) toLoadLanguages[lng] = true;
});
if (Object.keys(toLoad).length || Object.keys(pending).length) {
this.queue.push({
pending: pending,
pendingCount: Object.keys(pending).length,
loaded: {},
errors: [],
callback: callback
});
}
return {
toLoad: Object.keys(toLoad),
pending: Object.keys(pending),
toLoadLanguages: Object.keys(toLoadLanguages),
toLoadNamespaces: Object.keys(toLoadNamespaces)
};
}
}, {
key: "loaded",
value: function loaded(name, err, data) {
var s = name.split('|');
var lng = s[0];
var ns = s[1];
if (err) this.emit('failedLoading', lng, ns, err);
if (data) {
this.store.addResourceBundle(lng, ns, data);
}
this.state[name] = err ? -1 : 2;
var loaded = {};
this.queue.forEach(function (q) {
pushPath(q.loaded, [lng], ns);
removePending(q, name);
if (err) q.errors.push(err);
if (q.pendingCount === 0 && !q.done) {
Object.keys(q.loaded).forEach(function (l) {
if (!loaded[l]) loaded[l] = {};
var loadedKeys = q.loaded[l];
if (loadedKeys.length) {
loadedKeys.forEach(function (ns) {
if (loaded[l][ns] === undefined) loaded[l][ns] = true;
});
}
});
q.done = true;
if (q.errors.length) {
q.callback(q.errors);
} else {
q.callback();
}
}
});
this.emit('loaded', loaded);
this.queue = this.queue.filter(function (q) {
return !q.done;
});
}
}, {
key: "read",
value: function read(lng, ns, fcName) {
var _this3 = this;
var tried = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
var wait = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : this.retryTimeout;
var callback = arguments.length > 5 ? arguments[5] : undefined;
if (!lng.length) return callback(null, {});
if (this.readingCalls >= this.maxParallelReads) {
this.waitingReads.push({
lng: lng,
ns: ns,
fcName: fcName,
tried: tried,
wait: wait,
callback: callback
});
return;
}
this.readingCalls++;
return this.backend[fcName](lng, ns, function (err, data) {
_this3.readingCalls--;
if (_this3.waitingReads.length > 0) {
var next = _this3.waitingReads.shift();
_this3.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
}
if (err && data && tried < _this3.maxRetries) {
setTimeout(function () {
_this3.read.call(_this3, lng, ns, fcName, tried + 1, wait * 2, callback);
}, wait);
return;
}
callback(err, data);
});
}
}, {
key: "prepareLoading",
value: function prepareLoading(languages, namespaces) {
var _this4 = this;
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var callback = arguments.length > 3 ? arguments[3] : undefined;
if (!this.backend) {
this.logger.warn('No backend was added via i18next.use. Will not load resources.');
return callback && callback();
}
if (typeof languages === 'string') languages = this.languageUtils.toResolveHierarchy(languages);
if (typeof namespaces === 'string') namespaces = [namespaces];
var toLoad = this.queueLoad(languages, namespaces, options, callback);
if (!toLoad.toLoad.length) {
if (!toLoad.pending.length) callback();
return null;
}
toLoad.toLoad.forEach(function (name) {
_this4.loadOne(name);
});
}
}, {
key: "load",
value: function load(languages, namespaces, callback) {
this.prepareLoading(languages, namespaces, {}, callback);
}
}, {
key: "reload",
value: function reload(languages, namespaces, callback) {
this.prepareLoading(languages, namespaces, {
reload: true
}, callback);
}
}, {
key: "loadOne",
value: function loadOne(name) {
var _this5 = this;
var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var s = name.split('|');
var lng = s[0];
var ns = s[1];
this.read(lng, ns, 'read', undefined, undefined, function (err, data) {
if (err) _this5.logger.warn("".concat(prefix, "loading namespace ").concat(ns, " for language ").concat(lng, " failed"), err);
if (!err && data) _this5.logger.log("".concat(prefix, "loaded namespace ").concat(ns, " for language ").concat(lng), data);
_this5.loaded(name, err, data);
});
}
}, {
key: "saveMissing",
value: function saveMissing(languages, namespace, key, fallbackValue, isUpdate) {
var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace)) {
this.logger.warn("did not save key \"".concat(key, "\" as the namespace \"").concat(namespace, "\" was not yet loaded"), 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
return;
}
if (key === undefined || key === null || key === '') return;
if (this.backend && this.backend.create) {
this.backend.create(languages, namespace, key, fallbackValue, null, _objectSpread$5(_objectSpread$5({}, options), {}, {
isUpdate: isUpdate
}));
}
if (!languages || !languages[0]) return;
this.store.addResource(languages[0], namespace, key, fallbackValue);
}
}]);
return Connector;
}(EventEmitter);
function get() {
return {
debug: false,
initImmediate: true,
ns: ['translation'],
defaultNS: ['translation'],
fallbackLng: ['dev'],
fallbackNS: false,
supportedLngs: false,
nonExplicitSupportedLngs: false,
load: 'all',
preload: false,
simplifyPluralSuffix: true,
keySeparator: '.',
nsSeparator: ':',
pluralSeparator: '_',
contextSeparator: '_',
partialBundledLanguages: false,
saveMissing: false,
updateMissing: false,
saveMissingTo: 'fallback',
saveMissingPlurals: true,
missingKeyHandler: false,
missingInterpolationHandler: false,
postProcess: false,
postProcessPassResolved: false,
returnNull: true,
returnEmptyString: true,
returnObjects: false,
joinArrays: false,
returnedObjectHandler: false,
parseMissingKeyHandler: false,
appendNamespaceToMissingKey: false,
appendNamespaceToCIMode: false,
overloadTranslationOptionHandler: function handle(args) {
var ret = {};
if (_typeof__default['default'](args[1]) === 'object') ret = args[1];
if (typeof args[1] === 'string') ret.defaultValue = args[1];
if (typeof args[2] === 'string') ret.tDescription = args[2];
if (_typeof__default['default'](args[2]) === 'object' || _typeof__default['default'](args[3]) === 'object') {
var options = args[3] || args[2];
Object.keys(options).forEach(function (key) {
ret[key] = options[key];
});
}
return ret;
},
interpolation: {
escapeValue: true,
format: function format(value, _format, lng, options) {
return value;
},
prefix: '{{',
suffix: '}}',
formatSeparator: ',',
unescapePrefix: '-',
nestingPrefix: '$t(',
nestingSuffix: ')',
nestingOptionsSeparator: ',',
maxReplaces: 1000,
skipOnVariables: true
}
};
}
function transformOptions(options) {
if (typeof options.ns === 'string') options.ns = [options.ns];
if (typeof options.fallbackLng === 'string') options.fallbackLng = [options.fallbackLng];
if (typeof options.fallbackNS === 'string') options.fallbackNS = [options.fallbackNS];
if (options.supportedLngs && options.supportedLngs.indexOf('cimode') < 0) {
options.supportedLngs = options.supportedLngs.concat(['cimode']);
}
return options;
}
function ownKeys$6(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$6(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$6(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$6(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; }
function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function noop() {}
function bindMemberFunctions(inst) {
var mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
mems.forEach(function (mem) {
if (typeof inst[mem] === 'function') {
inst[mem] = inst[mem].bind(inst);
}
});
}
var I18n = function (_EventEmitter) {
_inherits__default['default'](I18n, _EventEmitter);
var _super = _createSuper$3(I18n);
function I18n() {
var _this;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var callback = arguments.length > 1 ? arguments[1] : undefined;
_classCallCheck__default['default'](this, I18n);
_this = _super.call(this);
if (isIE10) {
EventEmitter.call(_assertThisInitialized__default['default'](_this));
}
_this.options = transformOptions(options);
_this.services = {};
_this.logger = baseLogger;
_this.modules = {
external: []
};
bindMemberFunctions(_assertThisInitialized__default['default'](_this));
if (callback && !_this.isInitialized && !options.isClone) {
if (!_this.options.initImmediate) {
_this.init(options, callback);
return _possibleConstructorReturn__default['default'](_this, _assertThisInitialized__default['default'](_this));
}
setTimeout(function () {
_this.init(options, callback);
}, 0);
}
return _this;
}
_createClass__default['default'](I18n, [{
key: "init",
value: function init() {
var _this2 = this;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var callback = arguments.length > 1 ? arguments[1] : undefined;
if (typeof options === 'function') {
callback = options;
options = {};
}
if (!options.defaultNS && options.defaultNS !== false && options.ns) {
if (typeof options.ns === 'string') {
options.defaultNS = options.ns;
} else if (options.ns.indexOf('translation') < 0) {
options.defaultNS = options.ns[0];
}
}
var defOpts = get();
this.options = _objectSpread$6(_objectSpread$6(_objectSpread$6({}, defOpts), this.options), transformOptions(options));
if (this.options.compatibilityAPI !== 'v1') {
this.options.interpolation = _objectSpread$6(_objectSpread$6({}, defOpts.interpolation), this.options.interpolation);
}
if (options.keySeparator !== undefined) {
this.options.userDefinedKeySeparator = options.keySeparator;
}
if (options.nsSeparator !== undefined) {
this.options.userDefinedNsSeparator = options.nsSeparator;
}
function createClassOnDemand(ClassOrObject) {
if (!ClassOrObject) return null;
if (typeof ClassOrObject === 'function') return new ClassOrObject();
return ClassOrObject;
}
if (!this.options.isClone) {
if (this.modules.logger) {
baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
} else {
baseLogger.init(null, this.options);
}
var formatter;
if (this.modules.formatter) {
formatter = this.modules.formatter;
} else if (typeof Intl !== 'undefined') {
formatter = Formatter;
}
var lu = new LanguageUtil(this.options);
this.store = new ResourceStore(this.options.resources, this.options);
var s = this.services;
s.logger = baseLogger;
s.resourceStore = this.store;
s.languageUtils = lu;
s.pluralResolver = new PluralResolver(lu, {
prepend: this.options.pluralSeparator,
compatibilityJSON: this.options.compatibilityJSON,
simplifyPluralSuffix: this.options.simplifyPluralSuffix
});
if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
s.formatter = createClassOnDemand(formatter);
s.formatter.init(s, this.options);
this.options.interpolation.format = s.formatter.format.bind(s.formatter);
}
s.interpolator = new Interpolator(this.options);
s.utils = {
hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
};
s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
s.backendConnector.on('*', function (event) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
_this2.emit.apply(_this2, [event].concat(args));
});
if (this.modules.languageDetector) {
s.languageDetector = createClassOnDemand(this.modules.languageDetector);
s.languageDetector.init(s, this.options.detection, this.options);
}
if (this.modules.i18nFormat) {
s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
if (s.i18nFormat.init) s.i18nFormat.init(this);
}
this.translator = new Translator(this.services, this.options);
this.translator.on('*', function (event) {
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
_this2.emit.apply(_this2, [event].concat(args));
});
this.modules.external.forEach(function (m) {
if (m.init) m.init(_this2);
});
}
this.format = this.options.interpolation.format;
if (!callback) callback = noop;
if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
var codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];
}
if (!this.services.languageDetector && !this.options.lng) {
this.logger.warn('init: no languageDetector is used and no lng is defined');
}
var storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];
storeApi.forEach(function (fcName) {
_this2[fcName] = function () {
var _this2$store;
return (_this2$store = _this2.store)[fcName].apply(_this2$store, arguments);
};
});
var storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];
storeApiChained.forEach(function (fcName) {
_this2[fcName] = function () {
var _this2$store2;
(_this2$store2 = _this2.store)[fcName].apply(_this2$store2, arguments);
return _this2;
};
});
var deferred = defer();
var load = function load() {
var finish = function finish(err, t) {
if (_this2.isInitialized && !_this2.initializedStoreOnce) _this2.logger.warn('init: i18next is already initialized. You should call init just once!');
_this2.isInitialized = true;
if (!_this2.options.isClone) _this2.logger.log('initialized', _this2.options);
_this2.emit('initialized', _this2.options);
deferred.resolve(t);
callback(err, t);
};
if (_this2.languages && _this2.options.compatibilityAPI !== 'v1' && !_this2.isInitialized) return finish(null, _this2.t.bind(_this2));
_this2.changeLanguage(_this2.options.lng, finish);
};
if (this.options.resources || !this.options.initImmediate) {
load();
} else {
setTimeout(load, 0);
}
return deferred;
}
}, {
key: "loadResources",
value: function loadResources(language) {
var _this3 = this;
var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
var usedCallback = callback;
var usedLng = typeof language === 'string' ? language : this.language;
if (typeof language === 'function') usedCallback = language;
if (!this.options.resources || this.options.partialBundledLanguages) {
if (usedLng && usedLng.toLowerCase() === 'cimode') return usedCallback();
var toLoad = [];
var append = function append(lng) {
if (!lng) return;
var lngs = _this3.services.languageUtils.toResolveHierarchy(lng);
lngs.forEach(function (l) {
if (toLoad.indexOf(l) < 0) toLoad.push(l);
});
};
if (!usedLng) {
var fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
fallbacks.forEach(function (l) {
return append(l);
});
} else {
append(usedLng);
}
if (this.options.preload) {
this.options.preload.forEach(function (l) {
return append(l);
});
}
this.services.backendConnector.load(toLoad, this.options.ns, function (e) {
if (!e && !_this3.resolvedLanguage && _this3.language) _this3.setResolvedLanguage(_this3.language);
usedCallback(e);
});
} else {
usedCallback(null);
}
}
}, {
key: "reloadResources",
value: function reloadResources(lngs, ns, callback) {
var deferred = defer();
if (!lngs) lngs = this.languages;
if (!ns) ns = this.options.ns;
if (!callback) callback = noop;
this.services.backendConnector.reload(lngs, ns, function (err) {
deferred.resolve();
callback(err);
});
return deferred;
}
}, {
key: "use",
value: function use(module) {
if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');
if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');
if (module.type === 'backend') {
this.modules.backend = module;
}
if (module.type === 'logger' || module.log && module.warn && module.error) {
this.modules.logger = module;
}
if (module.type === 'languageDetector') {
this.modules.languageDetector = module;
}
if (module.type === 'i18nFormat') {
this.modules.i18nFormat = module;
}
if (module.type === 'postProcessor') {
postProcessor.addPostProcessor(module);
}
if (module.type === 'formatter') {
this.modules.formatter = module;
}
if (module.type === '3rdParty') {
this.modules.external.push(module);
}
return this;
}
}, {
key: "setResolvedLanguage",
value: function setResolvedLanguage(l) {
if (!l || !this.languages) return;
if (['cimode', 'dev'].indexOf(l) > -1) return;
for (var li = 0; li < this.languages.length; li++) {
var lngInLngs = this.languages[li];
if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;
if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
this.resolvedLanguage = lngInLngs;
break;
}
}
}
}, {
key: "changeLanguage",
value: function changeLanguage(lng, callback) {
var _this4 = this;
this.isLanguageChangingTo = lng;
var deferred = defer();
this.emit('languageChanging', lng);
var setLngProps = function setLngProps(l) {
_this4.language = l;
_this4.languages = _this4.services.languageUtils.toResolveHierarchy(l);
_this4.resolvedLanguage = undefined;
_this4.setResolvedLanguage(l);
};
var done = function done(err, l) {
if (l) {
setLngProps(l);
_this4.translator.changeLanguage(l);
_this4.isLanguageChangingTo = undefined;
_this4.emit('languageChanged', l);
_this4.logger.log('languageChanged', l);
} else {
_this4.isLanguageChangingTo = undefined;
}
deferred.resolve(function () {
return _this4.t.apply(_this4, arguments);
});
if (callback) callback(err, function () {
return _this4.t.apply(_this4, arguments);
});
};
var setLng = function setLng(lngs) {
if (!lng && !lngs && _this4.services.languageDetector) lngs = [];
var l = typeof lngs === 'string' ? lngs : _this4.services.languageUtils.getBestMatchFromCodes(lngs);
if (l) {
if (!_this4.language) {
setLngProps(l);
}
if (!_this4.translator.language) _this4.translator.changeLanguage(l);
if (_this4.services.languageDetector) _this4.services.languageDetector.cacheUserLanguage(l);
}
_this4.loadResources(l, function (err) {
done(err, l);
});
};
if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
setLng(this.services.languageDetector.detect());
} else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
this.services.languageDetector.detect(setLng);
} else {
setLng(lng);
}
return deferred;
}
}, {
key: "getFixedT",
value: function getFixedT(lng, ns, keyPrefix) {
var _this5 = this;
var fixedT = function fixedT(key, opts) {
var options;
if (_typeof__default['default'](opts) !== 'object') {
for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
rest[_key3 - 2] = arguments[_key3];
}
options = _this5.options.overloadTranslationOptionHandler([key, opts].concat(rest));
} else {
options = _objectSpread$6({}, opts);
}
options.lng = options.lng || fixedT.lng;
options.lngs = options.lngs || fixedT.lngs;
options.ns = options.ns || fixedT.ns;
options.keyPrefix = options.keyPrefix || keyPrefix || fixedT.keyPrefix;
var keySeparator = _this5.options.keySeparator || '.';
var resultKey = options.keyPrefix ? "".concat(options.keyPrefix).concat(keySeparator).concat(key) : key;
return _this5.t(resultKey, options);
};
if (typeof lng === 'string') {
fixedT.lng = lng;
} else {
fixedT.lngs = lng;
}
fixedT.ns = ns;
fixedT.keyPrefix = keyPrefix;
return fixedT;
}
}, {
key: "t",
value: function t() {
var _this$translator;
return this.translator && (_this$translator = this.translator).translate.apply(_this$translator, arguments);
}
}, {
key: "exists",
value: function exists() {
var _this$translator2;
return this.translator && (_this$translator2 = this.translator).exists.apply(_this$translator2, arguments);
}
}, {
key: "setDefaultNamespace",
value: function setDefaultNamespace(ns) {
this.options.defaultNS = ns;
}
}, {
key: "hasLoadedNamespace",
value: function hasLoadedNamespace(ns) {
var _this6 = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!this.isInitialized) {
this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);
return false;
}
if (!this.languages || !this.languages.length) {
this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);
return false;
}
var lng = this.resolvedLanguage || this.languages[0];
var fallbackLng = this.options ? this.options.fallbackLng : false;
var lastLng = this.languages[this.languages.length - 1];
if (lng.toLowerCase() === 'cimode') return true;
var loadNotPending = function loadNotPending(l, n) {
var loadState = _this6.services.backendConnector.state["".concat(l, "|").concat(n)];
return loadState === -1 || loadState === 2;
};
if (options.precheck) {
var preResult = options.precheck(this, loadNotPending);
if (preResult !== undefined) return preResult;
}
if (this.hasResourceBundle(lng, ns)) return true;
if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
return false;
}
}, {
key: "loadNamespaces",
value: function loadNamespaces(ns, callback) {
var _this7 = this;
var deferred = defer();
if (!this.options.ns) {
callback && callback();
return Promise.resolve();
}
if (typeof ns === 'string') ns = [ns];
ns.forEach(function (n) {
if (_this7.options.ns.indexOf(n) < 0) _this7.options.ns.push(n);
});
this.loadResources(function (err) {
deferred.resolve();
if (callback) callback(err);
});
return deferred;
}
}, {
key: "loadLanguages",
value: function loadLanguages(lngs, callback) {
var deferred = defer();
if (typeof lngs === 'string') lngs = [lngs];
var preloaded = this.options.preload || [];
var newLngs = lngs.filter(function (lng) {
return preloaded.indexOf(lng) < 0;
});
if (!newLngs.length) {
if (callback) callback();
return Promise.resolve();
}
this.options.preload = preloaded.concat(newLngs);
this.loadResources(function (err) {
deferred.resolve();
if (callback) callback(err);
});
return deferred;
}
}, {
key: "dir",
value: function dir(lng) {
if (!lng) lng = this.resolvedLanguage || (this.languages && this.languages.length > 0 ? this.languages[0] : this.language);
if (!lng) return 'rtl';
var rtlLngs = ['ar', 'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm', 'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp', 'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh', 'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'he', 'iw', 'ps', 'pbt', 'pbu', 'pst', 'prp', 'prd', 'ug', 'ur', 'ydd', 'yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam', 'ckb'];
return rtlLngs.indexOf(this.services.languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';
}
}, {
key: "cloneInstance",
value: function cloneInstance() {
var _this8 = this;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
var mergedOptions = _objectSpread$6(_objectSpread$6(_objectSpread$6({}, this.options), options), {
isClone: true
});
var clone = new I18n(mergedOptions);
if (options.debug !== undefined || options.prefix !== undefined) {
clone.logger = clone.logger.clone(options);
}
var membersToCopy = ['store', 'services', 'language'];
membersToCopy.forEach(function (m) {
clone[m] = _this8[m];
});
clone.services = _objectSpread$6({}, this.services);
clone.services.utils = {
hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
};
clone.translator = new Translator(clone.services, clone.options);
clone.translator.on('*', function (event) {
for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
args[_key4 - 1] = arguments[_key4];
}
clone.emit.apply(clone, [event].concat(args));
});
clone.init(mergedOptions, callback);
clone.translator.options = clone.options;
clone.translator.backendConnector.services.utils = {
hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
};
return clone;
}
}, {
key: "toJSON",
value: function toJSON() {
return {
options: this.options,
store: this.store,
language: this.language,
languages: this.languages,
resolvedLanguage: this.resolvedLanguage
};
}
}]);
return I18n;
}(EventEmitter);
_defineProperty__default['default'](I18n, "createInstance", function () {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var callback = arguments.length > 1 ? arguments[1] : undefined;
return new I18n(options, callback);
});
var instance = I18n.createInstance();
instance.createInstance = I18n.createInstance;
module.exports = instance;
},{"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/getPrototypeOf":8,"@babel/runtime/helpers/inherits":9,"@babel/runtime/helpers/possibleConstructorReturn":12,"@babel/runtime/helpers/toArray":14,"@babel/runtime/helpers/typeof":17}],100:[function(require,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
}
},{}],101:[function(require,module,exports){
var indexOf = [].indexOf;
module.exports = function(arr, obj){
if (indexOf) return arr.indexOf(obj);
for (var i = 0; i < arr.length; ++i) {
if (arr[i] === obj) return i;
}
return -1;
};
},{}],102:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
})
}
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
}
},{}],103:[function(require,module,exports){
/*jshint node:true */
/* globals define */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
/**
The following batches are equivalent:
var beautify_js = require('js-beautify');
var beautify_js = require('js-beautify').js;
var beautify_js = require('js-beautify').js_beautify;
var beautify_css = require('js-beautify').css;
var beautify_css = require('js-beautify').css_beautify;
var beautify_html = require('js-beautify').html;
var beautify_html = require('js-beautify').html_beautify;
All methods returned accept two arguments, the source string and an options object.
**/
function get_beautify(js_beautify, css_beautify, html_beautify) {
// the default is js
var beautify = function(src, config) {
return js_beautify.js_beautify(src, config);
};
// short aliases
beautify.js = js_beautify.js_beautify;
beautify.css = css_beautify.css_beautify;
beautify.html = html_beautify.html_beautify;
// legacy aliases
beautify.js_beautify = js_beautify.js_beautify;
beautify.css_beautify = css_beautify.css_beautify;
beautify.html_beautify = html_beautify.html_beautify;
return beautify;
}
if (typeof define === "function" && define.amd) {
// Add support for AMD ( https://github.com/amdjs/amdjs-api/wiki/AMD#defineamd-property- )
define([
"./lib/beautify",
"./lib/beautify-css",
"./lib/beautify-html"
], function(js_beautify, css_beautify, html_beautify) {
return get_beautify(js_beautify, css_beautify, html_beautify);
});
} else {
(function(mod) {
var beautifier = require('./src/index');
beautifier.js_beautify = beautifier.js;
beautifier.css_beautify = beautifier.css;
beautifier.html_beautify = beautifier.html;
mod.exports = get_beautify(beautifier, beautifier, beautifier);
})(module);
}
},{"./src/index":121}],104:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
function Directives(start_block_pattern, end_block_pattern) {
start_block_pattern = typeof start_block_pattern === 'string' ? start_block_pattern : start_block_pattern.source;
end_block_pattern = typeof end_block_pattern === 'string' ? end_block_pattern : end_block_pattern.source;
this.__directives_block_pattern = new RegExp(start_block_pattern + / beautify( \w+[:]\w+)+ /.source + end_block_pattern, 'g');
this.__directive_pattern = / (\w+)[:](\w+)/g;
this.__directives_end_ignore_pattern = new RegExp(start_block_pattern + /\sbeautify\signore:end\s/.source + end_block_pattern, 'g');
}
Directives.prototype.get_directives = function(text) {
if (!text.match(this.__directives_block_pattern)) {
return null;
}
var directives = {};
this.__directive_pattern.lastIndex = 0;
var directive_match = this.__directive_pattern.exec(text);
while (directive_match) {
directives[directive_match[1]] = directive_match[2];
directive_match = this.__directive_pattern.exec(text);
}
return directives;
};
Directives.prototype.readIgnored = function(input) {
return input.readUntilAfter(this.__directives_end_ignore_pattern);
};
module.exports.Directives = Directives;
},{}],105:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
var regexp_has_sticky = RegExp.prototype.hasOwnProperty('sticky');
function InputScanner(input_string) {
this.__input = input_string || '';
this.__input_length = this.__input.length;
this.__position = 0;
}
InputScanner.prototype.restart = function() {
this.__position = 0;
};
InputScanner.prototype.back = function() {
if (this.__position > 0) {
this.__position -= 1;
}
};
InputScanner.prototype.hasNext = function() {
return this.__position < this.__input_length;
};
InputScanner.prototype.next = function() {
var val = null;
if (this.hasNext()) {
val = this.__input.charAt(this.__position);
this.__position += 1;
}
return val;
};
InputScanner.prototype.peek = function(index) {
var val = null;
index = index || 0;
index += this.__position;
if (index >= 0 && index < this.__input_length) {
val = this.__input.charAt(index);
}
return val;
};
// This is a JavaScript only helper function (not in python)
// Javascript doesn't have a match method
// and not all implementation support "sticky" flag.
// If they do not support sticky then both this.match() and this.test() method
// must get the match and check the index of the match.
// If sticky is supported and set, this method will use it.
// Otherwise it will check that global is set, and fall back to the slower method.
InputScanner.prototype.__match = function(pattern, index) {
pattern.lastIndex = index;
var pattern_match = pattern.exec(this.__input);
if (pattern_match && !(regexp_has_sticky && pattern.sticky)) {
if (pattern_match.index !== index) {
pattern_match = null;
}
}
return pattern_match;
};
InputScanner.prototype.test = function(pattern, index) {
index = index || 0;
index += this.__position;
if (index >= 0 && index < this.__input_length) {
return !!this.__match(pattern, index);
} else {
return false;
}
};
InputScanner.prototype.testChar = function(pattern, index) {
// test one character regex match
var val = this.peek(index);
pattern.lastIndex = 0;
return val !== null && pattern.test(val);
};
InputScanner.prototype.match = function(pattern) {
var pattern_match = this.__match(pattern, this.__position);
if (pattern_match) {
this.__position += pattern_match[0].length;
} else {
pattern_match = null;
}
return pattern_match;
};
InputScanner.prototype.read = function(starting_pattern, until_pattern, until_after) {
var val = '';
var match;
if (starting_pattern) {
match = this.match(starting_pattern);
if (match) {
val += match[0];
}
}
if (until_pattern && (match || !starting_pattern)) {
val += this.readUntil(until_pattern, until_after);
}
return val;
};
InputScanner.prototype.readUntil = function(pattern, until_after) {
var val = '';
var match_index = this.__position;
pattern.lastIndex = this.__position;
var pattern_match = pattern.exec(this.__input);
if (pattern_match) {
match_index = pattern_match.index;
if (until_after) {
match_index += pattern_match[0].length;
}
} else {
match_index = this.__input_length;
}
val = this.__input.substring(this.__position, match_index);
this.__position = match_index;
return val;
};
InputScanner.prototype.readUntilAfter = function(pattern) {
return this.readUntil(pattern, true);
};
InputScanner.prototype.get_regexp = function(pattern, match_from) {
var result = null;
var flags = 'g';
if (match_from && regexp_has_sticky) {
flags = 'y';
}
// strings are converted to regexp
if (typeof pattern === "string" && pattern !== '') {
// result = new RegExp(pattern.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), flags);
result = new RegExp(pattern, flags);
} else if (pattern) {
result = new RegExp(pattern.source, flags);
}
return result;
};
InputScanner.prototype.get_literal_regexp = function(literal_string) {
return RegExp(literal_string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'));
};
/* css beautifier legacy helpers */
InputScanner.prototype.peekUntilAfter = function(pattern) {
var start = this.__position;
var val = this.readUntilAfter(pattern);
this.__position = start;
return val;
};
InputScanner.prototype.lookBack = function(testVal) {
var start = this.__position - 1;
return start >= testVal.length && this.__input.substring(start - testVal.length, start)
.toLowerCase() === testVal;
};
module.exports.InputScanner = InputScanner;
},{}],106:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
function Options(options, merge_child_field) {
this.raw_options = _mergeOpts(options, merge_child_field);
// Support passing the source text back with no change
this.disabled = this._get_boolean('disabled');
this.eol = this._get_characters('eol', 'auto');
this.end_with_newline = this._get_boolean('end_with_newline');
this.indent_size = this._get_number('indent_size', 4);
this.indent_char = this._get_characters('indent_char', ' ');
this.indent_level = this._get_number('indent_level');
this.preserve_newlines = this._get_boolean('preserve_newlines', true);
this.max_preserve_newlines = this._get_number('max_preserve_newlines', 32786);
if (!this.preserve_newlines) {
this.max_preserve_newlines = 0;
}
this.indent_with_tabs = this._get_boolean('indent_with_tabs', this.indent_char === '\t');
if (this.indent_with_tabs) {
this.indent_char = '\t';
// indent_size behavior changed after 1.8.6
// It used to be that indent_size would be
// set to 1 for indent_with_tabs. That is no longer needed and
// actually doesn't make sense - why not use spaces? Further,
// that might produce unexpected behavior - tabs being used
// for single-column alignment. So, when indent_with_tabs is true
// and indent_size is 1, reset indent_size to 4.
if (this.indent_size === 1) {
this.indent_size = 4;
}
}
// Backwards compat with 1.3.x
this.wrap_line_length = this._get_number('wrap_line_length', this._get_number('max_char'));
this.indent_empty_lines = this._get_boolean('indent_empty_lines');
// valid templating languages ['django', 'erb', 'handlebars', 'php', 'smarty']
// For now, 'auto' = all off for javascript, all on for html (and inline javascript).
// other values ignored
this.templating = this._get_selection_list('templating', ['auto', 'none', 'django', 'erb', 'handlebars', 'php', 'smarty'], ['auto']);
}
Options.prototype._get_array = function(name, default_value) {
var option_value = this.raw_options[name];
var result = default_value || [];
if (typeof option_value === 'object') {
if (option_value !== null && typeof option_value.concat === 'function') {
result = option_value.concat();
}
} else if (typeof option_value === 'string') {
result = option_value.split(/[^a-zA-Z0-9_\/\-]+/);
}
return result;
};
Options.prototype._get_boolean = function(name, default_value) {
var option_value = this.raw_options[name];
var result = option_value === undefined ? !!default_value : !!option_value;
return result;
};
Options.prototype._get_characters = function(name, default_value) {
var option_value = this.raw_options[name];
var result = default_value || '';
if (typeof option_value === 'string') {
result = option_value.replace(/\\r/, '\r').replace(/\\n/, '\n').replace(/\\t/, '\t');
}
return result;
};
Options.prototype._get_number = function(name, default_value) {
var option_value = this.raw_options[name];
default_value = parseInt(default_value, 10);
if (isNaN(default_value)) {
default_value = 0;
}
var result = parseInt(option_value, 10);
if (isNaN(result)) {
result = default_value;
}
return result;
};
Options.prototype._get_selection = function(name, selection_list, default_value) {
var result = this._get_selection_list(name, selection_list, default_value);
if (result.length !== 1) {
throw new Error(
"Invalid Option Value: The option '" + name + "' can only be one of the following values:\n" +
selection_list + "\nYou passed in: '" + this.raw_options[name] + "'");
}
return result[0];
};
Options.prototype._get_selection_list = function(name, selection_list, default_value) {
if (!selection_list || selection_list.length === 0) {
throw new Error("Selection list cannot be empty.");
}
default_value = default_value || [selection_list[0]];
if (!this._is_valid_selection(default_value, selection_list)) {
throw new Error("Invalid Default Value!");
}
var result = this._get_array(name, default_value);
if (!this._is_valid_selection(result, selection_list)) {
throw new Error(
"Invalid Option Value: The option '" + name + "' can contain only the following values:\n" +
selection_list + "\nYou passed in: '" + this.raw_options[name] + "'");
}
return result;
};
Options.prototype._is_valid_selection = function(result, selection_list) {
return result.length && selection_list.length &&
!result.some(function(item) { return selection_list.indexOf(item) === -1; });
};
// merges child options up with the parent options object
// Example: obj = {a: 1, b: {a: 2}}
// mergeOpts(obj, 'b')
//
// Returns: {a: 2}
function _mergeOpts(allOptions, childFieldName) {
var finalOpts = {};
allOptions = _normalizeOpts(allOptions);
var name;
for (name in allOptions) {
if (name !== childFieldName) {
finalOpts[name] = allOptions[name];
}
}
//merge in the per type settings for the childFieldName
if (childFieldName && allOptions[childFieldName]) {
for (name in allOptions[childFieldName]) {
finalOpts[name] = allOptions[childFieldName][name];
}
}
return finalOpts;
}
function _normalizeOpts(options) {
var convertedOpts = {};
var key;
for (key in options) {
var newKey = key.replace(/-/g, "_");
convertedOpts[newKey] = options[key];
}
return convertedOpts;
}
module.exports.Options = Options;
module.exports.normalizeOpts = _normalizeOpts;
module.exports.mergeOpts = _mergeOpts;
},{}],107:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
function OutputLine(parent) {
this.__parent = parent;
this.__character_count = 0;
// use indent_count as a marker for this.__lines that have preserved indentation
this.__indent_count = -1;
this.__alignment_count = 0;
this.__wrap_point_index = 0;
this.__wrap_point_character_count = 0;
this.__wrap_point_indent_count = -1;
this.__wrap_point_alignment_count = 0;
this.__items = [];
}
OutputLine.prototype.clone_empty = function() {
var line = new OutputLine(this.__parent);
line.set_indent(this.__indent_count, this.__alignment_count);
return line;
};
OutputLine.prototype.item = function(index) {
if (index < 0) {
return this.__items[this.__items.length + index];
} else {
return this.__items[index];
}
};
OutputLine.prototype.has_match = function(pattern) {
for (var lastCheckedOutput = this.__items.length - 1; lastCheckedOutput >= 0; lastCheckedOutput--) {
if (this.__items[lastCheckedOutput].match(pattern)) {
return true;
}
}
return false;
};
OutputLine.prototype.set_indent = function(indent, alignment) {
if (this.is_empty()) {
this.__indent_count = indent || 0;
this.__alignment_count = alignment || 0;
this.__character_count = this.__parent.get_indent_size(this.__indent_count, this.__alignment_count);
}
};
OutputLine.prototype._set_wrap_point = function() {
if (this.__parent.wrap_line_length) {
this.__wrap_point_index = this.__items.length;
this.__wrap_point_character_count = this.__character_count;
this.__wrap_point_indent_count = this.__parent.next_line.__indent_count;
this.__wrap_point_alignment_count = this.__parent.next_line.__alignment_count;
}
};
OutputLine.prototype._should_wrap = function() {
return this.__wrap_point_index &&
this.__character_count > this.__parent.wrap_line_length &&
this.__wrap_point_character_count > this.__parent.next_line.__character_count;
};
OutputLine.prototype._allow_wrap = function() {
if (this._should_wrap()) {
this.__parent.add_new_line();
var next = this.__parent.current_line;
next.set_indent(this.__wrap_point_indent_count, this.__wrap_point_alignment_count);
next.__items = this.__items.slice(this.__wrap_point_index);
this.__items = this.__items.slice(0, this.__wrap_point_index);
next.__character_count += this.__character_count - this.__wrap_point_character_count;
this.__character_count = this.__wrap_point_character_count;
if (next.__items[0] === " ") {
next.__items.splice(0, 1);
next.__character_count -= 1;
}
return true;
}
return false;
};
OutputLine.prototype.is_empty = function() {
return this.__items.length === 0;
};
OutputLine.prototype.last = function() {
if (!this.is_empty()) {
return this.__items[this.__items.length - 1];
} else {
return null;
}
};
OutputLine.prototype.push = function(item) {
this.__items.push(item);
var last_newline_index = item.lastIndexOf('\n');
if (last_newline_index !== -1) {
this.__character_count = item.length - last_newline_index;
} else {
this.__character_count += item.length;
}
};
OutputLine.prototype.pop = function() {
var item = null;
if (!this.is_empty()) {
item = this.__items.pop();
this.__character_count -= item.length;
}
return item;
};
OutputLine.prototype._remove_indent = function() {
if (this.__indent_count > 0) {
this.__indent_count -= 1;
this.__character_count -= this.__parent.indent_size;
}
};
OutputLine.prototype._remove_wrap_indent = function() {
if (this.__wrap_point_indent_count > 0) {
this.__wrap_point_indent_count -= 1;
}
};
OutputLine.prototype.trim = function() {
while (this.last() === ' ') {
this.__items.pop();
this.__character_count -= 1;
}
};
OutputLine.prototype.toString = function() {
var result = '';
if (this.is_empty()) {
if (this.__parent.indent_empty_lines) {
result = this.__parent.get_indent_string(this.__indent_count);
}
} else {
result = this.__parent.get_indent_string(this.__indent_count, this.__alignment_count);
result += this.__items.join('');
}
return result;
};
function IndentStringCache(options, baseIndentString) {
this.__cache = [''];
this.__indent_size = options.indent_size;
this.__indent_string = options.indent_char;
if (!options.indent_with_tabs) {
this.__indent_string = new Array(options.indent_size + 1).join(options.indent_char);
}
// Set to null to continue support for auto detection of base indent
baseIndentString = baseIndentString || '';
if (options.indent_level > 0) {
baseIndentString = new Array(options.indent_level + 1).join(this.__indent_string);
}
this.__base_string = baseIndentString;
this.__base_string_length = baseIndentString.length;
}
IndentStringCache.prototype.get_indent_size = function(indent, column) {
var result = this.__base_string_length;
column = column || 0;
if (indent < 0) {
result = 0;
}
result += indent * this.__indent_size;
result += column;
return result;
};
IndentStringCache.prototype.get_indent_string = function(indent_level, column) {
var result = this.__base_string;
column = column || 0;
if (indent_level < 0) {
indent_level = 0;
result = '';
}
column += indent_level * this.__indent_size;
this.__ensure_cache(column);
result += this.__cache[column];
return result;
};
IndentStringCache.prototype.__ensure_cache = function(column) {
while (column >= this.__cache.length) {
this.__add_column();
}
};
IndentStringCache.prototype.__add_column = function() {
var column = this.__cache.length;
var indent = 0;
var result = '';
if (this.__indent_size && column >= this.__indent_size) {
indent = Math.floor(column / this.__indent_size);
column -= indent * this.__indent_size;
result = new Array(indent + 1).join(this.__indent_string);
}
if (column) {
result += new Array(column + 1).join(' ');
}
this.__cache.push(result);
};
function Output(options, baseIndentString) {
this.__indent_cache = new IndentStringCache(options, baseIndentString);
this.raw = false;
this._end_with_newline = options.end_with_newline;
this.indent_size = options.indent_size;
this.wrap_line_length = options.wrap_line_length;
this.indent_empty_lines = options.indent_empty_lines;
this.__lines = [];
this.previous_line = null;
this.current_line = null;
this.next_line = new OutputLine(this);
this.space_before_token = false;
this.non_breaking_space = false;
this.previous_token_wrapped = false;
// initialize
this.__add_outputline();
}
Output.prototype.__add_outputline = function() {
this.previous_line = this.current_line;
this.current_line = this.next_line.clone_empty();
this.__lines.push(this.current_line);
};
Output.prototype.get_line_number = function() {
return this.__lines.length;
};
Output.prototype.get_indent_string = function(indent, column) {
return this.__indent_cache.get_indent_string(indent, column);
};
Output.prototype.get_indent_size = function(indent, column) {
return this.__indent_cache.get_indent_size(indent, column);
};
Output.prototype.is_empty = function() {
return !this.previous_line && this.current_line.is_empty();
};
Output.prototype.add_new_line = function(force_newline) {
// never newline at the start of file
// otherwise, newline only if we didn't just add one or we're forced
if (this.is_empty() ||
(!force_newline && this.just_added_newline())) {
return false;
}
// if raw output is enabled, don't print additional newlines,
// but still return True as though you had
if (!this.raw) {
this.__add_outputline();
}
return true;
};
Output.prototype.get_code = function(eol) {
this.trim(true);
// handle some edge cases where the last tokens
// has text that ends with newline(s)
var last_item = this.current_line.pop();
if (last_item) {
if (last_item[last_item.length - 1] === '\n') {
last_item = last_item.replace(/\n+$/g, '');
}
this.current_line.push(last_item);
}
if (this._end_with_newline) {
this.__add_outputline();
}
var sweet_code = this.__lines.join('\n');
if (eol !== '\n') {
sweet_code = sweet_code.replace(/[\n]/g, eol);
}
return sweet_code;
};
Output.prototype.set_wrap_point = function() {
this.current_line._set_wrap_point();
};
Output.prototype.set_indent = function(indent, alignment) {
indent = indent || 0;
alignment = alignment || 0;
// Next line stores alignment values
this.next_line.set_indent(indent, alignment);
// Never indent your first output indent at the start of the file
if (this.__lines.length > 1) {
this.current_line.set_indent(indent, alignment);
return true;
}
this.current_line.set_indent();
return false;
};
Output.prototype.add_raw_token = function(token) {
for (var x = 0; x < token.newlines; x++) {
this.__add_outputline();
}
this.current_line.set_indent(-1);
this.current_line.push(token.whitespace_before);
this.current_line.push(token.text);
this.space_before_token = false;
this.non_breaking_space = false;
this.previous_token_wrapped = false;
};
Output.prototype.add_token = function(printable_token) {
this.__add_space_before_token();
this.current_line.push(printable_token);
this.space_before_token = false;
this.non_breaking_space = false;
this.previous_token_wrapped = this.current_line._allow_wrap();
};
Output.prototype.__add_space_before_token = function() {
if (this.space_before_token && !this.just_added_newline()) {
if (!this.non_breaking_space) {
this.set_wrap_point();
}
this.current_line.push(' ');
}
};
Output.prototype.remove_indent = function(index) {
var output_length = this.__lines.length;
while (index < output_length) {
this.__lines[index]._remove_indent();
index++;
}
this.current_line._remove_wrap_indent();
};
Output.prototype.trim = function(eat_newlines) {
eat_newlines = (eat_newlines === undefined) ? false : eat_newlines;
this.current_line.trim();
while (eat_newlines && this.__lines.length > 1 &&
this.current_line.is_empty()) {
this.__lines.pop();
this.current_line = this.__lines[this.__lines.length - 1];
this.current_line.trim();
}
this.previous_line = this.__lines.length > 1 ?
this.__lines[this.__lines.length - 2] : null;
};
Output.prototype.just_added_newline = function() {
return this.current_line.is_empty();
};
Output.prototype.just_added_blankline = function() {
return this.is_empty() ||
(this.current_line.is_empty() && this.previous_line.is_empty());
};
Output.prototype.ensure_empty_line_above = function(starts_with, ends_with) {
var index = this.__lines.length - 2;
while (index >= 0) {
var potentialEmptyLine = this.__lines[index];
if (potentialEmptyLine.is_empty()) {
break;
} else if (potentialEmptyLine.item(0).indexOf(starts_with) !== 0 &&
potentialEmptyLine.item(-1) !== ends_with) {
this.__lines.splice(index + 1, 0, new OutputLine(this));
this.previous_line = this.__lines[this.__lines.length - 2];
break;
}
index--;
}
};
module.exports.Output = Output;
},{}],108:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
function Pattern(input_scanner, parent) {
this._input = input_scanner;
this._starting_pattern = null;
this._match_pattern = null;
this._until_pattern = null;
this._until_after = false;
if (parent) {
this._starting_pattern = this._input.get_regexp(parent._starting_pattern, true);
this._match_pattern = this._input.get_regexp(parent._match_pattern, true);
this._until_pattern = this._input.get_regexp(parent._until_pattern);
this._until_after = parent._until_after;
}
}
Pattern.prototype.read = function() {
var result = this._input.read(this._starting_pattern);
if (!this._starting_pattern || result) {
result += this._input.read(this._match_pattern, this._until_pattern, this._until_after);
}
return result;
};
Pattern.prototype.read_match = function() {
return this._input.match(this._match_pattern);
};
Pattern.prototype.until_after = function(pattern) {
var result = this._create();
result._until_after = true;
result._until_pattern = this._input.get_regexp(pattern);
result._update();
return result;
};
Pattern.prototype.until = function(pattern) {
var result = this._create();
result._until_after = false;
result._until_pattern = this._input.get_regexp(pattern);
result._update();
return result;
};
Pattern.prototype.starting_with = function(pattern) {
var result = this._create();
result._starting_pattern = this._input.get_regexp(pattern, true);
result._update();
return result;
};
Pattern.prototype.matching = function(pattern) {
var result = this._create();
result._match_pattern = this._input.get_regexp(pattern, true);
result._update();
return result;
};
Pattern.prototype._create = function() {
return new Pattern(this._input, this);
};
Pattern.prototype._update = function() {};
module.exports.Pattern = Pattern;
},{}],109:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
var Pattern = require('./pattern').Pattern;
var template_names = {
django: false,
erb: false,
handlebars: false,
php: false,
smarty: false
};
// This lets templates appear anywhere we would do a readUntil
// The cost is higher but it is pay to play.
function TemplatablePattern(input_scanner, parent) {
Pattern.call(this, input_scanner, parent);
this.__template_pattern = null;
this._disabled = Object.assign({}, template_names);
this._excluded = Object.assign({}, template_names);
if (parent) {
this.__template_pattern = this._input.get_regexp(parent.__template_pattern);
this._excluded = Object.assign(this._excluded, parent._excluded);
this._disabled = Object.assign(this._disabled, parent._disabled);
}
var pattern = new Pattern(input_scanner);
this.__patterns = {
handlebars_comment: pattern.starting_with(/{{!--/).until_after(/--}}/),
handlebars_unescaped: pattern.starting_with(/{{{/).until_after(/}}}/),
handlebars: pattern.starting_with(/{{/).until_after(/}}/),
php: pattern.starting_with(/<\?(?:[= ]|php)/).until_after(/\?>/),
erb: pattern.starting_with(/<%[^%]/).until_after(/[^%]%>/),
// django coflicts with handlebars a bit.
django: pattern.starting_with(/{%/).until_after(/%}/),
django_value: pattern.starting_with(/{{/).until_after(/}}/),
django_comment: pattern.starting_with(/{#/).until_after(/#}/),
smarty: pattern.starting_with(/{(?=[^}{\s\n])/).until_after(/[^\s\n]}/),
smarty_comment: pattern.starting_with(/{\*/).until_after(/\*}/),
smarty_literal: pattern.starting_with(/{literal}/).until_after(/{\/literal}/)
};
}
TemplatablePattern.prototype = new Pattern();
TemplatablePattern.prototype._create = function() {
return new TemplatablePattern(this._input, this);
};
TemplatablePattern.prototype._update = function() {
this.__set_templated_pattern();
};
TemplatablePattern.prototype.disable = function(language) {
var result = this._create();
result._disabled[language] = true;
result._update();
return result;
};
TemplatablePattern.prototype.read_options = function(options) {
var result = this._create();
for (var language in template_names) {
result._disabled[language] = options.templating.indexOf(language) === -1;
}
result._update();
return result;
};
TemplatablePattern.prototype.exclude = function(language) {
var result = this._create();
result._excluded[language] = true;
result._update();
return result;
};
TemplatablePattern.prototype.read = function() {
var result = '';
if (this._match_pattern) {
result = this._input.read(this._starting_pattern);
} else {
result = this._input.read(this._starting_pattern, this.__template_pattern);
}
var next = this._read_template();
while (next) {
if (this._match_pattern) {
next += this._input.read(this._match_pattern);
} else {
next += this._input.readUntil(this.__template_pattern);
}
result += next;
next = this._read_template();
}
if (this._until_after) {
result += this._input.readUntilAfter(this._until_pattern);
}
return result;
};
TemplatablePattern.prototype.__set_templated_pattern = function() {
var items = [];
if (!this._disabled.php) {
items.push(this.__patterns.php._starting_pattern.source);
}
if (!this._disabled.handlebars) {
items.push(this.__patterns.handlebars._starting_pattern.source);
}
if (!this._disabled.erb) {
items.push(this.__patterns.erb._starting_pattern.source);
}
if (!this._disabled.django) {
items.push(this.__patterns.django._starting_pattern.source);
// The starting pattern for django is more complex because it has different
// patterns for value, comment, and other sections
items.push(this.__patterns.django_value._starting_pattern.source);
items.push(this.__patterns.django_comment._starting_pattern.source);
}
if (!this._disabled.smarty) {
items.push(this.__patterns.smarty._starting_pattern.source);
}
if (this._until_pattern) {
items.push(this._until_pattern.source);
}
this.__template_pattern = this._input.get_regexp('(?:' + items.join('|') + ')');
};
TemplatablePattern.prototype._read_template = function() {
var resulting_string = '';
var c = this._input.peek();
if (c === '<') {
var peek1 = this._input.peek(1);
//if we're in a comment, do something special
// We treat all comments as literals, even more than preformatted tags
// we just look for the appropriate close tag
if (!this._disabled.php && !this._excluded.php && peek1 === '?') {
resulting_string = resulting_string ||
this.__patterns.php.read();
}
if (!this._disabled.erb && !this._excluded.erb && peek1 === '%') {
resulting_string = resulting_string ||
this.__patterns.erb.read();
}
} else if (c === '{') {
if (!this._disabled.handlebars && !this._excluded.handlebars) {
resulting_string = resulting_string ||
this.__patterns.handlebars_comment.read();
resulting_string = resulting_string ||
this.__patterns.handlebars_unescaped.read();
resulting_string = resulting_string ||
this.__patterns.handlebars.read();
}
if (!this._disabled.django) {
// django coflicts with handlebars a bit.
if (!this._excluded.django && !this._excluded.handlebars) {
resulting_string = resulting_string ||
this.__patterns.django_value.read();
}
if (!this._excluded.django) {
resulting_string = resulting_string ||
this.__patterns.django_comment.read();
resulting_string = resulting_string ||
this.__patterns.django.read();
}
}
if (!this._disabled.smarty) {
// smarty cannot be enabled with django or handlebars enabled
if (this._disabled.django && this._disabled.handlebars) {
resulting_string = resulting_string ||
this.__patterns.smarty_comment.read();
resulting_string = resulting_string ||
this.__patterns.smarty_literal.read();
resulting_string = resulting_string ||
this.__patterns.smarty.read();
}
}
}
return resulting_string;
};
module.exports.TemplatablePattern = TemplatablePattern;
},{"./pattern":108}],110:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
function Token(type, text, newlines, whitespace_before) {
this.type = type;
this.text = text;
// comments_before are
// comments that have a new line before them
// and may or may not have a newline after
// this is a set of comments before
this.comments_before = null; /* inline comment*/
// this.comments_after = new TokenStream(); // no new line before and newline after
this.newlines = newlines || 0;
this.whitespace_before = whitespace_before || '';
this.parent = null;
this.next = null;
this.previous = null;
this.opened = null;
this.closed = null;
this.directives = null;
}
module.exports.Token = Token;
},{}],111:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
var InputScanner = require('../core/inputscanner').InputScanner;
var Token = require('../core/token').Token;
var TokenStream = require('../core/tokenstream').TokenStream;
var WhitespacePattern = require('./whitespacepattern').WhitespacePattern;
var TOKEN = {
START: 'TK_START',
RAW: 'TK_RAW',
EOF: 'TK_EOF'
};
var Tokenizer = function(input_string, options) {
this._input = new InputScanner(input_string);
this._options = options || {};
this.__tokens = null;
this._patterns = {};
this._patterns.whitespace = new WhitespacePattern(this._input);
};
Tokenizer.prototype.tokenize = function() {
this._input.restart();
this.__tokens = new TokenStream();
this._reset();
var current;
var previous = new Token(TOKEN.START, '');
var open_token = null;
var open_stack = [];
var comments = new TokenStream();
while (previous.type !== TOKEN.EOF) {
current = this._get_next_token(previous, open_token);
while (this._is_comment(current)) {
comments.add(current);
current = this._get_next_token(previous, open_token);
}
if (!comments.isEmpty()) {
current.comments_before = comments;
comments = new TokenStream();
}
current.parent = open_token;
if (this._is_opening(current)) {
open_stack.push(open_token);
open_token = current;
} else if (open_token && this._is_closing(current, open_token)) {
current.opened = open_token;
open_token.closed = current;
open_token = open_stack.pop();
current.parent = open_token;
}
current.previous = previous;
previous.next = current;
this.__tokens.add(current);
previous = current;
}
return this.__tokens;
};
Tokenizer.prototype._is_first_token = function() {
return this.__tokens.isEmpty();
};
Tokenizer.prototype._reset = function() {};
Tokenizer.prototype._get_next_token = function(previous_token, open_token) { // jshint unused:false
this._readWhitespace();
var resulting_string = this._input.read(/.+/g);
if (resulting_string) {
return this._create_token(TOKEN.RAW, resulting_string);
} else {
return this._create_token(TOKEN.EOF, '');
}
};
Tokenizer.prototype._is_comment = function(current_token) { // jshint unused:false
return false;
};
Tokenizer.prototype._is_opening = function(current_token) { // jshint unused:false
return false;
};
Tokenizer.prototype._is_closing = function(current_token, open_token) { // jshint unused:false
return false;
};
Tokenizer.prototype._create_token = function(type, text) {
var token = new Token(type, text,
this._patterns.whitespace.newline_count,
this._patterns.whitespace.whitespace_before_token);
return token;
};
Tokenizer.prototype._readWhitespace = function() {
return this._patterns.whitespace.read();
};
module.exports.Tokenizer = Tokenizer;
module.exports.TOKEN = TOKEN;
},{"../core/inputscanner":105,"../core/token":110,"../core/tokenstream":112,"./whitespacepattern":113}],112:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
function TokenStream(parent_token) {
// private
this.__tokens = [];
this.__tokens_length = this.__tokens.length;
this.__position = 0;
this.__parent_token = parent_token;
}
TokenStream.prototype.restart = function() {
this.__position = 0;
};
TokenStream.prototype.isEmpty = function() {
return this.__tokens_length === 0;
};
TokenStream.prototype.hasNext = function() {
return this.__position < this.__tokens_length;
};
TokenStream.prototype.next = function() {
var val = null;
if (this.hasNext()) {
val = this.__tokens[this.__position];
this.__position += 1;
}
return val;
};
TokenStream.prototype.peek = function(index) {
var val = null;
index = index || 0;
index += this.__position;
if (index >= 0 && index < this.__tokens_length) {
val = this.__tokens[index];
}
return val;
};
TokenStream.prototype.add = function(token) {
if (this.__parent_token) {
token.parent = this.__parent_token;
}
this.__tokens.push(token);
this.__tokens_length += 1;
};
module.exports.TokenStream = TokenStream;
},{}],113:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
var Pattern = require('../core/pattern').Pattern;
function WhitespacePattern(input_scanner, parent) {
Pattern.call(this, input_scanner, parent);
if (parent) {
this._line_regexp = this._input.get_regexp(parent._line_regexp);
} else {
this.__set_whitespace_patterns('', '');
}
this.newline_count = 0;
this.whitespace_before_token = '';
}
WhitespacePattern.prototype = new Pattern();
WhitespacePattern.prototype.__set_whitespace_patterns = function(whitespace_chars, newline_chars) {
whitespace_chars += '\\t ';
newline_chars += '\\n\\r';
this._match_pattern = this._input.get_regexp(
'[' + whitespace_chars + newline_chars + ']+', true);
this._newline_regexp = this._input.get_regexp(
'\\r\\n|[' + newline_chars + ']');
};
WhitespacePattern.prototype.read = function() {
this.newline_count = 0;
this.whitespace_before_token = '';
var resulting_string = this._input.read(this._match_pattern);
if (resulting_string === ' ') {
this.whitespace_before_token = ' ';
} else if (resulting_string) {
var matches = this.__split(this._newline_regexp, resulting_string);
this.newline_count = matches.length - 1;
this.whitespace_before_token = matches[this.newline_count];
}
return resulting_string;
};
WhitespacePattern.prototype.matching = function(whitespace_chars, newline_chars) {
var result = this._create();
result.__set_whitespace_patterns(whitespace_chars, newline_chars);
result._update();
return result;
};
WhitespacePattern.prototype._create = function() {
return new WhitespacePattern(this._input, this);
};
WhitespacePattern.prototype.__split = function(regexp, input_string) {
regexp.lastIndex = 0;
var start_index = 0;
var result = [];
var next_match = regexp.exec(input_string);
while (next_match) {
result.push(input_string.substring(start_index, next_match.index));
start_index = next_match.index + next_match[0].length;
next_match = regexp.exec(input_string);
}
if (start_index < input_string.length) {
result.push(input_string.substring(start_index, input_string.length));
} else {
result.push('');
}
return result;
};
module.exports.WhitespacePattern = WhitespacePattern;
},{"../core/pattern":108}],114:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
var Options = require('./options').Options;
var Output = require('../core/output').Output;
var InputScanner = require('../core/inputscanner').InputScanner;
var Directives = require('../core/directives').Directives;
var directives_core = new Directives(/\/\*/, /\*\//);
var lineBreak = /\r\n|[\r\n]/;
var allLineBreaks = /\r\n|[\r\n]/g;
// tokenizer
var whitespaceChar = /\s/;
var whitespacePattern = /(?:\s|\n)+/g;
var block_comment_pattern = /\/\*(?:[\s\S]*?)((?:\*\/)|$)/g;
var comment_pattern = /\/\/(?:[^\n\r\u2028\u2029]*)/g;
function Beautifier(source_text, options) {
this._source_text = source_text || '';
// Allow the setting of language/file-type specific options
// with inheritance of overall settings
this._options = new Options(options);
this._ch = null;
this._input = null;
// https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule
this.NESTED_AT_RULE = {
"page": true,
"font-face": true,
"keyframes": true,
// also in CONDITIONAL_GROUP_RULE below
"media": true,
"supports": true,
"document": true
};
this.CONDITIONAL_GROUP_RULE = {
"media": true,
"supports": true,
"document": true
};
this.NON_SEMICOLON_NEWLINE_PROPERTY = [
"grid-template-areas",
"grid-template"
];
}
Beautifier.prototype.eatString = function(endChars) {
var result = '';
this._ch = this._input.next();
while (this._ch) {
result += this._ch;
if (this._ch === "\\") {
result += this._input.next();
} else if (endChars.indexOf(this._ch) !== -1 || this._ch === "\n") {
break;
}
this._ch = this._input.next();
}
return result;
};
// Skips any white space in the source text from the current position.
// When allowAtLeastOneNewLine is true, will output new lines for each
// newline character found; if the user has preserve_newlines off, only
// the first newline will be output
Beautifier.prototype.eatWhitespace = function(allowAtLeastOneNewLine) {
var result = whitespaceChar.test(this._input.peek());
var newline_count = 0;
while (whitespaceChar.test(this._input.peek())) {
this._ch = this._input.next();
if (allowAtLeastOneNewLine && this._ch === '\n') {
if (newline_count === 0 || newline_count < this._options.max_preserve_newlines) {
newline_count++;
this._output.add_new_line(true);
}
}
}
return result;
};
// Nested pseudo-class if we are insideRule
// and the next special character found opens
// a new block
Beautifier.prototype.foundNestedPseudoClass = function() {
var openParen = 0;
var i = 1;
var ch = this._input.peek(i);
while (ch) {
if (ch === "{") {
return true;
} else if (ch === '(') {
// pseudoclasses can contain ()
openParen += 1;
} else if (ch === ')') {
if (openParen === 0) {
return false;
}
openParen -= 1;
} else if (ch === ";" || ch === "}") {
return false;
}
i++;
ch = this._input.peek(i);
}
return false;
};
Beautifier.prototype.print_string = function(output_string) {
this._output.set_indent(this._indentLevel);
this._output.non_breaking_space = true;
this._output.add_token(output_string);
};
Beautifier.prototype.preserveSingleSpace = function(isAfterSpace) {
if (isAfterSpace) {
this._output.space_before_token = true;
}
};
Beautifier.prototype.indent = function() {
this._indentLevel++;
};
Beautifier.prototype.outdent = function() {
if (this._indentLevel > 0) {
this._indentLevel--;
}
};
/*_____________________--------------------_____________________*/
Beautifier.prototype.beautify = function() {
if (this._options.disabled) {
return this._source_text;
}
var source_text = this._source_text;
var eol = this._options.eol;
if (eol === 'auto') {
eol = '\n';
if (source_text && lineBreak.test(source_text || '')) {
eol = source_text.match(lineBreak)[0];
}
}
// HACK: newline parsing inconsistent. This brute force normalizes the this._input.
source_text = source_text.replace(allLineBreaks, '\n');
// reset
var baseIndentString = source_text.match(/^[\t ]*/)[0];
this._output = new Output(this._options, baseIndentString);
this._input = new InputScanner(source_text);
this._indentLevel = 0;
this._nestedLevel = 0;
this._ch = null;
var parenLevel = 0;
var insideRule = false;
// This is the value side of a property value pair (blue in the following ex)
// label { content: blue }
var insidePropertyValue = false;
var enteringConditionalGroup = false;
var insideNonNestedAtRule = false;
var insideScssMap = false;
var topCharacter = this._ch;
var insideNonSemiColonValues = false;
var whitespace;
var isAfterSpace;
var previous_ch;
while (true) {
whitespace = this._input.read(whitespacePattern);
isAfterSpace = whitespace !== '';
previous_ch = topCharacter;
this._ch = this._input.next();
if (this._ch === '\\' && this._input.hasNext()) {
this._ch += this._input.next();
}
topCharacter = this._ch;
if (!this._ch) {
break;
} else if (this._ch === '/' && this._input.peek() === '*') {
// /* css comment */
// Always start block comments on a new line.
// This handles scenarios where a block comment immediately
// follows a property definition on the same line or where
// minified code is being beautified.
this._output.add_new_line();
this._input.back();
var comment = this._input.read(block_comment_pattern);
// Handle ignore directive
var directives = directives_core.get_directives(comment);
if (directives && directives.ignore === 'start') {
comment += directives_core.readIgnored(this._input);
}
this.print_string(comment);
// Ensures any new lines following the comment are preserved
this.eatWhitespace(true);
// Block comments are followed by a new line so they don't
// share a line with other properties
this._output.add_new_line();
} else if (this._ch === '/' && this._input.peek() === '/') {
// // single line comment
// Preserves the space before a comment
// on the same line as a rule
this._output.space_before_token = true;
this._input.back();
this.print_string(this._input.read(comment_pattern));
// Ensures any new lines following the comment are preserved
this.eatWhitespace(true);
} else if (this._ch === '$') {
this.preserveSingleSpace(isAfterSpace);
this.print_string(this._ch);
// strip trailing space, if present, for hash property checks
var variable = this._input.peekUntilAfter(/[: ,;{}()[\]\/='"]/g);
if (variable.match(/[ :]$/)) {
// we have a variable or pseudo-class, add it and insert one space before continuing
variable = this.eatString(": ").replace(/\s$/, '');
this.print_string(variable);
this._output.space_before_token = true;
}
variable = variable.replace(/\s$/, '');
// might be sass variable
if (parenLevel === 0 && variable.indexOf(':') !== -1) {
insidePropertyValue = true;
this.indent();
}
} else if (this._ch === '@') {
this.preserveSingleSpace(isAfterSpace);
// deal with less property mixins @{...}
if (this._input.peek() === '{') {
this.print_string(this._ch + this.eatString('}'));
} else {
this.print_string(this._ch);
// strip trailing space, if present, for hash property checks
var variableOrRule = this._input.peekUntilAfter(/[: ,;{}()[\]\/='"]/g);
if (variableOrRule.match(/[ :]$/)) {
// we have a variable or pseudo-class, add it and insert one space before continuing
variableOrRule = this.eatString(": ").replace(/\s$/, '');
this.print_string(variableOrRule);
this._output.space_before_token = true;
}
variableOrRule = variableOrRule.replace(/\s$/, '');
// might be less variable
if (parenLevel === 0 && variableOrRule.indexOf(':') !== -1) {
insidePropertyValue = true;
this.indent();
// might be a nesting at-rule
} else if (variableOrRule in this.NESTED_AT_RULE) {
this._nestedLevel += 1;
if (variableOrRule in this.CONDITIONAL_GROUP_RULE) {
enteringConditionalGroup = true;
}
// might be a non-nested at-rule
} else if (parenLevel === 0 && !insidePropertyValue) {
insideNonNestedAtRule = true;
}
}
} else if (this._ch === '#' && this._input.peek() === '{') {
this.preserveSingleSpace(isAfterSpace);
this.print_string(this._ch + this.eatString('}'));
} else if (this._ch === '{') {
if (insidePropertyValue) {
insidePropertyValue = false;
this.outdent();
}
// non nested at rule becomes nested
insideNonNestedAtRule = false;
// when entering conditional groups, only rulesets are allowed
if (enteringConditionalGroup) {
enteringConditionalGroup = false;
insideRule = (this._indentLevel >= this._nestedLevel);
} else {
// otherwise, declarations are also allowed
insideRule = (this._indentLevel >= this._nestedLevel - 1);
}
if (this._options.newline_between_rules && insideRule) {
if (this._output.previous_line && this._output.previous_line.item(-1) !== '{') {
this._output.ensure_empty_line_above('/', ',');
}
}
this._output.space_before_token = true;
// The difference in print_string and indent order is necessary to indent the '{' correctly
if (this._options.brace_style === 'expand') {
this._output.add_new_line();
this.print_string(this._ch);
this.indent();
this._output.set_indent(this._indentLevel);
} else {
// inside mixin and first param is object
if (previous_ch === '(') {
this._output.space_before_token = false;
} else if (previous_ch !== ',') {
this.indent();
}
this.print_string(this._ch);
}
this.eatWhitespace(true);
this._output.add_new_line();
} else if (this._ch === '}') {
this.outdent();
this._output.add_new_line();
if (previous_ch === '{') {
this._output.trim(true);
}
if (insidePropertyValue) {
this.outdent();
insidePropertyValue = false;
}
this.print_string(this._ch);
insideRule = false;
if (this._nestedLevel) {
this._nestedLevel--;
}
this.eatWhitespace(true);
this._output.add_new_line();
if (this._options.newline_between_rules && !this._output.just_added_blankline()) {
if (this._input.peek() !== '}') {
this._output.add_new_line(true);
}
}
if (this._input.peek() === ')') {
this._output.trim(true);
if (this._options.brace_style === "expand") {
this._output.add_new_line(true);
}
}
} else if (this._ch === ":") {
for (var i = 0; i < this.NON_SEMICOLON_NEWLINE_PROPERTY.length; i++) {
if (this._input.lookBack(this.NON_SEMICOLON_NEWLINE_PROPERTY[i])) {
insideNonSemiColonValues = true;
break;
}
}
if ((insideRule || enteringConditionalGroup) && !(this._input.lookBack("&") || this.foundNestedPseudoClass()) && !this._input.lookBack("(") && !insideNonNestedAtRule && parenLevel === 0) {
// 'property: value' delimiter
// which could be in a conditional group query
this.print_string(':');
if (!insidePropertyValue) {
insidePropertyValue = true;
this._output.space_before_token = true;
this.eatWhitespace(true);
this.indent();
}
} else {
// sass/less parent reference don't use a space
// sass nested pseudo-class don't use a space
// preserve space before pseudoclasses/pseudoelements, as it means "in any child"
if (this._input.lookBack(" ")) {
this._output.space_before_token = true;
}
if (this._input.peek() === ":") {
// pseudo-element
this._ch = this._input.next();
this.print_string("::");
} else {
// pseudo-class
this.print_string(':');
}
}
} else if (this._ch === '"' || this._ch === '\'') {
var preserveQuoteSpace = previous_ch === '"' || previous_ch === '\'';
this.preserveSingleSpace(preserveQuoteSpace || isAfterSpace);
this.print_string(this._ch + this.eatString(this._ch));
this.eatWhitespace(true);
} else if (this._ch === ';') {
insideNonSemiColonValues = false;
if (parenLevel === 0) {
if (insidePropertyValue) {
this.outdent();
insidePropertyValue = false;
}
insideNonNestedAtRule = false;
this.print_string(this._ch);
this.eatWhitespace(true);
// This maintains single line comments on the same
// line. Block comments are also affected, but
// a new line is always output before one inside
// that section
if (this._input.peek() !== '/') {
this._output.add_new_line();
}
} else {
this.print_string(this._ch);
this.eatWhitespace(true);
this._output.space_before_token = true;
}
} else if (this._ch === '(') { // may be a url
if (this._input.lookBack("url")) {
this.print_string(this._ch);
this.eatWhitespace();
parenLevel++;
this.indent();
this._ch = this._input.next();
if (this._ch === ')' || this._ch === '"' || this._ch === '\'') {
this._input.back();
} else if (this._ch) {
this.print_string(this._ch + this.eatString(')'));
if (parenLevel) {
parenLevel--;
this.outdent();
}
}
} else {
var space_needed = false;
if (this._input.lookBack("with")) {
// look back is not an accurate solution, we need tokens to confirm without whitespaces
space_needed = true;
}
this.preserveSingleSpace(isAfterSpace || space_needed);
this.print_string(this._ch);
// handle scss/sass map
if (insidePropertyValue && previous_ch === "$" && this._options.selector_separator_newline) {
this._output.add_new_line();
insideScssMap = true;
} else {
this.eatWhitespace();
parenLevel++;
this.indent();
}
}
} else if (this._ch === ')') {
if (parenLevel) {
parenLevel--;
this.outdent();
}
if (insideScssMap && this._input.peek() === ";" && this._options.selector_separator_newline) {
insideScssMap = false;
this.outdent();
this._output.add_new_line();
}
this.print_string(this._ch);
} else if (this._ch === ',') {
this.print_string(this._ch);
this.eatWhitespace(true);
if (this._options.selector_separator_newline && (!insidePropertyValue || insideScssMap) && parenLevel === 0 && !insideNonNestedAtRule) {
this._output.add_new_line();
} else {
this._output.space_before_token = true;
}
} else if ((this._ch === '>' || this._ch === '+' || this._ch === '~') && !insidePropertyValue && parenLevel === 0) {
//handle combinator spacing
if (this._options.space_around_combinator) {
this._output.space_before_token = true;
this.print_string(this._ch);
this._output.space_before_token = true;
} else {
this.print_string(this._ch);
this.eatWhitespace();
// squash extra whitespace
if (this._ch && whitespaceChar.test(this._ch)) {
this._ch = '';
}
}
} else if (this._ch === ']') {
this.print_string(this._ch);
} else if (this._ch === '[') {
this.preserveSingleSpace(isAfterSpace);
this.print_string(this._ch);
} else if (this._ch === '=') { // no whitespace before or after
this.eatWhitespace();
this.print_string('=');
if (whitespaceChar.test(this._ch)) {
this._ch = '';
}
} else if (this._ch === '!' && !this._input.lookBack("\\")) { // !important
this._output.space_before_token = true;
this.print_string(this._ch);
} else {
var preserveAfterSpace = previous_ch === '"' || previous_ch === '\'';
this.preserveSingleSpace(preserveAfterSpace || isAfterSpace);
this.print_string(this._ch);
if (!this._output.just_added_newline() && this._input.peek() === '\n' && insideNonSemiColonValues) {
this._output.add_new_line();
}
}
}
var sweetCode = this._output.get_code(eol);
return sweetCode;
};
module.exports.Beautifier = Beautifier;
},{"../core/directives":104,"../core/inputscanner":105,"../core/output":107,"./options":116}],115:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
var Beautifier = require('./beautifier').Beautifier,
Options = require('./options').Options;
function css_beautify(source_text, options) {
var beautifier = new Beautifier(source_text, options);
return beautifier.beautify();
}
module.exports = css_beautify;
module.exports.defaultOptions = function() {
return new Options();
};
},{"./beautifier":114,"./options":116}],116:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
var BaseOptions = require('../core/options').Options;
function Options(options) {
BaseOptions.call(this, options, 'css');
this.selector_separator_newline = this._get_boolean('selector_separator_newline', true);
this.newline_between_rules = this._get_boolean('newline_between_rules', true);
var space_around_selector_separator = this._get_boolean('space_around_selector_separator');
this.space_around_combinator = this._get_boolean('space_around_combinator') || space_around_selector_separator;
var brace_style_split = this._get_selection_list('brace_style', ['collapse', 'expand', 'end-expand', 'none', 'preserve-inline']);
this.brace_style = 'collapse';
for (var bs = 0; bs < brace_style_split.length; bs++) {
if (brace_style_split[bs] !== 'expand') {
// default to collapse, as only collapse|expand is implemented for now
this.brace_style = 'collapse';
} else {
this.brace_style = brace_style_split[bs];
}
}
}
Options.prototype = new BaseOptions();
module.exports.Options = Options;
},{"../core/options":106}],117:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
var Options = require('../html/options').Options;
var Output = require('../core/output').Output;
var Tokenizer = require('../html/tokenizer').Tokenizer;
var TOKEN = require('../html/tokenizer').TOKEN;
var lineBreak = /\r\n|[\r\n]/;
var allLineBreaks = /\r\n|[\r\n]/g;
var Printer = function(options, base_indent_string) { //handles input/output and some other printing functions
this.indent_level = 0;
this.alignment_size = 0;
this.max_preserve_newlines = options.max_preserve_newlines;
this.preserve_newlines = options.preserve_newlines;
this._output = new Output(options, base_indent_string);
};
Printer.prototype.current_line_has_match = function(pattern) {
return this._output.current_line.has_match(pattern);
};
Printer.prototype.set_space_before_token = function(value, non_breaking) {
this._output.space_before_token = value;
this._output.non_breaking_space = non_breaking;
};
Printer.prototype.set_wrap_point = function() {
this._output.set_indent(this.indent_level, this.alignment_size);
this._output.set_wrap_point();
};
Printer.prototype.add_raw_token = function(token) {
this._output.add_raw_token(token);
};
Printer.prototype.print_preserved_newlines = function(raw_token) {
var newlines = 0;
if (raw_token.type !== TOKEN.TEXT && raw_token.previous.type !== TOKEN.TEXT) {
newlines = raw_token.newlines ? 1 : 0;
}
if (this.preserve_newlines) {
newlines = raw_token.newlines < this.max_preserve_newlines + 1 ? raw_token.newlines : this.max_preserve_newlines + 1;
}
for (var n = 0; n < newlines; n++) {
this.print_newline(n > 0);
}
return newlines !== 0;
};
Printer.prototype.traverse_whitespace = function(raw_token) {
if (raw_token.whitespace_before || raw_token.newlines) {
if (!this.print_preserved_newlines(raw_token)) {
this._output.space_before_token = true;
}
return true;
}
return false;
};
Printer.prototype.previous_token_wrapped = function() {
return this._output.previous_token_wrapped;
};
Printer.prototype.print_newline = function(force) {
this._output.add_new_line(force);
};
Printer.prototype.print_token = function(token) {
if (token.text) {
this._output.set_indent(this.indent_level, this.alignment_size);
this._output.add_token(token.text);
}
};
Printer.prototype.indent = function() {
this.indent_level++;
};
Printer.prototype.get_full_indent = function(level) {
level = this.indent_level + (level || 0);
if (level < 1) {
return '';
}
return this._output.get_indent_string(level);
};
var get_type_attribute = function(start_token) {
var result = null;
var raw_token = start_token.next;
// Search attributes for a type attribute
while (raw_token.type !== TOKEN.EOF && start_token.closed !== raw_token) {
if (raw_token.type === TOKEN.ATTRIBUTE && raw_token.text === 'type') {
if (raw_token.next && raw_token.next.type === TOKEN.EQUALS &&
raw_token.next.next && raw_token.next.next.type === TOKEN.VALUE) {
result = raw_token.next.next.text;
}
break;
}
raw_token = raw_token.next;
}
return result;
};
var get_custom_beautifier_name = function(tag_check, raw_token) {
var typeAttribute = null;
var result = null;
if (!raw_token.closed) {
return null;
}
if (tag_check === 'script') {
typeAttribute = 'text/javascript';
} else if (tag_check === 'style') {
typeAttribute = 'text/css';
}
typeAttribute = get_type_attribute(raw_token) || typeAttribute;
// For script and style tags that have a type attribute, only enable custom beautifiers for matching values
// For those without a type attribute use default;
if (typeAttribute.search('text/css') > -1) {
result = 'css';
} else if (typeAttribute.search(/module|((text|application|dojo)\/(x-)?(javascript|ecmascript|jscript|livescript|(ld\+)?json|method|aspect))/) > -1) {
result = 'javascript';
} else if (typeAttribute.search(/(text|application|dojo)\/(x-)?(html)/) > -1) {
result = 'html';
} else if (typeAttribute.search(/test\/null/) > -1) {
// Test only mime-type for testing the beautifier when null is passed as beautifing function
result = 'null';
}
return result;
};
function in_array(what, arr) {
return arr.indexOf(what) !== -1;
}
function TagFrame(parent, parser_token, indent_level) {
this.parent = parent || null;
this.tag = parser_token ? parser_token.tag_name : '';
this.indent_level = indent_level || 0;
this.parser_token = parser_token || null;
}
function TagStack(printer) {
this._printer = printer;
this._current_frame = null;
}
TagStack.prototype.get_parser_token = function() {
return this._current_frame ? this._current_frame.parser_token : null;
};
TagStack.prototype.record_tag = function(parser_token) { //function to record a tag and its parent in this.tags Object
var new_frame = new TagFrame(this._current_frame, parser_token, this._printer.indent_level);
this._current_frame = new_frame;
};
TagStack.prototype._try_pop_frame = function(frame) { //function to retrieve the opening tag to the corresponding closer
var parser_token = null;
if (frame) {
parser_token = frame.parser_token;
this._printer.indent_level = frame.indent_level;
this._current_frame = frame.parent;
}
return parser_token;
};
TagStack.prototype._get_frame = function(tag_list, stop_list) { //function to retrieve the opening tag to the corresponding closer
var frame = this._current_frame;
while (frame) { //till we reach '' (the initial value);
if (tag_list.indexOf(frame.tag) !== -1) { //if this is it use it
break;
} else if (stop_list && stop_list.indexOf(frame.tag) !== -1) {
frame = null;
break;
}
frame = frame.parent;
}
return frame;
};
TagStack.prototype.try_pop = function(tag, stop_list) { //function to retrieve the opening tag to the corresponding closer
var frame = this._get_frame([tag], stop_list);
return this._try_pop_frame(frame);
};
TagStack.prototype.indent_to_tag = function(tag_list) {
var frame = this._get_frame(tag_list);
if (frame) {
this._printer.indent_level = frame.indent_level;
}
};
function Beautifier(source_text, options, js_beautify, css_beautify) {
//Wrapper function to invoke all the necessary constructors and deal with the output.
this._source_text = source_text || '';
options = options || {};
this._js_beautify = js_beautify;
this._css_beautify = css_beautify;
this._tag_stack = null;
// Allow the setting of language/file-type specific options
// with inheritance of overall settings
var optionHtml = new Options(options, 'html');
this._options = optionHtml;
this._is_wrap_attributes_force = this._options.wrap_attributes.substr(0, 'force'.length) === 'force';
this._is_wrap_attributes_force_expand_multiline = (this._options.wrap_attributes === 'force-expand-multiline');
this._is_wrap_attributes_force_aligned = (this._options.wrap_attributes === 'force-aligned');
this._is_wrap_attributes_aligned_multiple = (this._options.wrap_attributes === 'aligned-multiple');
this._is_wrap_attributes_preserve = this._options.wrap_attributes.substr(0, 'preserve'.length) === 'preserve';
this._is_wrap_attributes_preserve_aligned = (this._options.wrap_attributes === 'preserve-aligned');
}
Beautifier.prototype.beautify = function() {
// if disabled, return the input unchanged.
if (this._options.disabled) {
return this._source_text;
}
var source_text = this._source_text;
var eol = this._options.eol;
if (this._options.eol === 'auto') {
eol = '\n';
if (source_text && lineBreak.test(source_text)) {
eol = source_text.match(lineBreak)[0];
}
}
// HACK: newline parsing inconsistent. This brute force normalizes the input.
source_text = source_text.replace(allLineBreaks, '\n');
var baseIndentString = source_text.match(/^[\t ]*/)[0];
var last_token = {
text: '',
type: ''
};
var last_tag_token = new TagOpenParserToken();
var printer = new Printer(this._options, baseIndentString);
var tokens = new Tokenizer(source_text, this._options).tokenize();
this._tag_stack = new TagStack(printer);
var parser_token = null;
var raw_token = tokens.next();
while (raw_token.type !== TOKEN.EOF) {
if (raw_token.type === TOKEN.TAG_OPEN || raw_token.type === TOKEN.COMMENT) {
parser_token = this._handle_tag_open(printer, raw_token, last_tag_token, last_token, tokens);
last_tag_token = parser_token;
} else if ((raw_token.type === TOKEN.ATTRIBUTE || raw_token.type === TOKEN.EQUALS || raw_token.type === TOKEN.VALUE) ||
(raw_token.type === TOKEN.TEXT && !last_tag_token.tag_complete)) {
parser_token = this._handle_inside_tag(printer, raw_token, last_tag_token, last_token);
} else if (raw_token.type === TOKEN.TAG_CLOSE) {
parser_token = this._handle_tag_close(printer, raw_token, last_tag_token);
} else if (raw_token.type === TOKEN.TEXT) {
parser_token = this._handle_text(printer, raw_token, last_tag_token);
} else {
// This should never happen, but if it does. Print the raw token
printer.add_raw_token(raw_token);
}
last_token = parser_token;
raw_token = tokens.next();
}
var sweet_code = printer._output.get_code(eol);
return sweet_code;
};
Beautifier.prototype._handle_tag_close = function(printer, raw_token, last_tag_token) {
var parser_token = {
text: raw_token.text,
type: raw_token.type
};
printer.alignment_size = 0;
last_tag_token.tag_complete = true;
printer.set_space_before_token(raw_token.newlines || raw_token.whitespace_before !== '', true);
if (last_tag_token.is_unformatted) {
printer.add_raw_token(raw_token);
} else {
if (last_tag_token.tag_start_char === '<') {
printer.set_space_before_token(raw_token.text[0] === '/', true); // space before />, no space before >
if (this._is_wrap_attributes_force_expand_multiline && last_tag_token.has_wrapped_attrs) {
printer.print_newline(false);
}
}
printer.print_token(raw_token);
}
if (last_tag_token.indent_content &&
!(last_tag_token.is_unformatted || last_tag_token.is_content_unformatted)) {
printer.indent();
// only indent once per opened tag
last_tag_token.indent_content = false;
}
if (!last_tag_token.is_inline_element &&
!(last_tag_token.is_unformatted || last_tag_token.is_content_unformatted)) {
printer.set_wrap_point();
}
return parser_token;
};
Beautifier.prototype._handle_inside_tag = function(printer, raw_token, last_tag_token, last_token) {
var wrapped = last_tag_token.has_wrapped_attrs;
var parser_token = {
text: raw_token.text,
type: raw_token.type
};
printer.set_space_before_token(raw_token.newlines || raw_token.whitespace_before !== '', true);
if (last_tag_token.is_unformatted) {
printer.add_raw_token(raw_token);
} else if (last_tag_token.tag_start_char === '{' && raw_token.type === TOKEN.TEXT) {
// For the insides of handlebars allow newlines or a single space between open and contents
if (printer.print_preserved_newlines(raw_token)) {
raw_token.newlines = 0;
printer.add_raw_token(raw_token);
} else {
printer.print_token(raw_token);
}
} else {
if (raw_token.type === TOKEN.ATTRIBUTE) {
printer.set_space_before_token(true);
} else if (raw_token.type === TOKEN.EQUALS) { //no space before =
printer.set_space_before_token(false);
} else if (raw_token.type === TOKEN.VALUE && raw_token.previous.type === TOKEN.EQUALS) { //no space before value
printer.set_space_before_token(false);
}
if (raw_token.type === TOKEN.ATTRIBUTE && last_tag_token.tag_start_char === '<') {
if (this._is_wrap_attributes_preserve || this._is_wrap_attributes_preserve_aligned) {
printer.traverse_whitespace(raw_token);
wrapped = wrapped || raw_token.newlines !== 0;
}
// Wrap for 'force' options, and if the number of attributes is at least that specified in 'wrap_attributes_min_attrs':
// 1. always wrap the second and beyond attributes
// 2. wrap the first attribute only if 'force-expand-multiline' is specified
if (this._is_wrap_attributes_force &&
last_tag_token.attr_count >= this._options.wrap_attributes_min_attrs &&
(last_token.type !== TOKEN.TAG_OPEN || // ie. second attribute and beyond
this._is_wrap_attributes_force_expand_multiline)) {
printer.print_newline(false);
wrapped = true;
}
}
printer.print_token(raw_token);
wrapped = wrapped || printer.previous_token_wrapped();
last_tag_token.has_wrapped_attrs = wrapped;
}
return parser_token;
};
Beautifier.prototype._handle_text = function(printer, raw_token, last_tag_token) {
var parser_token = {
text: raw_token.text,
type: 'TK_CONTENT'
};
if (last_tag_token.custom_beautifier_name) { //check if we need to format javascript
this._print_custom_beatifier_text(printer, raw_token, last_tag_token);
} else if (last_tag_token.is_unformatted || last_tag_token.is_content_unformatted) {
printer.add_raw_token(raw_token);
} else {
printer.traverse_whitespace(raw_token);
printer.print_token(raw_token);
}
return parser_token;
};
Beautifier.prototype._print_custom_beatifier_text = function(printer, raw_token, last_tag_token) {
var local = this;
if (raw_token.text !== '') {
var text = raw_token.text,
_beautifier,
script_indent_level = 1,
pre = '',
post = '';
if (last_tag_token.custom_beautifier_name === 'javascript' && typeof this._js_beautify === 'function') {
_beautifier = this._js_beautify;
} else if (last_tag_token.custom_beautifier_name === 'css' && typeof this._css_beautify === 'function') {
_beautifier = this._css_beautify;
} else if (last_tag_token.custom_beautifier_name === 'html') {
_beautifier = function(html_source, options) {
var beautifier = new Beautifier(html_source, options, local._js_beautify, local._css_beautify);
return beautifier.beautify();
};
}
if (this._options.indent_scripts === "keep") {
script_indent_level = 0;
} else if (this._options.indent_scripts === "separate") {
script_indent_level = -printer.indent_level;
}
var indentation = printer.get_full_indent(script_indent_level);
// if there is at least one empty line at the end of this text, strip it
// we'll be adding one back after the text but before the containing tag.
text = text.replace(/\n[ \t]*$/, '');
// Handle the case where content is wrapped in a comment or cdata.
if (last_tag_token.custom_beautifier_name !== 'html' &&
text[0] === '<' && text.match(/^(<!--|<!\[CDATA\[)/)) {
var matched = /^(<!--[^\n]*|<!\[CDATA\[)(\n?)([ \t\n]*)([\s\S]*)(-->|]]>)$/.exec(text);
// if we start to wrap but don't finish, print raw
if (!matched) {
printer.add_raw_token(raw_token);
return;
}
pre = indentation + matched[1] + '\n';
text = matched[4];
if (matched[5]) {
post = indentation + matched[5];
}
// if there is at least one empty line at the end of this text, strip it
// we'll be adding one back after the text but before the containing tag.
text = text.replace(/\n[ \t]*$/, '');
if (matched[2] || matched[3].indexOf('\n') !== -1) {
// if the first line of the non-comment text has spaces
// use that as the basis for indenting in null case.
matched = matched[3].match(/[ \t]+$/);
if (matched) {
raw_token.whitespace_before = matched[0];
}
}
}
if (text) {
if (_beautifier) {
// call the Beautifier if avaliable
var Child_options = function() {
this.eol = '\n';
};
Child_options.prototype = this._options.raw_options;
var child_options = new Child_options();
text = _beautifier(indentation + text, child_options);
} else {
// simply indent the string otherwise
var white = raw_token.whitespace_before;
if (white) {
text = text.replace(new RegExp('\n(' + white + ')?', 'g'), '\n');
}
text = indentation + text.replace(/\n/g, '\n' + indentation);
}
}
if (pre) {
if (!text) {
text = pre + post;
} else {
text = pre + text + '\n' + post;
}
}
printer.print_newline(false);
if (text) {
raw_token.text = text;
raw_token.whitespace_before = '';
raw_token.newlines = 0;
printer.add_raw_token(raw_token);
printer.print_newline(true);
}
}
};
Beautifier.prototype._handle_tag_open = function(printer, raw_token, last_tag_token, last_token, tokens) {
var parser_token = this._get_tag_open_token(raw_token);
if ((last_tag_token.is_unformatted || last_tag_token.is_content_unformatted) &&
!last_tag_token.is_empty_element &&
raw_token.type === TOKEN.TAG_OPEN && !parser_token.is_start_tag) {
// End element tags for unformatted or content_unformatted elements
// are printed raw to keep any newlines inside them exactly the same.
printer.add_raw_token(raw_token);
parser_token.start_tag_token = this._tag_stack.try_pop(parser_token.tag_name);
} else {
printer.traverse_whitespace(raw_token);
this._set_tag_position(printer, raw_token, parser_token, last_tag_token, last_token);
if (!parser_token.is_inline_element) {
printer.set_wrap_point();
}
printer.print_token(raw_token);
}
// count the number of attributes
if (parser_token.is_start_tag && this._is_wrap_attributes_force) {
var peek_index = 0;
var peek_token;
do {
peek_token = tokens.peek(peek_index);
if (peek_token.type === TOKEN.ATTRIBUTE) {
parser_token.attr_count += 1;
}
peek_index += 1;
} while (peek_token.type !== TOKEN.EOF && peek_token.type !== TOKEN.TAG_CLOSE);
}
//indent attributes an auto, forced, aligned or forced-align line-wrap
if (this._is_wrap_attributes_force_aligned || this._is_wrap_attributes_aligned_multiple || this._is_wrap_attributes_preserve_aligned) {
parser_token.alignment_size = raw_token.text.length + 1;
}
if (!parser_token.tag_complete && !parser_token.is_unformatted) {
printer.alignment_size = parser_token.alignment_size;
}
return parser_token;
};
var TagOpenParserToken = function(parent, raw_token) {
this.parent = parent || null;
this.text = '';
this.type = 'TK_TAG_OPEN';
this.tag_name = '';
this.is_inline_element = false;
this.is_unformatted = false;
this.is_content_unformatted = false;
this.is_empty_element = false;
this.is_start_tag = false;
this.is_end_tag = false;
this.indent_content = false;
this.multiline_content = false;
this.custom_beautifier_name = null;
this.start_tag_token = null;
this.attr_count = 0;
this.has_wrapped_attrs = false;
this.alignment_size = 0;
this.tag_complete = false;
this.tag_start_char = '';
this.tag_check = '';
if (!raw_token) {
this.tag_complete = true;
} else {
var tag_check_match;
this.tag_start_char = raw_token.text[0];
this.text = raw_token.text;
if (this.tag_start_char === '<') {
tag_check_match = raw_token.text.match(/^<([^\s>]*)/);
this.tag_check = tag_check_match ? tag_check_match[1] : '';
} else {
tag_check_match = raw_token.text.match(/^{{~?(?:[\^]|#\*?)?([^\s}]+)/);
this.tag_check = tag_check_match ? tag_check_match[1] : '';
// handle "{{#> myPartial}}" or "{{~#> myPartial}}"
if ((raw_token.text.startsWith('{{#>') || raw_token.text.startsWith('{{~#>')) && this.tag_check[0] === '>') {
if (this.tag_check === '>' && raw_token.next !== null) {
this.tag_check = raw_token.next.text.split(' ')[0];
} else {
this.tag_check = raw_token.text.split('>')[1];
}
}
}
this.tag_check = this.tag_check.toLowerCase();
if (raw_token.type === TOKEN.COMMENT) {
this.tag_complete = true;
}
this.is_start_tag = this.tag_check.charAt(0) !== '/';
this.tag_name = !this.is_start_tag ? this.tag_check.substr(1) : this.tag_check;
this.is_end_tag = !this.is_start_tag ||
(raw_token.closed && raw_token.closed.text === '/>');
// if whitespace handler ~ included (i.e. {{~#if true}}), handlebars tags start at pos 3 not pos 2
var handlebar_starts = 2;
if (this.tag_start_char === '{' && this.text.length >= 3) {
if (this.text.charAt(2) === '~') {
handlebar_starts = 3;
}
}
// handlebars tags that don't start with # or ^ are single_tags, and so also start and end.
this.is_end_tag = this.is_end_tag ||
(this.tag_start_char === '{' && (this.text.length < 3 || (/[^#\^]/.test(this.text.charAt(handlebar_starts)))));
}
};
Beautifier.prototype._get_tag_open_token = function(raw_token) { //function to get a full tag and parse its type
var parser_token = new TagOpenParserToken(this._tag_stack.get_parser_token(), raw_token);
parser_token.alignment_size = this._options.wrap_attributes_indent_size;
parser_token.is_end_tag = parser_token.is_end_tag ||
in_array(parser_token.tag_check, this._options.void_elements);
parser_token.is_empty_element = parser_token.tag_complete ||
(parser_token.is_start_tag && parser_token.is_end_tag);
parser_token.is_unformatted = !parser_token.tag_complete && in_array(parser_token.tag_check, this._options.unformatted);
parser_token.is_content_unformatted = !parser_token.is_empty_element && in_array(parser_token.tag_check, this._options.content_unformatted);
parser_token.is_inline_element = in_array(parser_token.tag_name, this._options.inline) || parser_token.tag_name.includes("-") || parser_token.tag_start_char === '{';
return parser_token;
};
Beautifier.prototype._set_tag_position = function(printer, raw_token, parser_token, last_tag_token, last_token) {
if (!parser_token.is_empty_element) {
if (parser_token.is_end_tag) { //this tag is a double tag so check for tag-ending
parser_token.start_tag_token = this._tag_stack.try_pop(parser_token.tag_name); //remove it and all ancestors
} else { // it's a start-tag
// check if this tag is starting an element that has optional end element
// and do an ending needed
if (this._do_optional_end_element(parser_token)) {
if (!parser_token.is_inline_element) {
printer.print_newline(false);
}
}
this._tag_stack.record_tag(parser_token); //push it on the tag stack
if ((parser_token.tag_name === 'script' || parser_token.tag_name === 'style') &&
!(parser_token.is_unformatted || parser_token.is_content_unformatted)) {
parser_token.custom_beautifier_name = get_custom_beautifier_name(parser_token.tag_check, raw_token);
}
}
}
if (in_array(parser_token.tag_check, this._options.extra_liners)) { //check if this double needs an extra line
printer.print_newline(false);
if (!printer._output.just_added_blankline()) {
printer.print_newline(true);
}
}
if (parser_token.is_empty_element) { //if this tag name is a single tag type (either in the list or has a closing /)
// if you hit an else case, reset the indent level if you are inside an:
// 'if', 'unless', or 'each' block.
if (parser_token.tag_start_char === '{' && parser_token.tag_check === 'else') {
this._tag_stack.indent_to_tag(['if', 'unless', 'each']);
parser_token.indent_content = true;
// Don't add a newline if opening {{#if}} tag is on the current line
var foundIfOnCurrentLine = printer.current_line_has_match(/{{#if/);
if (!foundIfOnCurrentLine) {
printer.print_newline(false);
}
}
// Don't add a newline before elements that should remain where they are.
if (parser_token.tag_name === '!--' && last_token.type === TOKEN.TAG_CLOSE &&
last_tag_token.is_end_tag && parser_token.text.indexOf('\n') === -1) {
//Do nothing. Leave comments on same line.
} else {
if (!(parser_token.is_inline_element || parser_token.is_unformatted)) {
printer.print_newline(false);
}
this._calcluate_parent_multiline(printer, parser_token);
}
} else if (parser_token.is_end_tag) { //this tag is a double tag so check for tag-ending
var do_end_expand = false;
// deciding whether a block is multiline should not be this hard
do_end_expand = parser_token.start_tag_token && parser_token.start_tag_token.multiline_content;
do_end_expand = do_end_expand || (!parser_token.is_inline_element &&
!(last_tag_token.is_inline_element || last_tag_token.is_unformatted) &&
!(last_token.type === TOKEN.TAG_CLOSE && parser_token.start_tag_token === last_tag_token) &&
last_token.type !== 'TK_CONTENT'
);
if (parser_token.is_content_unformatted || parser_token.is_unformatted) {
do_end_expand = false;
}
if (do_end_expand) {
printer.print_newline(false);
}
} else { // it's a start-tag
parser_token.indent_content = !parser_token.custom_beautifier_name;
if (parser_token.tag_start_char === '<') {
if (parser_token.tag_name === 'html') {
parser_token.indent_content = this._options.indent_inner_html;
} else if (parser_token.tag_name === 'head') {
parser_token.indent_content = this._options.indent_head_inner_html;
} else if (parser_token.tag_name === 'body') {
parser_token.indent_content = this._options.indent_body_inner_html;
}
}
if (!(parser_token.is_inline_element || parser_token.is_unformatted) &&
(last_token.type !== 'TK_CONTENT' || parser_token.is_content_unformatted)) {
printer.print_newline(false);
}
this._calcluate_parent_multiline(printer, parser_token);
}
};
Beautifier.prototype._calcluate_parent_multiline = function(printer, parser_token) {
if (parser_token.parent && printer._output.just_added_newline() &&
!((parser_token.is_inline_element || parser_token.is_unformatted) && parser_token.parent.is_inline_element)) {
parser_token.parent.multiline_content = true;
}
};
//To be used for <p> tag special case:
var p_closers = ['address', 'article', 'aside', 'blockquote', 'details', 'div', 'dl', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'main', 'menu', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul'];
var p_parent_excludes = ['a', 'audio', 'del', 'ins', 'map', 'noscript', 'video'];
Beautifier.prototype._do_optional_end_element = function(parser_token) {
var result = null;
// NOTE: cases of "if there is no more content in the parent element"
// are handled automatically by the beautifier.
// It assumes parent or ancestor close tag closes all children.
// https://www.w3.org/TR/html5/syntax.html#optional-tags
if (parser_token.is_empty_element || !parser_token.is_start_tag || !parser_token.parent) {
return;
}
if (parser_token.tag_name === 'body') {
// A head elements end tag may be omitted if the head element is not immediately followed by a space character or a comment.
result = result || this._tag_stack.try_pop('head');
//} else if (parser_token.tag_name === 'body') {
// DONE: A body elements end tag may be omitted if the body element is not immediately followed by a comment.
} else if (parser_token.tag_name === 'li') {
// An li elements end tag may be omitted if the li element is immediately followed by another li element or if there is no more content in the parent element.
result = result || this._tag_stack.try_pop('li', ['ol', 'ul', 'menu']);
} else if (parser_token.tag_name === 'dd' || parser_token.tag_name === 'dt') {
// A dd elements end tag may be omitted if the dd element is immediately followed by another dd element or a dt element, or if there is no more content in the parent element.
// A dt elements end tag may be omitted if the dt element is immediately followed by another dt element or a dd element.
result = result || this._tag_stack.try_pop('dt', ['dl']);
result = result || this._tag_stack.try_pop('dd', ['dl']);
} else if (parser_token.parent.tag_name === 'p' && p_closers.indexOf(parser_token.tag_name) !== -1) {
// IMPORTANT: this else-if works because p_closers has no overlap with any other element we look for in this method
// check for the parent element is an HTML element that is not an <a>, <audio>, <del>, <ins>, <map>, <noscript>, or <video> element, or an autonomous custom element.
// To do this right, this needs to be coded as an inclusion of the inverse of the exclusion above.
// But to start with (if we ignore "autonomous custom elements") the exclusion would be fine.
var p_parent = parser_token.parent.parent;
if (!p_parent || p_parent_excludes.indexOf(p_parent.tag_name) === -1) {
result = result || this._tag_stack.try_pop('p');
}
} else if (parser_token.tag_name === 'rp' || parser_token.tag_name === 'rt') {
// An rt elements end tag may be omitted if the rt element is immediately followed by an rt or rp element, or if there is no more content in the parent element.
// An rp elements end tag may be omitted if the rp element is immediately followed by an rt or rp element, or if there is no more content in the parent element.
result = result || this._tag_stack.try_pop('rt', ['ruby', 'rtc']);
result = result || this._tag_stack.try_pop('rp', ['ruby', 'rtc']);
} else if (parser_token.tag_name === 'optgroup') {
// An optgroup elements end tag may be omitted if the optgroup element is immediately followed by another optgroup element, or if there is no more content in the parent element.
// An option elements end tag may be omitted if the option element is immediately followed by another option element, or if it is immediately followed by an optgroup element, or if there is no more content in the parent element.
result = result || this._tag_stack.try_pop('optgroup', ['select']);
//result = result || this._tag_stack.try_pop('option', ['select']);
} else if (parser_token.tag_name === 'option') {
// An option elements end tag may be omitted if the option element is immediately followed by another option element, or if it is immediately followed by an optgroup element, or if there is no more content in the parent element.
result = result || this._tag_stack.try_pop('option', ['select', 'datalist', 'optgroup']);
} else if (parser_token.tag_name === 'colgroup') {
// DONE: A colgroup elements end tag may be omitted if the colgroup element is not immediately followed by a space character or a comment.
// A caption element's end tag may be ommitted if a colgroup, thead, tfoot, tbody, or tr element is started.
result = result || this._tag_stack.try_pop('caption', ['table']);
} else if (parser_token.tag_name === 'thead') {
// A colgroup element's end tag may be ommitted if a thead, tfoot, tbody, or tr element is started.
// A caption element's end tag may be ommitted if a colgroup, thead, tfoot, tbody, or tr element is started.
result = result || this._tag_stack.try_pop('caption', ['table']);
result = result || this._tag_stack.try_pop('colgroup', ['table']);
//} else if (parser_token.tag_name === 'caption') {
// DONE: A caption elements end tag may be omitted if the caption element is not immediately followed by a space character or a comment.
} else if (parser_token.tag_name === 'tbody' || parser_token.tag_name === 'tfoot') {
// A thead elements end tag may be omitted if the thead element is immediately followed by a tbody or tfoot element.
// A tbody elements end tag may be omitted if the tbody element is immediately followed by a tbody or tfoot element, or if there is no more content in the parent element.
// A colgroup element's end tag may be ommitted if a thead, tfoot, tbody, or tr element is started.
// A caption element's end tag may be ommitted if a colgroup, thead, tfoot, tbody, or tr element is started.
result = result || this._tag_stack.try_pop('caption', ['table']);
result = result || this._tag_stack.try_pop('colgroup', ['table']);
result = result || this._tag_stack.try_pop('thead', ['table']);
result = result || this._tag_stack.try_pop('tbody', ['table']);
//} else if (parser_token.tag_name === 'tfoot') {
// DONE: A tfoot elements end tag may be omitted if there is no more content in the parent element.
} else if (parser_token.tag_name === 'tr') {
// A tr elements end tag may be omitted if the tr element is immediately followed by another tr element, or if there is no more content in the parent element.
// A colgroup element's end tag may be ommitted if a thead, tfoot, tbody, or tr element is started.
// A caption element's end tag may be ommitted if a colgroup, thead, tfoot, tbody, or tr element is started.
result = result || this._tag_stack.try_pop('caption', ['table']);
result = result || this._tag_stack.try_pop('colgroup', ['table']);
result = result || this._tag_stack.try_pop('tr', ['table', 'thead', 'tbody', 'tfoot']);
} else if (parser_token.tag_name === 'th' || parser_token.tag_name === 'td') {
// A td elements end tag may be omitted if the td element is immediately followed by a td or th element, or if there is no more content in the parent element.
// A th elements end tag may be omitted if the th element is immediately followed by a td or th element, or if there is no more content in the parent element.
result = result || this._tag_stack.try_pop('td', ['table', 'thead', 'tbody', 'tfoot', 'tr']);
result = result || this._tag_stack.try_pop('th', ['table', 'thead', 'tbody', 'tfoot', 'tr']);
}
// Start element omission not handled currently
// A head elements start tag may be omitted if the element is empty, or if the first thing inside the head element is an element.
// A tbody elements start tag may be omitted if the first thing inside the tbody element is a tr element, and if the element is not immediately preceded by a tbody, thead, or tfoot element whose end tag has been omitted. (It cant be omitted if the element is empty.)
// A colgroup elements start tag may be omitted if the first thing inside the colgroup element is a col element, and if the element is not immediately preceded by another colgroup element whose end tag has been omitted. (It cant be omitted if the element is empty.)
// Fix up the parent of the parser token
parser_token.parent = this._tag_stack.get_parser_token();
return result;
};
module.exports.Beautifier = Beautifier;
},{"../core/output":107,"../html/options":119,"../html/tokenizer":120}],118:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
var Beautifier = require('./beautifier').Beautifier,
Options = require('./options').Options;
function style_html(html_source, options, js_beautify, css_beautify) {
var beautifier = new Beautifier(html_source, options, js_beautify, css_beautify);
return beautifier.beautify();
}
module.exports = style_html;
module.exports.defaultOptions = function() {
return new Options();
};
},{"./beautifier":117,"./options":119}],119:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
var BaseOptions = require('../core/options').Options;
function Options(options) {
BaseOptions.call(this, options, 'html');
if (this.templating.length === 1 && this.templating[0] === 'auto') {
this.templating = ['django', 'erb', 'handlebars', 'php'];
}
this.indent_inner_html = this._get_boolean('indent_inner_html');
this.indent_body_inner_html = this._get_boolean('indent_body_inner_html', true);
this.indent_head_inner_html = this._get_boolean('indent_head_inner_html', true);
this.indent_handlebars = this._get_boolean('indent_handlebars', true);
this.wrap_attributes = this._get_selection('wrap_attributes',
['auto', 'force', 'force-aligned', 'force-expand-multiline', 'aligned-multiple', 'preserve', 'preserve-aligned']);
this.wrap_attributes_min_attrs = this._get_number('wrap_attributes_min_attrs', 2);
this.wrap_attributes_indent_size = this._get_number('wrap_attributes_indent_size', this.indent_size);
this.extra_liners = this._get_array('extra_liners', ['head', 'body', '/html']);
// Block vs inline elements
// https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements
// https://developer.mozilla.org/en-US/docs/Web/HTML/Inline_elements
// https://www.w3.org/TR/html5/dom.html#phrasing-content
this.inline = this._get_array('inline', [
'a', 'abbr', 'area', 'audio', 'b', 'bdi', 'bdo', 'br', 'button', 'canvas', 'cite',
'code', 'data', 'datalist', 'del', 'dfn', 'em', 'embed', 'i', 'iframe', 'img',
'input', 'ins', 'kbd', 'keygen', 'label', 'map', 'mark', 'math', 'meter', 'noscript',
'object', 'output', 'progress', 'q', 'ruby', 's', 'samp', /* 'script', */ 'select', 'small',
'span', 'strong', 'sub', 'sup', 'svg', 'template', 'textarea', 'time', 'u', 'var',
'video', 'wbr', 'text',
// obsolete inline tags
'acronym', 'big', 'strike', 'tt'
]);
this.void_elements = this._get_array('void_elements', [
// HTLM void elements - aka self-closing tags - aka singletons
// https://www.w3.org/html/wg/drafts/html/master/syntax.html#void-elements
'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen',
'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr',
// NOTE: Optional tags are too complex for a simple list
// they are hard coded in _do_optional_end_element
// Doctype and xml elements
'!doctype', '?xml',
// obsolete tags
// basefont: https://www.computerhope.com/jargon/h/html-basefont-tag.htm
// isndex: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/isindex
'basefont', 'isindex'
]);
this.unformatted = this._get_array('unformatted', []);
this.content_unformatted = this._get_array('content_unformatted', [
'pre', 'textarea'
]);
this.unformatted_content_delimiter = this._get_characters('unformatted_content_delimiter');
this.indent_scripts = this._get_selection('indent_scripts', ['normal', 'keep', 'separate']);
}
Options.prototype = new BaseOptions();
module.exports.Options = Options;
},{"../core/options":106}],120:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
var BaseTokenizer = require('../core/tokenizer').Tokenizer;
var BASETOKEN = require('../core/tokenizer').TOKEN;
var Directives = require('../core/directives').Directives;
var TemplatablePattern = require('../core/templatablepattern').TemplatablePattern;
var Pattern = require('../core/pattern').Pattern;
var TOKEN = {
TAG_OPEN: 'TK_TAG_OPEN',
TAG_CLOSE: 'TK_TAG_CLOSE',
ATTRIBUTE: 'TK_ATTRIBUTE',
EQUALS: 'TK_EQUALS',
VALUE: 'TK_VALUE',
COMMENT: 'TK_COMMENT',
TEXT: 'TK_TEXT',
UNKNOWN: 'TK_UNKNOWN',
START: BASETOKEN.START,
RAW: BASETOKEN.RAW,
EOF: BASETOKEN.EOF
};
var directives_core = new Directives(/<\!--/, /-->/);
var Tokenizer = function(input_string, options) {
BaseTokenizer.call(this, input_string, options);
this._current_tag_name = '';
// Words end at whitespace or when a tag starts
// if we are indenting handlebars, they are considered tags
var templatable_reader = new TemplatablePattern(this._input).read_options(this._options);
var pattern_reader = new Pattern(this._input);
this.__patterns = {
word: templatable_reader.until(/[\n\r\t <]/),
single_quote: templatable_reader.until_after(/'/),
double_quote: templatable_reader.until_after(/"/),
attribute: templatable_reader.until(/[\n\r\t =>]|\/>/),
element_name: templatable_reader.until(/[\n\r\t >\/]/),
handlebars_comment: pattern_reader.starting_with(/{{!--/).until_after(/--}}/),
handlebars: pattern_reader.starting_with(/{{/).until_after(/}}/),
handlebars_open: pattern_reader.until(/[\n\r\t }]/),
handlebars_raw_close: pattern_reader.until(/}}/),
comment: pattern_reader.starting_with(/<!--/).until_after(/-->/),
cdata: pattern_reader.starting_with(/<!\[CDATA\[/).until_after(/]]>/),
// https://en.wikipedia.org/wiki/Conditional_comment
conditional_comment: pattern_reader.starting_with(/<!\[/).until_after(/]>/),
processing: pattern_reader.starting_with(/<\?/).until_after(/\?>/)
};
if (this._options.indent_handlebars) {
this.__patterns.word = this.__patterns.word.exclude('handlebars');
}
this._unformatted_content_delimiter = null;
if (this._options.unformatted_content_delimiter) {
var literal_regexp = this._input.get_literal_regexp(this._options.unformatted_content_delimiter);
this.__patterns.unformatted_content_delimiter =
pattern_reader.matching(literal_regexp)
.until_after(literal_regexp);
}
};
Tokenizer.prototype = new BaseTokenizer();
Tokenizer.prototype._is_comment = function(current_token) { // jshint unused:false
return false; //current_token.type === TOKEN.COMMENT || current_token.type === TOKEN.UNKNOWN;
};
Tokenizer.prototype._is_opening = function(current_token) {
return current_token.type === TOKEN.TAG_OPEN;
};
Tokenizer.prototype._is_closing = function(current_token, open_token) {
return current_token.type === TOKEN.TAG_CLOSE &&
(open_token && (
((current_token.text === '>' || current_token.text === '/>') && open_token.text[0] === '<') ||
(current_token.text === '}}' && open_token.text[0] === '{' && open_token.text[1] === '{')));
};
Tokenizer.prototype._reset = function() {
this._current_tag_name = '';
};
Tokenizer.prototype._get_next_token = function(previous_token, open_token) { // jshint unused:false
var token = null;
this._readWhitespace();
var c = this._input.peek();
if (c === null) {
return this._create_token(TOKEN.EOF, '');
}
token = token || this._read_open_handlebars(c, open_token);
token = token || this._read_attribute(c, previous_token, open_token);
token = token || this._read_close(c, open_token);
token = token || this._read_raw_content(c, previous_token, open_token);
token = token || this._read_content_word(c);
token = token || this._read_comment_or_cdata(c);
token = token || this._read_processing(c);
token = token || this._read_open(c, open_token);
token = token || this._create_token(TOKEN.UNKNOWN, this._input.next());
return token;
};
Tokenizer.prototype._read_comment_or_cdata = function(c) { // jshint unused:false
var token = null;
var resulting_string = null;
var directives = null;
if (c === '<') {
var peek1 = this._input.peek(1);
// We treat all comments as literals, even more than preformatted tags
// we only look for the appropriate closing marker
if (peek1 === '!') {
resulting_string = this.__patterns.comment.read();
// only process directive on html comments
if (resulting_string) {
directives = directives_core.get_directives(resulting_string);
if (directives && directives.ignore === 'start') {
resulting_string += directives_core.readIgnored(this._input);
}
} else {
resulting_string = this.__patterns.cdata.read();
}
}
if (resulting_string) {
token = this._create_token(TOKEN.COMMENT, resulting_string);
token.directives = directives;
}
}
return token;
};
Tokenizer.prototype._read_processing = function(c) { // jshint unused:false
var token = null;
var resulting_string = null;
var directives = null;
if (c === '<') {
var peek1 = this._input.peek(1);
if (peek1 === '!' || peek1 === '?') {
resulting_string = this.__patterns.conditional_comment.read();
resulting_string = resulting_string || this.__patterns.processing.read();
}
if (resulting_string) {
token = this._create_token(TOKEN.COMMENT, resulting_string);
token.directives = directives;
}
}
return token;
};
Tokenizer.prototype._read_open = function(c, open_token) {
var resulting_string = null;
var token = null;
if (!open_token) {
if (c === '<') {
resulting_string = this._input.next();
if (this._input.peek() === '/') {
resulting_string += this._input.next();
}
resulting_string += this.__patterns.element_name.read();
token = this._create_token(TOKEN.TAG_OPEN, resulting_string);
}
}
return token;
};
Tokenizer.prototype._read_open_handlebars = function(c, open_token) {
var resulting_string = null;
var token = null;
if (!open_token) {
if (this._options.indent_handlebars && c === '{' && this._input.peek(1) === '{') {
if (this._input.peek(2) === '!') {
resulting_string = this.__patterns.handlebars_comment.read();
resulting_string = resulting_string || this.__patterns.handlebars.read();
token = this._create_token(TOKEN.COMMENT, resulting_string);
} else {
resulting_string = this.__patterns.handlebars_open.read();
token = this._create_token(TOKEN.TAG_OPEN, resulting_string);
}
}
}
return token;
};
Tokenizer.prototype._read_close = function(c, open_token) {
var resulting_string = null;
var token = null;
if (open_token) {
if (open_token.text[0] === '<' && (c === '>' || (c === '/' && this._input.peek(1) === '>'))) {
resulting_string = this._input.next();
if (c === '/') { // for close tag "/>"
resulting_string += this._input.next();
}
token = this._create_token(TOKEN.TAG_CLOSE, resulting_string);
} else if (open_token.text[0] === '{' && c === '}' && this._input.peek(1) === '}') {
this._input.next();
this._input.next();
token = this._create_token(TOKEN.TAG_CLOSE, '}}');
}
}
return token;
};
Tokenizer.prototype._read_attribute = function(c, previous_token, open_token) {
var token = null;
var resulting_string = '';
if (open_token && open_token.text[0] === '<') {
if (c === '=') {
token = this._create_token(TOKEN.EQUALS, this._input.next());
} else if (c === '"' || c === "'") {
var content = this._input.next();
if (c === '"') {
content += this.__patterns.double_quote.read();
} else {
content += this.__patterns.single_quote.read();
}
token = this._create_token(TOKEN.VALUE, content);
} else {
resulting_string = this.__patterns.attribute.read();
if (resulting_string) {
if (previous_token.type === TOKEN.EQUALS) {
token = this._create_token(TOKEN.VALUE, resulting_string);
} else {
token = this._create_token(TOKEN.ATTRIBUTE, resulting_string);
}
}
}
}
return token;
};
Tokenizer.prototype._is_content_unformatted = function(tag_name) {
// void_elements have no content and so cannot have unformatted content
// script and style tags should always be read as unformatted content
// finally content_unformatted and unformatted element contents are unformatted
return this._options.void_elements.indexOf(tag_name) === -1 &&
(this._options.content_unformatted.indexOf(tag_name) !== -1 ||
this._options.unformatted.indexOf(tag_name) !== -1);
};
Tokenizer.prototype._read_raw_content = function(c, previous_token, open_token) { // jshint unused:false
var resulting_string = '';
if (open_token && open_token.text[0] === '{') {
resulting_string = this.__patterns.handlebars_raw_close.read();
} else if (previous_token.type === TOKEN.TAG_CLOSE &&
previous_token.opened.text[0] === '<' && previous_token.text[0] !== '/') {
// ^^ empty tag has no content
var tag_name = previous_token.opened.text.substr(1).toLowerCase();
if (tag_name === 'script' || tag_name === 'style') {
// Script and style tags are allowed to have comments wrapping their content
// or just have regular content.
var token = this._read_comment_or_cdata(c);
if (token) {
token.type = TOKEN.TEXT;
return token;
}
resulting_string = this._input.readUntil(new RegExp('</' + tag_name + '[\\n\\r\\t ]*?>', 'ig'));
} else if (this._is_content_unformatted(tag_name)) {
resulting_string = this._input.readUntil(new RegExp('</' + tag_name + '[\\n\\r\\t ]*?>', 'ig'));
}
}
if (resulting_string) {
return this._create_token(TOKEN.TEXT, resulting_string);
}
return null;
};
Tokenizer.prototype._read_content_word = function(c) {
var resulting_string = '';
if (this._options.unformatted_content_delimiter) {
if (c === this._options.unformatted_content_delimiter[0]) {
resulting_string = this.__patterns.unformatted_content_delimiter.read();
}
}
if (!resulting_string) {
resulting_string = this.__patterns.word.read();
}
if (resulting_string) {
return this._create_token(TOKEN.TEXT, resulting_string);
}
};
module.exports.Tokenizer = Tokenizer;
module.exports.TOKEN = TOKEN;
},{"../core/directives":104,"../core/pattern":108,"../core/templatablepattern":109,"../core/tokenizer":111}],121:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
var js_beautify = require('./javascript/index');
var css_beautify = require('./css/index');
var html_beautify = require('./html/index');
function style_html(html_source, options, js, css) {
js = js || js_beautify;
css = css || css_beautify;
return html_beautify(html_source, options, js, css);
}
style_html.defaultOptions = html_beautify.defaultOptions;
module.exports.js = js_beautify;
module.exports.css = css_beautify;
module.exports.html = style_html;
},{"./css/index":115,"./html/index":118,"./javascript/index":124}],122:[function(require,module,exports){
/* jshint node: true, curly: false */
// Parts of this section of code is taken from acorn.
//
// Acorn was written by Marijn Haverbeke and released under an MIT
// license. The Unicode regexps (for identifiers and whitespace) were
// taken from [Esprima](http://esprima.org) by Ariya Hidayat.
//
// Git repositories for Acorn are available at
//
// http://marijnhaverbeke.nl/git/acorn
// https://github.com/marijnh/acorn.git
// ## Character categories
'use strict';
// acorn used char codes to squeeze the last bit of performance out
// Beautifier is okay without that, so we're using regex
// permit # (23), $ (36), and @ (64). @ is used in ES7 decorators.
// 65 through 91 are uppercase letters.
// permit _ (95).
// 97 through 123 are lowercase letters.
var baseASCIIidentifierStartChars = "\\x23\\x24\\x40\\x41-\\x5a\\x5f\\x61-\\x7a";
// inside an identifier @ is not allowed but 0-9 are.
var baseASCIIidentifierChars = "\\x24\\x30-\\x39\\x41-\\x5a\\x5f\\x61-\\x7a";
// Big ugly regular expressions that match characters in the
// whitespace, identifier, and identifier-start categories. These
// are only applied when a character is found to actually have a
// code point above 128.
var nonASCIIidentifierStartChars = "\\xaa\\xb5\\xba\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0370-\\u0374\\u0376\\u0377\\u037a-\\u037d\\u0386\\u0388-\\u038a\\u038c\\u038e-\\u03a1\\u03a3-\\u03f5\\u03f7-\\u0481\\u048a-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05d0-\\u05ea\\u05f0-\\u05f2\\u0620-\\u064a\\u066e\\u066f\\u0671-\\u06d3\\u06d5\\u06e5\\u06e6\\u06ee\\u06ef\\u06fa-\\u06fc\\u06ff\\u0710\\u0712-\\u072f\\u074d-\\u07a5\\u07b1\\u07ca-\\u07ea\\u07f4\\u07f5\\u07fa\\u0800-\\u0815\\u081a\\u0824\\u0828\\u0840-\\u0858\\u08a0\\u08a2-\\u08ac\\u0904-\\u0939\\u093d\\u0950\\u0958-\\u0961\\u0971-\\u0977\\u0979-\\u097f\\u0985-\\u098c\\u098f\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bd\\u09ce\\u09dc\\u09dd\\u09df-\\u09e1\\u09f0\\u09f1\\u0a05-\\u0a0a\\u0a0f\\u0a10\\u0a13-\\u0a28\\u0a2a-\\u0a30\\u0a32\\u0a33\\u0a35\\u0a36\\u0a38\\u0a39\\u0a59-\\u0a5c\\u0a5e\\u0a72-\\u0a74\\u0a85-\\u0a8d\\u0a8f-\\u0a91\\u0a93-\\u0aa8\\u0aaa-\\u0ab0\\u0ab2\\u0ab3\\u0ab5-\\u0ab9\\u0abd\\u0ad0\\u0ae0\\u0ae1\\u0b05-\\u0b0c\\u0b0f\\u0b10\\u0b13-\\u0b28\\u0b2a-\\u0b30\\u0b32\\u0b33\\u0b35-\\u0b39\\u0b3d\\u0b5c\\u0b5d\\u0b5f-\\u0b61\\u0b71\\u0b83\\u0b85-\\u0b8a\\u0b8e-\\u0b90\\u0b92-\\u0b95\\u0b99\\u0b9a\\u0b9c\\u0b9e\\u0b9f\\u0ba3\\u0ba4\\u0ba8-\\u0baa\\u0bae-\\u0bb9\\u0bd0\\u0c05-\\u0c0c\\u0c0e-\\u0c10\\u0c12-\\u0c28\\u0c2a-\\u0c33\\u0c35-\\u0c39\\u0c3d\\u0c58\\u0c59\\u0c60\\u0c61\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbd\\u0cde\\u0ce0\\u0ce1\\u0cf1\\u0cf2\\u0d05-\\u0d0c\\u0d0e-\\u0d10\\u0d12-\\u0d3a\\u0d3d\\u0d4e\\u0d60\\u0d61\\u0d7a-\\u0d7f\\u0d85-\\u0d96\\u0d9a-\\u0db1\\u0db3-\\u0dbb\\u0dbd\\u0dc0-\\u0dc6\\u0e01-\\u0e30\\u0e32\\u0e33\\u0e40-\\u0e46\\u0e81\\u0e82\\u0e84\\u0e87\\u0e88\\u0e8a\\u0e8d\\u0e94-\\u0e97\\u0e99-\\u0e9f\\u0ea1-\\u0ea3\\u0ea5\\u0ea7\\u0eaa\\u0eab\\u0ead-\\u0eb0\\u0eb2\\u0eb3\\u0ebd\\u0ec0-\\u0ec4\\u0ec6\\u0edc-\\u0edf\\u0f00\\u0f40-\\u0f47\\u0f49-\\u0f6c\\u0f88-\\u0f8c\\u1000-\\u102a\\u103f\\u1050-\\u1055\\u105a-\\u105d\\u1061\\u1065\\u1066\\u106e-\\u1070\\u1075-\\u1081\\u108e\\u10a0-\\u10c5\\u10c7\\u10cd\\u10d0-\\u10fa\\u10fc-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u12b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u1380-\\u138f\\u13a0-\\u13f4\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16ee-\\u16f0\\u1700-\\u170c\\u170e-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176c\\u176e-\\u1770\\u1780-\\u17b3\\u17d7\\u17dc\\u1820-\\u1877\\u1880-\\u18a8\\u18aa\\u18b0-\\u18f5\\u1900-\\u191c\\u1950-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19c1-\\u19c7\\u1a00-\\u1a16\\u1a20-\\u1a54\\u1aa7\\u1b05-\\u1b33\\u1b45-\\u1b4b\\u1b83-\\u1ba0\\u1bae\\u1baf\\u1bba-\\u1be5\\u1c00-\\u1c23\\u1c4d-\\u1c4f\\u1c5a-\\u1c7d\\u1ce9-\\u1cec\\u1cee-\\u1cf1\\u1cf5\\u1cf6\\u1d00-\\u1dbf\\u1e00-\\u1f15\\u1f18-\\u1f1d\\u1f20-\\u1f45\\u1f48-\\u1f4d\\u1f50-\\u1f57\\u1f59\\u1f5b\\u1f5d\\u1f5f-\\u1f7d\\u1f80-\\u1fb4\\u1fb6-\\u1fbc\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fcc\\u1fd0-\\u1fd3\\u1fd6-\\u1fdb\\u1fe0-\\u1fec\\u1ff2-\\u1ff4\\u1ff6-\\u1ffc\\u2071\\u207f\\u2090-\\u209c\\u2102\\u2107\\u210a-\\u2113\\u2115\\u2119-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u212d\\u212f-\\u2139\\u213c-\\u213f\\u2145-\\u2149\\u214e\\u2160-\\u2188\\u2c00-\\u2c2e\\u2c30-\\u2c5e\\u2c60-\\u2ce4\\u2ceb-\\u2cee\\u2cf2\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\u2d30-\\u2d67\\u2d6f\\u2d80-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u2e2f\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303c\\u3041-\\u3096\\u309d-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312d\\u3131-\\u318e\\u31a0-\\u31ba\\u31f0-\\u31ff\\u3400-\\u4db5\\u4e00-\\u9fcc\\ua000-\\ua48c\\ua4d0-\\ua4fd\\ua500-\\ua60c\\ua610-\\ua61f\\ua62a\\ua62b\\ua640-\\ua66e\\ua67f-\\ua697\\ua6a0-\\ua6ef\\ua717-\\ua71f\\ua722-\\ua788\\ua78b-\\ua78e\\ua790-\\ua793\\ua7a0-\\ua7aa\\ua7f8-\\ua801\\ua803-\\ua805\\ua807-\\ua80a\\ua80c-\\ua822\\ua840-\\ua873\\ua882-\\ua8b3\\ua8f2-\\ua8f7\\ua8fb\\ua90a-\\ua925\\ua930-\\ua946\\ua960-\\ua97c\\ua984-\\ua9b2\\ua9cf\\uaa00-\\uaa28\\uaa40-\\uaa42\\uaa44-\\uaa4b\\uaa60-\\uaa76\\uaa7a\\uaa80-\\uaaaf\\uaab1\\uaab5\\uaab6\\uaab9-\\uaabd\\uaac0\\uaac2\\uaadb-\\uaadd\\uaae0-\\uaaea\\uaaf2-\\uaaf4\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uabc0-\\uabe2\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb00-\\ufb06\\ufb13-\\ufb17\\ufb1d\\ufb1f-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40\\ufb41\\ufb43\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdfb\\ufe70-\\ufe74\\ufe76-\\ufefc\\uff21-\\uff3a\\uff41-\\uff5a\\uff66-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc";
var nonASCIIidentifierChars = "\\u0300-\\u036f\\u0483-\\u0487\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u0620-\\u0649\\u0672-\\u06d3\\u06e7-\\u06e8\\u06fb-\\u06fc\\u0730-\\u074a\\u0800-\\u0814\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0840-\\u0857\\u08e4-\\u08fe\\u0900-\\u0903\\u093a-\\u093c\\u093e-\\u094f\\u0951-\\u0957\\u0962-\\u0963\\u0966-\\u096f\\u0981-\\u0983\\u09bc\\u09be-\\u09c4\\u09c7\\u09c8\\u09d7\\u09df-\\u09e0\\u0a01-\\u0a03\\u0a3c\\u0a3e-\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a66-\\u0a71\\u0a75\\u0a81-\\u0a83\\u0abc\\u0abe-\\u0ac5\\u0ac7-\\u0ac9\\u0acb-\\u0acd\\u0ae2-\\u0ae3\\u0ae6-\\u0aef\\u0b01-\\u0b03\\u0b3c\\u0b3e-\\u0b44\\u0b47\\u0b48\\u0b4b-\\u0b4d\\u0b56\\u0b57\\u0b5f-\\u0b60\\u0b66-\\u0b6f\\u0b82\\u0bbe-\\u0bc2\\u0bc6-\\u0bc8\\u0bca-\\u0bcd\\u0bd7\\u0be6-\\u0bef\\u0c01-\\u0c03\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62-\\u0c63\\u0c66-\\u0c6f\\u0c82\\u0c83\\u0cbc\\u0cbe-\\u0cc4\\u0cc6-\\u0cc8\\u0cca-\\u0ccd\\u0cd5\\u0cd6\\u0ce2-\\u0ce3\\u0ce6-\\u0cef\\u0d02\\u0d03\\u0d46-\\u0d48\\u0d57\\u0d62-\\u0d63\\u0d66-\\u0d6f\\u0d82\\u0d83\\u0dca\\u0dcf-\\u0dd4\\u0dd6\\u0dd8-\\u0ddf\\u0df2\\u0df3\\u0e34-\\u0e3a\\u0e40-\\u0e45\\u0e50-\\u0e59\\u0eb4-\\u0eb9\\u0ec8-\\u0ecd\\u0ed0-\\u0ed9\\u0f18\\u0f19\\u0f20-\\u0f29\\u0f35\\u0f37\\u0f39\\u0f41-\\u0f47\\u0f71-\\u0f84\\u0f86-\\u0f87\\u0f8d-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u1000-\\u1029\\u1040-\\u1049\\u1067-\\u106d\\u1071-\\u1074\\u1082-\\u108d\\u108f-\\u109d\\u135d-\\u135f\\u170e-\\u1710\\u1720-\\u1730\\u1740-\\u1750\\u1772\\u1773\\u1780-\\u17b2\\u17dd\\u17e0-\\u17e9\\u180b-\\u180d\\u1810-\\u1819\\u1920-\\u192b\\u1930-\\u193b\\u1951-\\u196d\\u19b0-\\u19c0\\u19c8-\\u19c9\\u19d0-\\u19d9\\u1a00-\\u1a15\\u1a20-\\u1a53\\u1a60-\\u1a7c\\u1a7f-\\u1a89\\u1a90-\\u1a99\\u1b46-\\u1b4b\\u1b50-\\u1b59\\u1b6b-\\u1b73\\u1bb0-\\u1bb9\\u1be6-\\u1bf3\\u1c00-\\u1c22\\u1c40-\\u1c49\\u1c5b-\\u1c7d\\u1cd0-\\u1cd2\\u1d00-\\u1dbe\\u1e01-\\u1f15\\u200c\\u200d\\u203f\\u2040\\u2054\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2d81-\\u2d96\\u2de0-\\u2dff\\u3021-\\u3028\\u3099\\u309a\\ua640-\\ua66d\\ua674-\\ua67d\\ua69f\\ua6f0-\\ua6f1\\ua7f8-\\ua800\\ua806\\ua80b\\ua823-\\ua827\\ua880-\\ua881\\ua8b4-\\ua8c4\\ua8d0-\\ua8d9\\ua8f3-\\ua8f7\\ua900-\\ua909\\ua926-\\ua92d\\ua930-\\ua945\\ua980-\\ua983\\ua9b3-\\ua9c0\\uaa00-\\uaa27\\uaa40-\\uaa41\\uaa4c-\\uaa4d\\uaa50-\\uaa59\\uaa7b\\uaae0-\\uaae9\\uaaf2-\\uaaf3\\uabc0-\\uabe1\\uabec\\uabed\\uabf0-\\uabf9\\ufb20-\\ufb28\\ufe00-\\ufe0f\\ufe20-\\ufe26\\ufe33\\ufe34\\ufe4d-\\ufe4f\\uff10-\\uff19\\uff3f";
//var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
//var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
var identifierStart = "(?:\\\\u[0-9a-fA-F]{4}|[" + baseASCIIidentifierStartChars + nonASCIIidentifierStartChars + "])";
var identifierChars = "(?:\\\\u[0-9a-fA-F]{4}|[" + baseASCIIidentifierChars + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "])*";
exports.identifier = new RegExp(identifierStart + identifierChars, 'g');
exports.identifierStart = new RegExp(identifierStart);
exports.identifierMatch = new RegExp("(?:\\\\u[0-9a-fA-F]{4}|[" + baseASCIIidentifierChars + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "])+");
var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/; // jshint ignore:line
// Whether a single character denotes a newline.
exports.newline = /[\n\r\u2028\u2029]/;
// Matches a whole line break (where CRLF is considered a single
// line break). Used to count lines.
// in javascript, these two differ
// in python they are the same, different methods are called on them
exports.lineBreak = new RegExp('\r\n|' + exports.newline.source);
exports.allLineBreaks = new RegExp(exports.lineBreak.source, 'g');
},{}],123:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
var Output = require('../core/output').Output;
var Token = require('../core/token').Token;
var acorn = require('./acorn');
var Options = require('./options').Options;
var Tokenizer = require('./tokenizer').Tokenizer;
var line_starters = require('./tokenizer').line_starters;
var positionable_operators = require('./tokenizer').positionable_operators;
var TOKEN = require('./tokenizer').TOKEN;
function in_array(what, arr) {
return arr.indexOf(what) !== -1;
}
function ltrim(s) {
return s.replace(/^\s+/g, '');
}
function generateMapFromStrings(list) {
var result = {};
for (var x = 0; x < list.length; x++) {
// make the mapped names underscored instead of dash
result[list[x].replace(/-/g, '_')] = list[x];
}
return result;
}
function reserved_word(token, word) {
return token && token.type === TOKEN.RESERVED && token.text === word;
}
function reserved_array(token, words) {
return token && token.type === TOKEN.RESERVED && in_array(token.text, words);
}
// Unsure of what they mean, but they work. Worth cleaning up in future.
var special_words = ['case', 'return', 'do', 'if', 'throw', 'else', 'await', 'break', 'continue', 'async'];
var validPositionValues = ['before-newline', 'after-newline', 'preserve-newline'];
// Generate map from array
var OPERATOR_POSITION = generateMapFromStrings(validPositionValues);
var OPERATOR_POSITION_BEFORE_OR_PRESERVE = [OPERATOR_POSITION.before_newline, OPERATOR_POSITION.preserve_newline];
var MODE = {
BlockStatement: 'BlockStatement', // 'BLOCK'
Statement: 'Statement', // 'STATEMENT'
ObjectLiteral: 'ObjectLiteral', // 'OBJECT',
ArrayLiteral: 'ArrayLiteral', //'[EXPRESSION]',
ForInitializer: 'ForInitializer', //'(FOR-EXPRESSION)',
Conditional: 'Conditional', //'(COND-EXPRESSION)',
Expression: 'Expression' //'(EXPRESSION)'
};
function remove_redundant_indentation(output, frame) {
// This implementation is effective but has some issues:
// - can cause line wrap to happen too soon due to indent removal
// after wrap points are calculated
// These issues are minor compared to ugly indentation.
if (frame.multiline_frame ||
frame.mode === MODE.ForInitializer ||
frame.mode === MODE.Conditional) {
return;
}
// remove one indent from each line inside this section
output.remove_indent(frame.start_line_index);
}
// we could use just string.split, but
// IE doesn't like returning empty strings
function split_linebreaks(s) {
//return s.split(/\x0d\x0a|\x0a/);
s = s.replace(acorn.allLineBreaks, '\n');
var out = [],
idx = s.indexOf("\n");
while (idx !== -1) {
out.push(s.substring(0, idx));
s = s.substring(idx + 1);
idx = s.indexOf("\n");
}
if (s.length) {
out.push(s);
}
return out;
}
function is_array(mode) {
return mode === MODE.ArrayLiteral;
}
function is_expression(mode) {
return in_array(mode, [MODE.Expression, MODE.ForInitializer, MODE.Conditional]);
}
function all_lines_start_with(lines, c) {
for (var i = 0; i < lines.length; i++) {
var line = lines[i].trim();
if (line.charAt(0) !== c) {
return false;
}
}
return true;
}
function each_line_matches_indent(lines, indent) {
var i = 0,
len = lines.length,
line;
for (; i < len; i++) {
line = lines[i];
// allow empty lines to pass through
if (line && line.indexOf(indent) !== 0) {
return false;
}
}
return true;
}
function Beautifier(source_text, options) {
options = options || {};
this._source_text = source_text || '';
this._output = null;
this._tokens = null;
this._last_last_text = null;
this._flags = null;
this._previous_flags = null;
this._flag_store = null;
this._options = new Options(options);
}
Beautifier.prototype.create_flags = function(flags_base, mode) {
var next_indent_level = 0;
if (flags_base) {
next_indent_level = flags_base.indentation_level;
if (!this._output.just_added_newline() &&
flags_base.line_indent_level > next_indent_level) {
next_indent_level = flags_base.line_indent_level;
}
}
var next_flags = {
mode: mode,
parent: flags_base,
last_token: flags_base ? flags_base.last_token : new Token(TOKEN.START_BLOCK, ''), // last token text
last_word: flags_base ? flags_base.last_word : '', // last TOKEN.WORD passed
declaration_statement: false,
declaration_assignment: false,
multiline_frame: false,
inline_frame: false,
if_block: false,
else_block: false,
class_start_block: false, // class A { INSIDE HERE } or class B extends C { INSIDE HERE }
do_block: false,
do_while: false,
import_block: false,
in_case_statement: false, // switch(..){ INSIDE HERE }
in_case: false, // we're on the exact line with "case 0:"
case_body: false, // the indented case-action block
case_block: false, // the indented case-action block is wrapped with {}
indentation_level: next_indent_level,
alignment: 0,
line_indent_level: flags_base ? flags_base.line_indent_level : next_indent_level,
start_line_index: this._output.get_line_number(),
ternary_depth: 0
};
return next_flags;
};
Beautifier.prototype._reset = function(source_text) {
var baseIndentString = source_text.match(/^[\t ]*/)[0];
this._last_last_text = ''; // pre-last token text
this._output = new Output(this._options, baseIndentString);
// If testing the ignore directive, start with output disable set to true
this._output.raw = this._options.test_output_raw;
// Stack of parsing/formatting states, including MODE.
// We tokenize, parse, and output in an almost purely a forward-only stream of token input
// and formatted output. This makes the beautifier less accurate than full parsers
// but also far more tolerant of syntax errors.
//
// For example, the default mode is MODE.BlockStatement. If we see a '{' we push a new frame of type
// MODE.BlockStatement on the the stack, even though it could be object literal. If we later
// encounter a ":", we'll switch to to MODE.ObjectLiteral. If we then see a ";",
// most full parsers would die, but the beautifier gracefully falls back to
// MODE.BlockStatement and continues on.
this._flag_store = [];
this.set_mode(MODE.BlockStatement);
var tokenizer = new Tokenizer(source_text, this._options);
this._tokens = tokenizer.tokenize();
return source_text;
};
Beautifier.prototype.beautify = function() {
// if disabled, return the input unchanged.
if (this._options.disabled) {
return this._source_text;
}
var sweet_code;
var source_text = this._reset(this._source_text);
var eol = this._options.eol;
if (this._options.eol === 'auto') {
eol = '\n';
if (source_text && acorn.lineBreak.test(source_text || '')) {
eol = source_text.match(acorn.lineBreak)[0];
}
}
var current_token = this._tokens.next();
while (current_token) {
this.handle_token(current_token);
this._last_last_text = this._flags.last_token.text;
this._flags.last_token = current_token;
current_token = this._tokens.next();
}
sweet_code = this._output.get_code(eol);
return sweet_code;
};
Beautifier.prototype.handle_token = function(current_token, preserve_statement_flags) {
if (current_token.type === TOKEN.START_EXPR) {
this.handle_start_expr(current_token);
} else if (current_token.type === TOKEN.END_EXPR) {
this.handle_end_expr(current_token);
} else if (current_token.type === TOKEN.START_BLOCK) {
this.handle_start_block(current_token);
} else if (current_token.type === TOKEN.END_BLOCK) {
this.handle_end_block(current_token);
} else if (current_token.type === TOKEN.WORD) {
this.handle_word(current_token);
} else if (current_token.type === TOKEN.RESERVED) {
this.handle_word(current_token);
} else if (current_token.type === TOKEN.SEMICOLON) {
this.handle_semicolon(current_token);
} else if (current_token.type === TOKEN.STRING) {
this.handle_string(current_token);
} else if (current_token.type === TOKEN.EQUALS) {
this.handle_equals(current_token);
} else if (current_token.type === TOKEN.OPERATOR) {
this.handle_operator(current_token);
} else if (current_token.type === TOKEN.COMMA) {
this.handle_comma(current_token);
} else if (current_token.type === TOKEN.BLOCK_COMMENT) {
this.handle_block_comment(current_token, preserve_statement_flags);
} else if (current_token.type === TOKEN.COMMENT) {
this.handle_comment(current_token, preserve_statement_flags);
} else if (current_token.type === TOKEN.DOT) {
this.handle_dot(current_token);
} else if (current_token.type === TOKEN.EOF) {
this.handle_eof(current_token);
} else if (current_token.type === TOKEN.UNKNOWN) {
this.handle_unknown(current_token, preserve_statement_flags);
} else {
this.handle_unknown(current_token, preserve_statement_flags);
}
};
Beautifier.prototype.handle_whitespace_and_comments = function(current_token, preserve_statement_flags) {
var newlines = current_token.newlines;
var keep_whitespace = this._options.keep_array_indentation && is_array(this._flags.mode);
if (current_token.comments_before) {
var comment_token = current_token.comments_before.next();
while (comment_token) {
// The cleanest handling of inline comments is to treat them as though they aren't there.
// Just continue formatting and the behavior should be logical.
// Also ignore unknown tokens. Again, this should result in better behavior.
this.handle_whitespace_and_comments(comment_token, preserve_statement_flags);
this.handle_token(comment_token, preserve_statement_flags);
comment_token = current_token.comments_before.next();
}
}
if (keep_whitespace) {
for (var i = 0; i < newlines; i += 1) {
this.print_newline(i > 0, preserve_statement_flags);
}
} else {
if (this._options.max_preserve_newlines && newlines > this._options.max_preserve_newlines) {
newlines = this._options.max_preserve_newlines;
}
if (this._options.preserve_newlines) {
if (newlines > 1) {
this.print_newline(false, preserve_statement_flags);
for (var j = 1; j < newlines; j += 1) {
this.print_newline(true, preserve_statement_flags);
}
}
}
}
};
var newline_restricted_tokens = ['async', 'break', 'continue', 'return', 'throw', 'yield'];
Beautifier.prototype.allow_wrap_or_preserved_newline = function(current_token, force_linewrap) {
force_linewrap = (force_linewrap === undefined) ? false : force_linewrap;
// Never wrap the first token on a line
if (this._output.just_added_newline()) {
return;
}
var shouldPreserveOrForce = (this._options.preserve_newlines && current_token.newlines) || force_linewrap;
var operatorLogicApplies = in_array(this._flags.last_token.text, positionable_operators) ||
in_array(current_token.text, positionable_operators);
if (operatorLogicApplies) {
var shouldPrintOperatorNewline = (
in_array(this._flags.last_token.text, positionable_operators) &&
in_array(this._options.operator_position, OPERATOR_POSITION_BEFORE_OR_PRESERVE)
) ||
in_array(current_token.text, positionable_operators);
shouldPreserveOrForce = shouldPreserveOrForce && shouldPrintOperatorNewline;
}
if (shouldPreserveOrForce) {
this.print_newline(false, true);
} else if (this._options.wrap_line_length) {
if (reserved_array(this._flags.last_token, newline_restricted_tokens)) {
// These tokens should never have a newline inserted
// between them and the following expression.
return;
}
this._output.set_wrap_point();
}
};
Beautifier.prototype.print_newline = function(force_newline, preserve_statement_flags) {
if (!preserve_statement_flags) {
if (this._flags.last_token.text !== ';' && this._flags.last_token.text !== ',' && this._flags.last_token.text !== '=' && (this._flags.last_token.type !== TOKEN.OPERATOR || this._flags.last_token.text === '--' || this._flags.last_token.text === '++')) {
var next_token = this._tokens.peek();
while (this._flags.mode === MODE.Statement &&
!(this._flags.if_block && reserved_word(next_token, 'else')) &&
!this._flags.do_block) {
this.restore_mode();
}
}
}
if (this._output.add_new_line(force_newline)) {
this._flags.multiline_frame = true;
}
};
Beautifier.prototype.print_token_line_indentation = function(current_token) {
if (this._output.just_added_newline()) {
if (this._options.keep_array_indentation &&
current_token.newlines &&
(current_token.text === '[' || is_array(this._flags.mode))) {
this._output.current_line.set_indent(-1);
this._output.current_line.push(current_token.whitespace_before);
this._output.space_before_token = false;
} else if (this._output.set_indent(this._flags.indentation_level, this._flags.alignment)) {
this._flags.line_indent_level = this._flags.indentation_level;
}
}
};
Beautifier.prototype.print_token = function(current_token) {
if (this._output.raw) {
this._output.add_raw_token(current_token);
return;
}
if (this._options.comma_first && current_token.previous && current_token.previous.type === TOKEN.COMMA &&
this._output.just_added_newline()) {
if (this._output.previous_line.last() === ',') {
var popped = this._output.previous_line.pop();
// if the comma was already at the start of the line,
// pull back onto that line and reprint the indentation
if (this._output.previous_line.is_empty()) {
this._output.previous_line.push(popped);
this._output.trim(true);
this._output.current_line.pop();
this._output.trim();
}
// add the comma in front of the next token
this.print_token_line_indentation(current_token);
this._output.add_token(',');
this._output.space_before_token = true;
}
}
this.print_token_line_indentation(current_token);
this._output.non_breaking_space = true;
this._output.add_token(current_token.text);
if (this._output.previous_token_wrapped) {
this._flags.multiline_frame = true;
}
};
Beautifier.prototype.indent = function() {
this._flags.indentation_level += 1;
this._output.set_indent(this._flags.indentation_level, this._flags.alignment);
};
Beautifier.prototype.deindent = function() {
if (this._flags.indentation_level > 0 &&
((!this._flags.parent) || this._flags.indentation_level > this._flags.parent.indentation_level)) {
this._flags.indentation_level -= 1;
this._output.set_indent(this._flags.indentation_level, this._flags.alignment);
}
};
Beautifier.prototype.set_mode = function(mode) {
if (this._flags) {
this._flag_store.push(this._flags);
this._previous_flags = this._flags;
} else {
this._previous_flags = this.create_flags(null, mode);
}
this._flags = this.create_flags(this._previous_flags, mode);
this._output.set_indent(this._flags.indentation_level, this._flags.alignment);
};
Beautifier.prototype.restore_mode = function() {
if (this._flag_store.length > 0) {
this._previous_flags = this._flags;
this._flags = this._flag_store.pop();
if (this._previous_flags.mode === MODE.Statement) {
remove_redundant_indentation(this._output, this._previous_flags);
}
this._output.set_indent(this._flags.indentation_level, this._flags.alignment);
}
};
Beautifier.prototype.start_of_object_property = function() {
return this._flags.parent.mode === MODE.ObjectLiteral && this._flags.mode === MODE.Statement && (
(this._flags.last_token.text === ':' && this._flags.ternary_depth === 0) || (reserved_array(this._flags.last_token, ['get', 'set'])));
};
Beautifier.prototype.start_of_statement = function(current_token) {
var start = false;
start = start || reserved_array(this._flags.last_token, ['var', 'let', 'const']) && current_token.type === TOKEN.WORD;
start = start || reserved_word(this._flags.last_token, 'do');
start = start || (!(this._flags.parent.mode === MODE.ObjectLiteral && this._flags.mode === MODE.Statement)) && reserved_array(this._flags.last_token, newline_restricted_tokens) && !current_token.newlines;
start = start || reserved_word(this._flags.last_token, 'else') &&
!(reserved_word(current_token, 'if') && !current_token.comments_before);
start = start || (this._flags.last_token.type === TOKEN.END_EXPR && (this._previous_flags.mode === MODE.ForInitializer || this._previous_flags.mode === MODE.Conditional));
start = start || (this._flags.last_token.type === TOKEN.WORD && this._flags.mode === MODE.BlockStatement &&
!this._flags.in_case &&
!(current_token.text === '--' || current_token.text === '++') &&
this._last_last_text !== 'function' &&
current_token.type !== TOKEN.WORD && current_token.type !== TOKEN.RESERVED);
start = start || (this._flags.mode === MODE.ObjectLiteral && (
(this._flags.last_token.text === ':' && this._flags.ternary_depth === 0) || reserved_array(this._flags.last_token, ['get', 'set'])));
if (start) {
this.set_mode(MODE.Statement);
this.indent();
this.handle_whitespace_and_comments(current_token, true);
// Issue #276:
// If starting a new statement with [if, for, while, do], push to a new line.
// if (a) if (b) if(c) d(); else e(); else f();
if (!this.start_of_object_property()) {
this.allow_wrap_or_preserved_newline(current_token,
reserved_array(current_token, ['do', 'for', 'if', 'while']));
}
return true;
}
return false;
};
Beautifier.prototype.handle_start_expr = function(current_token) {
// The conditional starts the statement if appropriate.
if (!this.start_of_statement(current_token)) {
this.handle_whitespace_and_comments(current_token);
}
var next_mode = MODE.Expression;
if (current_token.text === '[') {
if (this._flags.last_token.type === TOKEN.WORD || this._flags.last_token.text === ')') {
// this is array index specifier, break immediately
// a[x], fn()[x]
if (reserved_array(this._flags.last_token, line_starters)) {
this._output.space_before_token = true;
}
this.print_token(current_token);
this.set_mode(next_mode);
this.indent();
if (this._options.space_in_paren) {
this._output.space_before_token = true;
}
return;
}
next_mode = MODE.ArrayLiteral;
if (is_array(this._flags.mode)) {
if (this._flags.last_token.text === '[' ||
(this._flags.last_token.text === ',' && (this._last_last_text === ']' || this._last_last_text === '}'))) {
// ], [ goes to new line
// }, [ goes to new line
if (!this._options.keep_array_indentation) {
this.print_newline();
}
}
}
if (!in_array(this._flags.last_token.type, [TOKEN.START_EXPR, TOKEN.END_EXPR, TOKEN.WORD, TOKEN.OPERATOR, TOKEN.DOT])) {
this._output.space_before_token = true;
}
} else {
if (this._flags.last_token.type === TOKEN.RESERVED) {
if (this._flags.last_token.text === 'for') {
this._output.space_before_token = this._options.space_before_conditional;
next_mode = MODE.ForInitializer;
} else if (in_array(this._flags.last_token.text, ['if', 'while', 'switch'])) {
this._output.space_before_token = this._options.space_before_conditional;
next_mode = MODE.Conditional;
} else if (in_array(this._flags.last_word, ['await', 'async'])) {
// Should be a space between await and an IIFE, or async and an arrow function
this._output.space_before_token = true;
} else if (this._flags.last_token.text === 'import' && current_token.whitespace_before === '') {
this._output.space_before_token = false;
} else if (in_array(this._flags.last_token.text, line_starters) || this._flags.last_token.text === 'catch') {
this._output.space_before_token = true;
}
} else if (this._flags.last_token.type === TOKEN.EQUALS || this._flags.last_token.type === TOKEN.OPERATOR) {
// Support of this kind of newline preservation.
// a = (b &&
// (c || d));
if (!this.start_of_object_property()) {
this.allow_wrap_or_preserved_newline(current_token);
}
} else if (this._flags.last_token.type === TOKEN.WORD) {
this._output.space_before_token = false;
// function name() vs function name ()
// function* name() vs function* name ()
// async name() vs async name ()
// In ES6, you can also define the method properties of an object
// var obj = {a: function() {}}
// It can be abbreviated
// var obj = {a() {}}
// var obj = { a() {}} vs var obj = { a () {}}
// var obj = { * a() {}} vs var obj = { * a () {}}
var peek_back_two = this._tokens.peek(-3);
if (this._options.space_after_named_function && peek_back_two) {
// peek starts at next character so -1 is current token
var peek_back_three = this._tokens.peek(-4);
if (reserved_array(peek_back_two, ['async', 'function']) ||
(peek_back_two.text === '*' && reserved_array(peek_back_three, ['async', 'function']))) {
this._output.space_before_token = true;
} else if (this._flags.mode === MODE.ObjectLiteral) {
if ((peek_back_two.text === '{' || peek_back_two.text === ',') ||
(peek_back_two.text === '*' && (peek_back_three.text === '{' || peek_back_three.text === ','))) {
this._output.space_before_token = true;
}
} else if (this._flags.parent && this._flags.parent.class_start_block) {
this._output.space_before_token = true;
}
}
} else {
// Support preserving wrapped arrow function expressions
// a.b('c',
// () => d.e
// )
this.allow_wrap_or_preserved_newline(current_token);
}
// function() vs function ()
// yield*() vs yield* ()
// function*() vs function* ()
if ((this._flags.last_token.type === TOKEN.RESERVED && (this._flags.last_word === 'function' || this._flags.last_word === 'typeof')) ||
(this._flags.last_token.text === '*' &&
(in_array(this._last_last_text, ['function', 'yield']) ||
(this._flags.mode === MODE.ObjectLiteral && in_array(this._last_last_text, ['{', ',']))))) {
this._output.space_before_token = this._options.space_after_anon_function;
}
}
if (this._flags.last_token.text === ';' || this._flags.last_token.type === TOKEN.START_BLOCK) {
this.print_newline();
} else if (this._flags.last_token.type === TOKEN.END_EXPR || this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.END_BLOCK || this._flags.last_token.text === '.' || this._flags.last_token.type === TOKEN.COMMA) {
// do nothing on (( and )( and ][ and ]( and .(
// TODO: Consider whether forcing this is required. Review failing tests when removed.
this.allow_wrap_or_preserved_newline(current_token, current_token.newlines);
}
this.print_token(current_token);
this.set_mode(next_mode);
if (this._options.space_in_paren) {
this._output.space_before_token = true;
}
// In all cases, if we newline while inside an expression it should be indented.
this.indent();
};
Beautifier.prototype.handle_end_expr = function(current_token) {
// statements inside expressions are not valid syntax, but...
// statements must all be closed when their container closes
while (this._flags.mode === MODE.Statement) {
this.restore_mode();
}
this.handle_whitespace_and_comments(current_token);
if (this._flags.multiline_frame) {
this.allow_wrap_or_preserved_newline(current_token,
current_token.text === ']' && is_array(this._flags.mode) && !this._options.keep_array_indentation);
}
if (this._options.space_in_paren) {
if (this._flags.last_token.type === TOKEN.START_EXPR && !this._options.space_in_empty_paren) {
// () [] no inner space in empty parens like these, ever, ref #320
this._output.trim();
this._output.space_before_token = false;
} else {
this._output.space_before_token = true;
}
}
this.deindent();
this.print_token(current_token);
this.restore_mode();
remove_redundant_indentation(this._output, this._previous_flags);
// do {} while () // no statement required after
if (this._flags.do_while && this._previous_flags.mode === MODE.Conditional) {
this._previous_flags.mode = MODE.Expression;
this._flags.do_block = false;
this._flags.do_while = false;
}
};
Beautifier.prototype.handle_start_block = function(current_token) {
this.handle_whitespace_and_comments(current_token);
// Check if this is should be treated as a ObjectLiteral
var next_token = this._tokens.peek();
var second_token = this._tokens.peek(1);
if (this._flags.last_word === 'switch' && this._flags.last_token.type === TOKEN.END_EXPR) {
this.set_mode(MODE.BlockStatement);
this._flags.in_case_statement = true;
} else if (this._flags.case_body) {
this.set_mode(MODE.BlockStatement);
} else if (second_token && (
(in_array(second_token.text, [':', ',']) && in_array(next_token.type, [TOKEN.STRING, TOKEN.WORD, TOKEN.RESERVED])) ||
(in_array(next_token.text, ['get', 'set', '...']) && in_array(second_token.type, [TOKEN.WORD, TOKEN.RESERVED]))
)) {
// We don't support TypeScript,but we didn't break it for a very long time.
// We'll try to keep not breaking it.
if (in_array(this._last_last_text, ['class', 'interface']) && !in_array(second_token.text, [':', ','])) {
this.set_mode(MODE.BlockStatement);
} else {
this.set_mode(MODE.ObjectLiteral);
}
} else if (this._flags.last_token.type === TOKEN.OPERATOR && this._flags.last_token.text === '=>') {
// arrow function: (param1, paramN) => { statements }
this.set_mode(MODE.BlockStatement);
} else if (in_array(this._flags.last_token.type, [TOKEN.EQUALS, TOKEN.START_EXPR, TOKEN.COMMA, TOKEN.OPERATOR]) ||
reserved_array(this._flags.last_token, ['return', 'throw', 'import', 'default'])
) {
// Detecting shorthand function syntax is difficult by scanning forward,
// so check the surrounding context.
// If the block is being returned, imported, export default, passed as arg,
// assigned with = or assigned in a nested object, treat as an ObjectLiteral.
this.set_mode(MODE.ObjectLiteral);
} else {
this.set_mode(MODE.BlockStatement);
}
if (this._flags.last_token) {
if (reserved_array(this._flags.last_token.previous, ['class', 'extends'])) {
this._flags.class_start_block = true;
}
}
var empty_braces = !next_token.comments_before && next_token.text === '}';
var empty_anonymous_function = empty_braces && this._flags.last_word === 'function' &&
this._flags.last_token.type === TOKEN.END_EXPR;
if (this._options.brace_preserve_inline) // check for inline, set inline_frame if so
{
// search forward for a newline wanted inside this block
var index = 0;
var check_token = null;
this._flags.inline_frame = true;
do {
index += 1;
check_token = this._tokens.peek(index - 1);
if (check_token.newlines) {
this._flags.inline_frame = false;
break;
}
} while (check_token.type !== TOKEN.EOF &&
!(check_token.type === TOKEN.END_BLOCK && check_token.opened === current_token));
}
if ((this._options.brace_style === "expand" ||
(this._options.brace_style === "none" && current_token.newlines)) &&
!this._flags.inline_frame) {
if (this._flags.last_token.type !== TOKEN.OPERATOR &&
(empty_anonymous_function ||
this._flags.last_token.type === TOKEN.EQUALS ||
(reserved_array(this._flags.last_token, special_words) && this._flags.last_token.text !== 'else'))) {
this._output.space_before_token = true;
} else {
this.print_newline(false, true);
}
} else { // collapse || inline_frame
if (is_array(this._previous_flags.mode) && (this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.COMMA)) {
if (this._flags.last_token.type === TOKEN.COMMA || this._options.space_in_paren) {
this._output.space_before_token = true;
}
if (this._flags.last_token.type === TOKEN.COMMA || (this._flags.last_token.type === TOKEN.START_EXPR && this._flags.inline_frame)) {
this.allow_wrap_or_preserved_newline(current_token);
this._previous_flags.multiline_frame = this._previous_flags.multiline_frame || this._flags.multiline_frame;
this._flags.multiline_frame = false;
}
}
if (this._flags.last_token.type !== TOKEN.OPERATOR && this._flags.last_token.type !== TOKEN.START_EXPR) {
if (in_array(this._flags.last_token.type, [TOKEN.START_BLOCK, TOKEN.SEMICOLON]) && !this._flags.inline_frame) {
this.print_newline();
} else {
this._output.space_before_token = true;
}
}
}
this.print_token(current_token);
this.indent();
// Except for specific cases, open braces are followed by a new line.
if (!empty_braces && !(this._options.brace_preserve_inline && this._flags.inline_frame)) {
this.print_newline();
}
};
Beautifier.prototype.handle_end_block = function(current_token) {
// statements must all be closed when their container closes
this.handle_whitespace_and_comments(current_token);
while (this._flags.mode === MODE.Statement) {
this.restore_mode();
}
var empty_braces = this._flags.last_token.type === TOKEN.START_BLOCK;
if (this._flags.inline_frame && !empty_braces) { // try inline_frame (only set if this._options.braces-preserve-inline) first
this._output.space_before_token = true;
} else if (this._options.brace_style === "expand") {
if (!empty_braces) {
this.print_newline();
}
} else {
// skip {}
if (!empty_braces) {
if (is_array(this._flags.mode) && this._options.keep_array_indentation) {
// we REALLY need a newline here, but newliner would skip that
this._options.keep_array_indentation = false;
this.print_newline();
this._options.keep_array_indentation = true;
} else {
this.print_newline();
}
}
}
this.restore_mode();
this.print_token(current_token);
};
Beautifier.prototype.handle_word = function(current_token) {
if (current_token.type === TOKEN.RESERVED) {
if (in_array(current_token.text, ['set', 'get']) && this._flags.mode !== MODE.ObjectLiteral) {
current_token.type = TOKEN.WORD;
} else if (current_token.text === 'import' && in_array(this._tokens.peek().text, ['(', '.'])) {
current_token.type = TOKEN.WORD;
} else if (in_array(current_token.text, ['as', 'from']) && !this._flags.import_block) {
current_token.type = TOKEN.WORD;
} else if (this._flags.mode === MODE.ObjectLiteral) {
var next_token = this._tokens.peek();
if (next_token.text === ':') {
current_token.type = TOKEN.WORD;
}
}
}
if (this.start_of_statement(current_token)) {
// The conditional starts the statement if appropriate.
if (reserved_array(this._flags.last_token, ['var', 'let', 'const']) && current_token.type === TOKEN.WORD) {
this._flags.declaration_statement = true;
}
} else if (current_token.newlines && !is_expression(this._flags.mode) &&
(this._flags.last_token.type !== TOKEN.OPERATOR || (this._flags.last_token.text === '--' || this._flags.last_token.text === '++')) &&
this._flags.last_token.type !== TOKEN.EQUALS &&
(this._options.preserve_newlines || !reserved_array(this._flags.last_token, ['var', 'let', 'const', 'set', 'get']))) {
this.handle_whitespace_and_comments(current_token);
this.print_newline();
} else {
this.handle_whitespace_and_comments(current_token);
}
if (this._flags.do_block && !this._flags.do_while) {
if (reserved_word(current_token, 'while')) {
// do {} ## while ()
this._output.space_before_token = true;
this.print_token(current_token);
this._output.space_before_token = true;
this._flags.do_while = true;
return;
} else {
// do {} should always have while as the next word.
// if we don't see the expected while, recover
this.print_newline();
this._flags.do_block = false;
}
}
// if may be followed by else, or not
// Bare/inline ifs are tricky
// Need to unwind the modes correctly: if (a) if (b) c(); else d(); else e();
if (this._flags.if_block) {
if (!this._flags.else_block && reserved_word(current_token, 'else')) {
this._flags.else_block = true;
} else {
while (this._flags.mode === MODE.Statement) {
this.restore_mode();
}
this._flags.if_block = false;
this._flags.else_block = false;
}
}
if (this._flags.in_case_statement && reserved_array(current_token, ['case', 'default'])) {
this.print_newline();
if (!this._flags.case_block && (this._flags.case_body || this._options.jslint_happy)) {
// switch cases following one another
this.deindent();
}
this._flags.case_body = false;
this.print_token(current_token);
this._flags.in_case = true;
return;
}
if (this._flags.last_token.type === TOKEN.COMMA || this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.EQUALS || this._flags.last_token.type === TOKEN.OPERATOR) {
if (!this.start_of_object_property()) {
this.allow_wrap_or_preserved_newline(current_token);
}
}
if (reserved_word(current_token, 'function')) {
if (in_array(this._flags.last_token.text, ['}', ';']) ||
(this._output.just_added_newline() && !(in_array(this._flags.last_token.text, ['(', '[', '{', ':', '=', ',']) || this._flags.last_token.type === TOKEN.OPERATOR))) {
// make sure there is a nice clean space of at least one blank line
// before a new function definition
if (!this._output.just_added_blankline() && !current_token.comments_before) {
this.print_newline();
this.print_newline(true);
}
}
if (this._flags.last_token.type === TOKEN.RESERVED || this._flags.last_token.type === TOKEN.WORD) {
if (reserved_array(this._flags.last_token, ['get', 'set', 'new', 'export']) ||
reserved_array(this._flags.last_token, newline_restricted_tokens)) {
this._output.space_before_token = true;
} else if (reserved_word(this._flags.last_token, 'default') && this._last_last_text === 'export') {
this._output.space_before_token = true;
} else if (this._flags.last_token.text === 'declare') {
// accomodates Typescript declare function formatting
this._output.space_before_token = true;
} else {
this.print_newline();
}
} else if (this._flags.last_token.type === TOKEN.OPERATOR || this._flags.last_token.text === '=') {
// foo = function
this._output.space_before_token = true;
} else if (!this._flags.multiline_frame && (is_expression(this._flags.mode) || is_array(this._flags.mode))) {
// (function
} else {
this.print_newline();
}
this.print_token(current_token);
this._flags.last_word = current_token.text;
return;
}
var prefix = 'NONE';
if (this._flags.last_token.type === TOKEN.END_BLOCK) {
if (this._previous_flags.inline_frame) {
prefix = 'SPACE';
} else if (!reserved_array(current_token, ['else', 'catch', 'finally', 'from'])) {
prefix = 'NEWLINE';
} else {
if (this._options.brace_style === "expand" ||
this._options.brace_style === "end-expand" ||
(this._options.brace_style === "none" && current_token.newlines)) {
prefix = 'NEWLINE';
} else {
prefix = 'SPACE';
this._output.space_before_token = true;
}
}
} else if (this._flags.last_token.type === TOKEN.SEMICOLON && this._flags.mode === MODE.BlockStatement) {
// TODO: Should this be for STATEMENT as well?
prefix = 'NEWLINE';
} else if (this._flags.last_token.type === TOKEN.SEMICOLON && is_expression(this._flags.mode)) {
prefix = 'SPACE';
} else if (this._flags.last_token.type === TOKEN.STRING) {
prefix = 'NEWLINE';
} else if (this._flags.last_token.type === TOKEN.RESERVED || this._flags.last_token.type === TOKEN.WORD ||
(this._flags.last_token.text === '*' &&
(in_array(this._last_last_text, ['function', 'yield']) ||
(this._flags.mode === MODE.ObjectLiteral && in_array(this._last_last_text, ['{', ',']))))) {
prefix = 'SPACE';
} else if (this._flags.last_token.type === TOKEN.START_BLOCK) {
if (this._flags.inline_frame) {
prefix = 'SPACE';
} else {
prefix = 'NEWLINE';
}
} else if (this._flags.last_token.type === TOKEN.END_EXPR) {
this._output.space_before_token = true;
prefix = 'NEWLINE';
}
if (reserved_array(current_token, line_starters) && this._flags.last_token.text !== ')') {
if (this._flags.inline_frame || this._flags.last_token.text === 'else' || this._flags.last_token.text === 'export') {
prefix = 'SPACE';
} else {
prefix = 'NEWLINE';
}
}
if (reserved_array(current_token, ['else', 'catch', 'finally'])) {
if ((!(this._flags.last_token.type === TOKEN.END_BLOCK && this._previous_flags.mode === MODE.BlockStatement) ||
this._options.brace_style === "expand" ||
this._options.brace_style === "end-expand" ||
(this._options.brace_style === "none" && current_token.newlines)) &&
!this._flags.inline_frame) {
this.print_newline();
} else {
this._output.trim(true);
var line = this._output.current_line;
// If we trimmed and there's something other than a close block before us
// put a newline back in. Handles '} // comment' scenario.
if (line.last() !== '}') {
this.print_newline();
}
this._output.space_before_token = true;
}
} else if (prefix === 'NEWLINE') {
if (reserved_array(this._flags.last_token, special_words)) {
// no newline between 'return nnn'
this._output.space_before_token = true;
} else if (this._flags.last_token.text === 'declare' && reserved_array(current_token, ['var', 'let', 'const'])) {
// accomodates Typescript declare formatting
this._output.space_before_token = true;
} else if (this._flags.last_token.type !== TOKEN.END_EXPR) {
if ((this._flags.last_token.type !== TOKEN.START_EXPR || !reserved_array(current_token, ['var', 'let', 'const'])) && this._flags.last_token.text !== ':') {
// no need to force newline on 'var': for (var x = 0...)
if (reserved_word(current_token, 'if') && reserved_word(current_token.previous, 'else')) {
// no newline for } else if {
this._output.space_before_token = true;
} else {
this.print_newline();
}
}
} else if (reserved_array(current_token, line_starters) && this._flags.last_token.text !== ')') {
this.print_newline();
}
} else if (this._flags.multiline_frame && is_array(this._flags.mode) && this._flags.last_token.text === ',' && this._last_last_text === '}') {
this.print_newline(); // }, in lists get a newline treatment
} else if (prefix === 'SPACE') {
this._output.space_before_token = true;
}
if (current_token.previous && (current_token.previous.type === TOKEN.WORD || current_token.previous.type === TOKEN.RESERVED)) {
this._output.space_before_token = true;
}
this.print_token(current_token);
this._flags.last_word = current_token.text;
if (current_token.type === TOKEN.RESERVED) {
if (current_token.text === 'do') {
this._flags.do_block = true;
} else if (current_token.text === 'if') {
this._flags.if_block = true;
} else if (current_token.text === 'import') {
this._flags.import_block = true;
} else if (this._flags.import_block && reserved_word(current_token, 'from')) {
this._flags.import_block = false;
}
}
};
Beautifier.prototype.handle_semicolon = function(current_token) {
if (this.start_of_statement(current_token)) {
// The conditional starts the statement if appropriate.
// Semicolon can be the start (and end) of a statement
this._output.space_before_token = false;
} else {
this.handle_whitespace_and_comments(current_token);
}
var next_token = this._tokens.peek();
while (this._flags.mode === MODE.Statement &&
!(this._flags.if_block && reserved_word(next_token, 'else')) &&
!this._flags.do_block) {
this.restore_mode();
}
// hacky but effective for the moment
if (this._flags.import_block) {
this._flags.import_block = false;
}
this.print_token(current_token);
};
Beautifier.prototype.handle_string = function(current_token) {
if (current_token.text.startsWith("`") && current_token.newlines === 0 && current_token.whitespace_before === '' && (current_token.previous.text === ')' || this._flags.last_token.type === TOKEN.WORD)) {
//Conditional for detectign backtick strings
} else if (this.start_of_statement(current_token)) {
// The conditional starts the statement if appropriate.
// One difference - strings want at least a space before
this._output.space_before_token = true;
} else {
this.handle_whitespace_and_comments(current_token);
if (this._flags.last_token.type === TOKEN.RESERVED || this._flags.last_token.type === TOKEN.WORD || this._flags.inline_frame) {
this._output.space_before_token = true;
} else if (this._flags.last_token.type === TOKEN.COMMA || this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.EQUALS || this._flags.last_token.type === TOKEN.OPERATOR) {
if (!this.start_of_object_property()) {
this.allow_wrap_or_preserved_newline(current_token);
}
} else if ((current_token.text.startsWith("`") && this._flags.last_token.type === TOKEN.END_EXPR && (current_token.previous.text === ']' || current_token.previous.text === ')') && current_token.newlines === 0)) {
this._output.space_before_token = true;
} else {
this.print_newline();
}
}
this.print_token(current_token);
};
Beautifier.prototype.handle_equals = function(current_token) {
if (this.start_of_statement(current_token)) {
// The conditional starts the statement if appropriate.
} else {
this.handle_whitespace_and_comments(current_token);
}
if (this._flags.declaration_statement) {
// just got an '=' in a var-line, different formatting/line-breaking, etc will now be done
this._flags.declaration_assignment = true;
}
this._output.space_before_token = true;
this.print_token(current_token);
this._output.space_before_token = true;
};
Beautifier.prototype.handle_comma = function(current_token) {
this.handle_whitespace_and_comments(current_token, true);
this.print_token(current_token);
this._output.space_before_token = true;
if (this._flags.declaration_statement) {
if (is_expression(this._flags.parent.mode)) {
// do not break on comma, for(var a = 1, b = 2)
this._flags.declaration_assignment = false;
}
if (this._flags.declaration_assignment) {
this._flags.declaration_assignment = false;
this.print_newline(false, true);
} else if (this._options.comma_first) {
// for comma-first, we want to allow a newline before the comma
// to turn into a newline after the comma, which we will fixup later
this.allow_wrap_or_preserved_newline(current_token);
}
} else if (this._flags.mode === MODE.ObjectLiteral ||
(this._flags.mode === MODE.Statement && this._flags.parent.mode === MODE.ObjectLiteral)) {
if (this._flags.mode === MODE.Statement) {
this.restore_mode();
}
if (!this._flags.inline_frame) {
this.print_newline();
}
} else if (this._options.comma_first) {
// EXPR or DO_BLOCK
// for comma-first, we want to allow a newline before the comma
// to turn into a newline after the comma, which we will fixup later
this.allow_wrap_or_preserved_newline(current_token);
}
};
Beautifier.prototype.handle_operator = function(current_token) {
var isGeneratorAsterisk = current_token.text === '*' &&
(reserved_array(this._flags.last_token, ['function', 'yield']) ||
(in_array(this._flags.last_token.type, [TOKEN.START_BLOCK, TOKEN.COMMA, TOKEN.END_BLOCK, TOKEN.SEMICOLON]))
);
var isUnary = in_array(current_token.text, ['-', '+']) && (
in_array(this._flags.last_token.type, [TOKEN.START_BLOCK, TOKEN.START_EXPR, TOKEN.EQUALS, TOKEN.OPERATOR]) ||
in_array(this._flags.last_token.text, line_starters) ||
this._flags.last_token.text === ','
);
if (this.start_of_statement(current_token)) {
// The conditional starts the statement if appropriate.
} else {
var preserve_statement_flags = !isGeneratorAsterisk;
this.handle_whitespace_and_comments(current_token, preserve_statement_flags);
}
// hack for actionscript's import .*;
if (current_token.text === '*' && this._flags.last_token.type === TOKEN.DOT) {
this.print_token(current_token);
return;
}
if (current_token.text === '::') {
// no spaces around exotic namespacing syntax operator
this.print_token(current_token);
return;
}
// Allow line wrapping between operators when operator_position is
// set to before or preserve
if (this._flags.last_token.type === TOKEN.OPERATOR && in_array(this._options.operator_position, OPERATOR_POSITION_BEFORE_OR_PRESERVE)) {
this.allow_wrap_or_preserved_newline(current_token);
}
if (current_token.text === ':' && this._flags.in_case) {
this.print_token(current_token);
this._flags.in_case = false;
this._flags.case_body = true;
if (this._tokens.peek().type !== TOKEN.START_BLOCK) {
this.indent();
this.print_newline();
this._flags.case_block = false;
} else {
this._flags.case_block = true;
this._output.space_before_token = true;
}
return;
}
var space_before = true;
var space_after = true;
var in_ternary = false;
if (current_token.text === ':') {
if (this._flags.ternary_depth === 0) {
// Colon is invalid javascript outside of ternary and object, but do our best to guess what was meant.
space_before = false;
} else {
this._flags.ternary_depth -= 1;
in_ternary = true;
}
} else if (current_token.text === '?') {
this._flags.ternary_depth += 1;
}
// let's handle the operator_position option prior to any conflicting logic
if (!isUnary && !isGeneratorAsterisk && this._options.preserve_newlines && in_array(current_token.text, positionable_operators)) {
var isColon = current_token.text === ':';
var isTernaryColon = (isColon && in_ternary);
var isOtherColon = (isColon && !in_ternary);
switch (this._options.operator_position) {
case OPERATOR_POSITION.before_newline:
// if the current token is : and it's not a ternary statement then we set space_before to false
this._output.space_before_token = !isOtherColon;
this.print_token(current_token);
if (!isColon || isTernaryColon) {
this.allow_wrap_or_preserved_newline(current_token);
}
this._output.space_before_token = true;
return;
case OPERATOR_POSITION.after_newline:
// if the current token is anything but colon, or (via deduction) it's a colon and in a ternary statement,
// then print a newline.
this._output.space_before_token = true;
if (!isColon || isTernaryColon) {
if (this._tokens.peek().newlines) {
this.print_newline(false, true);
} else {
this.allow_wrap_or_preserved_newline(current_token);
}
} else {
this._output.space_before_token = false;
}
this.print_token(current_token);
this._output.space_before_token = true;
return;
case OPERATOR_POSITION.preserve_newline:
if (!isOtherColon) {
this.allow_wrap_or_preserved_newline(current_token);
}
// if we just added a newline, or the current token is : and it's not a ternary statement,
// then we set space_before to false
space_before = !(this._output.just_added_newline() || isOtherColon);
this._output.space_before_token = space_before;
this.print_token(current_token);
this._output.space_before_token = true;
return;
}
}
if (isGeneratorAsterisk) {
this.allow_wrap_or_preserved_newline(current_token);
space_before = false;
var next_token = this._tokens.peek();
space_after = next_token && in_array(next_token.type, [TOKEN.WORD, TOKEN.RESERVED]);
} else if (current_token.text === '...') {
this.allow_wrap_or_preserved_newline(current_token);
space_before = this._flags.last_token.type === TOKEN.START_BLOCK;
space_after = false;
} else if (in_array(current_token.text, ['--', '++', '!', '~']) || isUnary) {
// unary operators (and binary +/- pretending to be unary) special cases
if (this._flags.last_token.type === TOKEN.COMMA || this._flags.last_token.type === TOKEN.START_EXPR) {
this.allow_wrap_or_preserved_newline(current_token);
}
space_before = false;
space_after = false;
// http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1
// if there is a newline between -- or ++ and anything else we should preserve it.
if (current_token.newlines && (current_token.text === '--' || current_token.text === '++' || current_token.text === '~')) {
var new_line_needed = reserved_array(this._flags.last_token, special_words) && current_token.newlines;
if (new_line_needed && (this._previous_flags.if_block || this._previous_flags.else_block)) {
this.restore_mode();
}
this.print_newline(new_line_needed, true);
}
if (this._flags.last_token.text === ';' && is_expression(this._flags.mode)) {
// for (;; ++i)
// ^^^
space_before = true;
}
if (this._flags.last_token.type === TOKEN.RESERVED) {
space_before = true;
} else if (this._flags.last_token.type === TOKEN.END_EXPR) {
space_before = !(this._flags.last_token.text === ']' && (current_token.text === '--' || current_token.text === '++'));
} else if (this._flags.last_token.type === TOKEN.OPERATOR) {
// a++ + ++b;
// a - -b
space_before = in_array(current_token.text, ['--', '-', '++', '+']) && in_array(this._flags.last_token.text, ['--', '-', '++', '+']);
// + and - are not unary when preceeded by -- or ++ operator
// a-- + b
// a * +b
// a - -b
if (in_array(current_token.text, ['+', '-']) && in_array(this._flags.last_token.text, ['--', '++'])) {
space_after = true;
}
}
if (((this._flags.mode === MODE.BlockStatement && !this._flags.inline_frame) || this._flags.mode === MODE.Statement) &&
(this._flags.last_token.text === '{' || this._flags.last_token.text === ';')) {
// { foo; --i }
// foo(); --bar;
this.print_newline();
}
}
this._output.space_before_token = this._output.space_before_token || space_before;
this.print_token(current_token);
this._output.space_before_token = space_after;
};
Beautifier.prototype.handle_block_comment = function(current_token, preserve_statement_flags) {
if (this._output.raw) {
this._output.add_raw_token(current_token);
if (current_token.directives && current_token.directives.preserve === 'end') {
// If we're testing the raw output behavior, do not allow a directive to turn it off.
this._output.raw = this._options.test_output_raw;
}
return;
}
if (current_token.directives) {
this.print_newline(false, preserve_statement_flags);
this.print_token(current_token);
if (current_token.directives.preserve === 'start') {
this._output.raw = true;
}
this.print_newline(false, true);
return;
}
// inline block
if (!acorn.newline.test(current_token.text) && !current_token.newlines) {
this._output.space_before_token = true;
this.print_token(current_token);
this._output.space_before_token = true;
return;
} else {
this.print_block_commment(current_token, preserve_statement_flags);
}
};
Beautifier.prototype.print_block_commment = function(current_token, preserve_statement_flags) {
var lines = split_linebreaks(current_token.text);
var j; // iterator for this case
var javadoc = false;
var starless = false;
var lastIndent = current_token.whitespace_before;
var lastIndentLength = lastIndent.length;
// block comment starts with a new line
this.print_newline(false, preserve_statement_flags);
// first line always indented
this.print_token_line_indentation(current_token);
this._output.add_token(lines[0]);
this.print_newline(false, preserve_statement_flags);
if (lines.length > 1) {
lines = lines.slice(1);
javadoc = all_lines_start_with(lines, '*');
starless = each_line_matches_indent(lines, lastIndent);
if (javadoc) {
this._flags.alignment = 1;
}
for (j = 0; j < lines.length; j++) {
if (javadoc) {
// javadoc: reformat and re-indent
this.print_token_line_indentation(current_token);
this._output.add_token(ltrim(lines[j]));
} else if (starless && lines[j]) {
// starless: re-indent non-empty content, avoiding trim
this.print_token_line_indentation(current_token);
this._output.add_token(lines[j].substring(lastIndentLength));
} else {
// normal comments output raw
this._output.current_line.set_indent(-1);
this._output.add_token(lines[j]);
}
// for comments on their own line or more than one line, make sure there's a new line after
this.print_newline(false, preserve_statement_flags);
}
this._flags.alignment = 0;
}
};
Beautifier.prototype.handle_comment = function(current_token, preserve_statement_flags) {
if (current_token.newlines) {
this.print_newline(false, preserve_statement_flags);
} else {
this._output.trim(true);
}
this._output.space_before_token = true;
this.print_token(current_token);
this.print_newline(false, preserve_statement_flags);
};
Beautifier.prototype.handle_dot = function(current_token) {
if (this.start_of_statement(current_token)) {
// The conditional starts the statement if appropriate.
} else {
this.handle_whitespace_and_comments(current_token, true);
}
if (this._flags.last_token.text.match('^[0-9]+$')) {
this._output.space_before_token = true;
}
if (reserved_array(this._flags.last_token, special_words)) {
this._output.space_before_token = false;
} else {
// allow preserved newlines before dots in general
// force newlines on dots after close paren when break_chained - for bar().baz()
this.allow_wrap_or_preserved_newline(current_token,
this._flags.last_token.text === ')' && this._options.break_chained_methods);
}
// Only unindent chained method dot if this dot starts a new line.
// Otherwise the automatic extra indentation removal will handle the over indent
if (this._options.unindent_chained_methods && this._output.just_added_newline()) {
this.deindent();
}
this.print_token(current_token);
};
Beautifier.prototype.handle_unknown = function(current_token, preserve_statement_flags) {
this.print_token(current_token);
if (current_token.text[current_token.text.length - 1] === '\n') {
this.print_newline(false, preserve_statement_flags);
}
};
Beautifier.prototype.handle_eof = function(current_token) {
// Unwind any open statements
while (this._flags.mode === MODE.Statement) {
this.restore_mode();
}
this.handle_whitespace_and_comments(current_token);
};
module.exports.Beautifier = Beautifier;
},{"../core/output":107,"../core/token":110,"./acorn":122,"./options":125,"./tokenizer":126}],124:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
var Beautifier = require('./beautifier').Beautifier,
Options = require('./options').Options;
function js_beautify(js_source_text, options) {
var beautifier = new Beautifier(js_source_text, options);
return beautifier.beautify();
}
module.exports = js_beautify;
module.exports.defaultOptions = function() {
return new Options();
};
},{"./beautifier":123,"./options":125}],125:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
var BaseOptions = require('../core/options').Options;
var validPositionValues = ['before-newline', 'after-newline', 'preserve-newline'];
function Options(options) {
BaseOptions.call(this, options, 'js');
// compatibility, re
var raw_brace_style = this.raw_options.brace_style || null;
if (raw_brace_style === "expand-strict") { //graceful handling of deprecated option
this.raw_options.brace_style = "expand";
} else if (raw_brace_style === "collapse-preserve-inline") { //graceful handling of deprecated option
this.raw_options.brace_style = "collapse,preserve-inline";
} else if (this.raw_options.braces_on_own_line !== undefined) { //graceful handling of deprecated option
this.raw_options.brace_style = this.raw_options.braces_on_own_line ? "expand" : "collapse";
// } else if (!raw_brace_style) { //Nothing exists to set it
// raw_brace_style = "collapse";
}
//preserve-inline in delimited string will trigger brace_preserve_inline, everything
//else is considered a brace_style and the last one only will have an effect
var brace_style_split = this._get_selection_list('brace_style', ['collapse', 'expand', 'end-expand', 'none', 'preserve-inline']);
this.brace_preserve_inline = false; //Defaults in case one or other was not specified in meta-option
this.brace_style = "collapse";
for (var bs = 0; bs < brace_style_split.length; bs++) {
if (brace_style_split[bs] === "preserve-inline") {
this.brace_preserve_inline = true;
} else {
this.brace_style = brace_style_split[bs];
}
}
this.unindent_chained_methods = this._get_boolean('unindent_chained_methods');
this.break_chained_methods = this._get_boolean('break_chained_methods');
this.space_in_paren = this._get_boolean('space_in_paren');
this.space_in_empty_paren = this._get_boolean('space_in_empty_paren');
this.jslint_happy = this._get_boolean('jslint_happy');
this.space_after_anon_function = this._get_boolean('space_after_anon_function');
this.space_after_named_function = this._get_boolean('space_after_named_function');
this.keep_array_indentation = this._get_boolean('keep_array_indentation');
this.space_before_conditional = this._get_boolean('space_before_conditional', true);
this.unescape_strings = this._get_boolean('unescape_strings');
this.e4x = this._get_boolean('e4x');
this.comma_first = this._get_boolean('comma_first');
this.operator_position = this._get_selection('operator_position', validPositionValues);
// For testing of beautify preserve:start directive
this.test_output_raw = this._get_boolean('test_output_raw');
// force this._options.space_after_anon_function to true if this._options.jslint_happy
if (this.jslint_happy) {
this.space_after_anon_function = true;
}
}
Options.prototype = new BaseOptions();
module.exports.Options = Options;
},{"../core/options":106}],126:[function(require,module,exports){
/*jshint node:true */
/*
The MIT License (MIT)
Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
var InputScanner = require('../core/inputscanner').InputScanner;
var BaseTokenizer = require('../core/tokenizer').Tokenizer;
var BASETOKEN = require('../core/tokenizer').TOKEN;
var Directives = require('../core/directives').Directives;
var acorn = require('./acorn');
var Pattern = require('../core/pattern').Pattern;
var TemplatablePattern = require('../core/templatablepattern').TemplatablePattern;
function in_array(what, arr) {
return arr.indexOf(what) !== -1;
}
var TOKEN = {
START_EXPR: 'TK_START_EXPR',
END_EXPR: 'TK_END_EXPR',
START_BLOCK: 'TK_START_BLOCK',
END_BLOCK: 'TK_END_BLOCK',
WORD: 'TK_WORD',
RESERVED: 'TK_RESERVED',
SEMICOLON: 'TK_SEMICOLON',
STRING: 'TK_STRING',
EQUALS: 'TK_EQUALS',
OPERATOR: 'TK_OPERATOR',
COMMA: 'TK_COMMA',
BLOCK_COMMENT: 'TK_BLOCK_COMMENT',
COMMENT: 'TK_COMMENT',
DOT: 'TK_DOT',
UNKNOWN: 'TK_UNKNOWN',
START: BASETOKEN.START,
RAW: BASETOKEN.RAW,
EOF: BASETOKEN.EOF
};
var directives_core = new Directives(/\/\*/, /\*\//);
var number_pattern = /0[xX][0123456789abcdefABCDEF_]*n?|0[oO][01234567_]*n?|0[bB][01_]*n?|\d[\d_]*n|(?:\.\d[\d_]*|\d[\d_]*\.?[\d_]*)(?:[eE][+-]?[\d_]+)?/;
var digit = /[0-9]/;
// Dot "." must be distinguished from "..." and decimal
var dot_pattern = /[^\d\.]/;
var positionable_operators = (
">>> === !== &&= ??= ||= " +
"<< && >= ** != == <= >> || ?? |> " +
"< / - + > : & % ? ^ | *").split(' ');
// IMPORTANT: this must be sorted longest to shortest or tokenizing many not work.
// Also, you must update possitionable operators separately from punct
var punct =
">>>= " +
"... >>= <<= === >>> !== **= &&= ??= ||= " +
"=> ^= :: /= << <= == && -= >= >> != -- += ** || ?? ++ %= &= *= |= |> " +
"= ! ? > < : / ^ - + * & % ~ |";
punct = punct.replace(/[-[\]{}()*+?.,\\^$|#]/g, "\\$&");
// ?. but not if followed by a number
punct = '\\?\\.(?!\\d) ' + punct;
punct = punct.replace(/ /g, '|');
var punct_pattern = new RegExp(punct);
// words which should always start on new line.
var line_starters = 'continue,try,throw,return,var,let,const,if,switch,case,default,for,while,break,function,import,export'.split(',');
var reserved_words = line_starters.concat(['do', 'in', 'of', 'else', 'get', 'set', 'new', 'catch', 'finally', 'typeof', 'yield', 'async', 'await', 'from', 'as', 'class', 'extends']);
var reserved_word_pattern = new RegExp('^(?:' + reserved_words.join('|') + ')$');
// var template_pattern = /(?:(?:<\?php|<\?=)[\s\S]*?\?>)|(?:<%[\s\S]*?%>)/g;
var in_html_comment;
var Tokenizer = function(input_string, options) {
BaseTokenizer.call(this, input_string, options);
this._patterns.whitespace = this._patterns.whitespace.matching(
/\u00A0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff/.source,
/\u2028\u2029/.source);
var pattern_reader = new Pattern(this._input);
var templatable = new TemplatablePattern(this._input)
.read_options(this._options);
this.__patterns = {
template: templatable,
identifier: templatable.starting_with(acorn.identifier).matching(acorn.identifierMatch),
number: pattern_reader.matching(number_pattern),
punct: pattern_reader.matching(punct_pattern),
// comment ends just before nearest linefeed or end of file
comment: pattern_reader.starting_with(/\/\//).until(/[\n\r\u2028\u2029]/),
// /* ... */ comment ends with nearest */ or end of file
block_comment: pattern_reader.starting_with(/\/\*/).until_after(/\*\//),
html_comment_start: pattern_reader.matching(/<!--/),
html_comment_end: pattern_reader.matching(/-->/),
include: pattern_reader.starting_with(/#include/).until_after(acorn.lineBreak),
shebang: pattern_reader.starting_with(/#!/).until_after(acorn.lineBreak),
xml: pattern_reader.matching(/[\s\S]*?<(\/?)([-a-zA-Z:0-9_.]+|{[^}]+?}|!\[CDATA\[[^\]]*?\]\]|)(\s*{[^}]+?}|\s+[-a-zA-Z:0-9_.]+|\s+[-a-zA-Z:0-9_.]+\s*=\s*('[^']*'|"[^"]*"|{([^{}]|{[^}]+?})+?}))*\s*(\/?)\s*>/),
single_quote: templatable.until(/['\\\n\r\u2028\u2029]/),
double_quote: templatable.until(/["\\\n\r\u2028\u2029]/),
template_text: templatable.until(/[`\\$]/),
template_expression: templatable.until(/[`}\\]/)
};
};
Tokenizer.prototype = new BaseTokenizer();
Tokenizer.prototype._is_comment = function(current_token) {
return current_token.type === TOKEN.COMMENT || current_token.type === TOKEN.BLOCK_COMMENT || current_token.type === TOKEN.UNKNOWN;
};
Tokenizer.prototype._is_opening = function(current_token) {
return current_token.type === TOKEN.START_BLOCK || current_token.type === TOKEN.START_EXPR;
};
Tokenizer.prototype._is_closing = function(current_token, open_token) {
return (current_token.type === TOKEN.END_BLOCK || current_token.type === TOKEN.END_EXPR) &&
(open_token && (
(current_token.text === ']' && open_token.text === '[') ||
(current_token.text === ')' && open_token.text === '(') ||
(current_token.text === '}' && open_token.text === '{')));
};
Tokenizer.prototype._reset = function() {
in_html_comment = false;
};
Tokenizer.prototype._get_next_token = function(previous_token, open_token) { // jshint unused:false
var token = null;
this._readWhitespace();
var c = this._input.peek();
if (c === null) {
return this._create_token(TOKEN.EOF, '');
}
token = token || this._read_non_javascript(c);
token = token || this._read_string(c);
token = token || this._read_pair(c, this._input.peek(1)); // Issue #2062 hack for record type '#{'
token = token || this._read_word(previous_token);
token = token || this._read_singles(c);
token = token || this._read_comment(c);
token = token || this._read_regexp(c, previous_token);
token = token || this._read_xml(c, previous_token);
token = token || this._read_punctuation();
token = token || this._create_token(TOKEN.UNKNOWN, this._input.next());
return token;
};
Tokenizer.prototype._read_word = function(previous_token) {
var resulting_string;
resulting_string = this.__patterns.identifier.read();
if (resulting_string !== '') {
resulting_string = resulting_string.replace(acorn.allLineBreaks, '\n');
if (!(previous_token.type === TOKEN.DOT ||
(previous_token.type === TOKEN.RESERVED && (previous_token.text === 'set' || previous_token.text === 'get'))) &&
reserved_word_pattern.test(resulting_string)) {
if ((resulting_string === 'in' || resulting_string === 'of') &&
(previous_token.type === TOKEN.WORD || previous_token.type === TOKEN.STRING)) { // hack for 'in' and 'of' operators
return this._create_token(TOKEN.OPERATOR, resulting_string);
}
return this._create_token(TOKEN.RESERVED, resulting_string);
}
return this._create_token(TOKEN.WORD, resulting_string);
}
resulting_string = this.__patterns.number.read();
if (resulting_string !== '') {
return this._create_token(TOKEN.WORD, resulting_string);
}
};
Tokenizer.prototype._read_singles = function(c) {
var token = null;
if (c === '(' || c === '[') {
token = this._create_token(TOKEN.START_EXPR, c);
} else if (c === ')' || c === ']') {
token = this._create_token(TOKEN.END_EXPR, c);
} else if (c === '{') {
token = this._create_token(TOKEN.START_BLOCK, c);
} else if (c === '}') {
token = this._create_token(TOKEN.END_BLOCK, c);
} else if (c === ';') {
token = this._create_token(TOKEN.SEMICOLON, c);
} else if (c === '.' && dot_pattern.test(this._input.peek(1))) {
token = this._create_token(TOKEN.DOT, c);
} else if (c === ',') {
token = this._create_token(TOKEN.COMMA, c);
}
if (token) {
this._input.next();
}
return token;
};
Tokenizer.prototype._read_pair = function(c, d) {
var token = null;
if (c === '#' && d === '{') {
token = this._create_token(TOKEN.START_BLOCK, c + d);
}
if (token) {
this._input.next();
this._input.next();
}
return token;
};
Tokenizer.prototype._read_punctuation = function() {
var resulting_string = this.__patterns.punct.read();
if (resulting_string !== '') {
if (resulting_string === '=') {
return this._create_token(TOKEN.EQUALS, resulting_string);
} else if (resulting_string === '?.') {
return this._create_token(TOKEN.DOT, resulting_string);
} else {
return this._create_token(TOKEN.OPERATOR, resulting_string);
}
}
};
Tokenizer.prototype._read_non_javascript = function(c) {
var resulting_string = '';
if (c === '#') {
if (this._is_first_token()) {
resulting_string = this.__patterns.shebang.read();
if (resulting_string) {
return this._create_token(TOKEN.UNKNOWN, resulting_string.trim() + '\n');
}
}
// handles extendscript #includes
resulting_string = this.__patterns.include.read();
if (resulting_string) {
return this._create_token(TOKEN.UNKNOWN, resulting_string.trim() + '\n');
}
c = this._input.next();
// Spidermonkey-specific sharp variables for circular references. Considered obsolete.
var sharp = '#';
if (this._input.hasNext() && this._input.testChar(digit)) {
do {
c = this._input.next();
sharp += c;
} while (this._input.hasNext() && c !== '#' && c !== '=');
if (c === '#') {
//
} else if (this._input.peek() === '[' && this._input.peek(1) === ']') {
sharp += '[]';
this._input.next();
this._input.next();
} else if (this._input.peek() === '{' && this._input.peek(1) === '}') {
sharp += '{}';
this._input.next();
this._input.next();
}
return this._create_token(TOKEN.WORD, sharp);
}
this._input.back();
} else if (c === '<' && this._is_first_token()) {
resulting_string = this.__patterns.html_comment_start.read();
if (resulting_string) {
while (this._input.hasNext() && !this._input.testChar(acorn.newline)) {
resulting_string += this._input.next();
}
in_html_comment = true;
return this._create_token(TOKEN.COMMENT, resulting_string);
}
} else if (in_html_comment && c === '-') {
resulting_string = this.__patterns.html_comment_end.read();
if (resulting_string) {
in_html_comment = false;
return this._create_token(TOKEN.COMMENT, resulting_string);
}
}
return null;
};
Tokenizer.prototype._read_comment = function(c) {
var token = null;
if (c === '/') {
var comment = '';
if (this._input.peek(1) === '*') {
// peek for comment /* ... */
comment = this.__patterns.block_comment.read();
var directives = directives_core.get_directives(comment);
if (directives && directives.ignore === 'start') {
comment += directives_core.readIgnored(this._input);
}
comment = comment.replace(acorn.allLineBreaks, '\n');
token = this._create_token(TOKEN.BLOCK_COMMENT, comment);
token.directives = directives;
} else if (this._input.peek(1) === '/') {
// peek for comment // ...
comment = this.__patterns.comment.read();
token = this._create_token(TOKEN.COMMENT, comment);
}
}
return token;
};
Tokenizer.prototype._read_string = function(c) {
if (c === '`' || c === "'" || c === '"') {
var resulting_string = this._input.next();
this.has_char_escapes = false;
if (c === '`') {
resulting_string += this._read_string_recursive('`', true, '${');
} else {
resulting_string += this._read_string_recursive(c);
}
if (this.has_char_escapes && this._options.unescape_strings) {
resulting_string = unescape_string(resulting_string);
}
if (this._input.peek() === c) {
resulting_string += this._input.next();
}
resulting_string = resulting_string.replace(acorn.allLineBreaks, '\n');
return this._create_token(TOKEN.STRING, resulting_string);
}
return null;
};
Tokenizer.prototype._allow_regexp_or_xml = function(previous_token) {
// regex and xml can only appear in specific locations during parsing
return (previous_token.type === TOKEN.RESERVED && in_array(previous_token.text, ['return', 'case', 'throw', 'else', 'do', 'typeof', 'yield'])) ||
(previous_token.type === TOKEN.END_EXPR && previous_token.text === ')' &&
previous_token.opened.previous.type === TOKEN.RESERVED && in_array(previous_token.opened.previous.text, ['if', 'while', 'for'])) ||
(in_array(previous_token.type, [TOKEN.COMMENT, TOKEN.START_EXPR, TOKEN.START_BLOCK, TOKEN.START,
TOKEN.END_BLOCK, TOKEN.OPERATOR, TOKEN.EQUALS, TOKEN.EOF, TOKEN.SEMICOLON, TOKEN.COMMA
]));
};
Tokenizer.prototype._read_regexp = function(c, previous_token) {
if (c === '/' && this._allow_regexp_or_xml(previous_token)) {
// handle regexp
//
var resulting_string = this._input.next();
var esc = false;
var in_char_class = false;
while (this._input.hasNext() &&
((esc || in_char_class || this._input.peek() !== c) &&
!this._input.testChar(acorn.newline))) {
resulting_string += this._input.peek();
if (!esc) {
esc = this._input.peek() === '\\';
if (this._input.peek() === '[') {
in_char_class = true;
} else if (this._input.peek() === ']') {
in_char_class = false;
}
} else {
esc = false;
}
this._input.next();
}
if (this._input.peek() === c) {
resulting_string += this._input.next();
// regexps may have modifiers /regexp/MOD , so fetch those, too
// Only [gim] are valid, but if the user puts in garbage, do what we can to take it.
resulting_string += this._input.read(acorn.identifier);
}
return this._create_token(TOKEN.STRING, resulting_string);
}
return null;
};
Tokenizer.prototype._read_xml = function(c, previous_token) {
if (this._options.e4x && c === "<" && this._allow_regexp_or_xml(previous_token)) {
var xmlStr = '';
var match = this.__patterns.xml.read_match();
// handle e4x xml literals
//
if (match) {
// Trim root tag to attempt to
var rootTag = match[2].replace(/^{\s+/, '{').replace(/\s+}$/, '}');
var isCurlyRoot = rootTag.indexOf('{') === 0;
var depth = 0;
while (match) {
var isEndTag = !!match[1];
var tagName = match[2];
var isSingletonTag = (!!match[match.length - 1]) || (tagName.slice(0, 8) === "![CDATA[");
if (!isSingletonTag &&
(tagName === rootTag || (isCurlyRoot && tagName.replace(/^{\s+/, '{').replace(/\s+}$/, '}')))) {
if (isEndTag) {
--depth;
} else {
++depth;
}
}
xmlStr += match[0];
if (depth <= 0) {
break;
}
match = this.__patterns.xml.read_match();
}
// if we didn't close correctly, keep unformatted.
if (!match) {
xmlStr += this._input.match(/[\s\S]*/g)[0];
}
xmlStr = xmlStr.replace(acorn.allLineBreaks, '\n');
return this._create_token(TOKEN.STRING, xmlStr);
}
}
return null;
};
function unescape_string(s) {
// You think that a regex would work for this
// return s.replace(/\\x([0-9a-f]{2})/gi, function(match, val) {
// return String.fromCharCode(parseInt(val, 16));
// })
// However, dealing with '\xff', '\\xff', '\\\xff' makes this more fun.
var out = '',
escaped = 0;
var input_scan = new InputScanner(s);
var matched = null;
while (input_scan.hasNext()) {
// Keep any whitespace, non-slash characters
// also keep slash pairs.
matched = input_scan.match(/([\s]|[^\\]|\\\\)+/g);
if (matched) {
out += matched[0];
}
if (input_scan.peek() === '\\') {
input_scan.next();
if (input_scan.peek() === 'x') {
matched = input_scan.match(/x([0-9A-Fa-f]{2})/g);
} else if (input_scan.peek() === 'u') {
matched = input_scan.match(/u([0-9A-Fa-f]{4})/g);
} else {
out += '\\';
if (input_scan.hasNext()) {
out += input_scan.next();
}
continue;
}
// If there's some error decoding, return the original string
if (!matched) {
return s;
}
escaped = parseInt(matched[1], 16);
if (escaped > 0x7e && escaped <= 0xff && matched[0].indexOf('x') === 0) {
// we bail out on \x7f..\xff,
// leaving whole string escaped,
// as it's probably completely binary
return s;
} else if (escaped >= 0x00 && escaped < 0x20) {
// leave 0x00...0x1f escaped
out += '\\' + matched[0];
continue;
} else if (escaped === 0x22 || escaped === 0x27 || escaped === 0x5c) {
// single-quote, apostrophe, backslash - escape these
out += '\\' + String.fromCharCode(escaped);
} else {
out += String.fromCharCode(escaped);
}
}
}
return out;
}
// handle string
//
Tokenizer.prototype._read_string_recursive = function(delimiter, allow_unescaped_newlines, start_sub) {
var current_char;
var pattern;
if (delimiter === '\'') {
pattern = this.__patterns.single_quote;
} else if (delimiter === '"') {
pattern = this.__patterns.double_quote;
} else if (delimiter === '`') {
pattern = this.__patterns.template_text;
} else if (delimiter === '}') {
pattern = this.__patterns.template_expression;
}
var resulting_string = pattern.read();
var next = '';
while (this._input.hasNext()) {
next = this._input.next();
if (next === delimiter ||
(!allow_unescaped_newlines && acorn.newline.test(next))) {
this._input.back();
break;
} else if (next === '\\' && this._input.hasNext()) {
current_char = this._input.peek();
if (current_char === 'x' || current_char === 'u') {
this.has_char_escapes = true;
} else if (current_char === '\r' && this._input.peek(1) === '\n') {
this._input.next();
}
next += this._input.next();
} else if (start_sub) {
if (start_sub === '${' && next === '$' && this._input.peek() === '{') {
next += this._input.next();
}
if (start_sub === next) {
if (delimiter === '`') {
next += this._read_string_recursive('}', allow_unescaped_newlines, '`');
} else {
next += this._read_string_recursive('`', allow_unescaped_newlines, '${');
}
if (this._input.hasNext()) {
next += this._input.next();
}
}
}
next += pattern.read();
resulting_string += next;
}
return resulting_string;
};
module.exports.Tokenizer = Tokenizer;
module.exports.TOKEN = TOKEN;
module.exports.positionable_operators = positionable_operators.slice();
module.exports.line_starters = line_starters.slice();
},{"../core/directives":104,"../core/inputscanner":105,"../core/pattern":108,"../core/templatablepattern":109,"../core/tokenizer":111,"./acorn":122}],127:[function(require,module,exports){
assert.notEqual = notEqual
assert.notOk = notOk
assert.equal = equal
assert.ok = assert
module.exports = assert
function equal (a, b, m) {
assert(a == b, m) // eslint-disable-line eqeqeq
}
function notEqual (a, b, m) {
assert(a != b, m) // eslint-disable-line eqeqeq
}
function notOk (t, m) {
assert(!t, m)
}
function assert (t, m) {
if (!t) throw new Error(m || 'AssertionError')
}
},{}],128:[function(require,module,exports){
var splice = require('remove-array-items')
var nanotiming = require('nanotiming')
var assert = require('assert')
module.exports = Nanobus
function Nanobus (name) {
if (!(this instanceof Nanobus)) return new Nanobus(name)
this._name = name || 'nanobus'
this._starListeners = []
this._listeners = {}
}
Nanobus.prototype.emit = function (eventName) {
assert.ok(typeof eventName === 'string' || typeof eventName === 'symbol', 'nanobus.emit: eventName should be type string or symbol')
var data = []
for (var i = 1, len = arguments.length; i < len; i++) {
data.push(arguments[i])
}
var emitTiming = nanotiming(this._name + "('" + eventName.toString() + "')")
var listeners = this._listeners[eventName]
if (listeners && listeners.length > 0) {
this._emit(this._listeners[eventName], data)
}
if (this._starListeners.length > 0) {
this._emit(this._starListeners, eventName, data, emitTiming.uuid)
}
emitTiming()
return this
}
Nanobus.prototype.on = Nanobus.prototype.addListener = function (eventName, listener) {
assert.ok(typeof eventName === 'string' || typeof eventName === 'symbol', 'nanobus.on: eventName should be type string or symbol')
assert.equal(typeof listener, 'function', 'nanobus.on: listener should be type function')
if (eventName === '*') {
this._starListeners.push(listener)
} else {
if (!this._listeners[eventName]) this._listeners[eventName] = []
this._listeners[eventName].push(listener)
}
return this
}
Nanobus.prototype.prependListener = function (eventName, listener) {
assert.ok(typeof eventName === 'string' || typeof eventName === 'symbol', 'nanobus.prependListener: eventName should be type string or symbol')
assert.equal(typeof listener, 'function', 'nanobus.prependListener: listener should be type function')
if (eventName === '*') {
this._starListeners.unshift(listener)
} else {
if (!this._listeners[eventName]) this._listeners[eventName] = []
this._listeners[eventName].unshift(listener)
}
return this
}
Nanobus.prototype.once = function (eventName, listener) {
assert.ok(typeof eventName === 'string' || typeof eventName === 'symbol', 'nanobus.once: eventName should be type string or symbol')
assert.equal(typeof listener, 'function', 'nanobus.once: listener should be type function')
var self = this
this.on(eventName, once)
function once () {
listener.apply(self, arguments)
self.removeListener(eventName, once)
}
return this
}
Nanobus.prototype.prependOnceListener = function (eventName, listener) {
assert.ok(typeof eventName === 'string' || typeof eventName === 'symbol', 'nanobus.prependOnceListener: eventName should be type string or symbol')
assert.equal(typeof listener, 'function', 'nanobus.prependOnceListener: listener should be type function')
var self = this
this.prependListener(eventName, once)
function once () {
listener.apply(self, arguments)
self.removeListener(eventName, once)
}
return this
}
Nanobus.prototype.removeListener = function (eventName, listener) {
assert.ok(typeof eventName === 'string' || typeof eventName === 'symbol', 'nanobus.removeListener: eventName should be type string or symbol')
assert.equal(typeof listener, 'function', 'nanobus.removeListener: listener should be type function')
if (eventName === '*') {
this._starListeners = this._starListeners.slice()
return remove(this._starListeners, listener)
} else {
if (typeof this._listeners[eventName] !== 'undefined') {
this._listeners[eventName] = this._listeners[eventName].slice()
}
return remove(this._listeners[eventName], listener)
}
function remove (arr, listener) {
if (!arr) return
var index = arr.indexOf(listener)
if (index !== -1) {
splice(arr, index, 1)
return true
}
}
}
Nanobus.prototype.removeAllListeners = function (eventName) {
if (eventName) {
if (eventName === '*') {
this._starListeners = []
} else {
this._listeners[eventName] = []
}
} else {
this._starListeners = []
this._listeners = {}
}
return this
}
Nanobus.prototype.listeners = function (eventName) {
var listeners = eventName !== '*'
? this._listeners[eventName]
: this._starListeners
var ret = []
if (listeners) {
var ilength = listeners.length
for (var i = 0; i < ilength; i++) ret.push(listeners[i])
}
return ret
}
Nanobus.prototype._emit = function (arr, eventName, data, uuid) {
if (typeof arr === 'undefined') return
if (arr.length === 0) return
if (data === undefined) {
data = eventName
eventName = null
}
if (eventName) {
if (uuid !== undefined) {
data = [eventName].concat(data, uuid)
} else {
data = [eventName].concat(data)
}
}
var length = arr.length
for (var i = 0; i < length; i++) {
var listener = arr[i]
listener.apply(listener, data)
}
}
},{"assert":127,"nanotiming":150,"remove-array-items":129}],129:[function(require,module,exports){
'use strict'
/**
* Remove a range of items from an array
*
* @function removeItems
* @param {Array<*>} arr The target array
* @param {number} startIdx The index to begin removing from (inclusive)
* @param {number} removeCount How many items to remove
*/
module.exports = function removeItems (arr, startIdx, removeCount) {
var i, length = arr.length
if (startIdx >= length || removeCount === 0) {
return
}
removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount)
var len = length - removeCount
for (i = startIdx; i < len; ++i) {
arr[i] = arr[i + removeCount]
}
arr.length = len
}
},{}],130:[function(require,module,exports){
const document = require('global/document')
const nanotiming = require('nanotiming')
const morph = require('nanomorph')
const onload = require('on-load')
const assert = require('assert')
const OL_KEY_ID = onload.KEY_ID
const OL_ATTR_ID = onload.KEY_ATTR
module.exports = Nanocomponent
function makeID () {
return 'ncid-' + Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1)
}
Nanocomponent.makeID = makeID
function Nanocomponent (name) {
this._hasWindow = typeof window !== 'undefined'
this._id = null // represents the id of the root node
this._ncID = null // internal nanocomponent id
this._olID = null
this._proxy = null
this._loaded = false // Used to debounce on-load when child-reordering
this._rootNodeName = null
this._name = name || 'nanocomponent'
this._rerender = false
this._handleLoad = this._handleLoad.bind(this)
this._handleUnload = this._handleUnload.bind(this)
this._arguments = []
const self = this
Object.defineProperty(this, 'element', {
get: function () {
const el = document.getElementById(self._id)
if (el) return el.dataset.nanocomponent === self._ncID ? el : undefined
}
})
}
Nanocomponent.prototype.render = function () {
const renderTiming = nanotiming(this._name + '.render')
const self = this
const args = new Array(arguments.length)
let el
for (let i = 0; i < arguments.length; i++) args[i] = arguments[i]
if (!this._hasWindow) {
const createTiming = nanotiming(this._name + '.create')
el = this.createElement.apply(this, args)
createTiming()
renderTiming()
return el
} else if (this.element) {
el = this.element // retain reference, as the ID might change on render
const updateTiming = nanotiming(this._name + '.update')
const shouldUpdate = this._rerender || this.update.apply(this, args)
updateTiming()
if (this._rerender) this._rerender = false
if (shouldUpdate) {
const desiredHtml = this._handleRender(args)
const morphTiming = nanotiming(this._name + '.morph')
morph(el, desiredHtml)
morphTiming()
if (this.afterupdate) this.afterupdate(el)
}
if (!this._proxy) { this._proxy = this._createProxy() }
renderTiming()
return this._proxy
} else {
this._reset()
el = this._handleRender(args)
if (this.beforerender) this.beforerender(el)
if (this.load || this.unload || this.afterreorder) {
onload(el, self._handleLoad, self._handleUnload, self._ncID)
this._olID = el.dataset[OL_KEY_ID]
}
renderTiming()
return el
}
}
Nanocomponent.prototype.rerender = function () {
assert(this.element, 'nanocomponent: cant rerender on an unmounted dom node')
this._rerender = true
this.render.apply(this, this._arguments)
}
Nanocomponent.prototype._handleRender = function (args) {
const createElementTiming = nanotiming(this._name + '.createElement')
const el = this.createElement.apply(this, args)
createElementTiming()
if (!this._rootNodeName) this._rootNodeName = el.nodeName
assert(el instanceof window.Element, 'nanocomponent: createElement should return a single DOM node')
assert(this._rootNodeName === el.nodeName, 'nanocomponent: root node types cannot differ between re-renders')
this._arguments = args
return this._brandNode(this._ensureID(el))
}
Nanocomponent.prototype._createProxy = function () {
const proxy = document.createElement(this._rootNodeName)
const self = this
this._brandNode(proxy)
proxy.id = this._id
proxy.setAttribute('data-proxy', '')
proxy.isSameNode = function (el) {
return (el && el.dataset.nanocomponent === self._ncID)
}
return proxy
}
Nanocomponent.prototype._reset = function () {
this._ncID = Nanocomponent.makeID()
this._olID = null
this._id = null
this._proxy = null
this._rootNodeName = null
}
Nanocomponent.prototype._brandNode = function (node) {
node.setAttribute('data-nanocomponent', this._ncID)
if (this._olID) node.setAttribute(OL_ATTR_ID, this._olID)
return node
}
Nanocomponent.prototype._ensureID = function (node) {
if (node.id) this._id = node.id
else node.id = this._id = this._ncID
// Update proxy node ID if it changed
if (this._proxy && this._proxy.id !== this._id) this._proxy.id = this._id
return node
}
Nanocomponent.prototype._handleLoad = function (el) {
if (this._loaded) {
if (this.afterreorder) this.afterreorder(el)
return // Debounce child-reorders
}
this._loaded = true
if (this.load) this.load(el)
}
Nanocomponent.prototype._handleUnload = function (el) {
if (this.element) return // Debounce child-reorders
this._loaded = false
if (this.unload) this.unload(el)
}
Nanocomponent.prototype.createElement = function () {
throw new Error('nanocomponent: createElement should be implemented!')
}
Nanocomponent.prototype.update = function () {
throw new Error('nanocomponent: update should be implemented!')
}
},{"assert":131,"global/document":87,"nanomorph":143,"nanotiming":150,"on-load":154}],131:[function(require,module,exports){
module.exports = assert
class AssertionError extends Error {}
AssertionError.prototype.name = 'AssertionError'
/**
* Minimal assert function
* @param {any} t Value to check if falsy
* @param {string=} m Optional assertion error message
* @throws {AssertionError}
*/
function assert (t, m) {
if (!t) {
var err = new AssertionError(m)
if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
throw err
}
}
},{}],132:[function(require,module,exports){
var assert = require('assert')
var safeExternalLink = /(noopener|noreferrer) (noopener|noreferrer)/
var protocolLink = /^[\w-_]+:/
module.exports = href
function href (cb, root) {
assert.notEqual(typeof window, 'undefined', 'nanohref: expected window to exist')
root = root || window.document
assert.equal(typeof cb, 'function', 'nanohref: cb should be type function')
assert.equal(typeof root, 'object', 'nanohref: root should be type object')
window.addEventListener('click', function (e) {
if ((e.button && e.button !== 0) ||
e.ctrlKey || e.metaKey || e.altKey || e.shiftKey ||
e.defaultPrevented) return
var anchor = (function traverse (node) {
if (!node || node === root) return
if (node.localName !== 'a' || node.href === undefined) {
return traverse(node.parentNode)
}
return node
})(e.target)
if (!anchor) return
if (window.location.protocol !== anchor.protocol ||
window.location.hostname !== anchor.hostname ||
window.location.port !== anchor.port ||
anchor.hasAttribute('data-nanohref-ignore') ||
anchor.hasAttribute('download') ||
(anchor.getAttribute('target') === '_blank' &&
safeExternalLink.test(anchor.getAttribute('rel'))) ||
protocolLink.test(anchor.getAttribute('href'))) return
e.preventDefault()
cb(anchor)
})
}
},{"assert":127}],133:[function(require,module,exports){
'use strict'
var trailingNewlineRegex = /\n[\s]+$/
var leadingNewlineRegex = /^\n[\s]+/
var trailingSpaceRegex = /[\s]+$/
var leadingSpaceRegex = /^[\s]+/
var multiSpaceRegex = /[\n\s]+/g
var TEXT_TAGS = [
'a', 'abbr', 'b', 'bdi', 'bdo', 'br', 'cite', 'data', 'dfn', 'em', 'i',
'kbd', 'mark', 'q', 'rp', 'rt', 'rtc', 'ruby', 's', 'amp', 'small', 'span',
'strong', 'sub', 'sup', 'time', 'u', 'var', 'wbr'
]
var VERBATIM_TAGS = [
'code', 'pre', 'textarea'
]
module.exports = function appendChild (el, childs) {
if (!Array.isArray(childs)) return
var nodeName = el.nodeName.toLowerCase()
var hadText = false
var value, leader
for (var i = 0, len = childs.length; i < len; i++) {
var node = childs[i]
if (Array.isArray(node)) {
appendChild(el, node)
continue
}
if (typeof node === 'number' ||
typeof node === 'boolean' ||
typeof node === 'function' ||
node instanceof Date ||
node instanceof RegExp) {
node = node.toString()
}
var lastChild = el.childNodes[el.childNodes.length - 1]
// Iterate over text nodes
if (typeof node === 'string') {
hadText = true
// If we already had text, append to the existing text
if (lastChild && lastChild.nodeName === '#text') {
lastChild.nodeValue += node
// We didn't have a text node yet, create one
} else {
node = el.ownerDocument.createTextNode(node)
el.appendChild(node)
lastChild = node
}
// If this is the last of the child nodes, make sure we close it out
// right
if (i === len - 1) {
hadText = false
// Trim the child text nodes if the current node isn't a
// node where whitespace matters.
if (TEXT_TAGS.indexOf(nodeName) === -1 &&
VERBATIM_TAGS.indexOf(nodeName) === -1) {
value = lastChild.nodeValue
.replace(leadingNewlineRegex, '')
.replace(trailingSpaceRegex, '')
.replace(trailingNewlineRegex, '')
.replace(multiSpaceRegex, ' ')
if (value === '') {
el.removeChild(lastChild)
} else {
lastChild.nodeValue = value
}
} else if (VERBATIM_TAGS.indexOf(nodeName) === -1) {
// The very first node in the list should not have leading
// whitespace. Sibling text nodes should have whitespace if there
// was any.
leader = i === 0 ? '' : ' '
value = lastChild.nodeValue
.replace(leadingNewlineRegex, leader)
.replace(leadingSpaceRegex, ' ')
.replace(trailingSpaceRegex, '')
.replace(trailingNewlineRegex, '')
.replace(multiSpaceRegex, ' ')
lastChild.nodeValue = value
}
}
// Iterate over DOM nodes
} else if (node && node.nodeType) {
// If the last node was a text node, make sure it is properly closed out
if (hadText) {
hadText = false
// Trim the child text nodes if the current node isn't a
// text node or a code node
if (TEXT_TAGS.indexOf(nodeName) === -1 &&
VERBATIM_TAGS.indexOf(nodeName) === -1) {
value = lastChild.nodeValue
.replace(leadingNewlineRegex, '')
.replace(trailingNewlineRegex, ' ')
.replace(multiSpaceRegex, ' ')
// Remove empty text nodes, append otherwise
if (value === '') {
el.removeChild(lastChild)
} else {
lastChild.nodeValue = value
}
// Trim the child nodes but preserve the appropriate whitespace
} else if (VERBATIM_TAGS.indexOf(nodeName) === -1) {
value = lastChild.nodeValue
.replace(leadingSpaceRegex, ' ')
.replace(leadingNewlineRegex, '')
.replace(trailingNewlineRegex, ' ')
.replace(multiSpaceRegex, ' ')
lastChild.nodeValue = value
}
}
// Store the last nodename
var _nodeName = node.nodeName
if (_nodeName) nodeName = _nodeName.toLowerCase()
// Append the node to the DOM
el.appendChild(node)
}
}
}
},{}],134:[function(require,module,exports){
'use strict'
module.exports = [
'async', 'autofocus', 'autoplay', 'checked', 'controls', 'default',
'defaultchecked', 'defer', 'disabled', 'formnovalidate', 'hidden',
'ismap', 'loop', 'multiple', 'muted', 'novalidate', 'open', 'playsinline',
'readonly', 'required', 'reversed', 'selected'
]
},{}],135:[function(require,module,exports){
module.exports = require('./dom')(document)
},{"./dom":137}],136:[function(require,module,exports){
'use strict'
module.exports = [
'indeterminate'
]
},{}],137:[function(require,module,exports){
'use strict'
var hyperx = require('hyperx')
var appendChild = require('./append-child')
var SVG_TAGS = require('./svg-tags')
var BOOL_PROPS = require('./bool-props')
// Props that need to be set directly rather than with el.setAttribute()
var DIRECT_PROPS = require('./direct-props')
var SVGNS = 'http://www.w3.org/2000/svg'
var XLINKNS = 'http://www.w3.org/1999/xlink'
var COMMENT_TAG = '!--'
module.exports = function (document) {
function nanoHtmlCreateElement (tag, props, children) {
var el
// If an svg tag, it needs a namespace
if (SVG_TAGS.indexOf(tag) !== -1) {
props.namespace = SVGNS
}
// If we are using a namespace
var ns = false
if (props.namespace) {
ns = props.namespace
delete props.namespace
}
// If we are extending a builtin element
var isCustomElement = false
if (props.is) {
isCustomElement = props.is
delete props.is
}
// Create the element
if (ns) {
if (isCustomElement) {
el = document.createElementNS(ns, tag, { is: isCustomElement })
} else {
el = document.createElementNS(ns, tag)
}
} else if (tag === COMMENT_TAG) {
return document.createComment(props.comment)
} else if (isCustomElement) {
el = document.createElement(tag, { is: isCustomElement })
} else {
el = document.createElement(tag)
}
// Create the properties
for (var p in props) {
if (props.hasOwnProperty(p)) {
var key = p.toLowerCase()
var val = props[p]
// Normalize className
if (key === 'classname') {
key = 'class'
p = 'class'
}
// The for attribute gets transformed to htmlFor, but we just set as for
if (p === 'htmlFor') {
p = 'for'
}
// If a property is boolean, set itself to the key
if (BOOL_PROPS.indexOf(key) !== -1) {
if (String(val) === 'true') val = key
else if (String(val) === 'false') continue
}
// If a property prefers being set directly vs setAttribute
if (key.slice(0, 2) === 'on' || DIRECT_PROPS.indexOf(key) !== -1) {
el[p] = val
} else {
if (ns) {
if (p === 'xlink:href') {
el.setAttributeNS(XLINKNS, p, val)
} else if (/^xmlns($|:)/i.test(p)) {
// skip xmlns definitions
} else {
el.setAttributeNS(null, p, val)
}
} else {
el.setAttribute(p, val)
}
}
}
}
appendChild(el, children)
return el
}
function createFragment (nodes) {
var fragment = document.createDocumentFragment()
for (var i = 0; i < nodes.length; i++) {
if (nodes[i] == null) continue
if (Array.isArray(nodes[i])) {
fragment.appendChild(createFragment(nodes[i]))
} else {
if (typeof nodes[i] === 'string') nodes[i] = document.createTextNode(nodes[i])
fragment.appendChild(nodes[i])
}
}
return fragment
}
var exports = hyperx(nanoHtmlCreateElement, {
comments: true,
createFragment: createFragment
})
exports.default = exports
exports.createComment = nanoHtmlCreateElement
return exports
}
},{"./append-child":133,"./bool-props":134,"./direct-props":136,"./svg-tags":139,"hyperx":97}],138:[function(require,module,exports){
'use strict'
function nanohtmlRawBrowser (tag) {
var el = document.createElement('div')
el.innerHTML = tag
return toArray(el.childNodes)
}
function toArray (arr) {
return Array.isArray(arr) ? arr : [].slice.call(arr)
}
module.exports = nanohtmlRawBrowser
},{}],139:[function(require,module,exports){
'use strict'
module.exports = [
'svg', 'altGlyph', 'altGlyphDef', 'altGlyphItem', 'animate', 'animateColor',
'animateMotion', 'animateTransform', 'circle', 'clipPath', 'color-profile',
'cursor', 'defs', 'desc', 'ellipse', 'feBlend', 'feColorMatrix',
'feComponentTransfer', 'feComposite', 'feConvolveMatrix',
'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood',
'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage',
'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight',
'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence', 'filter',
'font', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src',
'font-face-uri', 'foreignObject', 'g', 'glyph', 'glyphRef', 'hkern', 'image',
'line', 'linearGradient', 'marker', 'mask', 'metadata', 'missing-glyph',
'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect',
'set', 'stop', 'switch', 'symbol', 'text', 'textPath', 'title', 'tref',
'tspan', 'use', 'view', 'vkern'
]
},{}],140:[function(require,module,exports){
// This file replaces `format.js` in bundlers like webpack or Rollup,
// according to `browser` config in `package.json`.
module.exports = function (random, alphabet, size) {
// We cant use bytes bigger than the alphabet. To make bytes values closer
// to the alphabet, we apply bitmask on them. We look for the closest
// `2 ** x - 1` number, which will be bigger than alphabet size. If we have
// 30 symbols in the alphabet, we will take 31 (00011111).
// We do not use faster Math.clz32, because it is not available in browsers.
var mask = (2 << Math.log(alphabet.length - 1) / Math.LN2) - 1
// Bitmask is not a perfect solution (in our example it will pass 31 bytes,
// which is bigger than the alphabet). As a result, we will need more bytes,
// than ID size, because we will refuse bytes bigger than the alphabet.
// Every hardware random generator call is costly,
// because we need to wait for entropy collection. This is why often it will
// be faster to ask for few extra bytes in advance, to avoid additional calls.
// Here we calculate how many random bytes should we call in advance.
// It depends on ID length, mask / alphabet size and magic number 1.6
// (which was selected according benchmarks).
// -~f => Math.ceil(f) if n is float number
// -~i => i + 1 if n is integer number
var step = -~(1.6 * mask * size / alphabet.length)
var id = ''
while (true) {
var bytes = random(step)
// Compact alternative for `for (var i = 0; i < step; i++)`
var i = step
while (i--) {
// If random byte is bigger than alphabet even after bitmask,
// we refuse it by `|| ''`.
id += alphabet[bytes[i] & mask] || ''
// More compact than `id.length + 1 === size`
if (id.length === +size) return id
}
}
}
},{}],141:[function(require,module,exports){
var assert = require('assert')
var emojis = {
trace: '🔍',
debug: '🐛',
info: '✨',
warn: '⚠️',
error: '🚨',
fatal: '💀'
}
var levels = {
trace: 10,
debug: 20,
info: 30,
warn: 40,
error: 50,
fatal: 60
}
var defaultColors = {
foreground: '#d3c0c8',
background: '#2d2d2d',
black: '#2d2d2d',
red: '#f2777a',
green: '#99cc99',
yellow: '#ffcc66',
blue: '#6699cc',
magenta: '#cc99cc',
cyan: '#66cccc',
white: '#d3d0c8',
brightBlack: '#747369'
}
module.exports = Nanologger
function Nanologger (name, opts) {
opts = opts || {}
if (!(this instanceof Nanologger)) return new Nanologger(name, opts)
assert.equal(typeof opts, 'object', 'nanologger: opts should be type object')
this._name = name || ''
this._colors = Object.assign({}, defaultColors, opts.colors || {})
try {
this.logLevel = window.localStorage.getItem('logLevel') || 'info'
} catch (e) {
this.logLevel = 'info'
}
this._logLevel = levels[this.logLevel]
}
Nanologger.prototype.trace = function () {
var args = [ 'trace' ]
for (var i = 0, len = arguments.length; i < len; i++) args.push(arguments[i])
this._print.apply(this, args)
}
Nanologger.prototype.debug = function () {
var args = [ 'debug' ]
for (var i = 0, len = arguments.length; i < len; i++) args.push(arguments[i])
this._print.apply(this, args)
}
Nanologger.prototype.info = function () {
var args = [ 'info' ]
for (var i = 0, len = arguments.length; i < len; i++) args.push(arguments[i])
this._print.apply(this, args)
}
Nanologger.prototype.warn = function () {
var args = [ 'warn' ]
for (var i = 0, len = arguments.length; i < len; i++) args.push(arguments[i])
this._print.apply(this, args)
}
Nanologger.prototype.error = function () {
var args = [ 'error' ]
for (var i = 0, len = arguments.length; i < len; i++) args.push(arguments[i])
this._print.apply(this, args)
}
Nanologger.prototype.fatal = function () {
var args = [ 'fatal' ]
for (var i = 0, len = arguments.length; i < len; i++) args.push(arguments[i])
this._print.apply(this, args)
}
Nanologger.prototype._print = function (level) {
if (levels[level] < this._logLevel) return
var time = getTimeStamp()
var emoji = emojis[level]
var name = this._name || 'unknown'
var msgColor = (level === 'error' || level.fatal)
? this._colors.red
: level === 'warn'
? this._colors.yellow
: this._colors.green
var objs = []
var args = [ null ]
var msg = '%c%s ' + emoji + ' %c%s'
args.push(color(this._colors.brightBlack), time)
args.push(color(this._colors.magenta), name)
for (var i = 1, len = arguments.length; i < len; i++) {
var arg = arguments[i]
if (typeof arg === 'string') {
if (i === 1) {
// first string argument is in color
msg += ' %c%s'
args.push(color(msgColor))
args.push(arg)
} else if (/ms$/.test(arg)) {
// arguments finishing with 'ms', grey out
msg += ' %c%s'
args.push(color(this._colors.brightBlack))
args.push(arg)
} else {
// normal colors
msg += ' %c%s'
args.push(color(this._colors.white))
args.push(arg)
}
} else if (typeof arg === 'number') {
msg += ' %c%d'
args.push(color(this._colors.magenta))
args.push(arg)
} else {
objs.push(arg)
}
}
args[0] = msg
objs.forEach(function (obj) {
args.push(obj)
})
// In IE/Edge console functions don't inherit from Function.prototype
// so this is necessary to get all the args applied.
Function.prototype.apply.apply(console.log, [console, args])
}
function color (color) {
return 'color: ' + color + ';'
}
function getTimeStamp () {
var date = new Date()
var hours = pad(date.getHours().toString())
var minutes = pad(date.getMinutes().toString())
var seconds = pad(date.getSeconds().toString())
return hours + ':' + minutes + ':' + seconds
}
function pad (str) {
return str.length !== 2 ? 0 + str : str
}
},{"assert":22}],142:[function(require,module,exports){
module.exports = LRU
function LRU (opts) {
if (!(this instanceof LRU)) return new LRU(opts)
if (typeof opts === 'number') opts = {max: opts}
if (!opts) opts = {}
this.cache = {}
this.head = this.tail = null
this.length = 0
this.max = opts.max || 1000
this.maxAge = opts.maxAge || 0
}
Object.defineProperty(LRU.prototype, 'keys', {
get: function () { return Object.keys(this.cache) }
})
LRU.prototype.clear = function () {
this.cache = {}
this.head = this.tail = null
this.length = 0
}
LRU.prototype.remove = function (key) {
if (typeof key !== 'string') key = '' + key
if (!this.cache.hasOwnProperty(key)) return
var element = this.cache[key]
delete this.cache[key]
this._unlink(key, element.prev, element.next)
return element.value
}
LRU.prototype._unlink = function (key, prev, next) {
this.length--
if (this.length === 0) {
this.head = this.tail = null
} else {
if (this.head === key) {
this.head = prev
this.cache[this.head].next = null
} else if (this.tail === key) {
this.tail = next
this.cache[this.tail].prev = null
} else {
this.cache[prev].next = next
this.cache[next].prev = prev
}
}
}
LRU.prototype.peek = function (key) {
if (!this.cache.hasOwnProperty(key)) return
var element = this.cache[key]
if (!this._checkAge(key, element)) return
return element.value
}
LRU.prototype.set = function (key, value) {
if (typeof key !== 'string') key = '' + key
var element
if (this.cache.hasOwnProperty(key)) {
element = this.cache[key]
element.value = value
if (this.maxAge) element.modified = Date.now()
// If it's already the head, there's nothing more to do:
if (key === this.head) return value
this._unlink(key, element.prev, element.next)
} else {
element = {value: value, modified: 0, next: null, prev: null}
if (this.maxAge) element.modified = Date.now()
this.cache[key] = element
// Eviction is only possible if the key didn't already exist:
if (this.length === this.max) this.evict()
}
this.length++
element.next = null
element.prev = this.head
if (this.head) this.cache[this.head].next = key
this.head = key
if (!this.tail) this.tail = key
return value
}
LRU.prototype._checkAge = function (key, element) {
if (this.maxAge && (Date.now() - element.modified) > this.maxAge) {
this.remove(key)
return false
}
return true
}
LRU.prototype.get = function (key) {
if (typeof key !== 'string') key = '' + key
if (!this.cache.hasOwnProperty(key)) return
var element = this.cache[key]
if (!this._checkAge(key, element)) return
if (this.head !== key) {
if (key === this.tail) {
this.tail = element.next
this.cache[this.tail].prev = null
} else {
// Set prev.next -> element.next:
this.cache[element.prev].next = element.next
}
// Set element.next.prev -> element.prev:
this.cache[element.next].prev = element.prev
// Element is the new head
this.cache[this.head].next = key
element.prev = this.head
element.next = null
this.head = key
}
return element.value
}
LRU.prototype.evict = function () {
if (!this.tail) return
this.remove(this.tail)
}
},{}],143:[function(require,module,exports){
var assert = require('nanoassert')
var morph = require('./lib/morph')
var TEXT_NODE = 3
// var DEBUG = false
module.exports = nanomorph
// Morph one tree into another tree
//
// no parent
// -> same: diff and walk children
// -> not same: replace and return
// old node doesn't exist
// -> insert new node
// new node doesn't exist
// -> delete old node
// nodes are not the same
// -> diff nodes and apply patch to old node
// nodes are the same
// -> walk all child nodes and append to old node
function nanomorph (oldTree, newTree, options) {
// if (DEBUG) {
// console.log(
// 'nanomorph\nold\n %s\nnew\n %s',
// oldTree && oldTree.outerHTML,
// newTree && newTree.outerHTML
// )
// }
assert.equal(typeof oldTree, 'object', 'nanomorph: oldTree should be an object')
assert.equal(typeof newTree, 'object', 'nanomorph: newTree should be an object')
if (options && options.childrenOnly) {
updateChildren(newTree, oldTree)
return oldTree
}
assert.notEqual(
newTree.nodeType,
11,
'nanomorph: newTree should have one root node (which is not a DocumentFragment)'
)
return walk(newTree, oldTree)
}
// Walk and morph a dom tree
function walk (newNode, oldNode) {
// if (DEBUG) {
// console.log(
// 'walk\nold\n %s\nnew\n %s',
// oldNode && oldNode.outerHTML,
// newNode && newNode.outerHTML
// )
// }
if (!oldNode) {
return newNode
} else if (!newNode) {
return null
} else if (newNode.isSameNode && newNode.isSameNode(oldNode)) {
return oldNode
} else if (newNode.tagName !== oldNode.tagName || getComponentId(newNode) !== getComponentId(oldNode)) {
return newNode
} else {
morph(newNode, oldNode)
updateChildren(newNode, oldNode)
return oldNode
}
}
function getComponentId (node) {
return node.dataset ? node.dataset.nanomorphComponentId : undefined
}
// Update the children of elements
// (obj, obj) -> null
function updateChildren (newNode, oldNode) {
// if (DEBUG) {
// console.log(
// 'updateChildren\nold\n %s\nnew\n %s',
// oldNode && oldNode.outerHTML,
// newNode && newNode.outerHTML
// )
// }
var oldChild, newChild, morphed, oldMatch
// The offset is only ever increased, and used for [i - offset] in the loop
var offset = 0
for (var i = 0; ; i++) {
oldChild = oldNode.childNodes[i]
newChild = newNode.childNodes[i - offset]
// if (DEBUG) {
// console.log(
// '===\n- old\n %s\n- new\n %s',
// oldChild && oldChild.outerHTML,
// newChild && newChild.outerHTML
// )
// }
// Both nodes are empty, do nothing
if (!oldChild && !newChild) {
break
// There is no new child, remove old
} else if (!newChild) {
oldNode.removeChild(oldChild)
i--
// There is no old child, add new
} else if (!oldChild) {
oldNode.appendChild(newChild)
offset++
// Both nodes are the same, morph
} else if (same(newChild, oldChild)) {
morphed = walk(newChild, oldChild)
if (morphed !== oldChild) {
oldNode.replaceChild(morphed, oldChild)
offset++
}
// Both nodes do not share an ID or a placeholder, try reorder
} else {
oldMatch = null
// Try and find a similar node somewhere in the tree
for (var j = i; j < oldNode.childNodes.length; j++) {
if (same(oldNode.childNodes[j], newChild)) {
oldMatch = oldNode.childNodes[j]
break
}
}
// If there was a node with the same ID or placeholder in the old list
if (oldMatch) {
morphed = walk(newChild, oldMatch)
if (morphed !== oldMatch) offset++
oldNode.insertBefore(morphed, oldChild)
// It's safe to morph two nodes in-place if neither has an ID
} else if (!newChild.id && !oldChild.id) {
morphed = walk(newChild, oldChild)
if (morphed !== oldChild) {
oldNode.replaceChild(morphed, oldChild)
offset++
}
// Insert the node at the index if we couldn't morph or find a matching node
} else {
oldNode.insertBefore(newChild, oldChild)
offset++
}
}
}
}
function same (a, b) {
if (a.id) return a.id === b.id
if (a.isSameNode) return a.isSameNode(b)
if (a.tagName !== b.tagName) return false
if (a.type === TEXT_NODE) return a.nodeValue === b.nodeValue
return false
}
},{"./lib/morph":145,"nanoassert":127}],144:[function(require,module,exports){
module.exports = [
// attribute events (can be set with attributes)
'onclick',
'ondblclick',
'onmousedown',
'onmouseup',
'onmouseover',
'onmousemove',
'onmouseout',
'onmouseenter',
'onmouseleave',
'ontouchcancel',
'ontouchend',
'ontouchmove',
'ontouchstart',
'ondragstart',
'ondrag',
'ondragenter',
'ondragleave',
'ondragover',
'ondrop',
'ondragend',
'onkeydown',
'onkeypress',
'onkeyup',
'onunload',
'onabort',
'onerror',
'onresize',
'onscroll',
'onselect',
'onchange',
'onsubmit',
'onreset',
'onfocus',
'onblur',
'oninput',
'onanimationend',
'onanimationiteration',
'onanimationstart',
// other common events
'oncontextmenu',
'onfocusin',
'onfocusout'
]
},{}],145:[function(require,module,exports){
var events = require('./events')
var eventsLength = events.length
var ELEMENT_NODE = 1
var TEXT_NODE = 3
var COMMENT_NODE = 8
module.exports = morph
// diff elements and apply the resulting patch to the old node
// (obj, obj) -> null
function morph (newNode, oldNode) {
var nodeType = newNode.nodeType
var nodeName = newNode.nodeName
if (nodeType === ELEMENT_NODE) {
copyAttrs(newNode, oldNode)
}
if (nodeType === TEXT_NODE || nodeType === COMMENT_NODE) {
if (oldNode.nodeValue !== newNode.nodeValue) {
oldNode.nodeValue = newNode.nodeValue
}
}
// Some DOM nodes are weird
// https://github.com/patrick-steele-idem/morphdom/blob/master/src/specialElHandlers.js
if (nodeName === 'INPUT') updateInput(newNode, oldNode)
else if (nodeName === 'OPTION') updateOption(newNode, oldNode)
else if (nodeName === 'TEXTAREA') updateTextarea(newNode, oldNode)
copyEvents(newNode, oldNode)
}
function copyAttrs (newNode, oldNode) {
var oldAttrs = oldNode.attributes
var newAttrs = newNode.attributes
var attrNamespaceURI = null
var attrValue = null
var fromValue = null
var attrName = null
var attr = null
for (var i = newAttrs.length - 1; i >= 0; --i) {
attr = newAttrs[i]
attrName = attr.name
attrNamespaceURI = attr.namespaceURI
attrValue = attr.value
if (attrNamespaceURI) {
attrName = attr.localName || attrName
fromValue = oldNode.getAttributeNS(attrNamespaceURI, attrName)
if (fromValue !== attrValue) {
oldNode.setAttributeNS(attrNamespaceURI, attrName, attrValue)
}
} else {
if (!oldNode.hasAttribute(attrName)) {
oldNode.setAttribute(attrName, attrValue)
} else {
fromValue = oldNode.getAttribute(attrName)
if (fromValue !== attrValue) {
// apparently values are always cast to strings, ah well
if (attrValue === 'null' || attrValue === 'undefined') {
oldNode.removeAttribute(attrName)
} else {
oldNode.setAttribute(attrName, attrValue)
}
}
}
}
}
// Remove any extra attributes found on the original DOM element that
// weren't found on the target element.
for (var j = oldAttrs.length - 1; j >= 0; --j) {
attr = oldAttrs[j]
if (attr.specified !== false) {
attrName = attr.name
attrNamespaceURI = attr.namespaceURI
if (attrNamespaceURI) {
attrName = attr.localName || attrName
if (!newNode.hasAttributeNS(attrNamespaceURI, attrName)) {
oldNode.removeAttributeNS(attrNamespaceURI, attrName)
}
} else {
if (!newNode.hasAttributeNS(null, attrName)) {
oldNode.removeAttribute(attrName)
}
}
}
}
}
function copyEvents (newNode, oldNode) {
for (var i = 0; i < eventsLength; i++) {
var ev = events[i]
if (newNode[ev]) { // if new element has a whitelisted attribute
oldNode[ev] = newNode[ev] // update existing element
} else if (oldNode[ev]) { // if existing element has it and new one doesnt
oldNode[ev] = undefined // remove it from existing element
}
}
}
function updateOption (newNode, oldNode) {
updateAttribute(newNode, oldNode, 'selected')
}
// The "value" attribute is special for the <input> element since it sets the
// initial value. Changing the "value" attribute without changing the "value"
// property will have no effect since it is only used to the set the initial
// value. Similar for the "checked" attribute, and "disabled".
function updateInput (newNode, oldNode) {
var newValue = newNode.value
var oldValue = oldNode.value
updateAttribute(newNode, oldNode, 'checked')
updateAttribute(newNode, oldNode, 'disabled')
// The "indeterminate" property can not be set using an HTML attribute.
// See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox
if (newNode.indeterminate !== oldNode.indeterminate) {
oldNode.indeterminate = newNode.indeterminate
}
// Persist file value since file inputs can't be changed programatically
if (oldNode.type === 'file') return
if (newValue !== oldValue) {
oldNode.setAttribute('value', newValue)
oldNode.value = newValue
}
if (newValue === 'null') {
oldNode.value = ''
oldNode.removeAttribute('value')
}
if (!newNode.hasAttributeNS(null, 'value')) {
oldNode.removeAttribute('value')
} else if (oldNode.type === 'range') {
// this is so elements like slider move their UI thingy
oldNode.value = newValue
}
}
function updateTextarea (newNode, oldNode) {
var newValue = newNode.value
if (newValue !== oldNode.value) {
oldNode.value = newValue
}
if (oldNode.firstChild && oldNode.firstChild.nodeValue !== newValue) {
// Needed for IE. Apparently IE sets the placeholder as the
// node value and vise versa. This ignores an empty update.
if (newValue === '' && oldNode.firstChild.nodeValue === oldNode.placeholder) {
return
}
oldNode.firstChild.nodeValue = newValue
}
}
function updateAttribute (newNode, oldNode, name) {
if (newNode[name] !== oldNode[name]) {
oldNode[name] = newNode[name]
if (newNode[name]) {
oldNode.setAttribute(name, '')
} else {
oldNode.removeAttribute(name)
}
}
}
},{"./events":144}],146:[function(require,module,exports){
var reg = /([^?=&]+)(=([^&]*))?/g
var assert = require('assert')
module.exports = qs
function qs (url) {
assert.equal(typeof url, 'string', 'nanoquery: url should be type string')
var obj = {}
url.replace(/^.*\?/, '').replace(reg, function (a0, a1, a2, a3) {
var value = decodeURIComponent(a3)
var key = decodeURIComponent(a1)
if (obj.hasOwnProperty(key)) {
if (Array.isArray(obj[key])) obj[key].push(value)
else obj[key] = [obj[key], value]
} else {
obj[key] = value
}
})
return obj
}
},{"assert":127}],147:[function(require,module,exports){
'use strict'
var assert = require('assert')
module.exports = nanoraf
// Only call RAF when needed
// (fn, fn?) -> fn
function nanoraf (render, raf) {
assert.equal(typeof render, 'function', 'nanoraf: render should be a function')
assert.ok(typeof raf === 'function' || typeof raf === 'undefined', 'nanoraf: raf should be a function or undefined')
if (!raf) raf = window.requestAnimationFrame
var redrawScheduled = false
var args = null
return function frame () {
if (args === null && !redrawScheduled) {
redrawScheduled = true
raf(function redraw () {
redrawScheduled = false
var length = args.length
var _args = new Array(length)
for (var i = 0; i < length; i++) _args[i] = args[i]
render.apply(render, _args)
args = null
})
}
args = arguments
}
}
},{"assert":127}],148:[function(require,module,exports){
var assert = require('assert')
var wayfarer = require('wayfarer')
// electron support
var isLocalFile = (/file:\/\//.test(
typeof window === 'object' &&
window.location &&
window.location.origin
))
/* eslint-disable no-useless-escape */
var electron = '^(file:\/\/|\/)(.*\.html?\/?)?'
var protocol = '^(http(s)?(:\/\/))?(www\.)?'
var domain = '[a-zA-Z0-9-_\.]+(:[0-9]{1,5})?(\/{1})?'
var qs = '[\?].*$'
/* eslint-enable no-useless-escape */
var stripElectron = new RegExp(electron)
var prefix = new RegExp(protocol + domain)
var normalize = new RegExp('#')
var suffix = new RegExp(qs)
module.exports = Nanorouter
function Nanorouter (opts) {
if (!(this instanceof Nanorouter)) return new Nanorouter(opts)
opts = opts || {}
this.router = wayfarer(opts.default || '/404')
}
Nanorouter.prototype.on = function (routename, listener) {
assert.equal(typeof routename, 'string')
routename = routename.replace(/^[#/]/, '')
this.router.on(routename, listener)
}
Nanorouter.prototype.emit = function (routename) {
assert.equal(typeof routename, 'string')
routename = pathname(routename, isLocalFile)
return this.router.emit(routename)
}
Nanorouter.prototype.match = function (routename) {
assert.equal(typeof routename, 'string')
routename = pathname(routename, isLocalFile)
return this.router.match(routename)
}
// replace everything in a route but the pathname and hash
function pathname (routename, isElectron) {
if (isElectron) routename = routename.replace(stripElectron, '')
else routename = routename.replace(prefix, '')
return decodeURI(routename.replace(suffix, '').replace(normalize, '/'))
}
},{"assert":127,"wayfarer":225}],149:[function(require,module,exports){
var assert = require('assert')
var hasWindow = typeof window !== 'undefined'
function createScheduler () {
var scheduler
if (hasWindow) {
if (!window._nanoScheduler) window._nanoScheduler = new NanoScheduler(true)
scheduler = window._nanoScheduler
} else {
scheduler = new NanoScheduler()
}
return scheduler
}
function NanoScheduler (hasWindow) {
this.hasWindow = hasWindow
this.hasIdle = this.hasWindow && window.requestIdleCallback
this.method = this.hasIdle ? window.requestIdleCallback.bind(window) : this.setTimeout
this.scheduled = false
this.queue = []
}
NanoScheduler.prototype.push = function (cb) {
assert.equal(typeof cb, 'function', 'nanoscheduler.push: cb should be type function')
this.queue.push(cb)
this.schedule()
}
NanoScheduler.prototype.schedule = function () {
if (this.scheduled) return
this.scheduled = true
var self = this
this.method(function (idleDeadline) {
var cb
while (self.queue.length && idleDeadline.timeRemaining() > 0) {
cb = self.queue.shift()
cb(idleDeadline)
}
self.scheduled = false
if (self.queue.length) self.schedule()
})
}
NanoScheduler.prototype.setTimeout = function (cb) {
setTimeout(cb, 0, {
timeRemaining: function () {
return 1
}
})
}
module.exports = createScheduler
},{"assert":127}],150:[function(require,module,exports){
var scheduler = require('nanoscheduler')()
var assert = require('assert')
var perf
nanotiming.disabled = true
try {
perf = window.performance
nanotiming.disabled = window.localStorage.DISABLE_NANOTIMING === 'true' || !perf.mark
} catch (e) { }
module.exports = nanotiming
function nanotiming (name) {
assert.equal(typeof name, 'string', 'nanotiming: name should be type string')
if (nanotiming.disabled) return noop
var uuid = (perf.now() * 10000).toFixed() % Number.MAX_SAFE_INTEGER
var startName = 'start-' + uuid + '-' + name
perf.mark(startName)
function end (cb) {
var endName = 'end-' + uuid + '-' + name
perf.mark(endName)
scheduler.push(function () {
var err = null
try {
var measureName = name + ' [' + uuid + ']'
perf.measure(measureName, startName, endName)
perf.clearMarks(startName)
perf.clearMarks(endName)
} catch (e) { err = e }
if (cb) cb(err, name)
})
}
end.uuid = uuid
return end
}
function noop (cb) {
if (cb) {
scheduler.push(function () {
cb(new Error('nanotiming: performance API unavailable'))
})
}
}
},{"assert":127,"nanoscheduler":149}],151:[function(require,module,exports){
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
'use strict';
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
},{}],152:[function(require,module,exports){
var assert = require('assert')
module.exports = objectChangeCallsite
function objectChangeCallsite (target, callback) {
assert.equal(typeof target, 'object', 'object-change-callsite: target should be type object')
assert.equal(typeof callback, 'function', 'object-change-callsite: callback should be type function')
return new Proxy(target, {
set: function (obj, prop, value) {
var err = new Error()
var trace = strip(err.stack)
callback(prop, value, trace)
obj[prop] = value
return true
},
deleteProperty: function (target, prop) {
var err = new Error()
var trace = strip(err.stack)
callback(prop, undefined, trace)
if (prop in target) {
delete target[prop]
return true
}
return false
}
})
}
function strip (str) {
var arr = str.split('\n')
arr = arr.length > 2 ? arr.slice(2) : arr
arr[0] = arr[0].replace(/^ {4}at /, '')
return '\n' + arr.join('\n')
}
},{"assert":22}],153:[function(require,module,exports){
var hasMap = typeof Map === 'function' && Map.prototype;
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
var mapForEach = hasMap && Map.prototype.forEach;
var hasSet = typeof Set === 'function' && Set.prototype;
var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;
var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;
var setForEach = hasSet && Set.prototype.forEach;
var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype;
var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype;
var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype;
var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;
var booleanValueOf = Boolean.prototype.valueOf;
var objectToString = Object.prototype.toString;
var functionToString = Function.prototype.toString;
var $match = String.prototype.match;
var $slice = String.prototype.slice;
var $replace = String.prototype.replace;
var $toUpperCase = String.prototype.toUpperCase;
var $toLowerCase = String.prototype.toLowerCase;
var $test = RegExp.prototype.test;
var $concat = Array.prototype.concat;
var $join = Array.prototype.join;
var $arrSlice = Array.prototype.slice;
var $floor = Math.floor;
var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null;
var gOPS = Object.getOwnPropertySymbols;
var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null;
var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object';
// ie, `has-tostringtag/shams
var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol')
? Symbol.toStringTag
: null;
var isEnumerable = Object.prototype.propertyIsEnumerable;
var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || (
[].__proto__ === Array.prototype // eslint-disable-line no-proto
? function (O) {
return O.__proto__; // eslint-disable-line no-proto
}
: null
);
function addNumericSeparator(num, str) {
if (
num === Infinity
|| num === -Infinity
|| num !== num
|| (num && num > -1000 && num < 1000)
|| $test.call(/e/, str)
) {
return str;
}
var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;
if (typeof num === 'number') {
var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num)
if (int !== num) {
var intStr = String(int);
var dec = $slice.call(str, intStr.length + 1);
return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, '');
}
}
return $replace.call(str, sepRegex, '$&_');
}
var utilInspect = require('./util.inspect');
var inspectCustom = utilInspect.custom;
var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null;
module.exports = function inspect_(obj, options, depth, seen) {
var opts = options || {};
if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) {
throw new TypeError('option "quoteStyle" must be "single" or "double"');
}
if (
has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number'
? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity
: opts.maxStringLength !== null
)
) {
throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');
}
var customInspect = has(opts, 'customInspect') ? opts.customInspect : true;
if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') {
throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`');
}
if (
has(opts, 'indent')
&& opts.indent !== null
&& opts.indent !== '\t'
&& !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)
) {
throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');
}
if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') {
throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');
}
var numericSeparator = opts.numericSeparator;
if (typeof obj === 'undefined') {
return 'undefined';
}
if (obj === null) {
return 'null';
}
if (typeof obj === 'boolean') {
return obj ? 'true' : 'false';
}
if (typeof obj === 'string') {
return inspectString(obj, opts);
}
if (typeof obj === 'number') {
if (obj === 0) {
return Infinity / obj > 0 ? '0' : '-0';
}
var str = String(obj);
return numericSeparator ? addNumericSeparator(obj, str) : str;
}
if (typeof obj === 'bigint') {
var bigIntStr = String(obj) + 'n';
return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr;
}
var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;
if (typeof depth === 'undefined') { depth = 0; }
if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {
return isArray(obj) ? '[Array]' : '[Object]';
}
var indent = getIndent(opts, depth);
if (typeof seen === 'undefined') {
seen = [];
} else if (indexOf(seen, obj) >= 0) {
return '[Circular]';
}
function inspect(value, from, noIndent) {
if (from) {
seen = $arrSlice.call(seen);
seen.push(from);
}
if (noIndent) {
var newOpts = {
depth: opts.depth
};
if (has(opts, 'quoteStyle')) {
newOpts.quoteStyle = opts.quoteStyle;
}
return inspect_(value, newOpts, depth + 1, seen);
}
return inspect_(value, opts, depth + 1, seen);
}
if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable
var name = nameOf(obj);
var keys = arrObjKeys(obj, inspect);
return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : '');
}
if (isSymbol(obj)) {
var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj);
return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString;
}
if (isElement(obj)) {
var s = '<' + $toLowerCase.call(String(obj.nodeName));
var attrs = obj.attributes || [];
for (var i = 0; i < attrs.length; i++) {
s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts);
}
s += '>';
if (obj.childNodes && obj.childNodes.length) { s += '...'; }
s += '</' + $toLowerCase.call(String(obj.nodeName)) + '>';
return s;
}
if (isArray(obj)) {
if (obj.length === 0) { return '[]'; }
var xs = arrObjKeys(obj, inspect);
if (indent && !singleLineValues(xs)) {
return '[' + indentedJoin(xs, indent) + ']';
}
return '[ ' + $join.call(xs, ', ') + ' ]';
}
if (isError(obj)) {
var parts = arrObjKeys(obj, inspect);
if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) {
return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }';
}
if (parts.length === 0) { return '[' + String(obj) + ']'; }
return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }';
}
if (typeof obj === 'object' && customInspect) {
if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) {
return utilInspect(obj, { depth: maxDepth - depth });
} else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') {
return obj.inspect();
}
}
if (isMap(obj)) {
var mapParts = [];
if (mapForEach) {
mapForEach.call(obj, function (value, key) {
mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj));
});
}
return collectionOf('Map', mapSize.call(obj), mapParts, indent);
}
if (isSet(obj)) {
var setParts = [];
if (setForEach) {
setForEach.call(obj, function (value) {
setParts.push(inspect(value, obj));
});
}
return collectionOf('Set', setSize.call(obj), setParts, indent);
}
if (isWeakMap(obj)) {
return weakCollectionOf('WeakMap');
}
if (isWeakSet(obj)) {
return weakCollectionOf('WeakSet');
}
if (isWeakRef(obj)) {
return weakCollectionOf('WeakRef');
}
if (isNumber(obj)) {
return markBoxed(inspect(Number(obj)));
}
if (isBigInt(obj)) {
return markBoxed(inspect(bigIntValueOf.call(obj)));
}
if (isBoolean(obj)) {
return markBoxed(booleanValueOf.call(obj));
}
if (isString(obj)) {
return markBoxed(inspect(String(obj)));
}
if (!isDate(obj) && !isRegExp(obj)) {
var ys = arrObjKeys(obj, inspect);
var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object;
var protoTag = obj instanceof Object ? '' : 'null prototype';
var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : '';
var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : '';
var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : '');
if (ys.length === 0) { return tag + '{}'; }
if (indent) {
return tag + '{' + indentedJoin(ys, indent) + '}';
}
return tag + '{ ' + $join.call(ys, ', ') + ' }';
}
return String(obj);
};
function wrapQuotes(s, defaultStyle, opts) {
var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'";
return quoteChar + s + quoteChar;
}
function quote(s) {
return $replace.call(String(s), /"/g, '&quot;');
}
function isArray(obj) { return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isDate(obj) { return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isError(obj) { return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isString(obj) { return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isNumber(obj) { return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }
// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives
function isSymbol(obj) {
if (hasShammedSymbols) {
return obj && typeof obj === 'object' && obj instanceof Symbol;
}
if (typeof obj === 'symbol') {
return true;
}
if (!obj || typeof obj !== 'object' || !symToString) {
return false;
}
try {
symToString.call(obj);
return true;
} catch (e) {}
return false;
}
function isBigInt(obj) {
if (!obj || typeof obj !== 'object' || !bigIntValueOf) {
return false;
}
try {
bigIntValueOf.call(obj);
return true;
} catch (e) {}
return false;
}
var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; };
function has(obj, key) {
return hasOwn.call(obj, key);
}
function toStr(obj) {
return objectToString.call(obj);
}
function nameOf(f) {
if (f.name) { return f.name; }
var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/);
if (m) { return m[1]; }
return null;
}
function indexOf(xs, x) {
if (xs.indexOf) { return xs.indexOf(x); }
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) { return i; }
}
return -1;
}
function isMap(x) {
if (!mapSize || !x || typeof x !== 'object') {
return false;
}
try {
mapSize.call(x);
try {
setSize.call(x);
} catch (s) {
return true;
}
return x instanceof Map; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isWeakMap(x) {
if (!weakMapHas || !x || typeof x !== 'object') {
return false;
}
try {
weakMapHas.call(x, weakMapHas);
try {
weakSetHas.call(x, weakSetHas);
} catch (s) {
return true;
}
return x instanceof WeakMap; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isWeakRef(x) {
if (!weakRefDeref || !x || typeof x !== 'object') {
return false;
}
try {
weakRefDeref.call(x);
return true;
} catch (e) {}
return false;
}
function isSet(x) {
if (!setSize || !x || typeof x !== 'object') {
return false;
}
try {
setSize.call(x);
try {
mapSize.call(x);
} catch (m) {
return true;
}
return x instanceof Set; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isWeakSet(x) {
if (!weakSetHas || !x || typeof x !== 'object') {
return false;
}
try {
weakSetHas.call(x, weakSetHas);
try {
weakMapHas.call(x, weakMapHas);
} catch (s) {
return true;
}
return x instanceof WeakSet; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isElement(x) {
if (!x || typeof x !== 'object') { return false; }
if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
return true;
}
return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function';
}
function inspectString(str, opts) {
if (str.length > opts.maxStringLength) {
var remaining = str.length - opts.maxStringLength;
var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : '');
return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer;
}
// eslint-disable-next-line no-control-regex
var s = $replace.call($replace.call(str, /(['\\])/g, '\\$1'), /[\x00-\x1f]/g, lowbyte);
return wrapQuotes(s, 'single', opts);
}
function lowbyte(c) {
var n = c.charCodeAt(0);
var x = {
8: 'b',
9: 't',
10: 'n',
12: 'f',
13: 'r'
}[n];
if (x) { return '\\' + x; }
return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16));
}
function markBoxed(str) {
return 'Object(' + str + ')';
}
function weakCollectionOf(type) {
return type + ' { ? }';
}
function collectionOf(type, size, entries, indent) {
var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', ');
return type + ' (' + size + ') {' + joinedEntries + '}';
}
function singleLineValues(xs) {
for (var i = 0; i < xs.length; i++) {
if (indexOf(xs[i], '\n') >= 0) {
return false;
}
}
return true;
}
function getIndent(opts, depth) {
var baseIndent;
if (opts.indent === '\t') {
baseIndent = '\t';
} else if (typeof opts.indent === 'number' && opts.indent > 0) {
baseIndent = $join.call(Array(opts.indent + 1), ' ');
} else {
return null;
}
return {
base: baseIndent,
prev: $join.call(Array(depth + 1), baseIndent)
};
}
function indentedJoin(xs, indent) {
if (xs.length === 0) { return ''; }
var lineJoiner = '\n' + indent.prev + indent.base;
return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev;
}
function arrObjKeys(obj, inspect) {
var isArr = isArray(obj);
var xs = [];
if (isArr) {
xs.length = obj.length;
for (var i = 0; i < obj.length; i++) {
xs[i] = has(obj, i) ? inspect(obj[i], obj) : '';
}
}
var syms = typeof gOPS === 'function' ? gOPS(obj) : [];
var symMap;
if (hasShammedSymbols) {
symMap = {};
for (var k = 0; k < syms.length; k++) {
symMap['$' + syms[k]] = syms[k];
}
}
for (var key in obj) { // eslint-disable-line no-restricted-syntax
if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue
if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) {
// this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section
continue; // eslint-disable-line no-restricted-syntax, no-continue
} else if ($test.call(/[^\w$]/, key)) {
xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj));
} else {
xs.push(key + ': ' + inspect(obj[key], obj));
}
}
if (typeof gOPS === 'function') {
for (var j = 0; j < syms.length; j++) {
if (isEnumerable.call(obj, syms[j])) {
xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj));
}
}
}
return xs;
}
},{"./util.inspect":34}],154:[function(require,module,exports){
/* global MutationObserver */
var document = require('global/document')
var window = require('global/window')
var watch = Object.create(null)
var KEY_ID = 'onloadid' + Math.random().toString(36).slice(2)
var KEY_ATTR = 'data-' + KEY_ID
var INDEX = 0
if (window && window.MutationObserver) {
var observer = new MutationObserver(function (mutations) {
if (Object.keys(watch).length < 1) return
for (var i = 0; i < mutations.length; i++) {
if (mutations[i].attributeName === KEY_ATTR) {
eachAttr(mutations[i], turnon, turnoff)
continue
}
eachMutation(mutations[i].removedNodes, function (index, el) {
if (!document.documentElement.contains(el)) turnoff(index, el)
})
eachMutation(mutations[i].addedNodes, function (index, el) {
if (document.documentElement.contains(el)) turnon(index, el)
})
}
})
observer.observe(document.documentElement, {
childList: true,
subtree: true,
attributes: true,
attributeOldValue: true,
attributeFilter: [KEY_ATTR]
})
}
module.exports = function onload (el, on, off, caller) {
on = on || function () {}
off = off || function () {}
el.setAttribute(KEY_ATTR, 'o' + INDEX)
watch['o' + INDEX] = [on, off, 0, caller || onload.caller]
INDEX += 1
return el
}
module.exports.KEY_ATTR = KEY_ATTR
module.exports.KEY_ID = KEY_ID
function turnon (index, el) {
if (watch[index][0] && watch[index][2] === 0) {
watch[index][0](el)
watch[index][2] = 1
}
}
function turnoff (index, el) {
if (watch[index][1] && watch[index][2] === 1) {
watch[index][1](el)
watch[index][2] = 0
}
}
function eachAttr (mutation, on, off) {
var newValue = mutation.target.getAttribute(KEY_ATTR)
if (sameOrigin(mutation.oldValue, newValue)) {
watch[newValue] = watch[mutation.oldValue]
return
}
if (watch[mutation.oldValue]) {
off(mutation.oldValue, mutation.target)
}
if (watch[newValue]) {
on(newValue, mutation.target)
}
}
function sameOrigin (oldValue, newValue) {
if (!oldValue || !newValue) return false
return watch[oldValue][3] === watch[newValue][3]
}
function eachMutation (nodes, fn) {
var keys = Object.keys(watch)
for (var i = 0; i < nodes.length; i++) {
if (nodes[i] && nodes[i].getAttribute && nodes[i].getAttribute(KEY_ATTR)) {
var onloadid = nodes[i].getAttribute(KEY_ATTR)
keys.forEach(function (k) {
if (onloadid === k) {
fn(k, nodes[i])
}
})
}
if (nodes[i] && nodes[i].childNodes.length > 0) {
eachMutation(nodes[i].childNodes, fn)
}
}
}
},{"global/document":87,"global/window":88}],155:[function(require,module,exports){
var scheduler = require('nanoscheduler')()
var assert = require('assert')
var entryTypes = [
'frame',
'measure',
'navigation',
'resource',
'longtask'
]
module.exports = onPerformance
function onPerformance (cb) {
assert.equal(typeof cb, 'function', 'on-performance: cb should be type function')
var PerformanceObserver = typeof window !== 'undefined' && window.PerformanceObserver
if (!PerformanceObserver) return
// Enable singleton.
if (window._onperformance) {
window._onperformance.push(cb)
return stop
}
window._onperformance = [cb]
var observer = new PerformanceObserver(parseEntries)
setTimeout(function () {
parseEntries(window.performance)
observer.observe({ entryTypes: entryTypes })
}, 0)
return stop
function stop () {
window._onperformance.splice(window._onperformance.indexOf(cb), 1)
}
function parseEntries (list) {
list.getEntries().forEach(function (entry) {
scheduler.push(function () {
clear(entry)
window._onperformance.forEach(function (cb) {
cb(entry)
})
})
})
}
// Navigation, longtask and frame don't have a clear method (yet)
// Resource timings can only be cleared in bulk
// see: https://developer.mozilla.org/en-US/docs/Web/API/Performance/clearMeasures
function clear (entry) {
var type = entry.entryType
if (type === 'measure') window.performance.clearMeasures(entry.name)
else if (type === 'resource') window.performance.clearResourceTimings()
}
}
},{"assert":127,"nanoscheduler":149}],156:[function(require,module,exports){
/**
* Compiles a querystring
* Returns string representation of the object
*
* @param {Object}
* @api private
*/
exports.encode = function (obj) {
var str = '';
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
if (str.length) str += '&';
str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
}
}
return str;
};
/**
* Parses a simple querystring into an object
*
* @param {String} qs
* @api private
*/
exports.decode = function(qs){
var qry = {};
var pairs = qs.split('&');
for (var i = 0, l = pairs.length; i < l; i++) {
var pair = pairs[i].split('=');
qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return qry;
};
},{}],157:[function(require,module,exports){
/**
* Parses an URI
*
* @author Steven Levithan <stevenlevithan.com> (MIT license)
* @api private
*/
var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
var parts = [
'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
];
module.exports = function parseuri(str) {
var src = str,
b = str.indexOf('['),
e = str.indexOf(']');
if (b != -1 && e != -1) {
str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
}
var m = re.exec(str || ''),
uri = {},
i = 14;
while (i--) {
uri[parts[i]] = m[i] || '';
}
if (b != -1 && e != -1) {
uri.source = src;
uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
uri.ipv6uri = true;
}
uri.pathNames = pathNames(uri, uri['path']);
uri.queryKey = queryKey(uri, uri['query']);
return uri;
};
function pathNames(obj, path) {
var regx = /\/{2,9}/g,
names = path.replace(regx, "/").split("/");
if (path.substr(0, 1) == '/' || path.length === 0) {
names.splice(0, 1);
}
if (path.substr(path.length - 1, 1) == '/') {
names.splice(names.length - 1, 1);
}
return names;
}
function queryKey(uri, query) {
var data = {};
query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
if ($1) {
data[$1] = $2;
}
});
return data;
}
},{}],158:[function(require,module,exports){
module.exports = plucker
function plucker(path, object) {
return arguments.length >= 2
? pluck(path)(object)
: pluck(path)
}
function pluck(path) {
path = typeof path === 'string'
? String(path).trim().split('.')
: path
if (path.length < 2) {
path = path[0]
return pluckSingle
} else {
var l = path.length
return pluckPath
}
function pluckSingle(object) {
return object[path]
}
function pluckPath(object) {
for (var i = 0; i < l; i++) {
if (typeof object === 'undefined') break
object = object[path[i]]
}
return object
}
}
},{}],159:[function(require,module,exports){
module.exports = prettierBytes
function prettierBytes (num) {
if (typeof num !== 'number' || isNaN(num)) {
throw new TypeError('Expected a number, got ' + typeof num)
}
var neg = num < 0
var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
if (neg) {
num = -num
}
if (num < 1) {
return (neg ? '-' : '') + num + ' B'
}
var exponent = Math.min(Math.floor(Math.log(num) / Math.log(1000)), units.length - 1)
num = Number(num / Math.pow(1000, exponent))
var unit = units[exponent]
if (num >= 10 || num % 1 === 0) {
// Do not show decimals when the number is two-digit, or if the number has no
// decimal component.
return (neg ? '-' : '') + num.toFixed(0) + ' ' + unit
} else {
return (neg ? '-' : '') + num.toFixed(1) + ' ' + unit
}
}
},{}],160:[function(require,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; };
},{}],161:[function(require,module,exports){
'use strict';
var replace = String.prototype.replace;
var percentTwenties = /%20/g;
var Format = {
RFC1738: 'RFC1738',
RFC3986: 'RFC3986'
};
module.exports = {
'default': Format.RFC3986,
formatters: {
RFC1738: function (value) {
return replace.call(value, percentTwenties, '+');
},
RFC3986: function (value) {
return String(value);
}
},
RFC1738: Format.RFC1738,
RFC3986: Format.RFC3986
};
},{}],162:[function(require,module,exports){
'use strict';
var stringify = require('./stringify');
var parse = require('./parse');
var formats = require('./formats');
module.exports = {
formats: formats,
parse: parse,
stringify: stringify
};
},{"./formats":161,"./parse":163,"./stringify":164}],163:[function(require,module,exports){
'use strict';
var utils = require('./utils');
var has = Object.prototype.hasOwnProperty;
var isArray = Array.isArray;
var defaults = {
allowDots: false,
allowPrototypes: false,
allowSparse: false,
arrayLimit: 20,
charset: 'utf-8',
charsetSentinel: false,
comma: false,
decoder: utils.decode,
delimiter: '&',
depth: 5,
ignoreQueryPrefix: false,
interpretNumericEntities: false,
parameterLimit: 1000,
parseArrays: true,
plainObjects: false,
strictNullHandling: false
};
var interpretNumericEntities = function (str) {
return str.replace(/&#(\d+);/g, function ($0, numberStr) {
return String.fromCharCode(parseInt(numberStr, 10));
});
};
var parseArrayValue = function (val, options) {
if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) {
return val.split(',');
}
return val;
};
// This is what browsers will submit when the ✓ character occurs in an
// application/x-www-form-urlencoded body and the encoding of the page containing
// the form is iso-8859-1, or when the submitted form has an accept-charset
// attribute of iso-8859-1. Presumably also with other charsets that do not contain
// the ✓ character, such as us-ascii.
var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('&#10003;')
// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded.
var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓')
var parseValues = function parseQueryStringValues(str, options) {
var obj = { __proto__: null };
var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
var parts = cleanStr.split(options.delimiter, limit);
var skipIndex = -1; // Keep track of where the utf8 sentinel was found
var i;
var charset = options.charset;
if (options.charsetSentinel) {
for (i = 0; i < parts.length; ++i) {
if (parts[i].indexOf('utf8=') === 0) {
if (parts[i] === charsetSentinel) {
charset = 'utf-8';
} else if (parts[i] === isoSentinel) {
charset = 'iso-8859-1';
}
skipIndex = i;
i = parts.length; // The eslint settings do not allow break;
}
}
}
for (i = 0; i < parts.length; ++i) {
if (i === skipIndex) {
continue;
}
var part = parts[i];
var bracketEqualsPos = part.indexOf(']=');
var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;
var key, val;
if (pos === -1) {
key = options.decoder(part, defaults.decoder, charset, 'key');
val = options.strictNullHandling ? null : '';
} else {
key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key');
val = utils.maybeMap(
parseArrayValue(part.slice(pos + 1), options),
function (encodedVal) {
return options.decoder(encodedVal, defaults.decoder, charset, 'value');
}
);
}
if (val && options.interpretNumericEntities && charset === 'iso-8859-1') {
val = interpretNumericEntities(val);
}
if (part.indexOf('[]=') > -1) {
val = isArray(val) ? [val] : val;
}
if (has.call(obj, key)) {
obj[key] = utils.combine(obj[key], val);
} else {
obj[key] = val;
}
}
return obj;
};
var parseObject = function (chain, val, options, valuesParsed) {
var leaf = valuesParsed ? val : parseArrayValue(val, options);
for (var i = chain.length - 1; i >= 0; --i) {
var obj;
var root = chain[i];
if (root === '[]' && options.parseArrays) {
obj = [].concat(leaf);
} else {
obj = options.plainObjects ? Object.create(null) : {};
var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
var index = parseInt(cleanRoot, 10);
if (!options.parseArrays && cleanRoot === '') {
obj = { 0: leaf };
} else if (
!isNaN(index)
&& root !== cleanRoot
&& String(index) === cleanRoot
&& index >= 0
&& (options.parseArrays && index <= options.arrayLimit)
) {
obj = [];
obj[index] = leaf;
} else if (cleanRoot !== '__proto__') {
obj[cleanRoot] = leaf;
}
}
leaf = obj;
}
return leaf;
};
var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) {
if (!givenKey) {
return;
}
// Transform dot notation to bracket notation
var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;
// The regex chunks
var brackets = /(\[[^[\]]*])/;
var child = /(\[[^[\]]*])/g;
// Get the parent
var segment = options.depth > 0 && brackets.exec(key);
var parent = segment ? key.slice(0, segment.index) : key;
// Stash the parent if it exists
var keys = [];
if (parent) {
// If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties
if (!options.plainObjects && has.call(Object.prototype, parent)) {
if (!options.allowPrototypes) {
return;
}
}
keys.push(parent);
}
// Loop through children appending to the array until we hit depth
var i = 0;
while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) {
i += 1;
if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
if (!options.allowPrototypes) {
return;
}
}
keys.push(segment[1]);
}
// If there's a remainder, just add whatever is left
if (segment) {
keys.push('[' + key.slice(segment.index) + ']');
}
return parseObject(keys, val, options, valuesParsed);
};
var normalizeParseOptions = function normalizeParseOptions(opts) {
if (!opts) {
return defaults;
}
if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') {
throw new TypeError('Decoder has to be a function.');
}
if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
}
var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset;
return {
allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,
allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes,
allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse,
arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit,
charset: charset,
charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma,
decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder,
delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter,
// eslint-disable-next-line no-implicit-coercion, no-extra-parens
depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth,
ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities,
parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit,
parseArrays: opts.parseArrays !== false,
plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects,
strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
};
};
module.exports = function (str, opts) {
var options = normalizeParseOptions(opts);
if (str === '' || str === null || typeof str === 'undefined') {
return options.plainObjects ? Object.create(null) : {};
}
var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
var obj = options.plainObjects ? Object.create(null) : {};
// Iterate over the keys and setup the new object
var keys = Object.keys(tempObj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string');
obj = utils.merge(obj, newObj, options);
}
if (options.allowSparse === true) {
return obj;
}
return utils.compact(obj);
};
},{"./utils":165}],164:[function(require,module,exports){
'use strict';
var getSideChannel = require('side-channel');
var utils = require('./utils');
var formats = require('./formats');
var has = Object.prototype.hasOwnProperty;
var arrayPrefixGenerators = {
brackets: function brackets(prefix) {
return prefix + '[]';
},
comma: 'comma',
indices: function indices(prefix, key) {
return prefix + '[' + key + ']';
},
repeat: function repeat(prefix) {
return prefix;
}
};
var isArray = Array.isArray;
var push = Array.prototype.push;
var pushToArray = function (arr, valueOrArray) {
push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]);
};
var toISO = Date.prototype.toISOString;
var defaultFormat = formats['default'];
var defaults = {
addQueryPrefix: false,
allowDots: false,
charset: 'utf-8',
charsetSentinel: false,
delimiter: '&',
encode: true,
encoder: utils.encode,
encodeValuesOnly: false,
format: defaultFormat,
formatter: formats.formatters[defaultFormat],
// deprecated
indices: false,
serializeDate: function serializeDate(date) {
return toISO.call(date);
},
skipNulls: false,
strictNullHandling: false
};
var isNonNullishPrimitive = function isNonNullishPrimitive(v) {
return typeof v === 'string'
|| typeof v === 'number'
|| typeof v === 'boolean'
|| typeof v === 'symbol'
|| typeof v === 'bigint';
};
var sentinel = {};
var stringify = function stringify(
object,
prefix,
generateArrayPrefix,
commaRoundTrip,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
format,
formatter,
encodeValuesOnly,
charset,
sideChannel
) {
var obj = object;
var tmpSc = sideChannel;
var step = 0;
var findFlag = false;
while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) {
// Where object last appeared in the ref tree
var pos = tmpSc.get(object);
step += 1;
if (typeof pos !== 'undefined') {
if (pos === step) {
throw new RangeError('Cyclic object value');
} else {
findFlag = true; // Break while
}
}
if (typeof tmpSc.get(sentinel) === 'undefined') {
step = 0;
}
}
if (typeof filter === 'function') {
obj = filter(prefix, obj);
} else if (obj instanceof Date) {
obj = serializeDate(obj);
} else if (generateArrayPrefix === 'comma' && isArray(obj)) {
obj = utils.maybeMap(obj, function (value) {
if (value instanceof Date) {
return serializeDate(value);
}
return value;
});
}
if (obj === null) {
if (strictNullHandling) {
return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix;
}
obj = '';
}
if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) {
if (encoder) {
var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format);
return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))];
}
return [formatter(prefix) + '=' + formatter(String(obj))];
}
var values = [];
if (typeof obj === 'undefined') {
return values;
}
var objKeys;
if (generateArrayPrefix === 'comma' && isArray(obj)) {
// we need to join elements in
if (encodeValuesOnly && encoder) {
obj = utils.maybeMap(obj, encoder);
}
objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }];
} else if (isArray(filter)) {
objKeys = filter;
} else {
var keys = Object.keys(obj);
objKeys = sort ? keys.sort(sort) : keys;
}
var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? prefix + '[]' : prefix;
for (var j = 0; j < objKeys.length; ++j) {
var key = objKeys[j];
var value = typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key];
if (skipNulls && value === null) {
continue;
}
var keyPrefix = isArray(obj)
? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, key) : adjustedPrefix
: adjustedPrefix + (allowDots ? '.' + key : '[' + key + ']');
sideChannel.set(object, step);
var valueSideChannel = getSideChannel();
valueSideChannel.set(sentinel, sideChannel);
pushToArray(values, stringify(
value,
keyPrefix,
generateArrayPrefix,
commaRoundTrip,
strictNullHandling,
skipNulls,
generateArrayPrefix === 'comma' && encodeValuesOnly && isArray(obj) ? null : encoder,
filter,
sort,
allowDots,
serializeDate,
format,
formatter,
encodeValuesOnly,
charset,
valueSideChannel
));
}
return values;
};
var normalizeStringifyOptions = function normalizeStringifyOptions(opts) {
if (!opts) {
return defaults;
}
if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') {
throw new TypeError('Encoder has to be a function.');
}
var charset = opts.charset || defaults.charset;
if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
}
var format = formats['default'];
if (typeof opts.format !== 'undefined') {
if (!has.call(formats.formatters, opts.format)) {
throw new TypeError('Unknown format option provided.');
}
format = opts.format;
}
var formatter = formats.formatters[format];
var filter = defaults.filter;
if (typeof opts.filter === 'function' || isArray(opts.filter)) {
filter = opts.filter;
}
return {
addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,
allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,
charset: charset,
charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,
encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,
encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,
encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,
filter: filter,
format: format,
formatter: formatter,
serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,
skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,
sort: typeof opts.sort === 'function' ? opts.sort : null,
strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
};
};
module.exports = function (object, opts) {
var obj = object;
var options = normalizeStringifyOptions(opts);
var objKeys;
var filter;
if (typeof options.filter === 'function') {
filter = options.filter;
obj = filter('', obj);
} else if (isArray(options.filter)) {
filter = options.filter;
objKeys = filter;
}
var keys = [];
if (typeof obj !== 'object' || obj === null) {
return '';
}
var arrayFormat;
if (opts && opts.arrayFormat in arrayPrefixGenerators) {
arrayFormat = opts.arrayFormat;
} else if (opts && 'indices' in opts) {
arrayFormat = opts.indices ? 'indices' : 'repeat';
} else {
arrayFormat = 'indices';
}
var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
if (opts && 'commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') {
throw new TypeError('`commaRoundTrip` must be a boolean, or absent');
}
var commaRoundTrip = generateArrayPrefix === 'comma' && opts && opts.commaRoundTrip;
if (!objKeys) {
objKeys = Object.keys(obj);
}
if (options.sort) {
objKeys.sort(options.sort);
}
var sideChannel = getSideChannel();
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (options.skipNulls && obj[key] === null) {
continue;
}
pushToArray(keys, stringify(
obj[key],
key,
generateArrayPrefix,
commaRoundTrip,
options.strictNullHandling,
options.skipNulls,
options.encode ? options.encoder : null,
options.filter,
options.sort,
options.allowDots,
options.serializeDate,
options.format,
options.formatter,
options.encodeValuesOnly,
options.charset,
sideChannel
));
}
var joined = keys.join(options.delimiter);
var prefix = options.addQueryPrefix === true ? '?' : '';
if (options.charsetSentinel) {
if (options.charset === 'iso-8859-1') {
// encodeURIComponent('&#10003;'), the "numeric entity" representation of a checkmark
prefix += 'utf8=%26%2310003%3B&';
} else {
// encodeURIComponent('✓')
prefix += 'utf8=%E2%9C%93&';
}
}
return joined.length > 0 ? prefix + joined : '';
};
},{"./formats":161,"./utils":165,"side-channel":180}],165:[function(require,module,exports){
'use strict';
var formats = require('./formats');
var has = Object.prototype.hasOwnProperty;
var isArray = Array.isArray;
var hexTable = (function () {
var array = [];
for (var i = 0; i < 256; ++i) {
array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
}
return array;
}());
var compactQueue = function compactQueue(queue) {
while (queue.length > 1) {
var item = queue.pop();
var obj = item.obj[item.prop];
if (isArray(obj)) {
var compacted = [];
for (var j = 0; j < obj.length; ++j) {
if (typeof obj[j] !== 'undefined') {
compacted.push(obj[j]);
}
}
item.obj[item.prop] = compacted;
}
}
};
var arrayToObject = function arrayToObject(source, options) {
var obj = options && options.plainObjects ? Object.create(null) : {};
for (var i = 0; i < source.length; ++i) {
if (typeof source[i] !== 'undefined') {
obj[i] = source[i];
}
}
return obj;
};
var merge = function merge(target, source, options) {
/* eslint no-param-reassign: 0 */
if (!source) {
return target;
}
if (typeof source !== 'object') {
if (isArray(target)) {
target.push(source);
} else if (target && typeof target === 'object') {
if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) {
target[source] = true;
}
} else {
return [target, source];
}
return target;
}
if (!target || typeof target !== 'object') {
return [target].concat(source);
}
var mergeTarget = target;
if (isArray(target) && !isArray(source)) {
mergeTarget = arrayToObject(target, options);
}
if (isArray(target) && isArray(source)) {
source.forEach(function (item, i) {
if (has.call(target, i)) {
var targetItem = target[i];
if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {
target[i] = merge(targetItem, item, options);
} else {
target.push(item);
}
} else {
target[i] = item;
}
});
return target;
}
return Object.keys(source).reduce(function (acc, key) {
var value = source[key];
if (has.call(acc, key)) {
acc[key] = merge(acc[key], value, options);
} else {
acc[key] = value;
}
return acc;
}, mergeTarget);
};
var assign = function assignSingleSource(target, source) {
return Object.keys(source).reduce(function (acc, key) {
acc[key] = source[key];
return acc;
}, target);
};
var decode = function (str, decoder, charset) {
var strWithoutPlus = str.replace(/\+/g, ' ');
if (charset === 'iso-8859-1') {
// unescape never throws, no try...catch needed:
return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
}
// utf-8
try {
return decodeURIComponent(strWithoutPlus);
} catch (e) {
return strWithoutPlus;
}
};
var encode = function encode(str, defaultEncoder, charset, kind, format) {
// This code was originally written by Brian White (mscdex) for the io.js core querystring library.
// It has been adapted here for stricter adherence to RFC 3986
if (str.length === 0) {
return str;
}
var string = str;
if (typeof str === 'symbol') {
string = Symbol.prototype.toString.call(str);
} else if (typeof str !== 'string') {
string = String(str);
}
if (charset === 'iso-8859-1') {
return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {
return '%26%23' + parseInt($0.slice(2), 16) + '%3B';
});
}
var out = '';
for (var i = 0; i < string.length; ++i) {
var c = string.charCodeAt(i);
if (
c === 0x2D // -
|| c === 0x2E // .
|| c === 0x5F // _
|| c === 0x7E // ~
|| (c >= 0x30 && c <= 0x39) // 0-9
|| (c >= 0x41 && c <= 0x5A) // a-z
|| (c >= 0x61 && c <= 0x7A) // A-Z
|| (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( )
) {
out += string.charAt(i);
continue;
}
if (c < 0x80) {
out = out + hexTable[c];
continue;
}
if (c < 0x800) {
out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
if (c < 0xD800 || c >= 0xE000) {
out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
i += 1;
c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
/* eslint operator-linebreak: [2, "before"] */
out += hexTable[0xF0 | (c >> 18)]
+ hexTable[0x80 | ((c >> 12) & 0x3F)]
+ hexTable[0x80 | ((c >> 6) & 0x3F)]
+ hexTable[0x80 | (c & 0x3F)];
}
return out;
};
var compact = function compact(value) {
var queue = [{ obj: { o: value }, prop: 'o' }];
var refs = [];
for (var i = 0; i < queue.length; ++i) {
var item = queue[i];
var obj = item.obj[item.prop];
var keys = Object.keys(obj);
for (var j = 0; j < keys.length; ++j) {
var key = keys[j];
var val = obj[key];
if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
queue.push({ obj: obj, prop: key });
refs.push(val);
}
}
}
compactQueue(queue);
return value;
};
var isRegExp = function isRegExp(obj) {
return Object.prototype.toString.call(obj) === '[object RegExp]';
};
var isBuffer = function isBuffer(obj) {
if (!obj || typeof obj !== 'object') {
return false;
}
return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
};
var combine = function combine(a, b) {
return [].concat(a, b);
};
var maybeMap = function maybeMap(val, fn) {
if (isArray(val)) {
var mapped = [];
for (var i = 0; i < val.length; i += 1) {
mapped.push(fn(val[i]));
}
return mapped;
}
return fn(val);
};
module.exports = {
arrayToObject: arrayToObject,
assign: assign,
combine: combine,
compact: compact,
decode: decode,
encode: encode,
isBuffer: isBuffer,
isRegExp: isRegExp,
maybeMap: maybeMap,
merge: merge
};
},{"./formats":161}],166:[function(require,module,exports){
(function (global){(function (){
/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
let promise
module.exports = typeof queueMicrotask === 'function'
? queueMicrotask.bind(typeof window !== 'undefined' ? window : global)
// reuse resolved promise, and allocate it lazily
: cb => (promise || (promise = Promise.resolve()))
.then(cb)
.catch(err => setTimeout(() => { throw err }, 0))
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],167:[function(require,module,exports){
(function (process,global){(function (){
'use strict'
// limit of Crypto.getRandomValues()
// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
var MAX_BYTES = 65536
// Node supports requesting up to this number of bytes
// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48
var MAX_UINT32 = 4294967295
function oldBrowser () {
throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11')
}
var Buffer = require('safe-buffer').Buffer
var crypto = global.crypto || global.msCrypto
if (crypto && crypto.getRandomValues) {
module.exports = randomBytes
} else {
module.exports = oldBrowser
}
function randomBytes (size, cb) {
// phantomjs needs to throw
if (size > MAX_UINT32) throw new RangeError('requested too many random bytes')
var bytes = Buffer.allocUnsafe(size)
if (size > 0) { // getRandomValues fails on IE if size == 0
if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues
// can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
for (var generated = 0; generated < size; generated += MAX_BYTES) {
// buffer.slice automatically checks if the end is past the end of
// the buffer so we don't have to here
crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES))
}
} else {
crypto.getRandomValues(bytes)
}
}
if (typeof cb === 'function') {
return process.nextTick(function () {
cb(null, bytes)
})
}
return bytes
}
}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":160,"safe-buffer":169}],168:[function(require,module,exports){
'use strict';
/**
* Remove a range of items from an array
*
* @function removeItems
* @param {Array<*>} arr The target array
* @param {number} startIdx The index to begin removing from (inclusive)
* @param {number} removeCount How many items to remove
*/
function removeItems (arr, startIdx, removeCount) {
var i, length = arr.length;
if (startIdx >= length || removeCount <= 0 || startIdx < 0) {
return
}
removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount);
var len = length - removeCount;
for (i = startIdx; i < len; ++i) {
arr[i] = arr[i + removeCount];
}
arr.length = len;
}
module.exports = removeItems;
},{}],169:[function(require,module,exports){
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
/* eslint-disable node/no-deprecated-api */
var buffer = require('buffer')
var Buffer = buffer.Buffer
// alternative to using Object.keys for old browsers
function copyProps (src, dst) {
for (var key in src) {
dst[key] = src[key]
}
}
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
module.exports = buffer
} else {
// Copy properties from require('buffer')
copyProps(buffer, exports)
exports.Buffer = SafeBuffer
}
function SafeBuffer (arg, encodingOrOffset, length) {
return Buffer(arg, encodingOrOffset, length)
}
SafeBuffer.prototype = Object.create(Buffer.prototype)
// Copy static methods from Buffer
copyProps(Buffer, SafeBuffer)
SafeBuffer.from = function (arg, encodingOrOffset, length) {
if (typeof arg === 'number') {
throw new TypeError('Argument must not be a number')
}
return Buffer(arg, encodingOrOffset, length)
}
SafeBuffer.alloc = function (size, fill, encoding) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
var buf = Buffer(size)
if (fill !== undefined) {
if (typeof encoding === 'string') {
buf.fill(fill, encoding)
} else {
buf.fill(fill)
}
} else {
buf.fill(0)
}
return buf
}
SafeBuffer.allocUnsafe = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return Buffer(size)
}
SafeBuffer.allocUnsafeSlow = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return buffer.SlowBuffer(size)
}
},{"buffer":35}],170:[function(require,module,exports){
module.exports = scrollToAnchor
function scrollToAnchor (anchor, options) {
if (anchor) {
try {
var el = document.querySelector(anchor)
if (el) el.scrollIntoView(options)
} catch (e) {}
}
}
},{}],171:[function(require,module,exports){
'use strict';
module.exports = require('./lib/index');
},{"./lib/index":175}],172:[function(require,module,exports){
'use strict';
var randomFromSeed = require('./random/random-from-seed');
var ORIGINAL = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-';
var alphabet;
var previousSeed;
var shuffled;
function reset() {
shuffled = false;
}
function setCharacters(_alphabet_) {
if (!_alphabet_) {
if (alphabet !== ORIGINAL) {
alphabet = ORIGINAL;
reset();
}
return;
}
if (_alphabet_ === alphabet) {
return;
}
if (_alphabet_.length !== ORIGINAL.length) {
throw new Error('Custom alphabet for shortid must be ' + ORIGINAL.length + ' unique characters. You submitted ' + _alphabet_.length + ' characters: ' + _alphabet_);
}
var unique = _alphabet_.split('').filter(function(item, ind, arr){
return ind !== arr.lastIndexOf(item);
});
if (unique.length) {
throw new Error('Custom alphabet for shortid must be ' + ORIGINAL.length + ' unique characters. These characters were not unique: ' + unique.join(', '));
}
alphabet = _alphabet_;
reset();
}
function characters(_alphabet_) {
setCharacters(_alphabet_);
return alphabet;
}
function setSeed(seed) {
randomFromSeed.seed(seed);
if (previousSeed !== seed) {
reset();
previousSeed = seed;
}
}
function shuffle() {
if (!alphabet) {
setCharacters(ORIGINAL);
}
var sourceArray = alphabet.split('');
var targetArray = [];
var r = randomFromSeed.nextValue();
var characterIndex;
while (sourceArray.length > 0) {
r = randomFromSeed.nextValue();
characterIndex = Math.floor(r * sourceArray.length);
targetArray.push(sourceArray.splice(characterIndex, 1)[0]);
}
return targetArray.join('');
}
function getShuffled() {
if (shuffled) {
return shuffled;
}
shuffled = shuffle();
return shuffled;
}
/**
* lookup shuffled letter
* @param index
* @returns {string}
*/
function lookup(index) {
var alphabetShuffled = getShuffled();
return alphabetShuffled[index];
}
function get () {
return alphabet || ORIGINAL;
}
module.exports = {
get: get,
characters: characters,
seed: setSeed,
lookup: lookup,
shuffled: getShuffled
};
},{"./random/random-from-seed":178}],173:[function(require,module,exports){
'use strict';
var generate = require('./generate');
var alphabet = require('./alphabet');
// Ignore all milliseconds before a certain time to reduce the size of the date entropy without sacrificing uniqueness.
// This number should be updated every year or so to keep the generated id short.
// To regenerate `new Date() - 0` and bump the version. Always bump the version!
var REDUCE_TIME = 1567752802062;
// don't change unless we change the algos or REDUCE_TIME
// must be an integer and less than 16
var version = 7;
// Counter is used when shortid is called multiple times in one second.
var counter;
// Remember the last time shortid was called in case counter is needed.
var previousSeconds;
/**
* Generate unique id
* Returns string id
*/
function build(clusterWorkerId) {
var str = '';
var seconds = Math.floor((Date.now() - REDUCE_TIME) * 0.001);
if (seconds === previousSeconds) {
counter++;
} else {
counter = 0;
previousSeconds = seconds;
}
str = str + generate(version);
str = str + generate(clusterWorkerId);
if (counter > 0) {
str = str + generate(counter);
}
str = str + generate(seconds);
return str;
}
module.exports = build;
},{"./alphabet":172,"./generate":174}],174:[function(require,module,exports){
'use strict';
var alphabet = require('./alphabet');
var random = require('./random/random-byte');
var format = require('nanoid/format');
function generate(number) {
var loopCounter = 0;
var done;
var str = '';
while (!done) {
str = str + format(random, alphabet.get(), 1);
done = number < (Math.pow(16, loopCounter + 1 ) );
loopCounter++;
}
return str;
}
module.exports = generate;
},{"./alphabet":172,"./random/random-byte":177,"nanoid/format":140}],175:[function(require,module,exports){
'use strict';
var alphabet = require('./alphabet');
var build = require('./build');
var isValid = require('./is-valid');
// if you are using cluster or multiple servers use this to make each instance
// has a unique value for worker
// Note: I don't know if this is automatically set when using third
// party cluster solutions such as pm2.
var clusterWorkerId = require('./util/cluster-worker-id') || 0;
/**
* Set the seed.
* Highly recommended if you don't want people to try to figure out your id schema.
* exposed as shortid.seed(int)
* @param seed Integer value to seed the random alphabet. ALWAYS USE THE SAME SEED or you might get overlaps.
*/
function seed(seedValue) {
alphabet.seed(seedValue);
return module.exports;
}
/**
* Set the cluster worker or machine id
* exposed as shortid.worker(int)
* @param workerId worker must be positive integer. Number less than 16 is recommended.
* returns shortid module so it can be chained.
*/
function worker(workerId) {
clusterWorkerId = workerId;
return module.exports;
}
/**
*
* sets new characters to use in the alphabet
* returns the shuffled alphabet
*/
function characters(newCharacters) {
if (newCharacters !== undefined) {
alphabet.characters(newCharacters);
}
return alphabet.shuffled();
}
/**
* Generate unique id
* Returns string id
*/
function generate() {
return build(clusterWorkerId);
}
// Export all other functions as properties of the generate function
module.exports = generate;
module.exports.generate = generate;
module.exports.seed = seed;
module.exports.worker = worker;
module.exports.characters = characters;
module.exports.isValid = isValid;
},{"./alphabet":172,"./build":173,"./is-valid":176,"./util/cluster-worker-id":179}],176:[function(require,module,exports){
'use strict';
var alphabet = require('./alphabet');
function isShortId(id) {
if (!id || typeof id !== 'string' || id.length < 6 ) {
return false;
}
var nonAlphabetic = new RegExp('[^' +
alphabet.get().replace(/[|\\{}()[\]^$+*?.-]/g, '\\$&') +
']');
return !nonAlphabetic.test(id);
}
module.exports = isShortId;
},{"./alphabet":172}],177:[function(require,module,exports){
'use strict';
var crypto = typeof window === 'object' && (window.crypto || window.msCrypto); // IE 11 uses window.msCrypto
var randomByte;
if (!crypto || !crypto.getRandomValues) {
randomByte = function(size) {
var bytes = [];
for (var i = 0; i < size; i++) {
bytes.push(Math.floor(Math.random() * 256));
}
return bytes;
};
} else {
randomByte = function(size) {
return crypto.getRandomValues(new Uint8Array(size));
};
}
module.exports = randomByte;
},{}],178:[function(require,module,exports){
'use strict';
// Found this seed-based random generator somewhere
// Based on The Central Randomizer 1.3 (C) 1997 by Paul Houle (houle@msc.cornell.edu)
var seed = 1;
/**
* return a random number based on a seed
* @param seed
* @returns {number}
*/
function getNextValue() {
seed = (seed * 9301 + 49297) % 233280;
return seed/(233280.0);
}
function setSeed(_seed_) {
seed = _seed_;
}
module.exports = {
nextValue: getNextValue,
seed: setSeed
};
},{}],179:[function(require,module,exports){
'use strict';
module.exports = 0;
},{}],180:[function(require,module,exports){
'use strict';
var GetIntrinsic = require('get-intrinsic');
var callBound = require('call-bind/callBound');
var inspect = require('object-inspect');
var $TypeError = GetIntrinsic('%TypeError%');
var $WeakMap = GetIntrinsic('%WeakMap%', true);
var $Map = GetIntrinsic('%Map%', true);
var $weakMapGet = callBound('WeakMap.prototype.get', true);
var $weakMapSet = callBound('WeakMap.prototype.set', true);
var $weakMapHas = callBound('WeakMap.prototype.has', true);
var $mapGet = callBound('Map.prototype.get', true);
var $mapSet = callBound('Map.prototype.set', true);
var $mapHas = callBound('Map.prototype.has', true);
/*
* This function traverses the list returning the node corresponding to the
* given key.
*
* That node is also moved to the head of the list, so that if it's accessed
* again we don't need to traverse the whole list. By doing so, all the recently
* used nodes can be accessed relatively quickly.
*/
var listGetNode = function (list, key) { // eslint-disable-line consistent-return
for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) {
if (curr.key === key) {
prev.next = curr.next;
curr.next = list.next;
list.next = curr; // eslint-disable-line no-param-reassign
return curr;
}
}
};
var listGet = function (objects, key) {
var node = listGetNode(objects, key);
return node && node.value;
};
var listSet = function (objects, key, value) {
var node = listGetNode(objects, key);
if (node) {
node.value = value;
} else {
// Prepend the new node to the beginning of the list
objects.next = { // eslint-disable-line no-param-reassign
key: key,
next: objects.next,
value: value
};
}
};
var listHas = function (objects, key) {
return !!listGetNode(objects, key);
};
module.exports = function getSideChannel() {
var $wm;
var $m;
var $o;
var channel = {
assert: function (key) {
if (!channel.has(key)) {
throw new $TypeError('Side channel does not contain ' + inspect(key));
}
},
get: function (key) { // eslint-disable-line consistent-return
if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
if ($wm) {
return $weakMapGet($wm, key);
}
} else if ($Map) {
if ($m) {
return $mapGet($m, key);
}
} else {
if ($o) { // eslint-disable-line no-lonely-if
return listGet($o, key);
}
}
},
has: function (key) {
if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
if ($wm) {
return $weakMapHas($wm, key);
}
} else if ($Map) {
if ($m) {
return $mapHas($m, key);
}
} else {
if ($o) { // eslint-disable-line no-lonely-if
return listHas($o, key);
}
}
return false;
},
set: function (key, value) {
if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) {
if (!$wm) {
$wm = new $WeakMap();
}
$weakMapSet($wm, key, value);
} else if ($Map) {
if (!$m) {
$m = new $Map();
}
$mapSet($m, key, value);
} else {
if (!$o) {
/*
* Initialize the linked list as an empty node, so that we don't have
* to special-case handling of the first node: we can always refer to
* it as (previous node).next, instead of something like (list).head
*/
$o = { key: {}, next: null };
}
listSet($o, key, value);
}
}
};
return channel;
};
},{"call-bind/callBound":36,"get-intrinsic":86,"object-inspect":153}],181:[function(require,module,exports){
/*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
const debug = require('debug')('simple-peer')
const getBrowserRTC = require('get-browser-rtc')
const randombytes = require('randombytes')
const stream = require('readable-stream')
const queueMicrotask = require('queue-microtask') // TODO: remove when Node 10 is not supported
const errCode = require('err-code')
const { Buffer } = require('buffer')
const MAX_BUFFERED_AMOUNT = 64 * 1024
const ICECOMPLETE_TIMEOUT = 5 * 1000
const CHANNEL_CLOSING_TIMEOUT = 5 * 1000
// HACK: Filter trickle lines when trickle is disabled #354
function filterTrickle (sdp) {
return sdp.replace(/a=ice-options:trickle\s\n/g, '')
}
function warn (message) {
console.warn(message)
}
/**
* WebRTC peer connection. Same API as node core `net.Socket`, plus a few extra methods.
* Duplex stream.
* @param {Object} opts
*/
class Peer extends stream.Duplex {
constructor (opts) {
opts = Object.assign({
allowHalfOpen: false
}, opts)
super(opts)
this._id = randombytes(4).toString('hex').slice(0, 7)
this._debug('new peer %o', opts)
this.channelName = opts.initiator
? opts.channelName || randombytes(20).toString('hex')
: null
this.initiator = opts.initiator || false
this.channelConfig = opts.channelConfig || Peer.channelConfig
this.channelNegotiated = this.channelConfig.negotiated
this.config = Object.assign({}, Peer.config, opts.config)
this.offerOptions = opts.offerOptions || {}
this.answerOptions = opts.answerOptions || {}
this.sdpTransform = opts.sdpTransform || (sdp => sdp)
this.streams = opts.streams || (opts.stream ? [opts.stream] : []) // support old "stream" option
this.trickle = opts.trickle !== undefined ? opts.trickle : true
this.allowHalfTrickle = opts.allowHalfTrickle !== undefined ? opts.allowHalfTrickle : false
this.iceCompleteTimeout = opts.iceCompleteTimeout || ICECOMPLETE_TIMEOUT
this.destroyed = false
this.destroying = false
this._connected = false
this.remoteAddress = undefined
this.remoteFamily = undefined
this.remotePort = undefined
this.localAddress = undefined
this.localFamily = undefined
this.localPort = undefined
this._wrtc = (opts.wrtc && typeof opts.wrtc === 'object')
? opts.wrtc
: getBrowserRTC()
if (!this._wrtc) {
if (typeof window === 'undefined') {
throw errCode(new Error('No WebRTC support: Specify `opts.wrtc` option in this environment'), 'ERR_WEBRTC_SUPPORT')
} else {
throw errCode(new Error('No WebRTC support: Not a supported browser'), 'ERR_WEBRTC_SUPPORT')
}
}
this._pcReady = false
this._channelReady = false
this._iceComplete = false // ice candidate trickle done (got null candidate)
this._iceCompleteTimer = null // send an offer/answer anyway after some timeout
this._channel = null
this._pendingCandidates = []
this._isNegotiating = false // is this peer waiting for negotiation to complete?
this._firstNegotiation = true
this._batchedNegotiation = false // batch synchronous negotiations
this._queuedNegotiation = false // is there a queued negotiation request?
this._sendersAwaitingStable = []
this._senderMap = new Map()
this._closingInterval = null
this._remoteTracks = []
this._remoteStreams = []
this._chunk = null
this._cb = null
this._interval = null
try {
this._pc = new (this._wrtc.RTCPeerConnection)(this.config)
} catch (err) {
this.destroy(errCode(err, 'ERR_PC_CONSTRUCTOR'))
return
}
// We prefer feature detection whenever possible, but sometimes that's not
// possible for certain implementations.
this._isReactNativeWebrtc = typeof this._pc._peerConnectionId === 'number'
this._pc.oniceconnectionstatechange = () => {
this._onIceStateChange()
}
this._pc.onicegatheringstatechange = () => {
this._onIceStateChange()
}
this._pc.onconnectionstatechange = () => {
this._onConnectionStateChange()
}
this._pc.onsignalingstatechange = () => {
this._onSignalingStateChange()
}
this._pc.onicecandidate = event => {
this._onIceCandidate(event)
}
// HACK: Fix for odd Firefox behavior, see: https://github.com/feross/simple-peer/pull/783
if (typeof this._pc.peerIdentity === 'object') {
this._pc.peerIdentity.catch(err => {
this.destroy(errCode(err, 'ERR_PC_PEER_IDENTITY'))
})
}
// Other spec events, unused by this implementation:
// - onconnectionstatechange
// - onicecandidateerror
// - onfingerprintfailure
// - onnegotiationneeded
if (this.initiator || this.channelNegotiated) {
this._setupData({
channel: this._pc.createDataChannel(this.channelName, this.channelConfig)
})
} else {
this._pc.ondatachannel = event => {
this._setupData(event)
}
}
if (this.streams) {
this.streams.forEach(stream => {
this.addStream(stream)
})
}
this._pc.ontrack = event => {
this._onTrack(event)
}
this._debug('initial negotiation')
this._needsNegotiation()
this._onFinishBound = () => {
this._onFinish()
}
this.once('finish', this._onFinishBound)
}
get bufferSize () {
return (this._channel && this._channel.bufferedAmount) || 0
}
// HACK: it's possible channel.readyState is "closing" before peer.destroy() fires
// https://bugs.chromium.org/p/chromium/issues/detail?id=882743
get connected () {
return (this._connected && this._channel.readyState === 'open')
}
address () {
return { port: this.localPort, family: this.localFamily, address: this.localAddress }
}
signal (data) {
if (this.destroying) return
if (this.destroyed) throw errCode(new Error('cannot signal after peer is destroyed'), 'ERR_DESTROYED')
if (typeof data === 'string') {
try {
data = JSON.parse(data)
} catch (err) {
data = {}
}
}
this._debug('signal()')
if (data.renegotiate && this.initiator) {
this._debug('got request to renegotiate')
this._needsNegotiation()
}
if (data.transceiverRequest && this.initiator) {
this._debug('got request for transceiver')
this.addTransceiver(data.transceiverRequest.kind, data.transceiverRequest.init)
}
if (data.candidate) {
if (this._pc.remoteDescription && this._pc.remoteDescription.type) {
this._addIceCandidate(data.candidate)
} else {
this._pendingCandidates.push(data.candidate)
}
}
if (data.sdp) {
this._pc.setRemoteDescription(new (this._wrtc.RTCSessionDescription)(data))
.then(() => {
if (this.destroyed) return
this._pendingCandidates.forEach(candidate => {
this._addIceCandidate(candidate)
})
this._pendingCandidates = []
if (this._pc.remoteDescription.type === 'offer') this._createAnswer()
})
.catch(err => {
this.destroy(errCode(err, 'ERR_SET_REMOTE_DESCRIPTION'))
})
}
if (!data.sdp && !data.candidate && !data.renegotiate && !data.transceiverRequest) {
this.destroy(errCode(new Error('signal() called with invalid signal data'), 'ERR_SIGNALING'))
}
}
_addIceCandidate (candidate) {
const iceCandidateObj = new this._wrtc.RTCIceCandidate(candidate)
this._pc.addIceCandidate(iceCandidateObj)
.catch(err => {
if (!iceCandidateObj.address || iceCandidateObj.address.endsWith('.local')) {
warn('Ignoring unsupported ICE candidate.')
} else {
this.destroy(errCode(err, 'ERR_ADD_ICE_CANDIDATE'))
}
})
}
/**
* Send text/binary data to the remote peer.
* @param {ArrayBufferView|ArrayBuffer|Buffer|string|Blob} chunk
*/
send (chunk) {
if (this.destroying) return
if (this.destroyed) throw errCode(new Error('cannot send after peer is destroyed'), 'ERR_DESTROYED')
this._channel.send(chunk)
}
/**
* Add a Transceiver to the connection.
* @param {String} kind
* @param {Object} init
*/
addTransceiver (kind, init) {
if (this.destroying) return
if (this.destroyed) throw errCode(new Error('cannot addTransceiver after peer is destroyed'), 'ERR_DESTROYED')
this._debug('addTransceiver()')
if (this.initiator) {
try {
this._pc.addTransceiver(kind, init)
this._needsNegotiation()
} catch (err) {
this.destroy(errCode(err, 'ERR_ADD_TRANSCEIVER'))
}
} else {
this.emit('signal', { // request initiator to renegotiate
type: 'transceiverRequest',
transceiverRequest: { kind, init }
})
}
}
/**
* Add a MediaStream to the connection.
* @param {MediaStream} stream
*/
addStream (stream) {
if (this.destroying) return
if (this.destroyed) throw errCode(new Error('cannot addStream after peer is destroyed'), 'ERR_DESTROYED')
this._debug('addStream()')
stream.getTracks().forEach(track => {
this.addTrack(track, stream)
})
}
/**
* Add a MediaStreamTrack to the connection.
* @param {MediaStreamTrack} track
* @param {MediaStream} stream
*/
addTrack (track, stream) {
if (this.destroying) return
if (this.destroyed) throw errCode(new Error('cannot addTrack after peer is destroyed'), 'ERR_DESTROYED')
this._debug('addTrack()')
const submap = this._senderMap.get(track) || new Map() // nested Maps map [track, stream] to sender
let sender = submap.get(stream)
if (!sender) {
sender = this._pc.addTrack(track, stream)
submap.set(stream, sender)
this._senderMap.set(track, submap)
this._needsNegotiation()
} else if (sender.removed) {
throw errCode(new Error('Track has been removed. You should enable/disable tracks that you want to re-add.'), 'ERR_SENDER_REMOVED')
} else {
throw errCode(new Error('Track has already been added to that stream.'), 'ERR_SENDER_ALREADY_ADDED')
}
}
/**
* Replace a MediaStreamTrack by another in the connection.
* @param {MediaStreamTrack} oldTrack
* @param {MediaStreamTrack} newTrack
* @param {MediaStream} stream
*/
replaceTrack (oldTrack, newTrack, stream) {
if (this.destroying) return
if (this.destroyed) throw errCode(new Error('cannot replaceTrack after peer is destroyed'), 'ERR_DESTROYED')
this._debug('replaceTrack()')
const submap = this._senderMap.get(oldTrack)
const sender = submap ? submap.get(stream) : null
if (!sender) {
throw errCode(new Error('Cannot replace track that was never added.'), 'ERR_TRACK_NOT_ADDED')
}
if (newTrack) this._senderMap.set(newTrack, submap)
if (sender.replaceTrack != null) {
sender.replaceTrack(newTrack)
} else {
this.destroy(errCode(new Error('replaceTrack is not supported in this browser'), 'ERR_UNSUPPORTED_REPLACETRACK'))
}
}
/**
* Remove a MediaStreamTrack from the connection.
* @param {MediaStreamTrack} track
* @param {MediaStream} stream
*/
removeTrack (track, stream) {
if (this.destroying) return
if (this.destroyed) throw errCode(new Error('cannot removeTrack after peer is destroyed'), 'ERR_DESTROYED')
this._debug('removeSender()')
const submap = this._senderMap.get(track)
const sender = submap ? submap.get(stream) : null
if (!sender) {
throw errCode(new Error('Cannot remove track that was never added.'), 'ERR_TRACK_NOT_ADDED')
}
try {
sender.removed = true
this._pc.removeTrack(sender)
} catch (err) {
if (err.name === 'NS_ERROR_UNEXPECTED') {
this._sendersAwaitingStable.push(sender) // HACK: Firefox must wait until (signalingState === stable) https://bugzilla.mozilla.org/show_bug.cgi?id=1133874
} else {
this.destroy(errCode(err, 'ERR_REMOVE_TRACK'))
}
}
this._needsNegotiation()
}
/**
* Remove a MediaStream from the connection.
* @param {MediaStream} stream
*/
removeStream (stream) {
if (this.destroying) return
if (this.destroyed) throw errCode(new Error('cannot removeStream after peer is destroyed'), 'ERR_DESTROYED')
this._debug('removeSenders()')
stream.getTracks().forEach(track => {
this.removeTrack(track, stream)
})
}
_needsNegotiation () {
this._debug('_needsNegotiation')
if (this._batchedNegotiation) return // batch synchronous renegotiations
this._batchedNegotiation = true
queueMicrotask(() => {
this._batchedNegotiation = false
if (this.initiator || !this._firstNegotiation) {
this._debug('starting batched negotiation')
this.negotiate()
} else {
this._debug('non-initiator initial negotiation request discarded')
}
this._firstNegotiation = false
})
}
negotiate () {
if (this.destroying) return
if (this.destroyed) throw errCode(new Error('cannot negotiate after peer is destroyed'), 'ERR_DESTROYED')
if (this.initiator) {
if (this._isNegotiating) {
this._queuedNegotiation = true
this._debug('already negotiating, queueing')
} else {
this._debug('start negotiation')
setTimeout(() => { // HACK: Chrome crashes if we immediately call createOffer
this._createOffer()
}, 0)
}
} else {
if (this._isNegotiating) {
this._queuedNegotiation = true
this._debug('already negotiating, queueing')
} else {
this._debug('requesting negotiation from initiator')
this.emit('signal', { // request initiator to renegotiate
type: 'renegotiate',
renegotiate: true
})
}
}
this._isNegotiating = true
}
// TODO: Delete this method once readable-stream is updated to contain a default
// implementation of destroy() that automatically calls _destroy()
// See: https://github.com/nodejs/readable-stream/issues/283
destroy (err) {
this._destroy(err, () => {})
}
_destroy (err, cb) {
if (this.destroyed || this.destroying) return
this.destroying = true
this._debug('destroying (error: %s)', err && (err.message || err))
queueMicrotask(() => { // allow events concurrent with the call to _destroy() to fire (see #692)
this.destroyed = true
this.destroying = false
this._debug('destroy (error: %s)', err && (err.message || err))
this.readable = this.writable = false
if (!this._readableState.ended) this.push(null)
if (!this._writableState.finished) this.end()
this._connected = false
this._pcReady = false
this._channelReady = false
this._remoteTracks = null
this._remoteStreams = null
this._senderMap = null
clearInterval(this._closingInterval)
this._closingInterval = null
clearInterval(this._interval)
this._interval = null
this._chunk = null
this._cb = null
if (this._onFinishBound) this.removeListener('finish', this._onFinishBound)
this._onFinishBound = null
if (this._channel) {
try {
this._channel.close()
} catch (err) {}
// allow events concurrent with destruction to be handled
this._channel.onmessage = null
this._channel.onopen = null
this._channel.onclose = null
this._channel.onerror = null
}
if (this._pc) {
try {
this._pc.close()
} catch (err) {}
// allow events concurrent with destruction to be handled
this._pc.oniceconnectionstatechange = null
this._pc.onicegatheringstatechange = null
this._pc.onsignalingstatechange = null
this._pc.onicecandidate = null
this._pc.ontrack = null
this._pc.ondatachannel = null
}
this._pc = null
this._channel = null
if (err) this.emit('error', err)
this.emit('close')
cb()
})
}
_setupData (event) {
if (!event.channel) {
// In some situations `pc.createDataChannel()` returns `undefined` (in wrtc),
// which is invalid behavior. Handle it gracefully.
// See: https://github.com/feross/simple-peer/issues/163
return this.destroy(errCode(new Error('Data channel event is missing `channel` property'), 'ERR_DATA_CHANNEL'))
}
this._channel = event.channel
this._channel.binaryType = 'arraybuffer'
if (typeof this._channel.bufferedAmountLowThreshold === 'number') {
this._channel.bufferedAmountLowThreshold = MAX_BUFFERED_AMOUNT
}
this.channelName = this._channel.label
this._channel.onmessage = event => {
this._onChannelMessage(event)
}
this._channel.onbufferedamountlow = () => {
this._onChannelBufferedAmountLow()
}
this._channel.onopen = () => {
this._onChannelOpen()
}
this._channel.onclose = () => {
this._onChannelClose()
}
this._channel.onerror = event => {
const err = event.error instanceof Error
? event.error
: new Error(`Datachannel error: ${event.message} ${event.filename}:${event.lineno}:${event.colno}`)
this.destroy(errCode(err, 'ERR_DATA_CHANNEL'))
}
// HACK: Chrome will sometimes get stuck in readyState "closing", let's check for this condition
// https://bugs.chromium.org/p/chromium/issues/detail?id=882743
let isClosing = false
this._closingInterval = setInterval(() => { // No "onclosing" event
if (this._channel && this._channel.readyState === 'closing') {
if (isClosing) this._onChannelClose() // closing timed out: equivalent to onclose firing
isClosing = true
} else {
isClosing = false
}
}, CHANNEL_CLOSING_TIMEOUT)
}
_read () {}
_write (chunk, encoding, cb) {
if (this.destroyed) return cb(errCode(new Error('cannot write after peer is destroyed'), 'ERR_DATA_CHANNEL'))
if (this._connected) {
try {
this.send(chunk)
} catch (err) {
return this.destroy(errCode(err, 'ERR_DATA_CHANNEL'))
}
if (this._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) {
this._debug('start backpressure: bufferedAmount %d', this._channel.bufferedAmount)
this._cb = cb
} else {
cb(null)
}
} else {
this._debug('write before connect')
this._chunk = chunk
this._cb = cb
}
}
// When stream finishes writing, close socket. Half open connections are not
// supported.
_onFinish () {
if (this.destroyed) return
// Wait a bit before destroying so the socket flushes.
// TODO: is there a more reliable way to accomplish this?
const destroySoon = () => {
setTimeout(() => this.destroy(), 1000)
}
if (this._connected) {
destroySoon()
} else {
this.once('connect', destroySoon)
}
}
_startIceCompleteTimeout () {
if (this.destroyed) return
if (this._iceCompleteTimer) return
this._debug('started iceComplete timeout')
this._iceCompleteTimer = setTimeout(() => {
if (!this._iceComplete) {
this._iceComplete = true
this._debug('iceComplete timeout completed')
this.emit('iceTimeout')
this.emit('_iceComplete')
}
}, this.iceCompleteTimeout)
}
_createOffer () {
if (this.destroyed) return
this._pc.createOffer(this.offerOptions)
.then(offer => {
if (this.destroyed) return
if (!this.trickle && !this.allowHalfTrickle) offer.sdp = filterTrickle(offer.sdp)
offer.sdp = this.sdpTransform(offer.sdp)
const sendOffer = () => {
if (this.destroyed) return
const signal = this._pc.localDescription || offer
this._debug('signal')
this.emit('signal', {
type: signal.type,
sdp: signal.sdp
})
}
const onSuccess = () => {
this._debug('createOffer success')
if (this.destroyed) return
if (this.trickle || this._iceComplete) sendOffer()
else this.once('_iceComplete', sendOffer) // wait for candidates
}
const onError = err => {
this.destroy(errCode(err, 'ERR_SET_LOCAL_DESCRIPTION'))
}
this._pc.setLocalDescription(offer)
.then(onSuccess)
.catch(onError)
})
.catch(err => {
this.destroy(errCode(err, 'ERR_CREATE_OFFER'))
})
}
_requestMissingTransceivers () {
if (this._pc.getTransceivers) {
this._pc.getTransceivers().forEach(transceiver => {
if (!transceiver.mid && transceiver.sender.track && !transceiver.requested) {
transceiver.requested = true // HACK: Safari returns negotiated transceivers with a null mid
this.addTransceiver(transceiver.sender.track.kind)
}
})
}
}
_createAnswer () {
if (this.destroyed) return
this._pc.createAnswer(this.answerOptions)
.then(answer => {
if (this.destroyed) return
if (!this.trickle && !this.allowHalfTrickle) answer.sdp = filterTrickle(answer.sdp)
answer.sdp = this.sdpTransform(answer.sdp)
const sendAnswer = () => {
if (this.destroyed) return
const signal = this._pc.localDescription || answer
this._debug('signal')
this.emit('signal', {
type: signal.type,
sdp: signal.sdp
})
if (!this.initiator) this._requestMissingTransceivers()
}
const onSuccess = () => {
if (this.destroyed) return
if (this.trickle || this._iceComplete) sendAnswer()
else this.once('_iceComplete', sendAnswer)
}
const onError = err => {
this.destroy(errCode(err, 'ERR_SET_LOCAL_DESCRIPTION'))
}
this._pc.setLocalDescription(answer)
.then(onSuccess)
.catch(onError)
})
.catch(err => {
this.destroy(errCode(err, 'ERR_CREATE_ANSWER'))
})
}
_onConnectionStateChange () {
if (this.destroyed) return
if (this._pc.connectionState === 'failed') {
this.destroy(errCode(new Error('Connection failed.'), 'ERR_CONNECTION_FAILURE'))
}
}
_onIceStateChange () {
if (this.destroyed) return
const iceConnectionState = this._pc.iceConnectionState
const iceGatheringState = this._pc.iceGatheringState
this._debug(
'iceStateChange (connection: %s) (gathering: %s)',
iceConnectionState,
iceGatheringState
)
this.emit('iceStateChange', iceConnectionState, iceGatheringState)
if (iceConnectionState === 'connected' || iceConnectionState === 'completed') {
this._pcReady = true
this._maybeReady()
}
if (iceConnectionState === 'failed') {
this.destroy(errCode(new Error('Ice connection failed.'), 'ERR_ICE_CONNECTION_FAILURE'))
}
if (iceConnectionState === 'closed') {
this.destroy(errCode(new Error('Ice connection closed.'), 'ERR_ICE_CONNECTION_CLOSED'))
}
}
getStats (cb) {
// statreports can come with a value array instead of properties
const flattenValues = report => {
if (Object.prototype.toString.call(report.values) === '[object Array]') {
report.values.forEach(value => {
Object.assign(report, value)
})
}
return report
}
// Promise-based getStats() (standard)
if (this._pc.getStats.length === 0 || this._isReactNativeWebrtc) {
this._pc.getStats()
.then(res => {
const reports = []
res.forEach(report => {
reports.push(flattenValues(report))
})
cb(null, reports)
}, err => cb(err))
// Single-parameter callback-based getStats() (non-standard)
} else if (this._pc.getStats.length > 0) {
this._pc.getStats(res => {
// If we destroy connection in `connect` callback this code might happen to run when actual connection is already closed
if (this.destroyed) return
const reports = []
res.result().forEach(result => {
const report = {}
result.names().forEach(name => {
report[name] = result.stat(name)
})
report.id = result.id
report.type = result.type
report.timestamp = result.timestamp
reports.push(flattenValues(report))
})
cb(null, reports)
}, err => cb(err))
// Unknown browser, skip getStats() since it's anyone's guess which style of
// getStats() they implement.
} else {
cb(null, [])
}
}
_maybeReady () {
this._debug('maybeReady pc %s channel %s', this._pcReady, this._channelReady)
if (this._connected || this._connecting || !this._pcReady || !this._channelReady) return
this._connecting = true
// HACK: We can't rely on order here, for details see https://github.com/js-platform/node-webrtc/issues/339
const findCandidatePair = () => {
if (this.destroyed) return
this.getStats((err, items) => {
if (this.destroyed) return
// Treat getStats error as non-fatal. It's not essential.
if (err) items = []
const remoteCandidates = {}
const localCandidates = {}
const candidatePairs = {}
let foundSelectedCandidatePair = false
items.forEach(item => {
// TODO: Once all browsers support the hyphenated stats report types, remove
// the non-hypenated ones
if (item.type === 'remotecandidate' || item.type === 'remote-candidate') {
remoteCandidates[item.id] = item
}
if (item.type === 'localcandidate' || item.type === 'local-candidate') {
localCandidates[item.id] = item
}
if (item.type === 'candidatepair' || item.type === 'candidate-pair') {
candidatePairs[item.id] = item
}
})
const setSelectedCandidatePair = selectedCandidatePair => {
foundSelectedCandidatePair = true
let local = localCandidates[selectedCandidatePair.localCandidateId]
if (local && (local.ip || local.address)) {
// Spec
this.localAddress = local.ip || local.address
this.localPort = Number(local.port)
} else if (local && local.ipAddress) {
// Firefox
this.localAddress = local.ipAddress
this.localPort = Number(local.portNumber)
} else if (typeof selectedCandidatePair.googLocalAddress === 'string') {
// TODO: remove this once Chrome 58 is released
local = selectedCandidatePair.googLocalAddress.split(':')
this.localAddress = local[0]
this.localPort = Number(local[1])
}
if (this.localAddress) {
this.localFamily = this.localAddress.includes(':') ? 'IPv6' : 'IPv4'
}
let remote = remoteCandidates[selectedCandidatePair.remoteCandidateId]
if (remote && (remote.ip || remote.address)) {
// Spec
this.remoteAddress = remote.ip || remote.address
this.remotePort = Number(remote.port)
} else if (remote && remote.ipAddress) {
// Firefox
this.remoteAddress = remote.ipAddress
this.remotePort = Number(remote.portNumber)
} else if (typeof selectedCandidatePair.googRemoteAddress === 'string') {
// TODO: remove this once Chrome 58 is released
remote = selectedCandidatePair.googRemoteAddress.split(':')
this.remoteAddress = remote[0]
this.remotePort = Number(remote[1])
}
if (this.remoteAddress) {
this.remoteFamily = this.remoteAddress.includes(':') ? 'IPv6' : 'IPv4'
}
this._debug(
'connect local: %s:%s remote: %s:%s',
this.localAddress,
this.localPort,
this.remoteAddress,
this.remotePort
)
}
items.forEach(item => {
// Spec-compliant
if (item.type === 'transport' && item.selectedCandidatePairId) {
setSelectedCandidatePair(candidatePairs[item.selectedCandidatePairId])
}
// Old implementations
if (
(item.type === 'googCandidatePair' && item.googActiveConnection === 'true') ||
((item.type === 'candidatepair' || item.type === 'candidate-pair') && item.selected)
) {
setSelectedCandidatePair(item)
}
})
// Ignore candidate pair selection in browsers like Safari 11 that do not have any local or remote candidates
// But wait until at least 1 candidate pair is available
if (!foundSelectedCandidatePair && (!Object.keys(candidatePairs).length || Object.keys(localCandidates).length)) {
setTimeout(findCandidatePair, 100)
return
} else {
this._connecting = false
this._connected = true
}
if (this._chunk) {
try {
this.send(this._chunk)
} catch (err) {
return this.destroy(errCode(err, 'ERR_DATA_CHANNEL'))
}
this._chunk = null
this._debug('sent chunk from "write before connect"')
const cb = this._cb
this._cb = null
cb(null)
}
// If `bufferedAmountLowThreshold` and 'onbufferedamountlow' are unsupported,
// fallback to using setInterval to implement backpressure.
if (typeof this._channel.bufferedAmountLowThreshold !== 'number') {
this._interval = setInterval(() => this._onInterval(), 150)
if (this._interval.unref) this._interval.unref()
}
this._debug('connect')
this.emit('connect')
})
}
findCandidatePair()
}
_onInterval () {
if (!this._cb || !this._channel || this._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) {
return
}
this._onChannelBufferedAmountLow()
}
_onSignalingStateChange () {
if (this.destroyed) return
if (this._pc.signalingState === 'stable') {
this._isNegotiating = false
// HACK: Firefox doesn't yet support removing tracks when signalingState !== 'stable'
this._debug('flushing sender queue', this._sendersAwaitingStable)
this._sendersAwaitingStable.forEach(sender => {
this._pc.removeTrack(sender)
this._queuedNegotiation = true
})
this._sendersAwaitingStable = []
if (this._queuedNegotiation) {
this._debug('flushing negotiation queue')
this._queuedNegotiation = false
this._needsNegotiation() // negotiate again
} else {
this._debug('negotiated')
this.emit('negotiated')
}
}
this._debug('signalingStateChange %s', this._pc.signalingState)
this.emit('signalingStateChange', this._pc.signalingState)
}
_onIceCandidate (event) {
if (this.destroyed) return
if (event.candidate && this.trickle) {
this.emit('signal', {
type: 'candidate',
candidate: {
candidate: event.candidate.candidate,
sdpMLineIndex: event.candidate.sdpMLineIndex,
sdpMid: event.candidate.sdpMid
}
})
} else if (!event.candidate && !this._iceComplete) {
this._iceComplete = true
this.emit('_iceComplete')
}
// as soon as we've received one valid candidate start timeout
if (event.candidate) {
this._startIceCompleteTimeout()
}
}
_onChannelMessage (event) {
if (this.destroyed) return
let data = event.data
if (data instanceof ArrayBuffer) data = Buffer.from(data)
this.push(data)
}
_onChannelBufferedAmountLow () {
if (this.destroyed || !this._cb) return
this._debug('ending backpressure: bufferedAmount %d', this._channel.bufferedAmount)
const cb = this._cb
this._cb = null
cb(null)
}
_onChannelOpen () {
if (this._connected || this.destroyed) return
this._debug('on channel open')
this._channelReady = true
this._maybeReady()
}
_onChannelClose () {
if (this.destroyed) return
this._debug('on channel close')
this.destroy()
}
_onTrack (event) {
if (this.destroyed) return
event.streams.forEach(eventStream => {
this._debug('on track')
this.emit('track', event.track, eventStream)
this._remoteTracks.push({
track: event.track,
stream: eventStream
})
if (this._remoteStreams.some(remoteStream => {
return remoteStream.id === eventStream.id
})) return // Only fire one 'stream' event, even though there may be multiple tracks per stream
this._remoteStreams.push(eventStream)
queueMicrotask(() => {
this._debug('on stream')
this.emit('stream', eventStream) // ensure all tracks have been added
})
})
}
_debug () {
const args = [].slice.call(arguments)
args[0] = '[' + this._id + '] ' + args[0]
debug.apply(null, args)
}
}
Peer.WEBRTC_SUPPORT = !!getBrowserRTC()
/**
* Expose peer and data channel config for overriding all Peer
* instances. Otherwise, just set opts.config or opts.channelConfig
* when constructing a Peer.
*/
Peer.config = {
iceServers: [
{
urls: [
'stun:stun.l.google.com:19302',
'stun:global.stun.twilio.com:3478'
]
}
],
sdpSemantics: 'unified-plan'
}
Peer.channelConfig = {}
module.exports = Peer
},{"buffer":35,"debug":182,"err-code":80,"get-browser-rtc":85,"queue-microtask":166,"randombytes":167,"readable-stream":199}],182:[function(require,module,exports){
(function (process){(function (){
/* eslint-env browser */
/**
* This is the web browser implementation of `debug()`.
*/
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
exports.destroy = (() => {
let warned = false;
return () => {
if (!warned) {
warned = true;
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
};
})();
/**
* Colors.
*/
exports.colors = [
'#0000CC',
'#0000FF',
'#0033CC',
'#0033FF',
'#0066CC',
'#0066FF',
'#0099CC',
'#0099FF',
'#00CC00',
'#00CC33',
'#00CC66',
'#00CC99',
'#00CCCC',
'#00CCFF',
'#3300CC',
'#3300FF',
'#3333CC',
'#3333FF',
'#3366CC',
'#3366FF',
'#3399CC',
'#3399FF',
'#33CC00',
'#33CC33',
'#33CC66',
'#33CC99',
'#33CCCC',
'#33CCFF',
'#6600CC',
'#6600FF',
'#6633CC',
'#6633FF',
'#66CC00',
'#66CC33',
'#9900CC',
'#9900FF',
'#9933CC',
'#9933FF',
'#99CC00',
'#99CC33',
'#CC0000',
'#CC0033',
'#CC0066',
'#CC0099',
'#CC00CC',
'#CC00FF',
'#CC3300',
'#CC3333',
'#CC3366',
'#CC3399',
'#CC33CC',
'#CC33FF',
'#CC6600',
'#CC6633',
'#CC9900',
'#CC9933',
'#CCCC00',
'#CCCC33',
'#FF0000',
'#FF0033',
'#FF0066',
'#FF0099',
'#FF00CC',
'#FF00FF',
'#FF3300',
'#FF3333',
'#FF3366',
'#FF3399',
'#FF33CC',
'#FF33FF',
'#FF6600',
'#FF6633',
'#FF9900',
'#FF9933',
'#FFCC00',
'#FFCC33'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
// eslint-disable-next-line complexity
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
return true;
}
// Internet Explorer and Edge do not support colors.
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
// Is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// Is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// Double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
args[0] = (this.useColors ? '%c' : '') +
this.namespace +
(this.useColors ? ' %c' : ' ') +
args[0] +
(this.useColors ? '%c ' : ' ') +
'+' + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit');
// The final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, match => {
if (match === '%%') {
return;
}
index++;
if (match === '%c') {
// We only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.debug()` when available.
* No-op when `console.debug` is not a "function".
* If `console.debug` is not available, falls back
* to `console.log`.
*
* @api public
*/
exports.log = console.debug || console.log || (() => {});
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem('debug', namespaces);
} else {
exports.storage.removeItem('debug');
}
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
let r;
try {
r = exports.storage.getItem('debug');
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
// The Browser also has localStorage in the global context.
return localStorage;
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
module.exports = require('./common')(exports);
const {formatters} = module.exports;
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
formatters.j = function (v) {
try {
return JSON.stringify(v);
} catch (error) {
return '[UnexpectedJSONParseError]: ' + error.message;
}
};
}).call(this)}).call(this,require('_process'))
},{"./common":183,"_process":160}],183:[function(require,module,exports){
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require('ms');
createDebug.destroy = destroy;
Object.keys(env).forEach(key => {
createDebug[key] = env[key];
});
/**
* The currently active debug mode names, and names to skip.
*/
createDebug.names = [];
createDebug.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = {};
/**
* Selects a color for a debug namespace
* @param {String} namespace The namespace string for the debug instance to be colored
* @return {Number|String} An ANSI color code for the given namespace
* @api private
*/
function selectColor(namespace) {
let hash = 0;
for (let i = 0; i < namespace.length; i++) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
let namespacesCache;
let enabledCache;
function debug(...args) {
// Disabled?
if (!debug.enabled) {
return;
}
const self = debug;
// Set `diff` timestamp
const curr = Number(new Date());
const ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== 'string') {
// Anything else let's inspect with %O
args.unshift('%O');
}
// Apply any `formatters` transformations
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
// If we encounter an escaped % then don't increase the array index
if (match === '%%') {
return '%';
}
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter === 'function') {
const val = args[index];
match = formatter.call(self, val);
// Now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// Apply env-specific formatting (colors, etc.)
createDebug.formatArgs.call(self, args);
const logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.useColors = createDebug.useColors();
debug.color = createDebug.selectColor(namespace);
debug.extend = extend;
debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
Object.defineProperty(debug, 'enabled', {
enumerable: true,
configurable: false,
get: () => {
if (enableOverride !== null) {
return enableOverride;
}
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
},
set: v => {
enableOverride = v;
}
});
// Env-specific initialization logic for debug instances
if (typeof createDebug.init === 'function') {
createDebug.init(debug);
}
return debug;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.namespaces = namespaces;
createDebug.names = [];
createDebug.skips = [];
let i;
const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
const len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
// ignore empty strings
continue;
}
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
} else {
createDebug.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @return {String} namespaces
* @api public
*/
function disable() {
const namespaces = [
...createDebug.names.map(toNamespace),
...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
].join(',');
createDebug.enable('');
return namespaces;
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
if (name[name.length - 1] === '*') {
return true;
}
let i;
let len;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Convert regexp to namespace
*
* @param {RegExp} regxep
* @return {String} namespace
* @api private
*/
function toNamespace(regexp) {
return regexp.toString()
.substring(2, regexp.toString().length - 2)
.replace(/\.\*\?$/, '*');
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
/**
* XXX DO NOT USE. This is a temporary stub function.
* XXX It WILL be removed in the next major release.
*/
function destroy() {
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
createDebug.enable(createDebug.load());
return createDebug;
}
module.exports = setup;
},{"ms":184}],184:[function(require,module,exports){
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'weeks':
case 'week':
case 'w':
return n * w;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + 'd';
}
if (msAbs >= h) {
return Math.round(ms / h) + 'h';
}
if (msAbs >= m) {
return Math.round(ms / m) + 'm';
}
if (msAbs >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, 'day');
}
if (msAbs >= h) {
return plural(ms, msAbs, h, 'hour');
}
if (msAbs >= m) {
return plural(ms, msAbs, m, 'minute');
}
if (msAbs >= s) {
return plural(ms, msAbs, s, 'second');
}
return ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}
},{}],185:[function(require,module,exports){
'use strict';
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var codes = {};
function createErrorType(code, message, Base) {
if (!Base) {
Base = Error;
}
function getMessage(arg1, arg2, arg3) {
if (typeof message === 'string') {
return message;
} else {
return message(arg1, arg2, arg3);
}
}
var NodeError =
/*#__PURE__*/
function (_Base) {
_inheritsLoose(NodeError, _Base);
function NodeError(arg1, arg2, arg3) {
return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
}
return NodeError;
}(Base);
NodeError.prototype.name = Base.name;
NodeError.prototype.code = code;
codes[code] = NodeError;
} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
function oneOf(expected, thing) {
if (Array.isArray(expected)) {
var len = expected.length;
expected = expected.map(function (i) {
return String(i);
});
if (len > 2) {
return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
} else if (len === 2) {
return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
} else {
return "of ".concat(thing, " ").concat(expected[0]);
}
} else {
return "of ".concat(thing, " ").concat(String(expected));
}
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
function startsWith(str, search, pos) {
return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
function endsWith(str, search, this_len) {
if (this_len === undefined || this_len > str.length) {
this_len = str.length;
}
return str.substring(this_len - search.length, this_len) === search;
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
function includes(str, search, start) {
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > str.length) {
return false;
} else {
return str.indexOf(search, start) !== -1;
}
}
createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
return 'The value "' + value + '" is invalid for option "' + name + '"';
}, TypeError);
createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
// determiner: 'must be' or 'must not be'
var determiner;
if (typeof expected === 'string' && startsWith(expected, 'not ')) {
determiner = 'must not be';
expected = expected.replace(/^not /, '');
} else {
determiner = 'must be';
}
var msg;
if (endsWith(name, ' argument')) {
// For cases like 'first argument'
msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
} else {
var type = includes(name, '.') ? 'property' : 'argument';
msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
}
msg += ". Received type ".concat(typeof actual);
return msg;
}, TypeError);
createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
return 'The ' + name + ' method is not implemented';
});
createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
createErrorType('ERR_STREAM_DESTROYED', function (name) {
return 'Cannot call ' + name + ' after a stream was destroyed';
});
createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
return 'Unknown encoding: ' + arg;
}, TypeError);
createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
module.exports.codes = codes;
},{}],186:[function(require,module,exports){
(function (process){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
'use strict';
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
};
/*</replacement>*/
module.exports = Duplex;
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
require('inherits')(Duplex, Readable);
{
// Allow the keys array to be GC'ed.
var keys = objectKeys(Writable.prototype);
for (var v = 0; v < keys.length; v++) {
var method = keys[v];
if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
}
}
function Duplex(options) {
if (!(this instanceof Duplex)) return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
this.allowHalfOpen = true;
if (options) {
if (options.readable === false) this.readable = false;
if (options.writable === false) this.writable = false;
if (options.allowHalfOpen === false) {
this.allowHalfOpen = false;
this.once('end', onend);
}
}
}
Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._writableState.highWaterMark;
}
});
Object.defineProperty(Duplex.prototype, 'writableBuffer', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._writableState && this._writableState.getBuffer();
}
});
Object.defineProperty(Duplex.prototype, 'writableLength', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._writableState.length;
}
});
// the no-half-open enforcer
function onend() {
// If the writable side ended, then we're ok.
if (this._writableState.ended) return;
// no more data can be written.
// But allow more writes to happen in this tick.
process.nextTick(onEndNT, this);
}
function onEndNT(self) {
self.end();
}
Object.defineProperty(Duplex.prototype, 'destroyed', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
if (this._readableState === undefined || this._writableState === undefined) {
return false;
}
return this._readableState.destroyed && this._writableState.destroyed;
},
set: function set(value) {
// we ignore the value if the stream
// has not been initialized yet
if (this._readableState === undefined || this._writableState === undefined) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
this._writableState.destroyed = value;
}
});
}).call(this)}).call(this,require('_process'))
},{"./_stream_readable":188,"./_stream_writable":190,"_process":160,"inherits":102}],187:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
'use strict';
module.exports = PassThrough;
var Transform = require('./_stream_transform');
require('inherits')(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough)) return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function (chunk, encoding, cb) {
cb(null, chunk);
};
},{"./_stream_transform":189,"inherits":102}],188:[function(require,module,exports){
(function (process,global){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
module.exports = Readable;
/*<replacement>*/
var Duplex;
/*</replacement>*/
Readable.ReadableState = ReadableState;
/*<replacement>*/
var EE = require('events').EventEmitter;
var EElistenerCount = function EElistenerCount(emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
/*<replacement>*/
var Stream = require('./internal/streams/stream');
/*</replacement>*/
var Buffer = require('buffer').Buffer;
var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
/*<replacement>*/
var debugUtil = require('util');
var debug;
if (debugUtil && debugUtil.debuglog) {
debug = debugUtil.debuglog('stream');
} else {
debug = function debug() {};
}
/*</replacement>*/
var BufferList = require('./internal/streams/buffer_list');
var destroyImpl = require('./internal/streams/destroy');
var _require = require('./internal/streams/state'),
getHighWaterMark = _require.getHighWaterMark;
var _require$codes = require('../errors').codes,
ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;
// Lazy loaded to improve the startup performance.
var StringDecoder;
var createReadableStreamAsyncIterator;
var from;
require('inherits')(Readable, Stream);
var errorOrDestroy = destroyImpl.errorOrDestroy;
var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
function prependListener(emitter, event, fn) {
// Sadly this is not cacheable as some libraries bundle their own
// event emitter implementation with them.
if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
// This is a hack to make sure that our error handler is attached before any
// userland ones. NEVER DO THIS. This is here only because this code needs
// to continue to work with older versions of Node.js that do not include
// the prependListener() method. The goal is to eventually remove this hack.
if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
}
function ReadableState(options, stream, isDuplex) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// Duplex streams are both readable and writable, but share
// the same options object.
// However, some cases require setting options to different
// values for the readable and the writable sides of the duplex stream.
// These options can be provided separately as readableXXX and writableXXX.
if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex);
// A linked list is used to store data chunks instead of an array because the
// linked list can remove elements from the beginning faster than
// array.shift()
this.buffer = new BufferList();
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = null;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// a flag to be able to tell if the event 'readable'/'data' is emitted
// immediately, or on a later tick. We set this to true at first, because
// any actions that shouldn't happen until "later" should generally also
// not happen before the first read call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
this.resumeScheduled = false;
this.paused = true;
// Should close be emitted on destroy. Defaults to true.
this.emitClose = options.emitClose !== false;
// Should .destroy() be called after 'end' (and potentially 'finish')
this.autoDestroy = !!options.autoDestroy;
// has it been destroyed
this.destroyed = false;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
function Readable(options) {
Duplex = Duplex || require('./_stream_duplex');
if (!(this instanceof Readable)) return new Readable(options);
// Checking for a Stream.Duplex instance is faster here instead of inside
// the ReadableState constructor, at least with V8 6.5
var isDuplex = this instanceof Duplex;
this._readableState = new ReadableState(options, this, isDuplex);
// legacy
this.readable = true;
if (options) {
if (typeof options.read === 'function') this._read = options.read;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
}
Stream.call(this);
}
Object.defineProperty(Readable.prototype, 'destroyed', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
if (this._readableState === undefined) {
return false;
}
return this._readableState.destroyed;
},
set: function set(value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._readableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
}
});
Readable.prototype.destroy = destroyImpl.destroy;
Readable.prototype._undestroy = destroyImpl.undestroy;
Readable.prototype._destroy = function (err, cb) {
cb(err);
};
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
var state = this._readableState;
var skipChunkCheck;
if (!state.objectMode) {
if (typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = Buffer.from(chunk, encoding);
encoding = '';
}
skipChunkCheck = true;
}
} else {
skipChunkCheck = true;
}
return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function (chunk) {
return readableAddChunk(this, chunk, null, true, false);
};
function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
debug('readableAddChunk', chunk);
var state = stream._readableState;
if (chunk === null) {
state.reading = false;
onEofChunk(stream, state);
} else {
var er;
if (!skipChunkCheck) er = chunkInvalid(state, chunk);
if (er) {
errorOrDestroy(stream, er);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (addToFront) {
if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
} else if (state.ended) {
errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
} else if (state.destroyed) {
return false;
} else {
state.reading = false;
if (state.decoder && !encoding) {
chunk = state.decoder.write(chunk);
if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
} else {
addChunk(stream, state, chunk, false);
}
}
} else if (!addToFront) {
state.reading = false;
maybeReadMore(stream, state);
}
}
// We can push more data if we are below the highWaterMark.
// Also, if we have no data yet, we can stand some more bytes.
// This is to work around cases where hwm=0, such as the repl.
return !state.ended && (state.length < state.highWaterMark || state.length === 0);
}
function addChunk(stream, state, chunk, addToFront) {
if (state.flowing && state.length === 0 && !state.sync) {
state.awaitDrain = 0;
stream.emit('data', chunk);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
if (state.needReadable) emitReadable(stream);
}
maybeReadMore(stream, state);
}
function chunkInvalid(state, chunk) {
var er;
if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
}
return er;
}
Readable.prototype.isPaused = function () {
return this._readableState.flowing === false;
};
// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
var decoder = new StringDecoder(enc);
this._readableState.decoder = decoder;
// If setEncoding(null), decoder.encoding equals utf8
this._readableState.encoding = this._readableState.decoder.encoding;
// Iterate over current buffer to convert already stored Buffers:
var p = this._readableState.buffer.head;
var content = '';
while (p !== null) {
content += decoder.write(p.data);
p = p.next;
}
this._readableState.buffer.clear();
if (content !== '') this._readableState.buffer.push(content);
this._readableState.length = content.length;
return this;
};
// Don't raise the hwm > 1GB
var MAX_HWM = 0x40000000;
function computeNewHighWaterMark(n) {
if (n >= MAX_HWM) {
// TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
n = MAX_HWM;
} else {
// Get the next highest power of 2 to prevent increasing hwm excessively in
// tiny amounts
n--;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
n++;
}
return n;
}
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
if (n <= 0 || state.length === 0 && state.ended) return 0;
if (state.objectMode) return 1;
if (n !== n) {
// Only flow one buffer at a time
if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
}
// If we're asking for more than the current hwm, then raise the hwm.
if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
if (n <= state.length) return n;
// Don't have enough
if (!state.ended) {
state.needReadable = true;
return 0;
}
return state.length;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
debug('read', n);
n = parseInt(n, 10);
var state = this._readableState;
var nOrig = n;
if (n !== 0) state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
debug('read: emitReadable', state.length, state.ended);
if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
if (state.length === 0) endReadable(this);
return null;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
debug('need readable', doRead);
// if we currently have less than the highWaterMark, then also read some
if (state.length === 0 || state.length - n < state.highWaterMark) {
doRead = true;
debug('length less than watermark', doRead);
}
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading) {
doRead = false;
debug('reading or ended', doRead);
} else if (doRead) {
debug('do read');
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0) state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
// If _read pushed data synchronously, then `reading` will be false,
// and we need to re-evaluate how much data we can return to the user.
if (!state.reading) n = howMuchToRead(nOrig, state);
}
var ret;
if (n > 0) ret = fromList(n, state);else ret = null;
if (ret === null) {
state.needReadable = state.length <= state.highWaterMark;
n = 0;
} else {
state.length -= n;
state.awaitDrain = 0;
}
if (state.length === 0) {
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (!state.ended) state.needReadable = true;
// If we tried to read() past the EOF, then emit end on the next tick.
if (nOrig !== n && state.ended) endReadable(this);
}
if (ret !== null) this.emit('data', ret);
return ret;
};
function onEofChunk(stream, state) {
debug('onEofChunk');
if (state.ended) return;
if (state.decoder) {
var chunk = state.decoder.end();
if (chunk && chunk.length) {
state.buffer.push(chunk);
state.length += state.objectMode ? 1 : chunk.length;
}
}
state.ended = true;
if (state.sync) {
// if we are sync, wait until next tick to emit the data.
// Otherwise we risk emitting data in the flow()
// the readable code triggers during a read() call
emitReadable(stream);
} else {
// emit 'readable' now to make sure it gets picked up.
state.needReadable = false;
if (!state.emittedReadable) {
state.emittedReadable = true;
emitReadable_(stream);
}
}
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
debug('emitReadable', state.needReadable, state.emittedReadable);
state.needReadable = false;
if (!state.emittedReadable) {
debug('emitReadable', state.flowing);
state.emittedReadable = true;
process.nextTick(emitReadable_, stream);
}
}
function emitReadable_(stream) {
var state = stream._readableState;
debug('emitReadable_', state.destroyed, state.length, state.ended);
if (!state.destroyed && (state.length || state.ended)) {
stream.emit('readable');
state.emittedReadable = false;
}
// The stream needs another readable event if
// 1. It is not flowing, as the flow mechanism will take
// care of it.
// 2. It is not ended.
// 3. It is below the highWaterMark, so we can schedule
// another readable later.
state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
flow(stream);
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
process.nextTick(maybeReadMore_, stream, state);
}
}
function maybeReadMore_(stream, state) {
// Attempt to read more data if we should.
//
// The conditions for reading more data are (one of):
// - Not enough data buffered (state.length < state.highWaterMark). The loop
// is responsible for filling the buffer with enough data if such data
// is available. If highWaterMark is 0 and we are not in the flowing mode
// we should _not_ attempt to buffer any extra data. We'll get more data
// when the stream consumer calls read() instead.
// - No data in the buffer, and the stream is in flowing mode. In this mode
// the loop below is responsible for ensuring read() is called. Failing to
// call read here would abort the flow and there's no other mechanism for
// continuing the flow if the stream consumer has just subscribed to the
// 'data' event.
//
// In addition to the above conditions to keep reading data, the following
// conditions prevent the data from being read:
// - The stream has ended (state.ended).
// - There is already a pending 'read' operation (state.reading). This is a
// case where the the stream has called the implementation defined _read()
// method, but they are processing the call asynchronously and have _not_
// called push() with new data. In this case we skip performing more
// read()s. The execution ends in this method again after the _read() ends
// up calling push() with more data.
while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
var len = state.length;
debug('maybeReadMore read 0');
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
};
Readable.prototype.pipe = function (dest, pipeOpts) {
var src = this;
var state = this._readableState;
switch (state.pipesCount) {
case 0:
state.pipes = dest;
break;
case 1:
state.pipes = [state.pipes, dest];
break;
default:
state.pipes.push(dest);
break;
}
state.pipesCount += 1;
debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
var endFn = doEnd ? onend : unpipe;
if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable, unpipeInfo) {
debug('onunpipe');
if (readable === src) {
if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
unpipeInfo.hasUnpiped = true;
cleanup();
}
}
}
function onend() {
debug('onend');
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
var cleanedUp = false;
function cleanup() {
debug('cleanup');
// cleanup event handlers once the pipe is broken
dest.removeListener('close', onclose);
dest.removeListener('finish', onfinish);
dest.removeListener('drain', ondrain);
dest.removeListener('error', onerror);
dest.removeListener('unpipe', onunpipe);
src.removeListener('end', onend);
src.removeListener('end', unpipe);
src.removeListener('data', ondata);
cleanedUp = true;
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
}
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
var ret = dest.write(chunk);
debug('dest.write', ret);
if (ret === false) {
// If the user unpiped during `dest.write()`, it is possible
// to get stuck in a permanently paused state if that write
// also returned false.
// => Check whether `dest` is still a piping destination.
if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
debug('false write response, pause', state.awaitDrain);
state.awaitDrain++;
}
src.pause();
}
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
debug('onerror', er);
unpipe();
dest.removeListener('error', onerror);
if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
}
// Make sure our error handler is attached before userland ones.
prependListener(dest, 'error', onerror);
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
debug('onfinish');
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
debug('unpipe');
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
debug('pipe resume');
src.resume();
}
return dest;
};
function pipeOnDrain(src) {
return function pipeOnDrainFunctionResult() {
var state = src._readableState;
debug('pipeOnDrain', state.awaitDrain);
if (state.awaitDrain) state.awaitDrain--;
if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
state.flowing = true;
flow(src);
}
};
}
Readable.prototype.unpipe = function (dest) {
var state = this._readableState;
var unpipeInfo = {
hasUnpiped: false
};
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0) return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes) return this;
if (!dest) dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
if (dest) dest.emit('unpipe', this, unpipeInfo);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, {
hasUnpiped: false
});
return this;
}
// try to find the right one.
var index = indexOf(state.pipes, dest);
if (index === -1) return this;
state.pipes.splice(index, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1) state.pipes = state.pipes[0];
dest.emit('unpipe', this, unpipeInfo);
return this;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
var state = this._readableState;
if (ev === 'data') {
// update readableListening so that resume() may be a no-op
// a few lines down. This is needed to support once('readable').
state.readableListening = this.listenerCount('readable') > 0;
// Try start flowing on next tick if stream isn't explicitly paused
if (state.flowing !== false) this.resume();
} else if (ev === 'readable') {
if (!state.endEmitted && !state.readableListening) {
state.readableListening = state.needReadable = true;
state.flowing = false;
state.emittedReadable = false;
debug('on readable', state.length, state.reading);
if (state.length) {
emitReadable(this);
} else if (!state.reading) {
process.nextTick(nReadingNextTick, this);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
Readable.prototype.removeListener = function (ev, fn) {
var res = Stream.prototype.removeListener.call(this, ev, fn);
if (ev === 'readable') {
// We need to check if there is someone still listening to
// readable and reset the state. However this needs to happen
// after readable has been emitted but before I/O (nextTick) to
// support once('readable', fn) cycles. This means that calling
// resume within the same tick will have no
// effect.
process.nextTick(updateReadableListening, this);
}
return res;
};
Readable.prototype.removeAllListeners = function (ev) {
var res = Stream.prototype.removeAllListeners.apply(this, arguments);
if (ev === 'readable' || ev === undefined) {
// We need to check if there is someone still listening to
// readable and reset the state. However this needs to happen
// after readable has been emitted but before I/O (nextTick) to
// support once('readable', fn) cycles. This means that calling
// resume within the same tick will have no
// effect.
process.nextTick(updateReadableListening, this);
}
return res;
};
function updateReadableListening(self) {
var state = self._readableState;
state.readableListening = self.listenerCount('readable') > 0;
if (state.resumeScheduled && !state.paused) {
// flowing needs to be set to true now, otherwise
// the upcoming resume will not flow.
state.flowing = true;
// crude way to check if we should resume
} else if (self.listenerCount('data') > 0) {
self.resume();
}
}
function nReadingNextTick(self) {
debug('readable nexttick read 0');
self.read(0);
}
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
var state = this._readableState;
if (!state.flowing) {
debug('resume');
// we flow only if there is no one listening
// for readable, but we still have to call
// resume()
state.flowing = !state.readableListening;
resume(this, state);
}
state.paused = false;
return this;
};
function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;
process.nextTick(resume_, stream, state);
}
}
function resume_(stream, state) {
debug('resume', state.reading);
if (!state.reading) {
stream.read(0);
}
state.resumeScheduled = false;
stream.emit('resume');
flow(stream);
if (state.flowing && !state.reading) stream.read(0);
}
Readable.prototype.pause = function () {
debug('call pause flowing=%j', this._readableState.flowing);
if (this._readableState.flowing !== false) {
debug('pause');
this._readableState.flowing = false;
this.emit('pause');
}
this._readableState.paused = true;
return this;
};
function flow(stream) {
var state = stream._readableState;
debug('flow', state.flowing);
while (state.flowing && stream.read() !== null);
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
var _this = this;
var state = this._readableState;
var paused = false;
stream.on('end', function () {
debug('wrapped end');
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) _this.push(chunk);
}
_this.push(null);
});
stream.on('data', function (chunk) {
debug('wrapped data');
if (state.decoder) chunk = state.decoder.write(chunk);
// don't skip over falsy values in objectMode
if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
var ret = _this.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (this[i] === undefined && typeof stream[i] === 'function') {
this[i] = function methodWrap(method) {
return function methodWrapReturnFunction() {
return stream[method].apply(stream, arguments);
};
}(i);
}
}
// proxy certain important events.
for (var n = 0; n < kProxyEvents.length; n++) {
stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
}
// when we try to consume some more bytes, simply unpause the
// underlying stream.
this._read = function (n) {
debug('wrapped _read', n);
if (paused) {
paused = false;
stream.resume();
}
};
return this;
};
if (typeof Symbol === 'function') {
Readable.prototype[Symbol.asyncIterator] = function () {
if (createReadableStreamAsyncIterator === undefined) {
createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');
}
return createReadableStreamAsyncIterator(this);
};
}
Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._readableState.highWaterMark;
}
});
Object.defineProperty(Readable.prototype, 'readableBuffer', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._readableState && this._readableState.buffer;
}
});
Object.defineProperty(Readable.prototype, 'readableFlowing', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._readableState.flowing;
},
set: function set(state) {
if (this._readableState) {
this._readableState.flowing = state;
}
}
});
// exposed for testing purposes only.
Readable._fromList = fromList;
Object.defineProperty(Readable.prototype, 'readableLength', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._readableState.length;
}
});
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromList(n, state) {
// nothing buffered
if (state.length === 0) return null;
var ret;
if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
// read it all, truncate the list
if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
state.buffer.clear();
} else {
// read part of list
ret = state.buffer.consume(n, state.decoder);
}
return ret;
}
function endReadable(stream) {
var state = stream._readableState;
debug('endReadable', state.endEmitted);
if (!state.endEmitted) {
state.ended = true;
process.nextTick(endReadableNT, state, stream);
}
}
function endReadableNT(state, stream) {
debug('endReadableNT', state.endEmitted, state.length);
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
if (state.autoDestroy) {
// In case of duplex streams we need a way to detect
// if the writable side is ready for autoDestroy as well
var wState = stream._writableState;
if (!wState || wState.autoDestroy && wState.finished) {
stream.destroy();
}
}
}
}
if (typeof Symbol === 'function') {
Readable.from = function (iterable, opts) {
if (from === undefined) {
from = require('./internal/streams/from');
}
return from(Readable, iterable, opts);
};
}
function indexOf(xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../errors":185,"./_stream_duplex":186,"./internal/streams/async_iterator":191,"./internal/streams/buffer_list":192,"./internal/streams/destroy":193,"./internal/streams/from":195,"./internal/streams/state":197,"./internal/streams/stream":198,"_process":160,"buffer":35,"events":81,"inherits":102,"string_decoder/":216,"util":34}],189:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
'use strict';
module.exports = Transform;
var _require$codes = require('../errors').codes,
ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
var Duplex = require('./_stream_duplex');
require('inherits')(Transform, Duplex);
function afterTransform(er, data) {
var ts = this._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (cb === null) {
return this.emit('error', new ERR_MULTIPLE_CALLBACK());
}
ts.writechunk = null;
ts.writecb = null;
if (data != null)
// single equals check for both `null` and `undefined`
this.push(data);
cb(er);
var rs = this._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
this._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform)) return new Transform(options);
Duplex.call(this, options);
this._transformState = {
afterTransform: afterTransform.bind(this),
needTransform: false,
transforming: false,
writecb: null,
writechunk: null,
writeencoding: null
};
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
if (options) {
if (typeof options.transform === 'function') this._transform = options.transform;
if (typeof options.flush === 'function') this._flush = options.flush;
}
// When the writable side finishes, then flush out anything remaining.
this.on('prefinish', prefinish);
}
function prefinish() {
var _this = this;
if (typeof this._flush === 'function' && !this._readableState.destroyed) {
this._flush(function (er, data) {
done(_this, er, data);
});
} else {
done(this, null, null);
}
}
Transform.prototype.push = function (chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
};
Transform.prototype._write = function (chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
var ts = this._transformState;
if (ts.writechunk !== null && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
Transform.prototype._destroy = function (err, cb) {
Duplex.prototype._destroy.call(this, err, function (err2) {
cb(err2);
});
};
function done(stream, er, data) {
if (er) return stream.emit('error', er);
if (data != null)
// single equals check for both `null` and `undefined`
stream.push(data);
// TODO(BridgeAR): Write a test for these two error cases
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
return stream.push(null);
}
},{"../errors":185,"./_stream_duplex":186,"inherits":102}],190:[function(require,module,exports){
(function (process,global){(function (){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.
'use strict';
module.exports = Writable;
/* <replacement> */
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
this.next = null;
}
// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
var _this = this;
this.next = null;
this.entry = null;
this.finish = function () {
onCorkedFinish(_this, state);
};
}
/* </replacement> */
/*<replacement>*/
var Duplex;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var internalUtil = {
deprecate: require('util-deprecate')
};
/*</replacement>*/
/*<replacement>*/
var Stream = require('./internal/streams/stream');
/*</replacement>*/
var Buffer = require('buffer').Buffer;
var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
var destroyImpl = require('./internal/streams/destroy');
var _require = require('./internal/streams/state'),
getHighWaterMark = _require.getHighWaterMark;
var _require$codes = require('../errors').codes,
ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
var errorOrDestroy = destroyImpl.errorOrDestroy;
require('inherits')(Writable, Stream);
function nop() {}
function WritableState(options, stream, isDuplex) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// Duplex streams are both readable and writable, but share
// the same options object.
// However, some cases require setting options to different
// values for the readable and the writable sides of the duplex stream,
// e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex);
// if _final has been called
this.finalCalled = false;
// drain event flag.
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// has it been destroyed
this.destroyed = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function (er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.bufferedRequest = null;
this.lastBufferedRequest = null;
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
// Should close be emitted on destroy. Defaults to true.
this.emitClose = options.emitClose !== false;
// Should .destroy() be called after 'finish' (and potentially 'end')
this.autoDestroy = !!options.autoDestroy;
// count buffered requests
this.bufferedRequestCount = 0;
// allocate the first CorkedRequest, there is always
// one allocated and free to use, and we maintain at most two
this.corkedRequestsFree = new CorkedRequest(this);
}
WritableState.prototype.getBuffer = function getBuffer() {
var current = this.bufferedRequest;
var out = [];
while (current) {
out.push(current);
current = current.next;
}
return out;
};
(function () {
try {
Object.defineProperty(WritableState.prototype, 'buffer', {
get: internalUtil.deprecate(function writableStateBufferGetter() {
return this.getBuffer();
}, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
});
} catch (_) {}
})();
// Test _writableState for inheritance to account for Duplex streams,
// whose prototype chain only points to Readable.
var realHasInstance;
if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
realHasInstance = Function.prototype[Symbol.hasInstance];
Object.defineProperty(Writable, Symbol.hasInstance, {
value: function value(object) {
if (realHasInstance.call(this, object)) return true;
if (this !== Writable) return false;
return object && object._writableState instanceof WritableState;
}
});
} else {
realHasInstance = function realHasInstance(object) {
return object instanceof this;
};
}
function Writable(options) {
Duplex = Duplex || require('./_stream_duplex');
// Writable ctor is applied to Duplexes, too.
// `realHasInstance` is necessary because using plain `instanceof`
// would return false, as no `_writableState` property is attached.
// Trying to use the custom `instanceof` for Writable here will also break the
// Node.js LazyTransform implementation, which has a non-trivial getter for
// `_writableState` that would lead to infinite recursion.
// Checking for a Stream.Duplex instance is faster here instead of inside
// the WritableState constructor, at least with V8 6.5
var isDuplex = this instanceof Duplex;
if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
this._writableState = new WritableState(options, this, isDuplex);
// legacy.
this.writable = true;
if (options) {
if (typeof options.write === 'function') this._write = options.write;
if (typeof options.writev === 'function') this._writev = options.writev;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
if (typeof options.final === 'function') this._final = options.final;
}
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
};
function writeAfterEnd(stream, cb) {
var er = new ERR_STREAM_WRITE_AFTER_END();
// TODO: defer error events consistently everywhere, not just the cb
errorOrDestroy(stream, er);
process.nextTick(cb, er);
}
// Checks that a user-supplied chunk is valid, especially for the particular
// mode the stream is in. Currently this means that `null` is never accepted
// and undefined/non-string values are only allowed in object mode.
function validChunk(stream, state, chunk, cb) {
var er;
if (chunk === null) {
er = new ERR_STREAM_NULL_VALUES();
} else if (typeof chunk !== 'string' && !state.objectMode) {
er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
}
if (er) {
errorOrDestroy(stream, er);
process.nextTick(cb, er);
return false;
}
return true;
}
Writable.prototype.write = function (chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
var isBuf = !state.objectMode && _isUint8Array(chunk);
if (isBuf && !Buffer.isBuffer(chunk)) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
if (typeof cb !== 'function') cb = nop;
if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function () {
this._writableState.corked++;
};
Writable.prototype.uncork = function () {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
}
};
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
// node::ParseEncoding() requires lower case.
if (typeof encoding === 'string') encoding = encoding.toLowerCase();
if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
this._writableState.defaultEncoding = encoding;
return this;
};
Object.defineProperty(Writable.prototype, 'writableBuffer', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._writableState && this._writableState.getBuffer();
}
});
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
chunk = Buffer.from(chunk, encoding);
}
return chunk;
}
Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._writableState.highWaterMark;
}
});
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
if (!isBuf) {
var newChunk = decodeChunk(state, chunk, encoding);
if (chunk !== newChunk) {
isBuf = true;
encoding = 'buffer';
chunk = newChunk;
}
}
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret) state.needDrain = true;
if (state.writing || state.corked) {
var last = state.lastBufferedRequest;
state.lastBufferedRequest = {
chunk: chunk,
encoding: encoding,
isBuf: isBuf,
callback: cb,
next: null
};
if (last) {
last.next = state.lastBufferedRequest;
} else {
state.bufferedRequest = state.lastBufferedRequest;
}
state.bufferedRequestCount += 1;
} else {
doWrite(stream, state, false, len, chunk, encoding, cb);
}
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
--state.pendingcb;
if (sync) {
// defer the callback if we are being called synchronously
// to avoid piling up things on the stack
process.nextTick(cb, er);
// this can emit finish, and it will always happen
// after error
process.nextTick(finishMaybe, stream, state);
stream._writableState.errorEmitted = true;
errorOrDestroy(stream, er);
} else {
// the caller expect this to happen before if
// it is async
cb(er);
stream._writableState.errorEmitted = true;
errorOrDestroy(stream, er);
// this can emit finish, but finish must
// always follow error
finishMaybe(stream, state);
}
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
onwriteStateUpdate(state);
if (er) onwriteError(stream, state, sync, er, cb);else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(state) || stream.destroyed;
if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
clearBuffer(stream, state);
}
if (sync) {
process.nextTick(afterWrite, stream, state, finished, cb);
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished) onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
var entry = state.bufferedRequest;
if (stream._writev && entry && entry.next) {
// Fast case, write everything using _writev()
var l = state.bufferedRequestCount;
var buffer = new Array(l);
var holder = state.corkedRequestsFree;
holder.entry = entry;
var count = 0;
var allBuffers = true;
while (entry) {
buffer[count] = entry;
if (!entry.isBuf) allBuffers = false;
entry = entry.next;
count += 1;
}
buffer.allBuffers = allBuffers;
doWrite(stream, state, true, state.length, buffer, '', holder.finish);
// doWrite is almost always async, defer these to save a bit of time
// as the hot path ends with doWrite
state.pendingcb++;
state.lastBufferedRequest = null;
if (holder.next) {
state.corkedRequestsFree = holder.next;
holder.next = null;
} else {
state.corkedRequestsFree = new CorkedRequest(state);
}
state.bufferedRequestCount = 0;
} else {
// Slow case, write chunks one-by-one
while (entry) {
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
entry = entry.next;
state.bufferedRequestCount--;
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
break;
}
}
if (entry === null) state.lastBufferedRequest = null;
}
state.bufferedRequest = entry;
state.bufferProcessing = false;
}
Writable.prototype._write = function (chunk, encoding, cb) {
cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function (chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending) endWritable(this, state, cb);
return this;
};
Object.defineProperty(Writable.prototype, 'writableLength', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._writableState.length;
}
});
function needFinish(state) {
return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function callFinal(stream, state) {
stream._final(function (err) {
state.pendingcb--;
if (err) {
errorOrDestroy(stream, err);
}
state.prefinished = true;
stream.emit('prefinish');
finishMaybe(stream, state);
});
}
function prefinish(stream, state) {
if (!state.prefinished && !state.finalCalled) {
if (typeof stream._final === 'function' && !state.destroyed) {
state.pendingcb++;
state.finalCalled = true;
process.nextTick(callFinal, stream, state);
} else {
state.prefinished = true;
stream.emit('prefinish');
}
}
}
function finishMaybe(stream, state) {
var need = needFinish(state);
if (need) {
prefinish(stream, state);
if (state.pendingcb === 0) {
state.finished = true;
stream.emit('finish');
if (state.autoDestroy) {
// In case of duplex streams we need a way to detect
// if the readable side is ready for autoDestroy as well
var rState = stream._readableState;
if (!rState || rState.autoDestroy && rState.endEmitted) {
stream.destroy();
}
}
}
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
}
state.ended = true;
stream.writable = false;
}
function onCorkedFinish(corkReq, state, err) {
var entry = corkReq.entry;
corkReq.entry = null;
while (entry) {
var cb = entry.callback;
state.pendingcb--;
cb(err);
entry = entry.next;
}
// reuse the free corkReq.
state.corkedRequestsFree.next = corkReq;
}
Object.defineProperty(Writable.prototype, 'destroyed', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
if (this._writableState === undefined) {
return false;
}
return this._writableState.destroyed;
},
set: function set(value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._writableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._writableState.destroyed = value;
}
});
Writable.prototype.destroy = destroyImpl.destroy;
Writable.prototype._undestroy = destroyImpl.undestroy;
Writable.prototype._destroy = function (err, cb) {
cb(err);
};
}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../errors":185,"./_stream_duplex":186,"./internal/streams/destroy":193,"./internal/streams/state":197,"./internal/streams/stream":198,"_process":160,"buffer":35,"inherits":102,"util-deprecate":223}],191:[function(require,module,exports){
(function (process){(function (){
'use strict';
var _Object$setPrototypeO;
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var finished = require('./end-of-stream');
var kLastResolve = Symbol('lastResolve');
var kLastReject = Symbol('lastReject');
var kError = Symbol('error');
var kEnded = Symbol('ended');
var kLastPromise = Symbol('lastPromise');
var kHandlePromise = Symbol('handlePromise');
var kStream = Symbol('stream');
function createIterResult(value, done) {
return {
value: value,
done: done
};
}
function readAndResolve(iter) {
var resolve = iter[kLastResolve];
if (resolve !== null) {
var data = iter[kStream].read();
// we defer if data is null
// we can be expecting either 'end' or
// 'error'
if (data !== null) {
iter[kLastPromise] = null;
iter[kLastResolve] = null;
iter[kLastReject] = null;
resolve(createIterResult(data, false));
}
}
}
function onReadable(iter) {
// we wait for the next tick, because it might
// emit an error with process.nextTick
process.nextTick(readAndResolve, iter);
}
function wrapForNext(lastPromise, iter) {
return function (resolve, reject) {
lastPromise.then(function () {
if (iter[kEnded]) {
resolve(createIterResult(undefined, true));
return;
}
iter[kHandlePromise](resolve, reject);
}, reject);
};
}
var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
get stream() {
return this[kStream];
},
next: function next() {
var _this = this;
// if we have detected an error in the meanwhile
// reject straight away
var error = this[kError];
if (error !== null) {
return Promise.reject(error);
}
if (this[kEnded]) {
return Promise.resolve(createIterResult(undefined, true));
}
if (this[kStream].destroyed) {
// We need to defer via nextTick because if .destroy(err) is
// called, the error will be emitted via nextTick, and
// we cannot guarantee that there is no error lingering around
// waiting to be emitted.
return new Promise(function (resolve, reject) {
process.nextTick(function () {
if (_this[kError]) {
reject(_this[kError]);
} else {
resolve(createIterResult(undefined, true));
}
});
});
}
// if we have multiple next() calls
// we will wait for the previous Promise to finish
// this logic is optimized to support for await loops,
// where next() is only called once at a time
var lastPromise = this[kLastPromise];
var promise;
if (lastPromise) {
promise = new Promise(wrapForNext(lastPromise, this));
} else {
// fast path needed to support multiple this.push()
// without triggering the next() queue
var data = this[kStream].read();
if (data !== null) {
return Promise.resolve(createIterResult(data, false));
}
promise = new Promise(this[kHandlePromise]);
}
this[kLastPromise] = promise;
return promise;
}
}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
return this;
}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
var _this2 = this;
// destroy(err, cb) is a private API
// we can guarantee we have that here, because we control the
// Readable class this is attached to
return new Promise(function (resolve, reject) {
_this2[kStream].destroy(null, function (err) {
if (err) {
reject(err);
return;
}
resolve(createIterResult(undefined, true));
});
});
}), _Object$setPrototypeO), AsyncIteratorPrototype);
var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
var _Object$create;
var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
value: stream,
writable: true
}), _defineProperty(_Object$create, kLastResolve, {
value: null,
writable: true
}), _defineProperty(_Object$create, kLastReject, {
value: null,
writable: true
}), _defineProperty(_Object$create, kError, {
value: null,
writable: true
}), _defineProperty(_Object$create, kEnded, {
value: stream._readableState.endEmitted,
writable: true
}), _defineProperty(_Object$create, kHandlePromise, {
value: function value(resolve, reject) {
var data = iterator[kStream].read();
if (data) {
iterator[kLastPromise] = null;
iterator[kLastResolve] = null;
iterator[kLastReject] = null;
resolve(createIterResult(data, false));
} else {
iterator[kLastResolve] = resolve;
iterator[kLastReject] = reject;
}
},
writable: true
}), _Object$create));
iterator[kLastPromise] = null;
finished(stream, function (err) {
if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
var reject = iterator[kLastReject];
// reject if we are waiting for data in the Promise
// returned by next() and store the error
if (reject !== null) {
iterator[kLastPromise] = null;
iterator[kLastResolve] = null;
iterator[kLastReject] = null;
reject(err);
}
iterator[kError] = err;
return;
}
var resolve = iterator[kLastResolve];
if (resolve !== null) {
iterator[kLastPromise] = null;
iterator[kLastResolve] = null;
iterator[kLastReject] = null;
resolve(createIterResult(undefined, true));
}
iterator[kEnded] = true;
});
stream.on('readable', onReadable.bind(null, iterator));
return iterator;
};
module.exports = createReadableStreamAsyncIterator;
}).call(this)}).call(this,require('_process'))
},{"./end-of-stream":194,"_process":160}],192:[function(require,module,exports){
'use strict';
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var _require = require('buffer'),
Buffer = _require.Buffer;
var _require2 = require('util'),
inspect = _require2.inspect;
var custom = inspect && inspect.custom || 'inspect';
function copyBuffer(src, target, offset) {
Buffer.prototype.copy.call(src, target, offset);
}
module.exports = /*#__PURE__*/function () {
function BufferList() {
_classCallCheck(this, BufferList);
this.head = null;
this.tail = null;
this.length = 0;
}
_createClass(BufferList, [{
key: "push",
value: function push(v) {
var entry = {
data: v,
next: null
};
if (this.length > 0) this.tail.next = entry;else this.head = entry;
this.tail = entry;
++this.length;
}
}, {
key: "unshift",
value: function unshift(v) {
var entry = {
data: v,
next: this.head
};
if (this.length === 0) this.tail = entry;
this.head = entry;
++this.length;
}
}, {
key: "shift",
value: function shift() {
if (this.length === 0) return;
var ret = this.head.data;
if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
--this.length;
return ret;
}
}, {
key: "clear",
value: function clear() {
this.head = this.tail = null;
this.length = 0;
}
}, {
key: "join",
value: function join(s) {
if (this.length === 0) return '';
var p = this.head;
var ret = '' + p.data;
while (p = p.next) ret += s + p.data;
return ret;
}
}, {
key: "concat",
value: function concat(n) {
if (this.length === 0) return Buffer.alloc(0);
var ret = Buffer.allocUnsafe(n >>> 0);
var p = this.head;
var i = 0;
while (p) {
copyBuffer(p.data, ret, i);
i += p.data.length;
p = p.next;
}
return ret;
}
// Consumes a specified amount of bytes or characters from the buffered data.
}, {
key: "consume",
value: function consume(n, hasStrings) {
var ret;
if (n < this.head.data.length) {
// `slice` is the same for buffers and strings.
ret = this.head.data.slice(0, n);
this.head.data = this.head.data.slice(n);
} else if (n === this.head.data.length) {
// First chunk is a perfect match.
ret = this.shift();
} else {
// Result spans more than one buffer.
ret = hasStrings ? this._getString(n) : this._getBuffer(n);
}
return ret;
}
}, {
key: "first",
value: function first() {
return this.head.data;
}
// Consumes a specified amount of characters from the buffered data.
}, {
key: "_getString",
value: function _getString(n) {
var p = this.head;
var c = 1;
var ret = p.data;
n -= ret.length;
while (p = p.next) {
var str = p.data;
var nb = n > str.length ? str.length : n;
if (nb === str.length) ret += str;else ret += str.slice(0, n);
n -= nb;
if (n === 0) {
if (nb === str.length) {
++c;
if (p.next) this.head = p.next;else this.head = this.tail = null;
} else {
this.head = p;
p.data = str.slice(nb);
}
break;
}
++c;
}
this.length -= c;
return ret;
}
// Consumes a specified amount of bytes from the buffered data.
}, {
key: "_getBuffer",
value: function _getBuffer(n) {
var ret = Buffer.allocUnsafe(n);
var p = this.head;
var c = 1;
p.data.copy(ret);
n -= p.data.length;
while (p = p.next) {
var buf = p.data;
var nb = n > buf.length ? buf.length : n;
buf.copy(ret, ret.length - n, 0, nb);
n -= nb;
if (n === 0) {
if (nb === buf.length) {
++c;
if (p.next) this.head = p.next;else this.head = this.tail = null;
} else {
this.head = p;
p.data = buf.slice(nb);
}
break;
}
++c;
}
this.length -= c;
return ret;
}
// Make sure the linked list only shows the minimal necessary information.
}, {
key: custom,
value: function value(_, options) {
return inspect(this, _objectSpread(_objectSpread({}, options), {}, {
// Only inspect one level.
depth: 0,
// It should not recurse.
customInspect: false
}));
}
}]);
return BufferList;
}();
},{"buffer":35,"util":34}],193:[function(require,module,exports){
(function (process){(function (){
'use strict';
// undocumented cb() API, needed for core, not for public API
function destroy(err, cb) {
var _this = this;
var readableDestroyed = this._readableState && this._readableState.destroyed;
var writableDestroyed = this._writableState && this._writableState.destroyed;
if (readableDestroyed || writableDestroyed) {
if (cb) {
cb(err);
} else if (err) {
if (!this._writableState) {
process.nextTick(emitErrorNT, this, err);
} else if (!this._writableState.errorEmitted) {
this._writableState.errorEmitted = true;
process.nextTick(emitErrorNT, this, err);
}
}
return this;
}
// we set destroyed to true before firing error callbacks in order
// to make it re-entrance safe in case destroy() is called within callbacks
if (this._readableState) {
this._readableState.destroyed = true;
}
// if this is a duplex stream mark the writable part as destroyed as well
if (this._writableState) {
this._writableState.destroyed = true;
}
this._destroy(err || null, function (err) {
if (!cb && err) {
if (!_this._writableState) {
process.nextTick(emitErrorAndCloseNT, _this, err);
} else if (!_this._writableState.errorEmitted) {
_this._writableState.errorEmitted = true;
process.nextTick(emitErrorAndCloseNT, _this, err);
} else {
process.nextTick(emitCloseNT, _this);
}
} else if (cb) {
process.nextTick(emitCloseNT, _this);
cb(err);
} else {
process.nextTick(emitCloseNT, _this);
}
});
return this;
}
function emitErrorAndCloseNT(self, err) {
emitErrorNT(self, err);
emitCloseNT(self);
}
function emitCloseNT(self) {
if (self._writableState && !self._writableState.emitClose) return;
if (self._readableState && !self._readableState.emitClose) return;
self.emit('close');
}
function undestroy() {
if (this._readableState) {
this._readableState.destroyed = false;
this._readableState.reading = false;
this._readableState.ended = false;
this._readableState.endEmitted = false;
}
if (this._writableState) {
this._writableState.destroyed = false;
this._writableState.ended = false;
this._writableState.ending = false;
this._writableState.finalCalled = false;
this._writableState.prefinished = false;
this._writableState.finished = false;
this._writableState.errorEmitted = false;
}
}
function emitErrorNT(self, err) {
self.emit('error', err);
}
function errorOrDestroy(stream, err) {
// We have tests that rely on errors being emitted
// in the same tick, so changing this is semver major.
// For now when you opt-in to autoDestroy we allow
// the error to be emitted nextTick. In a future
// semver major update we should change the default to this.
var rState = stream._readableState;
var wState = stream._writableState;
if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
}
module.exports = {
destroy: destroy,
undestroy: undestroy,
errorOrDestroy: errorOrDestroy
};
}).call(this)}).call(this,require('_process'))
},{"_process":160}],194:[function(require,module,exports){
// Ported from https://github.com/mafintosh/end-of-stream with
// permission from the author, Mathias Buus (@mafintosh).
'use strict';
var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;
function once(callback) {
var called = false;
return function () {
if (called) return;
called = true;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
callback.apply(this, args);
};
}
function noop() {}
function isRequest(stream) {
return stream.setHeader && typeof stream.abort === 'function';
}
function eos(stream, opts, callback) {
if (typeof opts === 'function') return eos(stream, null, opts);
if (!opts) opts = {};
callback = once(callback || noop);
var readable = opts.readable || opts.readable !== false && stream.readable;
var writable = opts.writable || opts.writable !== false && stream.writable;
var onlegacyfinish = function onlegacyfinish() {
if (!stream.writable) onfinish();
};
var writableEnded = stream._writableState && stream._writableState.finished;
var onfinish = function onfinish() {
writable = false;
writableEnded = true;
if (!readable) callback.call(stream);
};
var readableEnded = stream._readableState && stream._readableState.endEmitted;
var onend = function onend() {
readable = false;
readableEnded = true;
if (!writable) callback.call(stream);
};
var onerror = function onerror(err) {
callback.call(stream, err);
};
var onclose = function onclose() {
var err;
if (readable && !readableEnded) {
if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
return callback.call(stream, err);
}
if (writable && !writableEnded) {
if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
return callback.call(stream, err);
}
};
var onrequest = function onrequest() {
stream.req.on('finish', onfinish);
};
if (isRequest(stream)) {
stream.on('complete', onfinish);
stream.on('abort', onclose);
if (stream.req) onrequest();else stream.on('request', onrequest);
} else if (writable && !stream._writableState) {
// legacy streams
stream.on('end', onlegacyfinish);
stream.on('close', onlegacyfinish);
}
stream.on('end', onend);
stream.on('finish', onfinish);
if (opts.error !== false) stream.on('error', onerror);
stream.on('close', onclose);
return function () {
stream.removeListener('complete', onfinish);
stream.removeListener('abort', onclose);
stream.removeListener('request', onrequest);
if (stream.req) stream.req.removeListener('finish', onfinish);
stream.removeListener('end', onlegacyfinish);
stream.removeListener('close', onlegacyfinish);
stream.removeListener('finish', onfinish);
stream.removeListener('end', onend);
stream.removeListener('error', onerror);
stream.removeListener('close', onclose);
};
}
module.exports = eos;
},{"../../../errors":185}],195:[function(require,module,exports){
module.exports = function () {
throw new Error('Readable.from is not available in the browser')
};
},{}],196:[function(require,module,exports){
// Ported from https://github.com/mafintosh/pump with
// permission from the author, Mathias Buus (@mafintosh).
'use strict';
var eos;
function once(callback) {
var called = false;
return function () {
if (called) return;
called = true;
callback.apply(void 0, arguments);
};
}
var _require$codes = require('../../../errors').codes,
ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
function noop(err) {
// Rethrow the error if it exists to avoid swallowing it
if (err) throw err;
}
function isRequest(stream) {
return stream.setHeader && typeof stream.abort === 'function';
}
function destroyer(stream, reading, writing, callback) {
callback = once(callback);
var closed = false;
stream.on('close', function () {
closed = true;
});
if (eos === undefined) eos = require('./end-of-stream');
eos(stream, {
readable: reading,
writable: writing
}, function (err) {
if (err) return callback(err);
closed = true;
callback();
});
var destroyed = false;
return function (err) {
if (closed) return;
if (destroyed) return;
destroyed = true;
// request.destroy just do .end - .abort is what we want
if (isRequest(stream)) return stream.abort();
if (typeof stream.destroy === 'function') return stream.destroy();
callback(err || new ERR_STREAM_DESTROYED('pipe'));
};
}
function call(fn) {
fn();
}
function pipe(from, to) {
return from.pipe(to);
}
function popCallback(streams) {
if (!streams.length) return noop;
if (typeof streams[streams.length - 1] !== 'function') return noop;
return streams.pop();
}
function pipeline() {
for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
streams[_key] = arguments[_key];
}
var callback = popCallback(streams);
if (Array.isArray(streams[0])) streams = streams[0];
if (streams.length < 2) {
throw new ERR_MISSING_ARGS('streams');
}
var error;
var destroys = streams.map(function (stream, i) {
var reading = i < streams.length - 1;
var writing = i > 0;
return destroyer(stream, reading, writing, function (err) {
if (!error) error = err;
if (err) destroys.forEach(call);
if (reading) return;
destroys.forEach(call);
callback(error);
});
});
return streams.reduce(pipe);
}
module.exports = pipeline;
},{"../../../errors":185,"./end-of-stream":194}],197:[function(require,module,exports){
'use strict';
var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;
function highWaterMarkFrom(options, isDuplex, duplexKey) {
return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
}
function getHighWaterMark(state, options, duplexKey, isDuplex) {
var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
if (hwm != null) {
if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
var name = isDuplex ? duplexKey : 'highWaterMark';
throw new ERR_INVALID_OPT_VALUE(name, hwm);
}
return Math.floor(hwm);
}
// Default value
return state.objectMode ? 16 : 16 * 1024;
}
module.exports = {
getHighWaterMark: getHighWaterMark
};
},{"../../../errors":185}],198:[function(require,module,exports){
module.exports = require('events').EventEmitter;
},{"events":81}],199:[function(require,module,exports){
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = exports;
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
exports.finished = require('./lib/internal/streams/end-of-stream.js');
exports.pipeline = require('./lib/internal/streams/pipeline.js');
},{"./lib/_stream_duplex.js":186,"./lib/_stream_passthrough.js":187,"./lib/_stream_readable.js":188,"./lib/_stream_transform.js":189,"./lib/_stream_writable.js":190,"./lib/internal/streams/end-of-stream.js":194,"./lib/internal/streams/pipeline.js":196}],200:[function(require,module,exports){
/**
* Module dependencies.
*/
var url = require('./url');
var parser = require('socket.io-parser');
var Manager = require('./manager');
var debug = require('debug')('socket.io-client');
/**
* Module exports.
*/
module.exports = exports = lookup;
/**
* Managers cache.
*/
var cache = exports.managers = {};
/**
* Looks up an existing `Manager` for multiplexing.
* If the user summons:
*
* `io('http://localhost/a');`
* `io('http://localhost/b');`
*
* We reuse the existing instance based on same scheme/port/host,
* and we initialize sockets for each namespace.
*
* @api public
*/
function lookup (uri, opts) {
if (typeof uri === 'object') {
opts = uri;
uri = undefined;
}
opts = opts || {};
var parsed = url(uri);
var source = parsed.source;
var id = parsed.id;
var path = parsed.path;
var sameNamespace = cache[id] && path in cache[id].nsps;
var newConnection = opts.forceNew || opts['force new connection'] ||
false === opts.multiplex || sameNamespace;
var io;
if (newConnection) {
debug('ignoring socket cache for %s', source);
io = Manager(source, opts);
} else {
if (!cache[id]) {
debug('new io instance for %s', source);
cache[id] = Manager(source, opts);
}
io = cache[id];
}
if (parsed.query && !opts.query) {
opts.query = parsed.query;
}
return io.socket(parsed.path, opts);
}
/**
* Protocol version.
*
* @api public
*/
exports.protocol = parser.protocol;
/**
* `connect`.
*
* @param {String} uri
* @api public
*/
exports.connect = lookup;
/**
* Expose constructors for standalone build.
*
* @api public
*/
exports.Manager = require('./manager');
exports.Socket = require('./socket');
},{"./manager":201,"./socket":203,"./url":204,"debug":205,"socket.io-parser":209}],201:[function(require,module,exports){
/**
* Module dependencies.
*/
var eio = require('engine.io-client');
var Socket = require('./socket');
var Emitter = require('component-emitter');
var parser = require('socket.io-parser');
var on = require('./on');
var bind = require('component-bind');
var debug = require('debug')('socket.io-client:manager');
var indexOf = require('indexof');
var Backoff = require('backo2');
/**
* IE6+ hasOwnProperty
*/
var has = Object.prototype.hasOwnProperty;
/**
* Module exports
*/
module.exports = Manager;
/**
* `Manager` constructor.
*
* @param {String} engine instance or engine uri/opts
* @param {Object} options
* @api public
*/
function Manager (uri, opts) {
if (!(this instanceof Manager)) return new Manager(uri, opts);
if (uri && ('object' === typeof uri)) {
opts = uri;
uri = undefined;
}
opts = opts || {};
opts.path = opts.path || '/socket.io';
this.nsps = {};
this.subs = [];
this.opts = opts;
this.reconnection(opts.reconnection !== false);
this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
this.reconnectionDelay(opts.reconnectionDelay || 1000);
this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
this.randomizationFactor(opts.randomizationFactor || 0.5);
this.backoff = new Backoff({
min: this.reconnectionDelay(),
max: this.reconnectionDelayMax(),
jitter: this.randomizationFactor()
});
this.timeout(null == opts.timeout ? 20000 : opts.timeout);
this.readyState = 'closed';
this.uri = uri;
this.connecting = [];
this.lastPing = null;
this.encoding = false;
this.packetBuffer = [];
var _parser = opts.parser || parser;
this.encoder = new _parser.Encoder();
this.decoder = new _parser.Decoder();
this.autoConnect = opts.autoConnect !== false;
if (this.autoConnect) this.open();
}
/**
* Propagate given event to sockets and emit on `this`
*
* @api private
*/
Manager.prototype.emitAll = function () {
this.emit.apply(this, arguments);
for (var nsp in this.nsps) {
if (has.call(this.nsps, nsp)) {
this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
}
}
};
/**
* Update `socket.id` of all sockets
*
* @api private
*/
Manager.prototype.updateSocketIds = function () {
for (var nsp in this.nsps) {
if (has.call(this.nsps, nsp)) {
this.nsps[nsp].id = this.generateId(nsp);
}
}
};
/**
* generate `socket.id` for the given `nsp`
*
* @param {String} nsp
* @return {String}
* @api private
*/
Manager.prototype.generateId = function (nsp) {
return (nsp === '/' ? '' : (nsp + '#')) + this.engine.id;
};
/**
* Mix in `Emitter`.
*/
Emitter(Manager.prototype);
/**
* Sets the `reconnection` config.
*
* @param {Boolean} true/false if it should automatically reconnect
* @return {Manager} self or value
* @api public
*/
Manager.prototype.reconnection = function (v) {
if (!arguments.length) return this._reconnection;
this._reconnection = !!v;
return this;
};
/**
* Sets the reconnection attempts config.
*
* @param {Number} max reconnection attempts before giving up
* @return {Manager} self or value
* @api public
*/
Manager.prototype.reconnectionAttempts = function (v) {
if (!arguments.length) return this._reconnectionAttempts;
this._reconnectionAttempts = v;
return this;
};
/**
* Sets the delay between reconnections.
*
* @param {Number} delay
* @return {Manager} self or value
* @api public
*/
Manager.prototype.reconnectionDelay = function (v) {
if (!arguments.length) return this._reconnectionDelay;
this._reconnectionDelay = v;
this.backoff && this.backoff.setMin(v);
return this;
};
Manager.prototype.randomizationFactor = function (v) {
if (!arguments.length) return this._randomizationFactor;
this._randomizationFactor = v;
this.backoff && this.backoff.setJitter(v);
return this;
};
/**
* Sets the maximum delay between reconnections.
*
* @param {Number} delay
* @return {Manager} self or value
* @api public
*/
Manager.prototype.reconnectionDelayMax = function (v) {
if (!arguments.length) return this._reconnectionDelayMax;
this._reconnectionDelayMax = v;
this.backoff && this.backoff.setMax(v);
return this;
};
/**
* Sets the connection timeout. `false` to disable
*
* @return {Manager} self or value
* @api public
*/
Manager.prototype.timeout = function (v) {
if (!arguments.length) return this._timeout;
this._timeout = v;
return this;
};
/**
* Starts trying to reconnect if reconnection is enabled and we have not
* started reconnecting yet
*
* @api private
*/
Manager.prototype.maybeReconnectOnOpen = function () {
// Only try to reconnect if it's the first time we're connecting
if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
// keeps reconnection from firing twice for the same reconnection loop
this.reconnect();
}
};
/**
* Sets the current transport `socket`.
*
* @param {Function} optional, callback
* @return {Manager} self
* @api public
*/
Manager.prototype.open =
Manager.prototype.connect = function (fn, opts) {
debug('readyState %s', this.readyState);
if (~this.readyState.indexOf('open')) return this;
debug('opening %s', this.uri);
this.engine = eio(this.uri, this.opts);
var socket = this.engine;
var self = this;
this.readyState = 'opening';
this.skipReconnect = false;
// emit `open`
var openSub = on(socket, 'open', function () {
self.onopen();
fn && fn();
});
// emit `connect_error`
var errorSub = on(socket, 'error', function (data) {
debug('connect_error');
self.cleanup();
self.readyState = 'closed';
self.emitAll('connect_error', data);
if (fn) {
var err = new Error('Connection error');
err.data = data;
fn(err);
} else {
// Only do this if there is no fn to handle the error
self.maybeReconnectOnOpen();
}
});
// emit `connect_timeout`
if (false !== this._timeout) {
var timeout = this._timeout;
debug('connect attempt will timeout after %d', timeout);
if (timeout === 0) {
openSub.destroy(); // prevents a race condition with the 'open' event
}
// set timer
var timer = setTimeout(function () {
debug('connect attempt timed out after %d', timeout);
openSub.destroy();
socket.close();
socket.emit('error', 'timeout');
self.emitAll('connect_timeout', timeout);
}, timeout);
this.subs.push({
destroy: function () {
clearTimeout(timer);
}
});
}
this.subs.push(openSub);
this.subs.push(errorSub);
return this;
};
/**
* Called upon transport open.
*
* @api private
*/
Manager.prototype.onopen = function () {
debug('open');
// clear old subs
this.cleanup();
// mark as open
this.readyState = 'open';
this.emit('open');
// add new subs
var socket = this.engine;
this.subs.push(on(socket, 'data', bind(this, 'ondata')));
this.subs.push(on(socket, 'ping', bind(this, 'onping')));
this.subs.push(on(socket, 'pong', bind(this, 'onpong')));
this.subs.push(on(socket, 'error', bind(this, 'onerror')));
this.subs.push(on(socket, 'close', bind(this, 'onclose')));
this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
};
/**
* Called upon a ping.
*
* @api private
*/
Manager.prototype.onping = function () {
this.lastPing = new Date();
this.emitAll('ping');
};
/**
* Called upon a packet.
*
* @api private
*/
Manager.prototype.onpong = function () {
this.emitAll('pong', new Date() - this.lastPing);
};
/**
* Called with data.
*
* @api private
*/
Manager.prototype.ondata = function (data) {
this.decoder.add(data);
};
/**
* Called when parser fully decodes a packet.
*
* @api private
*/
Manager.prototype.ondecoded = function (packet) {
this.emit('packet', packet);
};
/**
* Called upon socket error.
*
* @api private
*/
Manager.prototype.onerror = function (err) {
debug('error', err);
this.emitAll('error', err);
};
/**
* Creates a new socket for the given `nsp`.
*
* @return {Socket}
* @api public
*/
Manager.prototype.socket = function (nsp, opts) {
var socket = this.nsps[nsp];
if (!socket) {
socket = new Socket(this, nsp, opts);
this.nsps[nsp] = socket;
var self = this;
socket.on('connecting', onConnecting);
socket.on('connect', function () {
socket.id = self.generateId(nsp);
});
if (this.autoConnect) {
// manually call here since connecting event is fired before listening
onConnecting();
}
}
function onConnecting () {
if (!~indexOf(self.connecting, socket)) {
self.connecting.push(socket);
}
}
return socket;
};
/**
* Called upon a socket close.
*
* @param {Socket} socket
*/
Manager.prototype.destroy = function (socket) {
var index = indexOf(this.connecting, socket);
if (~index) this.connecting.splice(index, 1);
if (this.connecting.length) return;
this.close();
};
/**
* Writes a packet.
*
* @param {Object} packet
* @api private
*/
Manager.prototype.packet = function (packet) {
debug('writing packet %j', packet);
var self = this;
if (packet.query && packet.type === 0) packet.nsp += '?' + packet.query;
if (!self.encoding) {
// encode, then write to engine with result
self.encoding = true;
this.encoder.encode(packet, function (encodedPackets) {
for (var i = 0; i < encodedPackets.length; i++) {
self.engine.write(encodedPackets[i], packet.options);
}
self.encoding = false;
self.processPacketQueue();
});
} else { // add packet to the queue
self.packetBuffer.push(packet);
}
};
/**
* If packet buffer is non-empty, begins encoding the
* next packet in line.
*
* @api private
*/
Manager.prototype.processPacketQueue = function () {
if (this.packetBuffer.length > 0 && !this.encoding) {
var pack = this.packetBuffer.shift();
this.packet(pack);
}
};
/**
* Clean up transport subscriptions and packet buffer.
*
* @api private
*/
Manager.prototype.cleanup = function () {
debug('cleanup');
var subsLength = this.subs.length;
for (var i = 0; i < subsLength; i++) {
var sub = this.subs.shift();
sub.destroy();
}
this.packetBuffer = [];
this.encoding = false;
this.lastPing = null;
this.decoder.destroy();
};
/**
* Close the current socket.
*
* @api private
*/
Manager.prototype.close =
Manager.prototype.disconnect = function () {
debug('disconnect');
this.skipReconnect = true;
this.reconnecting = false;
if ('opening' === this.readyState) {
// `onclose` will not fire because
// an open event never happened
this.cleanup();
}
this.backoff.reset();
this.readyState = 'closed';
if (this.engine) this.engine.close();
};
/**
* Called upon engine close.
*
* @api private
*/
Manager.prototype.onclose = function (reason) {
debug('onclose');
this.cleanup();
this.backoff.reset();
this.readyState = 'closed';
this.emit('close', reason);
if (this._reconnection && !this.skipReconnect) {
this.reconnect();
}
};
/**
* Attempt a reconnection.
*
* @api private
*/
Manager.prototype.reconnect = function () {
if (this.reconnecting || this.skipReconnect) return this;
var self = this;
if (this.backoff.attempts >= this._reconnectionAttempts) {
debug('reconnect failed');
this.backoff.reset();
this.emitAll('reconnect_failed');
this.reconnecting = false;
} else {
var delay = this.backoff.duration();
debug('will wait %dms before reconnect attempt', delay);
this.reconnecting = true;
var timer = setTimeout(function () {
if (self.skipReconnect) return;
debug('attempting reconnect');
self.emitAll('reconnect_attempt', self.backoff.attempts);
self.emitAll('reconnecting', self.backoff.attempts);
// check again for the case socket closed in above events
if (self.skipReconnect) return;
self.open(function (err) {
if (err) {
debug('reconnect attempt error');
self.reconnecting = false;
self.reconnect();
self.emitAll('reconnect_error', err.data);
} else {
debug('reconnect success');
self.onreconnect();
}
});
}, delay);
this.subs.push({
destroy: function () {
clearTimeout(timer);
}
});
}
};
/**
* Called upon successful reconnect.
*
* @api private
*/
Manager.prototype.onreconnect = function () {
var attempt = this.backoff.attempts;
this.reconnecting = false;
this.backoff.reset();
this.updateSocketIds();
this.emitAll('reconnect', attempt);
};
},{"./on":202,"./socket":203,"backo2":30,"component-bind":60,"component-emitter":61,"debug":205,"engine.io-client":65,"indexof":101,"socket.io-parser":209}],202:[function(require,module,exports){
/**
* Module exports.
*/
module.exports = on;
/**
* Helper for subscriptions.
*
* @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
* @param {String} event name
* @param {Function} callback
* @api public
*/
function on (obj, ev, fn) {
obj.on(ev, fn);
return {
destroy: function () {
obj.removeListener(ev, fn);
}
};
}
},{}],203:[function(require,module,exports){
/**
* Module dependencies.
*/
var parser = require('socket.io-parser');
var Emitter = require('component-emitter');
var toArray = require('to-array');
var on = require('./on');
var bind = require('component-bind');
var debug = require('debug')('socket.io-client:socket');
var parseqs = require('parseqs');
var hasBin = require('has-binary2');
/**
* Module exports.
*/
module.exports = exports = Socket;
/**
* Internal events (blacklisted).
* These events can't be emitted by the user.
*
* @api private
*/
var events = {
connect: 1,
connect_error: 1,
connect_timeout: 1,
connecting: 1,
disconnect: 1,
error: 1,
reconnect: 1,
reconnect_attempt: 1,
reconnect_failed: 1,
reconnect_error: 1,
reconnecting: 1,
ping: 1,
pong: 1
};
/**
* Shortcut to `Emitter#emit`.
*/
var emit = Emitter.prototype.emit;
/**
* `Socket` constructor.
*
* @api public
*/
function Socket (io, nsp, opts) {
this.io = io;
this.nsp = nsp;
this.json = this; // compat
this.ids = 0;
this.acks = {};
this.receiveBuffer = [];
this.sendBuffer = [];
this.connected = false;
this.disconnected = true;
this.flags = {};
if (opts && opts.query) {
this.query = opts.query;
}
if (this.io.autoConnect) this.open();
}
/**
* Mix in `Emitter`.
*/
Emitter(Socket.prototype);
/**
* Subscribe to open, close and packet events
*
* @api private
*/
Socket.prototype.subEvents = function () {
if (this.subs) return;
var io = this.io;
this.subs = [
on(io, 'open', bind(this, 'onopen')),
on(io, 'packet', bind(this, 'onpacket')),
on(io, 'close', bind(this, 'onclose'))
];
};
/**
* "Opens" the socket.
*
* @api public
*/
Socket.prototype.open =
Socket.prototype.connect = function () {
if (this.connected) return this;
this.subEvents();
if (!this.io.reconnecting) this.io.open(); // ensure open
if ('open' === this.io.readyState) this.onopen();
this.emit('connecting');
return this;
};
/**
* Sends a `message` event.
*
* @return {Socket} self
* @api public
*/
Socket.prototype.send = function () {
var args = toArray(arguments);
args.unshift('message');
this.emit.apply(this, args);
return this;
};
/**
* Override `emit`.
* If the event is in `events`, it's emitted normally.
*
* @param {String} event name
* @return {Socket} self
* @api public
*/
Socket.prototype.emit = function (ev) {
if (events.hasOwnProperty(ev)) {
emit.apply(this, arguments);
return this;
}
var args = toArray(arguments);
var packet = {
type: (this.flags.binary !== undefined ? this.flags.binary : hasBin(args)) ? parser.BINARY_EVENT : parser.EVENT,
data: args
};
packet.options = {};
packet.options.compress = !this.flags || false !== this.flags.compress;
// event ack callback
if ('function' === typeof args[args.length - 1]) {
debug('emitting packet with ack id %d', this.ids);
this.acks[this.ids] = args.pop();
packet.id = this.ids++;
}
if (this.connected) {
this.packet(packet);
} else {
this.sendBuffer.push(packet);
}
this.flags = {};
return this;
};
/**
* Sends a packet.
*
* @param {Object} packet
* @api private
*/
Socket.prototype.packet = function (packet) {
packet.nsp = this.nsp;
this.io.packet(packet);
};
/**
* Called upon engine `open`.
*
* @api private
*/
Socket.prototype.onopen = function () {
debug('transport is open - connecting');
// write connect packet if necessary
if ('/' !== this.nsp) {
if (this.query) {
var query = typeof this.query === 'object' ? parseqs.encode(this.query) : this.query;
debug('sending connect packet with query %s', query);
this.packet({type: parser.CONNECT, query: query});
} else {
this.packet({type: parser.CONNECT});
}
}
};
/**
* Called upon engine `close`.
*
* @param {String} reason
* @api private
*/
Socket.prototype.onclose = function (reason) {
debug('close (%s)', reason);
this.connected = false;
this.disconnected = true;
delete this.id;
this.emit('disconnect', reason);
};
/**
* Called with socket packet.
*
* @param {Object} packet
* @api private
*/
Socket.prototype.onpacket = function (packet) {
var sameNamespace = packet.nsp === this.nsp;
var rootNamespaceError = packet.type === parser.ERROR && packet.nsp === '/';
if (!sameNamespace && !rootNamespaceError) return;
switch (packet.type) {
case parser.CONNECT:
this.onconnect();
break;
case parser.EVENT:
this.onevent(packet);
break;
case parser.BINARY_EVENT:
this.onevent(packet);
break;
case parser.ACK:
this.onack(packet);
break;
case parser.BINARY_ACK:
this.onack(packet);
break;
case parser.DISCONNECT:
this.ondisconnect();
break;
case parser.ERROR:
this.emit('error', packet.data);
break;
}
};
/**
* Called upon a server event.
*
* @param {Object} packet
* @api private
*/
Socket.prototype.onevent = function (packet) {
var args = packet.data || [];
debug('emitting event %j', args);
if (null != packet.id) {
debug('attaching ack callback to event');
args.push(this.ack(packet.id));
}
if (this.connected) {
emit.apply(this, args);
} else {
this.receiveBuffer.push(args);
}
};
/**
* Produces an ack callback to emit with an event.
*
* @api private
*/
Socket.prototype.ack = function (id) {
var self = this;
var sent = false;
return function () {
// prevent double callbacks
if (sent) return;
sent = true;
var args = toArray(arguments);
debug('sending ack %j', args);
self.packet({
type: hasBin(args) ? parser.BINARY_ACK : parser.ACK,
id: id,
data: args
});
};
};
/**
* Called upon a server acknowlegement.
*
* @param {Object} packet
* @api private
*/
Socket.prototype.onack = function (packet) {
var ack = this.acks[packet.id];
if ('function' === typeof ack) {
debug('calling ack %s with %j', packet.id, packet.data);
ack.apply(this, packet.data);
delete this.acks[packet.id];
} else {
debug('bad ack %s', packet.id);
}
};
/**
* Called upon server connect.
*
* @api private
*/
Socket.prototype.onconnect = function () {
this.connected = true;
this.disconnected = false;
this.emitBuffered();
this.emit('connect');
};
/**
* Emit buffered events (received and emitted).
*
* @api private
*/
Socket.prototype.emitBuffered = function () {
var i;
for (i = 0; i < this.receiveBuffer.length; i++) {
emit.apply(this, this.receiveBuffer[i]);
}
this.receiveBuffer = [];
for (i = 0; i < this.sendBuffer.length; i++) {
this.packet(this.sendBuffer[i]);
}
this.sendBuffer = [];
};
/**
* Called upon server disconnect.
*
* @api private
*/
Socket.prototype.ondisconnect = function () {
debug('server disconnect (%s)', this.nsp);
this.destroy();
this.onclose('io server disconnect');
};
/**
* Called upon forced client/server side disconnections,
* this method ensures the manager stops tracking us and
* that reconnections don't get triggered for this.
*
* @api private.
*/
Socket.prototype.destroy = function () {
if (this.subs) {
// clean subscriptions to avoid reconnections
for (var i = 0; i < this.subs.length; i++) {
this.subs[i].destroy();
}
this.subs = null;
}
this.io.destroy(this);
};
/**
* Disconnects the socket manually.
*
* @return {Socket} self
* @api public
*/
Socket.prototype.close =
Socket.prototype.disconnect = function () {
if (this.connected) {
debug('performing disconnect (%s)', this.nsp);
this.packet({ type: parser.DISCONNECT });
}
// remove socket from pool
this.destroy();
if (this.connected) {
// fire events
this.onclose('io client disconnect');
}
return this;
};
/**
* Sets the compress flag.
*
* @param {Boolean} if `true`, compresses the sending data
* @return {Socket} self
* @api public
*/
Socket.prototype.compress = function (compress) {
this.flags.compress = compress;
return this;
};
/**
* Sets the binary flag
*
* @param {Boolean} whether the emitted data contains binary
* @return {Socket} self
* @api public
*/
Socket.prototype.binary = function (binary) {
this.flags.binary = binary;
return this;
};
},{"./on":202,"component-bind":60,"component-emitter":61,"debug":205,"has-binary2":89,"parseqs":156,"socket.io-parser":209,"to-array":222}],204:[function(require,module,exports){
/**
* Module dependencies.
*/
var parseuri = require('parseuri');
var debug = require('debug')('socket.io-client:url');
/**
* Module exports.
*/
module.exports = url;
/**
* URL parser.
*
* @param {String} url
* @param {Object} An object meant to mimic window.location.
* Defaults to window.location.
* @api public
*/
function url (uri, loc) {
var obj = uri;
// default to window.location
loc = loc || (typeof location !== 'undefined' && location);
if (null == uri) uri = loc.protocol + '//' + loc.host;
// relative path support
if ('string' === typeof uri) {
if ('/' === uri.charAt(0)) {
if ('/' === uri.charAt(1)) {
uri = loc.protocol + uri;
} else {
uri = loc.host + uri;
}
}
if (!/^(https?|wss?):\/\//.test(uri)) {
debug('protocol-less url %s', uri);
if ('undefined' !== typeof loc) {
uri = loc.protocol + '//' + uri;
} else {
uri = 'https://' + uri;
}
}
// parse
debug('parse %s', uri);
obj = parseuri(uri);
}
// make sure we treat `localhost:80` and `localhost` equally
if (!obj.port) {
if (/^(http|ws)$/.test(obj.protocol)) {
obj.port = '80';
} else if (/^(http|ws)s$/.test(obj.protocol)) {
obj.port = '443';
}
}
obj.path = obj.path || '/';
var ipv6 = obj.host.indexOf(':') !== -1;
var host = ipv6 ? '[' + obj.host + ']' : obj.host;
// define unique id
obj.id = obj.protocol + '://' + host + ':' + obj.port;
// define href
obj.href = obj.protocol + '://' + host + (loc && loc.port === obj.port ? '' : (':' + obj.port));
return obj;
}
},{"debug":205,"parseuri":157}],205:[function(require,module,exports){
arguments[4][74][0].apply(exports,arguments)
},{"./debug":206,"_process":160,"dup":74}],206:[function(require,module,exports){
arguments[4][75][0].apply(exports,arguments)
},{"dup":75,"ms":207}],207:[function(require,module,exports){
arguments[4][76][0].apply(exports,arguments)
},{"dup":76}],208:[function(require,module,exports){
/*global Blob,File*/
/**
* Module requirements
*/
var isArray = require('isarray');
var isBuf = require('./is-buffer');
var toString = Object.prototype.toString;
var withNativeBlob = typeof Blob === 'function' || (typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]');
var withNativeFile = typeof File === 'function' || (typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]');
/**
* Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
* Anything with blobs or files should be fed through removeBlobs before coming
* here.
*
* @param {Object} packet - socket.io event packet
* @return {Object} with deconstructed packet and list of buffers
* @api public
*/
exports.deconstructPacket = function(packet) {
var buffers = [];
var packetData = packet.data;
var pack = packet;
pack.data = _deconstructPacket(packetData, buffers);
pack.attachments = buffers.length; // number of binary 'attachments'
return {packet: pack, buffers: buffers};
};
function _deconstructPacket(data, buffers) {
if (!data) return data;
if (isBuf(data)) {
var placeholder = { _placeholder: true, num: buffers.length };
buffers.push(data);
return placeholder;
} else if (isArray(data)) {
var newData = new Array(data.length);
for (var i = 0; i < data.length; i++) {
newData[i] = _deconstructPacket(data[i], buffers);
}
return newData;
} else if (typeof data === 'object' && !(data instanceof Date)) {
var newData = {};
for (var key in data) {
newData[key] = _deconstructPacket(data[key], buffers);
}
return newData;
}
return data;
}
/**
* Reconstructs a binary packet from its placeholder packet and buffers
*
* @param {Object} packet - event packet with placeholders
* @param {Array} buffers - binary buffers to put in placeholder positions
* @return {Object} reconstructed packet
* @api public
*/
exports.reconstructPacket = function(packet, buffers) {
packet.data = _reconstructPacket(packet.data, buffers);
packet.attachments = undefined; // no longer useful
return packet;
};
function _reconstructPacket(data, buffers) {
if (!data) return data;
if (data && data._placeholder === true) {
var isIndexValid =
typeof data.num === "number" &&
data.num >= 0 &&
data.num < buffers.length;
if (isIndexValid) {
return buffers[data.num]; // appropriate buffer (should be natural order anyway)
} else {
throw new Error("illegal attachments");
}
} else if (isArray(data)) {
for (var i = 0; i < data.length; i++) {
data[i] = _reconstructPacket(data[i], buffers);
}
} else if (typeof data === 'object') {
for (var key in data) {
data[key] = _reconstructPacket(data[key], buffers);
}
}
return data;
}
/**
* Asynchronously removes Blobs or Files from data via
* FileReader's readAsArrayBuffer method. Used before encoding
* data as msgpack. Calls callback with the blobless data.
*
* @param {Object} data
* @param {Function} callback
* @api private
*/
exports.removeBlobs = function(data, callback) {
function _removeBlobs(obj, curKey, containingObject) {
if (!obj) return obj;
// convert any blob
if ((withNativeBlob && obj instanceof Blob) ||
(withNativeFile && obj instanceof File)) {
pendingBlobs++;
// async filereader
var fileReader = new FileReader();
fileReader.onload = function() { // this.result == arraybuffer
if (containingObject) {
containingObject[curKey] = this.result;
}
else {
bloblessData = this.result;
}
// if nothing pending its callback time
if(! --pendingBlobs) {
callback(bloblessData);
}
};
fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
} else if (isArray(obj)) { // handle array
for (var i = 0; i < obj.length; i++) {
_removeBlobs(obj[i], i, obj);
}
} else if (typeof obj === 'object' && !isBuf(obj)) { // and object
for (var key in obj) {
_removeBlobs(obj[key], key, obj);
}
}
}
var pendingBlobs = 0;
var bloblessData = data;
_removeBlobs(bloblessData);
if (!pendingBlobs) {
callback(bloblessData);
}
};
},{"./is-buffer":210,"isarray":213}],209:[function(require,module,exports){
/**
* Module dependencies.
*/
var debug = require('debug')('socket.io-parser');
var Emitter = require('component-emitter');
var binary = require('./binary');
var isArray = require('isarray');
var isBuf = require('./is-buffer');
/**
* Protocol version.
*
* @api public
*/
exports.protocol = 4;
/**
* Packet types.
*
* @api public
*/
exports.types = [
'CONNECT',
'DISCONNECT',
'EVENT',
'ACK',
'ERROR',
'BINARY_EVENT',
'BINARY_ACK'
];
/**
* Packet type `connect`.
*
* @api public
*/
exports.CONNECT = 0;
/**
* Packet type `disconnect`.
*
* @api public
*/
exports.DISCONNECT = 1;
/**
* Packet type `event`.
*
* @api public
*/
exports.EVENT = 2;
/**
* Packet type `ack`.
*
* @api public
*/
exports.ACK = 3;
/**
* Packet type `error`.
*
* @api public
*/
exports.ERROR = 4;
/**
* Packet type 'binary event'
*
* @api public
*/
exports.BINARY_EVENT = 5;
/**
* Packet type `binary ack`. For acks with binary arguments.
*
* @api public
*/
exports.BINARY_ACK = 6;
/**
* Encoder constructor.
*
* @api public
*/
exports.Encoder = Encoder;
/**
* Decoder constructor.
*
* @api public
*/
exports.Decoder = Decoder;
/**
* A socket.io Encoder instance
*
* @api public
*/
function Encoder() {}
var ERROR_PACKET = exports.ERROR + '"encode error"';
/**
* Encode a packet as a single string if non-binary, or as a
* buffer sequence, depending on packet type.
*
* @param {Object} obj - packet object
* @param {Function} callback - function to handle encodings (likely engine.write)
* @return Calls callback with Array of encodings
* @api public
*/
Encoder.prototype.encode = function(obj, callback){
debug('encoding packet %j', obj);
if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) {
encodeAsBinary(obj, callback);
} else {
var encoding = encodeAsString(obj);
callback([encoding]);
}
};
/**
* Encode packet as string.
*
* @param {Object} packet
* @return {String} encoded
* @api private
*/
function encodeAsString(obj) {
// first is type
var str = '' + obj.type;
// attachments if we have them
if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) {
str += obj.attachments + '-';
}
// if we have a namespace other than `/`
// we append it followed by a comma `,`
if (obj.nsp && '/' !== obj.nsp) {
str += obj.nsp + ',';
}
// immediately followed by the id
if (null != obj.id) {
str += obj.id;
}
// json data
if (null != obj.data) {
var payload = tryStringify(obj.data);
if (payload !== false) {
str += payload;
} else {
return ERROR_PACKET;
}
}
debug('encoded %j as %s', obj, str);
return str;
}
function tryStringify(str) {
try {
return JSON.stringify(str);
} catch(e){
return false;
}
}
/**
* Encode packet as 'buffer sequence' by removing blobs, and
* deconstructing packet into object with placeholders and
* a list of buffers.
*
* @param {Object} packet
* @return {Buffer} encoded
* @api private
*/
function encodeAsBinary(obj, callback) {
function writeEncoding(bloblessData) {
var deconstruction = binary.deconstructPacket(bloblessData);
var pack = encodeAsString(deconstruction.packet);
var buffers = deconstruction.buffers;
buffers.unshift(pack); // add packet info to beginning of data list
callback(buffers); // write all the buffers
}
binary.removeBlobs(obj, writeEncoding);
}
/**
* A socket.io Decoder instance
*
* @return {Object} decoder
* @api public
*/
function Decoder() {
this.reconstructor = null;
}
/**
* Mix in `Emitter` with Decoder.
*/
Emitter(Decoder.prototype);
/**
* Decodes an encoded packet string into packet JSON.
*
* @param {String} obj - encoded packet
* @return {Object} packet
* @api public
*/
Decoder.prototype.add = function(obj) {
var packet;
if (typeof obj === 'string') {
if (this.reconstructor) {
throw new Error("got plaintext data when reconstructing a packet");
}
packet = decodeString(obj);
if (exports.BINARY_EVENT === packet.type || exports.BINARY_ACK === packet.type) { // binary packet's json
this.reconstructor = new BinaryReconstructor(packet);
// no attachments, labeled binary but no binary data to follow
if (this.reconstructor.reconPack.attachments === 0) {
this.emit('decoded', packet);
}
} else { // non-binary full packet
this.emit('decoded', packet);
}
} else if (isBuf(obj) || obj.base64) { // raw binary data
if (!this.reconstructor) {
throw new Error('got binary data when not reconstructing a packet');
} else {
packet = this.reconstructor.takeBinaryData(obj);
if (packet) { // received final buffer
this.reconstructor = null;
this.emit('decoded', packet);
}
}
} else {
throw new Error('Unknown type: ' + obj);
}
};
/**
* Decode a packet String (JSON data)
*
* @param {String} str
* @return {Object} packet
* @api private
*/
function decodeString(str) {
var i = 0;
// look up type
var p = {
type: Number(str.charAt(0))
};
if (null == exports.types[p.type]) {
return error('unknown packet type ' + p.type);
}
// look up attachments if type binary
if (exports.BINARY_EVENT === p.type || exports.BINARY_ACK === p.type) {
var start = i + 1;
while (str.charAt(++i) !== '-' && i != str.length) {}
var buf = str.substring(start, i);
if (buf != Number(buf) || str.charAt(i) !== '-') {
throw new Error('Illegal attachments');
}
p.attachments = Number(buf);
}
// look up namespace (if any)
if ('/' === str.charAt(i + 1)) {
var start = i + 1;
while (++i) {
var c = str.charAt(i);
if (',' === c) break;
if (i === str.length) break;
}
p.nsp = str.substring(start, i);
} else {
p.nsp = '/';
}
// look up id
var next = str.charAt(i + 1);
if ('' !== next && Number(next) == next) {
var start = i + 1;
while (++i) {
var c = str.charAt(i);
if (null == c || Number(c) != c) {
--i;
break;
}
if (i === str.length) break;
}
p.id = Number(str.substring(start, i + 1));
}
// look up json data
if (str.charAt(++i)) {
var payload = tryParse(str.substr(i));
var isPayloadValid = payload !== false && (p.type === exports.ERROR || isArray(payload));
if (isPayloadValid) {
p.data = payload;
} else {
return error('invalid payload');
}
}
debug('decoded %s as %j', str, p);
return p;
}
function tryParse(str) {
try {
return JSON.parse(str);
} catch(e){
return false;
}
}
/**
* Deallocates a parser's resources
*
* @api public
*/
Decoder.prototype.destroy = function() {
if (this.reconstructor) {
this.reconstructor.finishedReconstruction();
}
};
/**
* A manager of a binary event's 'buffer sequence'. Should
* be constructed whenever a packet of type BINARY_EVENT is
* decoded.
*
* @param {Object} packet
* @return {BinaryReconstructor} initialized reconstructor
* @api private
*/
function BinaryReconstructor(packet) {
this.reconPack = packet;
this.buffers = [];
}
/**
* Method to be called when binary data received from connection
* after a BINARY_EVENT packet.
*
* @param {Buffer | ArrayBuffer} binData - the raw binary data received
* @return {null | Object} returns null if more binary data is expected or
* a reconstructed packet object if all buffers have been received.
* @api private
*/
BinaryReconstructor.prototype.takeBinaryData = function(binData) {
this.buffers.push(binData);
if (this.buffers.length === this.reconPack.attachments) { // done with buffer list
var packet = binary.reconstructPacket(this.reconPack, this.buffers);
this.finishedReconstruction();
return packet;
}
return null;
};
/**
* Cleans up binary packet reconstruction variables.
*
* @api private
*/
BinaryReconstructor.prototype.finishedReconstruction = function() {
this.reconPack = null;
this.buffers = [];
};
function error(msg) {
return {
type: exports.ERROR,
data: 'parser error: ' + msg
};
}
},{"./binary":208,"./is-buffer":210,"component-emitter":61,"debug":211,"isarray":213}],210:[function(require,module,exports){
(function (Buffer){(function (){
module.exports = isBuf;
var withNativeBuffer = typeof Buffer === 'function' && typeof Buffer.isBuffer === 'function';
var withNativeArrayBuffer = typeof ArrayBuffer === 'function';
var isView = function (obj) {
return typeof ArrayBuffer.isView === 'function' ? ArrayBuffer.isView(obj) : (obj.buffer instanceof ArrayBuffer);
};
/**
* Returns true if obj is a buffer or an arraybuffer.
*
* @api private
*/
function isBuf(obj) {
return (withNativeBuffer && Buffer.isBuffer(obj)) ||
(withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)));
}
}).call(this)}).call(this,require("buffer").Buffer)
},{"buffer":35}],211:[function(require,module,exports){
arguments[4][74][0].apply(exports,arguments)
},{"./debug":212,"_process":160,"dup":74}],212:[function(require,module,exports){
arguments[4][75][0].apply(exports,arguments)
},{"dup":75,"ms":214}],213:[function(require,module,exports){
arguments[4][90][0].apply(exports,arguments)
},{"dup":90}],214:[function(require,module,exports){
arguments[4][76][0].apply(exports,arguments)
},{"dup":76}],215:[function(require,module,exports){
var fastSafeStringify = require('fast-safe-stringify')
var copy = require('clipboard-copy')
function tryStringify (obj) {
try {
return JSON.stringify(obj)
} catch (e) {}
}
function stateCopy (obj) {
var str = tryStringify(obj) || fastSafeStringify(obj)
copy(str)
}
module.exports = stateCopy
},{"clipboard-copy":52,"fast-safe-stringify":82}],216:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
/*<replacement>*/
var Buffer = require('safe-buffer').Buffer;
/*</replacement>*/
var isEncoding = Buffer.isEncoding || function (encoding) {
encoding = '' + encoding;
switch (encoding && encoding.toLowerCase()) {
case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
return true;
default:
return false;
}
};
function _normalizeEncoding(enc) {
if (!enc) return 'utf8';
var retried;
while (true) {
switch (enc) {
case 'utf8':
case 'utf-8':
return 'utf8';
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return 'utf16le';
case 'latin1':
case 'binary':
return 'latin1';
case 'base64':
case 'ascii':
case 'hex':
return enc;
default:
if (retried) return; // undefined
enc = ('' + enc).toLowerCase();
retried = true;
}
}
};
// Do not cache `Buffer.isEncoding` when checking encoding names as some
// modules monkey-patch it to support additional encodings
function normalizeEncoding(enc) {
var nenc = _normalizeEncoding(enc);
if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
return nenc || enc;
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters.
exports.StringDecoder = StringDecoder;
function StringDecoder(encoding) {
this.encoding = normalizeEncoding(encoding);
var nb;
switch (this.encoding) {
case 'utf16le':
this.text = utf16Text;
this.end = utf16End;
nb = 4;
break;
case 'utf8':
this.fillLast = utf8FillLast;
nb = 4;
break;
case 'base64':
this.text = base64Text;
this.end = base64End;
nb = 3;
break;
default:
this.write = simpleWrite;
this.end = simpleEnd;
return;
}
this.lastNeed = 0;
this.lastTotal = 0;
this.lastChar = Buffer.allocUnsafe(nb);
}
StringDecoder.prototype.write = function (buf) {
if (buf.length === 0) return '';
var r;
var i;
if (this.lastNeed) {
r = this.fillLast(buf);
if (r === undefined) return '';
i = this.lastNeed;
this.lastNeed = 0;
} else {
i = 0;
}
if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
return r || '';
};
StringDecoder.prototype.end = utf8End;
// Returns only complete characters in a Buffer
StringDecoder.prototype.text = utf8Text;
// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
StringDecoder.prototype.fillLast = function (buf) {
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
this.lastNeed -= buf.length;
};
// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
// continuation byte. If an invalid byte is detected, -2 is returned.
function utf8CheckByte(byte) {
if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
return byte >> 6 === 0x02 ? -1 : -2;
}
// Checks at most 3 bytes at the end of a Buffer in order to detect an
// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
// needed to complete the UTF-8 character (if applicable) are returned.
function utf8CheckIncomplete(self, buf, i) {
var j = buf.length - 1;
if (j < i) return 0;
var nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 1;
return nb;
}
if (--j < i || nb === -2) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 2;
return nb;
}
if (--j < i || nb === -2) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) {
if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
}
return nb;
}
return 0;
}
// Validates as many continuation bytes for a multi-byte UTF-8 character as
// needed or are available. If we see a non-continuation byte where we expect
// one, we "replace" the validated continuation bytes we've seen so far with
// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
// behavior. The continuation byte check is included three times in the case
// where all of the continuation bytes for a character exist in the same buffer.
// It is also done this way as a slight performance increase instead of using a
// loop.
function utf8CheckExtraBytes(self, buf, p) {
if ((buf[0] & 0xC0) !== 0x80) {
self.lastNeed = 0;
return '\ufffd';
}
if (self.lastNeed > 1 && buf.length > 1) {
if ((buf[1] & 0xC0) !== 0x80) {
self.lastNeed = 1;
return '\ufffd';
}
if (self.lastNeed > 2 && buf.length > 2) {
if ((buf[2] & 0xC0) !== 0x80) {
self.lastNeed = 2;
return '\ufffd';
}
}
}
}
// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
function utf8FillLast(buf) {
var p = this.lastTotal - this.lastNeed;
var r = utf8CheckExtraBytes(this, buf, p);
if (r !== undefined) return r;
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, p, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, p, 0, buf.length);
this.lastNeed -= buf.length;
}
// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
// partial character, the character's bytes are buffered until the required
// number of bytes are available.
function utf8Text(buf, i) {
var total = utf8CheckIncomplete(this, buf, i);
if (!this.lastNeed) return buf.toString('utf8', i);
this.lastTotal = total;
var end = buf.length - (total - this.lastNeed);
buf.copy(this.lastChar, 0, end);
return buf.toString('utf8', i, end);
}
// For UTF-8, a replacement character is added when ending on a partial
// character.
function utf8End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + '\ufffd';
return r;
}
// UTF-16LE typically needs two bytes per character, but even if we have an even
// number of bytes available, we need to check if we end on a leading/high
// surrogate. In that case, we need to wait for the next two bytes in order to
// decode the last character properly.
function utf16Text(buf, i) {
if ((buf.length - i) % 2 === 0) {
var r = buf.toString('utf16le', i);
if (r) {
var c = r.charCodeAt(r.length - 1);
if (c >= 0xD800 && c <= 0xDBFF) {
this.lastNeed = 2;
this.lastTotal = 4;
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
return r.slice(0, -1);
}
}
return r;
}
this.lastNeed = 1;
this.lastTotal = 2;
this.lastChar[0] = buf[buf.length - 1];
return buf.toString('utf16le', i, buf.length - 1);
}
// For UTF-16LE we do not explicitly append special replacement characters if we
// end on a partial character, we simply let v8 handle that.
function utf16End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) {
var end = this.lastTotal - this.lastNeed;
return r + this.lastChar.toString('utf16le', 0, end);
}
return r;
}
function base64Text(buf, i) {
var n = (buf.length - i) % 3;
if (n === 0) return buf.toString('base64', i);
this.lastNeed = 3 - n;
this.lastTotal = 3;
if (n === 1) {
this.lastChar[0] = buf[buf.length - 1];
} else {
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
}
return buf.toString('base64', i, buf.length - n);
}
function base64End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
return r;
}
// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
function simpleWrite(buf) {
return buf.toString(this.encoding);
}
function simpleEnd(buf) {
return buf && buf.length ? this.write(buf) : '';
}
},{"safe-buffer":169}],217:[function(require,module,exports){
"use strict";
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function Agent() {
this._defaults = [];
}
var _loop = function _loop() {
var fn = _arr[_i];
// Default setting for all requests from this agent
Agent.prototype[fn] = function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
this._defaults.push({
fn: fn,
args: args
});
return this;
};
};
for (var _i = 0, _arr = ['use', 'on', 'once', 'set', 'query', 'type', 'accept', 'auth', 'withCredentials', 'sortQuery', 'retry', 'ok', 'redirects', 'timeout', 'buffer', 'serialize', 'parse', 'ca', 'key', 'pfx', 'cert', 'disableTLSCerts']; _i < _arr.length; _i++) {
_loop();
}
Agent.prototype._setDefaults = function (request) {
var _iterator = _createForOfIteratorHelper(this._defaults),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var def = _step.value;
request[def.fn].apply(request, _toConsumableArray(def.args));
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
};
module.exports = Agent;
},{}],218:[function(require,module,exports){
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
/**
* Root reference for iframes.
*/
var root;
if (typeof window !== 'undefined') {
// Browser window
root = window;
} else if (typeof self === 'undefined') {
// Other environments
console.warn('Using browser-only version of superagent in non-browser environment');
root = void 0;
} else {
// Web Worker
root = self;
}
var Emitter = require('component-emitter');
var safeStringify = require('fast-safe-stringify');
var qs = require('qs');
var RequestBase = require('./request-base');
var _require = require('./utils'),
isObject = _require.isObject,
mixin = _require.mixin,
hasOwn = _require.hasOwn;
var ResponseBase = require('./response-base');
var Agent = require('./agent-base');
/**
* Noop.
*/
function noop() {}
/**
* Expose `request`.
*/
module.exports = function (method, url) {
// callback
if (typeof url === 'function') {
return new exports.Request('GET', method).end(url);
} // url first
if (arguments.length === 1) {
return new exports.Request('GET', method);
}
return new exports.Request(method, url);
};
exports = module.exports;
var request = exports;
exports.Request = Request;
/**
* Determine XHR.
*/
request.getXHR = function () {
if (root.XMLHttpRequest && (!root.location || root.location.protocol !== 'file:' || !root.ActiveXObject)) {
return new XMLHttpRequest();
}
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch (_unused) {
/**/
}
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch (_unused2) {
/**/
}
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch (_unused3) {
/**/
}
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch (_unused4) {
/**/
}
throw new Error('Browser-only version of superagent could not find XHR');
};
/**
* Removes leading and trailing whitespace, added to support IE.
*
* @param {String} s
* @return {String}
* @api private
*/
var trim = ''.trim ? function (s) {
return s.trim();
} : function (s) {
return s.replace(/(^\s*|\s*$)/g, '');
};
/**
* Serialize the given `obj`.
*
* @param {Object} obj
* @return {String}
* @api private
*/
function serialize(object) {
if (!isObject(object)) return object;
var pairs = [];
for (var key in object) {
if (hasOwn(object, key)) pushEncodedKeyValuePair(pairs, key, object[key]);
}
return pairs.join('&');
}
/**
* Helps 'serialize' with serializing arrays.
* Mutates the pairs array.
*
* @param {Array} pairs
* @param {String} key
* @param {Mixed} val
*/
function pushEncodedKeyValuePair(pairs, key, value) {
if (value === undefined) return;
if (value === null) {
pairs.push(encodeURI(key));
return;
}
if (Array.isArray(value)) {
var _iterator = _createForOfIteratorHelper(value),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var v = _step.value;
pushEncodedKeyValuePair(pairs, key, v);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
} else if (isObject(value)) {
for (var subkey in value) {
if (hasOwn(value, subkey)) pushEncodedKeyValuePair(pairs, "".concat(key, "[").concat(subkey, "]"), value[subkey]);
}
} else {
pairs.push(encodeURI(key) + '=' + encodeURIComponent(value));
}
}
/**
* Expose serialization method.
*/
request.serializeObject = serialize;
/**
* Parse the given x-www-form-urlencoded `str`.
*
* @param {String} str
* @return {Object}
* @api private
*/
function parseString(string_) {
var object = {};
var pairs = string_.split('&');
var pair;
var pos;
for (var i = 0, length_ = pairs.length; i < length_; ++i) {
pair = pairs[i];
pos = pair.indexOf('=');
if (pos === -1) {
object[decodeURIComponent(pair)] = '';
} else {
object[decodeURIComponent(pair.slice(0, pos))] = decodeURIComponent(pair.slice(pos + 1));
}
}
return object;
}
/**
* Expose parser.
*/
request.parseString = parseString;
/**
* Default MIME type map.
*
* superagent.types.xml = 'application/xml';
*
*/
request.types = {
html: 'text/html',
json: 'application/json',
xml: 'text/xml',
urlencoded: 'application/x-www-form-urlencoded',
form: 'application/x-www-form-urlencoded',
'form-data': 'application/x-www-form-urlencoded'
};
/**
* Default serialization map.
*
* superagent.serialize['application/xml'] = function(obj){
* return 'generated xml here';
* };
*
*/
request.serialize = {
'application/x-www-form-urlencoded': qs.stringify,
'application/json': safeStringify
};
/**
* Default parsers.
*
* superagent.parse['application/xml'] = function(str){
* return { object parsed from str };
* };
*
*/
request.parse = {
'application/x-www-form-urlencoded': parseString,
'application/json': JSON.parse
};
/**
* Parse the given header `str` into
* an object containing the mapped fields.
*
* @param {String} str
* @return {Object}
* @api private
*/
function parseHeader(string_) {
var lines = string_.split(/\r?\n/);
var fields = {};
var index;
var line;
var field;
var value;
for (var i = 0, length_ = lines.length; i < length_; ++i) {
line = lines[i];
index = line.indexOf(':');
if (index === -1) {
// could be empty line, just skip it
continue;
}
field = line.slice(0, index).toLowerCase();
value = trim(line.slice(index + 1));
fields[field] = value;
}
return fields;
}
/**
* Check if `mime` is json or has +json structured syntax suffix.
*
* @param {String} mime
* @return {Boolean}
* @api private
*/
function isJSON(mime) {
// should match /json or +json
// but not /json-seq
return /[/+]json($|[^-\w])/i.test(mime);
}
/**
* Initialize a new `Response` with the given `xhr`.
*
* - set flags (.ok, .error, etc)
* - parse header
*
* Examples:
*
* Aliasing `superagent` as `request` is nice:
*
* request = superagent;
*
* We can use the promise-like API, or pass callbacks:
*
* request.get('/').end(function(res){});
* request.get('/', function(res){});
*
* Sending data can be chained:
*
* request
* .post('/user')
* .send({ name: 'tj' })
* .end(function(res){});
*
* Or passed to `.send()`:
*
* request
* .post('/user')
* .send({ name: 'tj' }, function(res){});
*
* Or passed to `.post()`:
*
* request
* .post('/user', { name: 'tj' })
* .end(function(res){});
*
* Or further reduced to a single call for simple cases:
*
* request
* .post('/user', { name: 'tj' }, function(res){});
*
* @param {XMLHTTPRequest} xhr
* @param {Object} options
* @api private
*/
function Response(request_) {
this.req = request_;
this.xhr = this.req.xhr; // responseText is accessible only if responseType is '' or 'text' and on older browsers
this.text = this.req.method !== 'HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text') || typeof this.xhr.responseType === 'undefined' ? this.xhr.responseText : null;
this.statusText = this.req.xhr.statusText;
var status = this.xhr.status; // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
if (status === 1223) {
status = 204;
}
this._setStatusProperties(status);
this.headers = parseHeader(this.xhr.getAllResponseHeaders());
this.header = this.headers; // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but
// getResponseHeader still works. so we get content-type even if getting
// other headers fails.
this.header['content-type'] = this.xhr.getResponseHeader('content-type');
this._setHeaderProperties(this.header);
if (this.text === null && request_._responseType) {
this.body = this.xhr.response;
} else {
this.body = this.req.method === 'HEAD' ? null : this._parseBody(this.text ? this.text : this.xhr.response);
}
}
mixin(Response.prototype, ResponseBase.prototype);
/**
* Parse the given body `str`.
*
* Used for auto-parsing of bodies. Parsers
* are defined on the `superagent.parse` object.
*
* @param {String} str
* @return {Mixed}
* @api private
*/
Response.prototype._parseBody = function (string_) {
var parse = request.parse[this.type];
if (this.req._parser) {
return this.req._parser(this, string_);
}
if (!parse && isJSON(this.type)) {
parse = request.parse['application/json'];
}
return parse && string_ && (string_.length > 0 || string_ instanceof Object) ? parse(string_) : null;
};
/**
* Return an `Error` representative of this response.
*
* @return {Error}
* @api public
*/
Response.prototype.toError = function () {
var req = this.req;
var method = req.method;
var url = req.url;
var message = "cannot ".concat(method, " ").concat(url, " (").concat(this.status, ")");
var error = new Error(message);
error.status = this.status;
error.method = method;
error.url = url;
return error;
};
/**
* Expose `Response`.
*/
request.Response = Response;
/**
* Initialize a new `Request` with the given `method` and `url`.
*
* @param {String} method
* @param {String} url
* @api public
*/
function Request(method, url) {
var self = this;
this._query = this._query || [];
this.method = method;
this.url = url;
this.header = {}; // preserves header name case
this._header = {}; // coerces header names to lowercase
this.on('end', function () {
var error = null;
var res = null;
try {
res = new Response(self);
} catch (err) {
error = new Error('Parser is unable to parse the response');
error.parse = true;
error.original = err; // issue #675: return the raw response if the response parsing fails
if (self.xhr) {
// ie9 doesn't have 'response' property
error.rawResponse = typeof self.xhr.responseType === 'undefined' ? self.xhr.responseText : self.xhr.response; // issue #876: return the http status code if the response parsing fails
error.status = self.xhr.status ? self.xhr.status : null;
error.statusCode = error.status; // backwards-compat only
} else {
error.rawResponse = null;
error.status = null;
}
return self.callback(error);
}
self.emit('response', res);
var new_error;
try {
if (!self._isResponseOK(res)) {
new_error = new Error(res.statusText || res.text || 'Unsuccessful HTTP response');
}
} catch (err) {
new_error = err; // ok() callback can throw
} // #1000 don't catch errors from the callback to avoid double calling it
if (new_error) {
new_error.original = error;
new_error.response = res;
new_error.status = res.status;
self.callback(new_error, res);
} else {
self.callback(null, res);
}
});
}
/**
* Mixin `Emitter` and `RequestBase`.
*/
// eslint-disable-next-line new-cap
Emitter(Request.prototype);
mixin(Request.prototype, RequestBase.prototype);
/**
* Set Content-Type to `type`, mapping values from `request.types`.
*
* Examples:
*
* superagent.types.xml = 'application/xml';
*
* request.post('/')
* .type('xml')
* .send(xmlstring)
* .end(callback);
*
* request.post('/')
* .type('application/xml')
* .send(xmlstring)
* .end(callback);
*
* @param {String} type
* @return {Request} for chaining
* @api public
*/
Request.prototype.type = function (type) {
this.set('Content-Type', request.types[type] || type);
return this;
};
/**
* Set Accept to `type`, mapping values from `request.types`.
*
* Examples:
*
* superagent.types.json = 'application/json';
*
* request.get('/agent')
* .accept('json')
* .end(callback);
*
* request.get('/agent')
* .accept('application/json')
* .end(callback);
*
* @param {String} accept
* @return {Request} for chaining
* @api public
*/
Request.prototype.accept = function (type) {
this.set('Accept', request.types[type] || type);
return this;
};
/**
* Set Authorization field value with `user` and `pass`.
*
* @param {String} user
* @param {String} [pass] optional in case of using 'bearer' as type
* @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic')
* @return {Request} for chaining
* @api public
*/
Request.prototype.auth = function (user, pass, options) {
if (arguments.length === 1) pass = '';
if (_typeof(pass) === 'object' && pass !== null) {
// pass is optional and can be replaced with options
options = pass;
pass = '';
}
if (!options) {
options = {
type: typeof btoa === 'function' ? 'basic' : 'auto'
};
}
var encoder = options.encoder ? options.encoder : function (string) {
if (typeof btoa === 'function') {
return btoa(string);
}
throw new Error('Cannot use basic auth, btoa is not a function');
};
return this._auth(user, pass, options, encoder);
};
/**
* Add query-string `val`.
*
* Examples:
*
* request.get('/shoes')
* .query('size=10')
* .query({ color: 'blue' })
*
* @param {Object|String} val
* @return {Request} for chaining
* @api public
*/
Request.prototype.query = function (value) {
if (typeof value !== 'string') value = serialize(value);
if (value) this._query.push(value);
return this;
};
/**
* Queue the given `file` as an attachment to the specified `field`,
* with optional `options` (or filename).
*
* ``` js
* request.post('/upload')
* .attach('content', new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"}))
* .end(callback);
* ```
*
* @param {String} field
* @param {Blob|File} file
* @param {String|Object} options
* @return {Request} for chaining
* @api public
*/
Request.prototype.attach = function (field, file, options) {
if (file) {
if (this._data) {
throw new Error("superagent can't mix .send() and .attach()");
}
this._getFormData().append(field, file, options || file.name);
}
return this;
};
Request.prototype._getFormData = function () {
if (!this._formData) {
this._formData = new root.FormData();
}
return this._formData;
};
/**
* Invoke the callback with `err` and `res`
* and handle arity check.
*
* @param {Error} err
* @param {Response} res
* @api private
*/
Request.prototype.callback = function (error, res) {
if (this._shouldRetry(error, res)) {
return this._retry();
}
var fn = this._callback;
this.clearTimeout();
if (error) {
if (this._maxRetries) error.retries = this._retries - 1;
this.emit('error', error);
}
fn(error, res);
};
/**
* Invoke callback with x-domain error.
*
* @api private
*/
Request.prototype.crossDomainError = function () {
var error = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.');
error.crossDomain = true;
error.status = this.status;
error.method = this.method;
error.url = this.url;
this.callback(error);
}; // This only warns, because the request is still likely to work
Request.prototype.agent = function () {
console.warn('This is not supported in browser version of superagent');
return this;
};
Request.prototype.ca = Request.prototype.agent;
Request.prototype.buffer = Request.prototype.ca; // This throws, because it can't send/receive data as expected
Request.prototype.write = function () {
throw new Error('Streaming is not supported in browser version of superagent');
};
Request.prototype.pipe = Request.prototype.write;
/**
* Check if `obj` is a host object,
* we don't want to serialize these :)
*
* @param {Object} obj host object
* @return {Boolean} is a host object
* @api private
*/
Request.prototype._isHost = function (object) {
// Native objects stringify to [object File], [object Blob], [object FormData], etc.
return object && _typeof(object) === 'object' && !Array.isArray(object) && Object.prototype.toString.call(object) !== '[object Object]';
};
/**
* Initiate request, invoking callback `fn(res)`
* with an instanceof `Response`.
*
* @param {Function} fn
* @return {Request} for chaining
* @api public
*/
Request.prototype.end = function (fn) {
if (this._endCalled) {
console.warn('Warning: .end() was called twice. This is not supported in superagent');
}
this._endCalled = true; // store callback
this._callback = fn || noop; // querystring
this._finalizeQueryString();
this._end();
};
Request.prototype._setUploadTimeout = function () {
var self = this; // upload timeout it's wokrs only if deadline timeout is off
if (this._uploadTimeout && !this._uploadTimeoutTimer) {
this._uploadTimeoutTimer = setTimeout(function () {
self._timeoutError('Upload timeout of ', self._uploadTimeout, 'ETIMEDOUT');
}, this._uploadTimeout);
}
}; // eslint-disable-next-line complexity
Request.prototype._end = function () {
if (this._aborted) return this.callback(new Error('The request has been aborted even before .end() was called'));
var self = this;
this.xhr = request.getXHR();
var xhr = this.xhr;
var data = this._formData || this._data;
this._setTimeouts(); // state change
xhr.addEventListener('readystatechange', function () {
var readyState = xhr.readyState;
if (readyState >= 2 && self._responseTimeoutTimer) {
clearTimeout(self._responseTimeoutTimer);
}
if (readyState !== 4) {
return;
} // In IE9, reads to any property (e.g. status) off of an aborted XHR will
// result in the error "Could not complete the operation due to error c00c023f"
var status;
try {
status = xhr.status;
} catch (_unused5) {
status = 0;
}
if (!status) {
if (self.timedout || self._aborted) return;
return self.crossDomainError();
}
self.emit('end');
}); // progress
var handleProgress = function handleProgress(direction, e) {
if (e.total > 0) {
e.percent = e.loaded / e.total * 100;
if (e.percent === 100) {
clearTimeout(self._uploadTimeoutTimer);
}
}
e.direction = direction;
self.emit('progress', e);
};
if (this.hasListeners('progress')) {
try {
xhr.addEventListener('progress', handleProgress.bind(null, 'download'));
if (xhr.upload) {
xhr.upload.addEventListener('progress', handleProgress.bind(null, 'upload'));
}
} catch (_unused6) {// Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist.
// Reported here:
// https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context
}
}
if (xhr.upload) {
this._setUploadTimeout();
} // initiate request
try {
if (this.username && this.password) {
xhr.open(this.method, this.url, true, this.username, this.password);
} else {
xhr.open(this.method, this.url, true);
}
} catch (err) {
// see #1149
return this.callback(err);
} // CORS
if (this._withCredentials) xhr.withCredentials = true; // body
if (!this._formData && this.method !== 'GET' && this.method !== 'HEAD' && typeof data !== 'string' && !this._isHost(data)) {
// serialize stuff
var contentType = this._header['content-type'];
var _serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : ''];
if (!_serialize && isJSON(contentType)) {
_serialize = request.serialize['application/json'];
}
if (_serialize) data = _serialize(data);
} // set header fields
for (var field in this.header) {
if (this.header[field] === null) continue;
if (hasOwn(this.header, field)) xhr.setRequestHeader(field, this.header[field]);
}
if (this._responseType) {
xhr.responseType = this._responseType;
} // send stuff
this.emit('request', this); // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing)
// We need null here if data is undefined
xhr.send(typeof data === 'undefined' ? null : data);
};
request.agent = function () {
return new Agent();
};
var _loop = function _loop() {
var method = _arr[_i];
Agent.prototype[method.toLowerCase()] = function (url, fn) {
var request_ = new request.Request(method, url);
this._setDefaults(request_);
if (fn) {
request_.end(fn);
}
return request_;
};
};
for (var _i = 0, _arr = ['GET', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE']; _i < _arr.length; _i++) {
_loop();
}
Agent.prototype.del = Agent.prototype.delete;
/**
* GET `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Mixed|Function} [data] or fn
* @param {Function} [fn]
* @return {Request}
* @api public
*/
request.get = function (url, data, fn) {
var request_ = request('GET', url);
if (typeof data === 'function') {
fn = data;
data = null;
}
if (data) request_.query(data);
if (fn) request_.end(fn);
return request_;
};
/**
* HEAD `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Mixed|Function} [data] or fn
* @param {Function} [fn]
* @return {Request}
* @api public
*/
request.head = function (url, data, fn) {
var request_ = request('HEAD', url);
if (typeof data === 'function') {
fn = data;
data = null;
}
if (data) request_.query(data);
if (fn) request_.end(fn);
return request_;
};
/**
* OPTIONS query to `url` with optional callback `fn(res)`.
*
* @param {String} url
* @param {Mixed|Function} [data] or fn
* @param {Function} [fn]
* @return {Request}
* @api public
*/
request.options = function (url, data, fn) {
var request_ = request('OPTIONS', url);
if (typeof data === 'function') {
fn = data;
data = null;
}
if (data) request_.send(data);
if (fn) request_.end(fn);
return request_;
};
/**
* DELETE `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} [data]
* @param {Function} [fn]
* @return {Request}
* @api public
*/
function del(url, data, fn) {
var request_ = request('DELETE', url);
if (typeof data === 'function') {
fn = data;
data = null;
}
if (data) request_.send(data);
if (fn) request_.end(fn);
return request_;
}
request.del = del;
request.delete = del;
/**
* PATCH `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} [data]
* @param {Function} [fn]
* @return {Request}
* @api public
*/
request.patch = function (url, data, fn) {
var request_ = request('PATCH', url);
if (typeof data === 'function') {
fn = data;
data = null;
}
if (data) request_.send(data);
if (fn) request_.end(fn);
return request_;
};
/**
* POST `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed} [data]
* @param {Function} [fn]
* @return {Request}
* @api public
*/
request.post = function (url, data, fn) {
var request_ = request('POST', url);
if (typeof data === 'function') {
fn = data;
data = null;
}
if (data) request_.send(data);
if (fn) request_.end(fn);
return request_;
};
/**
* PUT `url` with optional `data` and callback `fn(res)`.
*
* @param {String} url
* @param {Mixed|Function} [data] or fn
* @param {Function} [fn]
* @return {Request}
* @api public
*/
request.put = function (url, data, fn) {
var request_ = request('PUT', url);
if (typeof data === 'function') {
fn = data;
data = null;
}
if (data) request_.send(data);
if (fn) request_.end(fn);
return request_;
};
},{"./agent-base":217,"./request-base":219,"./response-base":220,"./utils":221,"component-emitter":61,"fast-safe-stringify":82,"qs":162}],219:[function(require,module,exports){
(function (process){(function (){
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
var semver = require('semver');
/**
* Module of mixed-in functions shared between node and client code
*/
var _require = require('./utils'),
isObject = _require.isObject,
hasOwn = _require.hasOwn;
/**
* Expose `RequestBase`.
*/
module.exports = RequestBase;
/**
* Initialize a new `RequestBase`.
*
* @api public
*/
function RequestBase() {}
/**
* Clear previous timeout.
*
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.clearTimeout = function () {
clearTimeout(this._timer);
clearTimeout(this._responseTimeoutTimer);
clearTimeout(this._uploadTimeoutTimer);
delete this._timer;
delete this._responseTimeoutTimer;
delete this._uploadTimeoutTimer;
return this;
};
/**
* Override default response body parser
*
* This function will be called to convert incoming data into request.body
*
* @param {Function}
* @api public
*/
RequestBase.prototype.parse = function (fn) {
this._parser = fn;
return this;
};
/**
* Set format of binary response body.
* In browser valid formats are 'blob' and 'arraybuffer',
* which return Blob and ArrayBuffer, respectively.
*
* In Node all values result in Buffer.
*
* Examples:
*
* req.get('/')
* .responseType('blob')
* .end(callback);
*
* @param {String} val
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.responseType = function (value) {
this._responseType = value;
return this;
};
/**
* Override default request body serializer
*
* This function will be called to convert data set via .send or .attach into payload to send
*
* @param {Function}
* @api public
*/
RequestBase.prototype.serialize = function (fn) {
this._serializer = fn;
return this;
};
/**
* Set timeouts.
*
* - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time.
* - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections.
* - upload is the time since last bit of data was sent or received. This timeout works only if deadline timeout is off
*
* Value of 0 or false means no timeout.
*
* @param {Number|Object} ms or {response, deadline}
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.timeout = function (options) {
if (!options || _typeof(options) !== 'object') {
this._timeout = options;
this._responseTimeout = 0;
this._uploadTimeout = 0;
return this;
}
for (var option in options) {
if (hasOwn(options, option)) {
switch (option) {
case 'deadline':
this._timeout = options.deadline;
break;
case 'response':
this._responseTimeout = options.response;
break;
case 'upload':
this._uploadTimeout = options.upload;
break;
default:
console.warn('Unknown timeout option', option);
}
}
}
return this;
};
/**
* Set number of retry attempts on error.
*
* Failed requests will be retried 'count' times if timeout or err.code >= 500.
*
* @param {Number} count
* @param {Function} [fn]
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.retry = function (count, fn) {
// Default to 1 if no count passed or true
if (arguments.length === 0 || count === true) count = 1;
if (count <= 0) count = 0;
this._maxRetries = count;
this._retries = 0;
this._retryCallback = fn;
return this;
}; //
// NOTE: we do not include ESOCKETTIMEDOUT because that is from `request` package
// <https://github.com/sindresorhus/got/pull/537>
//
// NOTE: we do not include EADDRINFO because it was removed from libuv in 2014
// <https://github.com/libuv/libuv/commit/02e1ebd40b807be5af46343ea873331b2ee4e9c1>
// <https://github.com/request/request/search?q=ESOCKETTIMEDOUT&unscoped_q=ESOCKETTIMEDOUT>
//
//
// TODO: expose these as configurable defaults
//
var ERROR_CODES = new Set(['ETIMEDOUT', 'ECONNRESET', 'EADDRINUSE', 'ECONNREFUSED', 'EPIPE', 'ENOTFOUND', 'ENETUNREACH', 'EAI_AGAIN']);
var STATUS_CODES = new Set([408, 413, 429, 500, 502, 503, 504, 521, 522, 524]); // TODO: we would need to make this easily configurable before adding it in (e.g. some might want to add POST)
// const METHODS = new Set(['GET', 'PUT', 'HEAD', 'DELETE', 'OPTIONS', 'TRACE']);
/**
* Determine if a request should be retried.
* (Inspired by https://github.com/sindresorhus/got#retry)
*
* @param {Error} err an error
* @param {Response} [res] response
* @returns {Boolean} if segment should be retried
*/
RequestBase.prototype._shouldRetry = function (error, res) {
if (!this._maxRetries || this._retries++ >= this._maxRetries) {
return false;
}
if (this._retryCallback) {
try {
var override = this._retryCallback(error, res);
if (override === true) return true;
if (override === false) return false; // undefined falls back to defaults
} catch (err) {
console.error(err);
}
} // TODO: we would need to make this easily configurable before adding it in (e.g. some might want to add POST)
/*
if (
this.req &&
this.req.method &&
!METHODS.has(this.req.method.toUpperCase())
)
return false;
*/
if (res && res.status && STATUS_CODES.has(res.status)) return true;
if (error) {
if (error.code && ERROR_CODES.has(error.code)) return true; // Superagent timeout
if (error.timeout && error.code === 'ECONNABORTED') return true;
if (error.crossDomain) return true;
}
return false;
};
/**
* Retry request
*
* @return {Request} for chaining
* @api private
*/
RequestBase.prototype._retry = function () {
this.clearTimeout(); // node
if (this.req) {
this.req = null;
this.req = this.request();
}
this._aborted = false;
this.timedout = false;
this.timedoutError = null;
return this._end();
};
/**
* Promise support
*
* @param {Function} resolve
* @param {Function} [reject]
* @return {Request}
*/
RequestBase.prototype.then = function (resolve, reject) {
var _this = this;
if (!this._fullfilledPromise) {
var self = this;
if (this._endCalled) {
console.warn('Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises');
}
this._fullfilledPromise = new Promise(function (resolve, reject) {
self.on('abort', function () {
if (_this._maxRetries && _this._maxRetries > _this._retries) {
return;
}
if (_this.timedout && _this.timedoutError) {
reject(_this.timedoutError);
return;
}
var error = new Error('Aborted');
error.code = 'ABORTED';
error.status = _this.status;
error.method = _this.method;
error.url = _this.url;
reject(error);
});
self.end(function (error, res) {
if (error) reject(error);else resolve(res);
});
});
}
return this._fullfilledPromise.then(resolve, reject);
};
RequestBase.prototype.catch = function (callback) {
return this.then(undefined, callback);
};
/**
* Allow for extension
*/
RequestBase.prototype.use = function (fn) {
fn(this);
return this;
};
RequestBase.prototype.ok = function (callback) {
if (typeof callback !== 'function') throw new Error('Callback required');
this._okCallback = callback;
return this;
};
RequestBase.prototype._isResponseOK = function (res) {
if (!res) {
return false;
}
if (this._okCallback) {
return this._okCallback(res);
}
return res.status >= 200 && res.status < 300;
};
/**
* Get request header `field`.
* Case-insensitive.
*
* @param {String} field
* @return {String}
* @api public
*/
RequestBase.prototype.get = function (field) {
return this._header[field.toLowerCase()];
};
/**
* Get case-insensitive header `field` value.
* This is a deprecated internal API. Use `.get(field)` instead.
*
* (getHeader is no longer used internally by the superagent code base)
*
* @param {String} field
* @return {String}
* @api private
* @deprecated
*/
RequestBase.prototype.getHeader = RequestBase.prototype.get;
/**
* Set header `field` to `val`, or multiple fields with one object.
* Case-insensitive.
*
* Examples:
*
* req.get('/')
* .set('Accept', 'application/json')
* .set('X-API-Key', 'foobar')
* .end(callback);
*
* req.get('/')
* .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
* .end(callback);
*
* @param {String|Object} field
* @param {String} val
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.set = function (field, value) {
if (isObject(field)) {
for (var key in field) {
if (hasOwn(field, key)) this.set(key, field[key]);
}
return this;
}
this._header[field.toLowerCase()] = value;
this.header[field] = value;
return this;
};
/**
* Remove header `field`.
* Case-insensitive.
*
* Example:
*
* req.get('/')
* .unset('User-Agent')
* .end(callback);
*
* @param {String} field field name
*/
RequestBase.prototype.unset = function (field) {
delete this._header[field.toLowerCase()];
delete this.header[field];
return this;
};
/**
* Write the field `name` and `val`, or multiple fields with one object
* for "multipart/form-data" request bodies.
*
* ``` js
* request.post('/upload')
* .field('foo', 'bar')
* .end(callback);
*
* request.post('/upload')
* .field({ foo: 'bar', baz: 'qux' })
* .end(callback);
* ```
*
* @param {String|Object} name name of field
* @param {String|Blob|File|Buffer|fs.ReadStream} val value of field
* @param {String} options extra options, e.g. 'blob'
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.field = function (name, value, options) {
// name should be either a string or an object.
if (name === null || undefined === name) {
throw new Error('.field(name, val) name can not be empty');
}
if (this._data) {
throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()");
}
if (isObject(name)) {
for (var key in name) {
if (hasOwn(name, key)) this.field(key, name[key]);
}
return this;
}
if (Array.isArray(value)) {
for (var i in value) {
if (hasOwn(value, i)) this.field(name, value[i]);
}
return this;
} // val should be defined now
if (value === null || undefined === value) {
throw new Error('.field(name, val) val can not be empty');
}
if (typeof value === 'boolean') {
value = String(value);
} //fix https://github.com/visionmedia/superagent/issues/1680
if (options) this._getFormData().append(name, value, options);else this._getFormData().append(name, value);
return this;
};
/**
* Abort the request, and clear potential timeout.
*
* @return {Request} request
* @api public
*/
RequestBase.prototype.abort = function () {
if (this._aborted) {
return this;
}
this._aborted = true;
if (this.xhr) this.xhr.abort(); // browser
if (this.req) {
// Node v13 has major differences in `abort()`
// https://github.com/nodejs/node/blob/v12.x/lib/internal/streams/end-of-stream.js
// https://github.com/nodejs/node/blob/v13.x/lib/internal/streams/end-of-stream.js
// https://github.com/nodejs/node/blob/v14.x/lib/internal/streams/end-of-stream.js
// (if you run a diff across these you will see the differences)
//
// References:
// <https://github.com/nodejs/node/issues/31630>
// <https://github.com/visionmedia/superagent/pull/1084/commits/dc18679a7c5ccfc6046d882015e5126888973bc8>
//
// Thanks to @shadowgate15 and @niftylettuce
if (semver.gte(process.version, 'v13.0.0') && semver.lt(process.version, 'v14.0.0')) {
// Note that the reason this doesn't work is because in v13 as compared to v14
// there is no `callback = nop` set in end-of-stream.js above
throw new Error('Superagent does not work in v13 properly with abort() due to Node.js core changes');
} else if (semver.gte(process.version, 'v14.0.0')) {
// We have to manually set `destroyed` to `true` in order for this to work
// (see core internals of end-of-stream.js above in v14 branch as compared to v12)
this.req.destroyed = true;
}
this.req.abort(); // node
}
this.clearTimeout();
this.emit('abort');
return this;
};
RequestBase.prototype._auth = function (user, pass, options, base64Encoder) {
switch (options.type) {
case 'basic':
this.set('Authorization', "Basic ".concat(base64Encoder("".concat(user, ":").concat(pass))));
break;
case 'auto':
this.username = user;
this.password = pass;
break;
case 'bearer':
// usage would be .auth(accessToken, { type: 'bearer' })
this.set('Authorization', "Bearer ".concat(user));
break;
default:
break;
}
return this;
};
/**
* Enable transmission of cookies with x-domain requests.
*
* Note that for this to work the origin must not be
* using "Access-Control-Allow-Origin" with a wildcard,
* and also must set "Access-Control-Allow-Credentials"
* to "true".
*
* @api public
*/
RequestBase.prototype.withCredentials = function (on) {
// This is browser-only functionality. Node side is no-op.
if (on === undefined) on = true;
this._withCredentials = on;
return this;
};
/**
* Set the max redirects to `n`. Does nothing in browser XHR implementation.
*
* @param {Number} n
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.redirects = function (n) {
this._maxRedirects = n;
return this;
};
/**
* Maximum size of buffered response body, in bytes. Counts uncompressed size.
* Default 200MB.
*
* @param {Number} n number of bytes
* @return {Request} for chaining
*/
RequestBase.prototype.maxResponseSize = function (n) {
if (typeof n !== 'number') {
throw new TypeError('Invalid argument');
}
this._maxResponseSize = n;
return this;
};
/**
* Convert to a plain javascript object (not JSON string) of scalar properties.
* Note as this method is designed to return a useful non-this value,
* it cannot be chained.
*
* @return {Object} describing method, url, and data of this request
* @api public
*/
RequestBase.prototype.toJSON = function () {
return {
method: this.method,
url: this.url,
data: this._data,
headers: this._header
};
};
/**
* Send `data` as the request body, defaulting the `.type()` to "json" when
* an object is given.
*
* Examples:
*
* // manual json
* request.post('/user')
* .type('json')
* .send('{"name":"tj"}')
* .end(callback)
*
* // auto json
* request.post('/user')
* .send({ name: 'tj' })
* .end(callback)
*
* // manual x-www-form-urlencoded
* request.post('/user')
* .type('form')
* .send('name=tj')
* .end(callback)
*
* // auto x-www-form-urlencoded
* request.post('/user')
* .type('form')
* .send({ name: 'tj' })
* .end(callback)
*
* // defaults to x-www-form-urlencoded
* request.post('/user')
* .send('name=tobi')
* .send('species=ferret')
* .end(callback)
*
* @param {String|Object} data
* @return {Request} for chaining
* @api public
*/
// eslint-disable-next-line complexity
RequestBase.prototype.send = function (data) {
var isObject_ = isObject(data);
var type = this._header['content-type'];
if (this._formData) {
throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()");
}
if (isObject_ && !this._data) {
if (Array.isArray(data)) {
this._data = [];
} else if (!this._isHost(data)) {
this._data = {};
}
} else if (data && this._data && this._isHost(this._data)) {
throw new Error("Can't merge these send calls");
} // merge
if (isObject_ && isObject(this._data)) {
for (var key in data) {
if (hasOwn(data, key)) this._data[key] = data[key];
}
} else if (typeof data === 'string') {
// default to x-www-form-urlencoded
if (!type) this.type('form');
type = this._header['content-type'];
if (type) type = type.toLowerCase().trim();
if (type === 'application/x-www-form-urlencoded') {
this._data = this._data ? "".concat(this._data, "&").concat(data) : data;
} else {
this._data = (this._data || '') + data;
}
} else {
this._data = data;
}
if (!isObject_ || this._isHost(data)) {
return this;
} // default to json
if (!type) this.type('json');
return this;
};
/**
* Sort `querystring` by the sort function
*
*
* Examples:
*
* // default order
* request.get('/user')
* .query('name=Nick')
* .query('search=Manny')
* .sortQuery()
* .end(callback)
*
* // customized sort function
* request.get('/user')
* .query('name=Nick')
* .query('search=Manny')
* .sortQuery(function(a, b){
* return a.length - b.length;
* })
* .end(callback)
*
*
* @param {Function} sort
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.sortQuery = function (sort) {
// _sort default to true but otherwise can be a function or boolean
this._sort = typeof sort === 'undefined' ? true : sort;
return this;
};
/**
* Compose querystring to append to req.url
*
* @api private
*/
RequestBase.prototype._finalizeQueryString = function () {
var query = this._query.join('&');
if (query) {
this.url += (this.url.includes('?') ? '&' : '?') + query;
}
this._query.length = 0; // Makes the call idempotent
if (this._sort) {
var index = this.url.indexOf('?');
if (index >= 0) {
var queryArray = this.url.slice(index + 1).split('&');
if (typeof this._sort === 'function') {
queryArray.sort(this._sort);
} else {
queryArray.sort();
}
this.url = this.url.slice(0, index) + '?' + queryArray.join('&');
}
}
}; // For backwards compat only
RequestBase.prototype._appendQueryString = function () {
console.warn('Unsupported');
};
/**
* Invoke callback with timeout error.
*
* @api private
*/
RequestBase.prototype._timeoutError = function (reason, timeout, errno) {
if (this._aborted) {
return;
}
var error = new Error("".concat(reason + timeout, "ms exceeded"));
error.timeout = timeout;
error.code = 'ECONNABORTED';
error.errno = errno;
this.timedout = true;
this.timedoutError = error;
this.abort();
this.callback(error);
};
RequestBase.prototype._setTimeouts = function () {
var self = this; // deadline
if (this._timeout && !this._timer) {
this._timer = setTimeout(function () {
self._timeoutError('Timeout of ', self._timeout, 'ETIME');
}, this._timeout);
} // response timeout
if (this._responseTimeout && !this._responseTimeoutTimer) {
this._responseTimeoutTimer = setTimeout(function () {
self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT');
}, this._responseTimeout);
}
};
}).call(this)}).call(this,require('_process'))
},{"./utils":221,"_process":160,"semver":34}],220:[function(require,module,exports){
"use strict";
/**
* Module dependencies.
*/
var utils = require('./utils');
/**
* Expose `ResponseBase`.
*/
module.exports = ResponseBase;
/**
* Initialize a new `ResponseBase`.
*
* @api public
*/
function ResponseBase() {}
/**
* Get case-insensitive `field` value.
*
* @param {String} field
* @return {String}
* @api public
*/
ResponseBase.prototype.get = function (field) {
return this.header[field.toLowerCase()];
};
/**
* Set header related properties:
*
* - `.type` the content type without params
*
* A response of "Content-Type: text/plain; charset=utf-8"
* will provide you with a `.type` of "text/plain".
*
* @param {Object} header
* @api private
*/
ResponseBase.prototype._setHeaderProperties = function (header) {
// TODO: moar!
// TODO: make this a util
// content-type
var ct = header['content-type'] || '';
this.type = utils.type(ct); // params
var parameters = utils.params(ct);
for (var key in parameters) {
if (Object.prototype.hasOwnProperty.call(parameters, key)) this[key] = parameters[key];
}
this.links = {}; // links
try {
if (header.link) {
this.links = utils.parseLinks(header.link);
}
} catch (_unused) {// ignore
}
};
/**
* Set flags such as `.ok` based on `status`.
*
* For example a 2xx response will give you a `.ok` of __true__
* whereas 5xx will be __false__ and `.error` will be __true__. The
* `.clientError` and `.serverError` are also available to be more
* specific, and `.statusType` is the class of error ranging from 1..5
* sometimes useful for mapping respond colors etc.
*
* "sugar" properties are also defined for common cases. Currently providing:
*
* - .noContent
* - .badRequest
* - .unauthorized
* - .notAcceptable
* - .notFound
*
* @param {Number} status
* @api private
*/
ResponseBase.prototype._setStatusProperties = function (status) {
var type = Math.trunc(status / 100); // status / class
this.statusCode = status;
this.status = this.statusCode;
this.statusType = type; // basics
this.info = type === 1;
this.ok = type === 2;
this.redirect = type === 3;
this.clientError = type === 4;
this.serverError = type === 5;
this.error = type === 4 || type === 5 ? this.toError() : false; // sugar
this.created = status === 201;
this.accepted = status === 202;
this.noContent = status === 204;
this.badRequest = status === 400;
this.unauthorized = status === 401;
this.notAcceptable = status === 406;
this.forbidden = status === 403;
this.notFound = status === 404;
this.unprocessableEntity = status === 422;
};
},{"./utils":221}],221:[function(require,module,exports){
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
/**
* Return the mime type for the given `str`.
*
* @param {String} str
* @return {String}
* @api private
*/
exports.type = function (string_) {
return string_.split(/ *; */).shift();
};
/**
* Return header field parameters.
*
* @param {String} str
* @return {Object}
* @api private
*/
exports.params = function (value) {
var object = {};
var _iterator = _createForOfIteratorHelper(value.split(/ *; */)),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var string_ = _step.value;
var parts = string_.split(/ *= */);
var key = parts.shift();
var _value = parts.shift();
if (key && _value) object[key] = _value;
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return object;
};
/**
* Parse Link header fields.
*
* @param {String} str
* @return {Object}
* @api private
*/
exports.parseLinks = function (value) {
var object = {};
var _iterator2 = _createForOfIteratorHelper(value.split(/ *, */)),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var string_ = _step2.value;
var parts = string_.split(/ *; */);
var url = parts[0].slice(1, -1);
var rel = parts[1].split(/ *= */)[1].slice(1, -1);
object[rel] = url;
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
return object;
};
/**
* Strip content related fields from `header`.
*
* @param {Object} header
* @return {Object} header
* @api private
*/
exports.cleanHeader = function (header, changesOrigin) {
delete header['content-type'];
delete header['content-length'];
delete header['transfer-encoding'];
delete header.host; // secuirty
if (changesOrigin) {
delete header.authorization;
delete header.cookie;
}
return header;
};
/**
* Check if `obj` is an object.
*
* @param {Object} object
* @return {Boolean}
* @api private
*/
exports.isObject = function (object) {
return object !== null && _typeof(object) === 'object';
};
/**
* Object.hasOwn fallback/polyfill.
*
* @type {(object: object, property: string) => boolean} object
* @api private
*/
exports.hasOwn = Object.hasOwn || function (object, property) {
if (object == null) {
throw new TypeError('Cannot convert undefined or null to object');
}
return Object.prototype.hasOwnProperty.call(new Object(object), property);
};
exports.mixin = function (target, source) {
for (var key in source) {
if (exports.hasOwn(source, key)) {
target[key] = source[key];
}
}
};
},{}],222:[function(require,module,exports){
module.exports = toArray
function toArray(list, index) {
var array = []
index = index || 0
for (var i = index || 0; i < list.length; i++) {
array[i - index] = list[i]
}
return array
}
},{}],223:[function(require,module,exports){
(function (global){(function (){
/**
* Module exports.
*/
module.exports = deprecate;
/**
* Mark that a method should not be used.
* Returns a modified function which warns once by default.
*
* If `localStorage.noDeprecation = true` is set, then it is a no-op.
*
* If `localStorage.throwDeprecation = true` is set, then deprecated functions
* will throw an Error when invoked.
*
* If `localStorage.traceDeprecation = true` is set, then deprecated functions
* will invoke `console.trace()` instead of `console.error()`.
*
* @param {Function} fn - the function to deprecate
* @param {String} msg - the string to print to the console when `fn` is invoked
* @returns {Function} a new "deprecated" version of `fn`
* @api public
*/
function deprecate (fn, msg) {
if (config('noDeprecation')) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (config('throwDeprecation')) {
throw new Error(msg);
} else if (config('traceDeprecation')) {
console.trace(msg);
} else {
console.warn(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
}
/**
* Checks `localStorage` for boolean values for the given `name`.
*
* @param {String} name
* @returns {Boolean}
* @api private
*/
function config (name) {
// accessing global.localStorage can trigger a DOMException in sandboxed iframes
try {
if (!global.localStorage) return false;
} catch (_) {
return false;
}
var val = global.localStorage[name];
if (null == val) return false;
return String(val).toLowerCase() === 'true';
}
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],224:[function(require,module,exports){
/* eslint-disable node/no-deprecated-api */
var assert = require('assert')
module.exports = getAllRoutes
var transform = function (trie, previous) {
var prev = previous || '/'
var routes = {}
var nodes = trie.nodes
Object.keys(nodes).forEach(function (key) {
var path = (prev === '/' ? prev : prev + '/') + (key === '$$' ? ':' + trie.name : key)
var cb = nodes[key].cb
if (cb !== undefined) {
routes[path] = cb
}
if (Object.keys(nodes[key].nodes).length !== 0) {
var obj = transform(nodes[key], path)
Object.keys(obj).forEach(function (r) {
routes[r] = obj[r]
})
}
})
return routes
}
// walk a wayfarer trie
// (obj, fn) -> null
function getAllRoutes (router) {
assert.equal(typeof router, 'function', 'wayfarer.getAllRoutes: router should be an function')
var trie = router._trie
assert.equal(typeof trie, 'object', 'wayfarer.getAllRoutes: trie should be an object')
var tree = trie.trie
return transform(tree)
}
},{"assert":127}],225:[function(require,module,exports){
/* eslint-disable node/no-deprecated-api */
var assert = require('assert')
var trie = require('./trie')
module.exports = Wayfarer
// create a router
// str -> obj
function Wayfarer (dft) {
if (!(this instanceof Wayfarer)) return new Wayfarer(dft)
var _default = (dft || '').replace(/^\//, '')
var _trie = trie()
emit._trie = _trie
emit.on = on
emit.emit = emit
emit.match = match
emit._wayfarer = true
return emit
// define a route
// (str, fn) -> obj
function on (route, cb) {
assert.equal(typeof route, 'string')
assert.equal(typeof cb, 'function')
route = route || '/'
if (cb._wayfarer && cb._trie) {
_trie.mount(route, cb._trie.trie)
} else {
var node = _trie.create(route)
node.cb = cb
node.route = route
}
return emit
}
// match and call a route
// (str, obj?) -> null
function emit (route) {
var matched = match(route)
var args = new Array(arguments.length)
args[0] = matched.params
for (var i = 1; i < args.length; i++) {
args[i] = arguments[i]
}
return matched.cb.apply(matched.cb, args)
}
function match (route) {
assert.notEqual(route, undefined, "'route' must be defined")
var matched = _trie.match(route)
if (matched && matched.cb) return new Route(matched)
var dft = _trie.match(_default)
if (dft && dft.cb) return new Route(dft)
throw new Error("route '" + route + "' did not match")
}
function Route (matched) {
this.cb = matched.cb
this.route = matched.route
this.params = matched.params
}
}
},{"./trie":226,"assert":127}],226:[function(require,module,exports){
/* eslint-disable node/no-deprecated-api */
var assert = require('assert')
module.exports = Trie
// create a new trie
// null -> obj
function Trie () {
if (!(this instanceof Trie)) return new Trie()
this.trie = { nodes: {} }
}
// create a node on the trie at route
// and return a node
// str -> obj
Trie.prototype.create = function (route) {
assert.equal(typeof route, 'string', 'route should be a string')
// strip leading '/' and split routes
var routes = route.replace(/^\//, '').split('/')
function createNode (index, trie) {
var thisRoute = (has(routes, index) && routes[index])
if (thisRoute === false) return trie
var node = null
if (/^:|^\*/.test(thisRoute)) {
// if node is a name match, set name and append to ':' node
if (!has(trie.nodes, '$$')) {
node = { nodes: {} }
trie.nodes.$$ = node
} else {
node = trie.nodes.$$
}
if (thisRoute[0] === '*') {
trie.wildcard = true
}
trie.name = thisRoute.replace(/^:|^\*/, '')
} else if (!has(trie.nodes, thisRoute)) {
node = { nodes: {} }
trie.nodes[thisRoute] = node
} else {
node = trie.nodes[thisRoute]
}
// we must recurse deeper
return createNode(index + 1, node)
}
return createNode(0, this.trie)
}
// match a route on the trie
// and return the node
// str -> obj
Trie.prototype.match = function (route) {
assert.equal(typeof route, 'string', 'route should be a string')
var routes = route.replace(/^\//, '').split('/')
var params = {}
function search (index, trie) {
// either there's no match, or we're done searching
if (trie === undefined) return undefined
var thisRoute = routes[index]
if (thisRoute === undefined) return trie
if (has(trie.nodes, thisRoute)) {
// match regular routes first
return search(index + 1, trie.nodes[thisRoute])
} else if (trie.name) {
// match named routes
try {
params[trie.name] = decodeURIComponent(thisRoute)
} catch (e) {
return search(index, undefined)
}
return search(index + 1, trie.nodes.$$)
} else if (trie.wildcard) {
// match wildcards
try {
params.wildcard = decodeURIComponent(routes.slice(index).join('/'))
} catch (e) {
return search(index, undefined)
}
// return early, or else search may keep recursing through the wildcard
return trie.nodes.$$
} else {
// no matches found
return search(index + 1)
}
}
var node = search(0, this.trie)
if (!node) return undefined
node = Object.assign({}, node)
node.params = params
return node
}
// mount a trie onto a node at route
// (str, obj) -> null
Trie.prototype.mount = function (route, trie) {
assert.equal(typeof route, 'string', 'route should be a string')
assert.equal(typeof trie, 'object', 'trie should be a object')
var split = route.replace(/^\//, '').split('/')
var node = null
var key = null
if (split.length === 1) {
key = split[0]
node = this.create(key)
} else {
var head = split.join('/')
key = split[0]
node = this.create(head)
}
Object.assign(node.nodes, trie.nodes)
if (trie.name) node.name = trie.name
// delegate properties from '/' to the new node
// '/' cannot be reached once mounted
if (node.nodes['']) {
Object.keys(node.nodes['']).forEach(function (key) {
if (key === 'nodes') return
node[key] = node.nodes[''][key]
})
Object.assign(node.nodes, node.nodes[''].nodes)
delete node.nodes[''].nodes
}
}
function has (object, property) {
return Object.prototype.hasOwnProperty.call(object, property)
}
},{"assert":127}],227:[function(require,module,exports){
'use strict';
var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
, length = 64
, map = {}
, seed = 0
, i = 0
, prev;
/**
* Return a string representing the specified number.
*
* @param {Number} num The number to convert.
* @returns {String} The string representation of the number.
* @api public
*/
function encode(num) {
var encoded = '';
do {
encoded = alphabet[num % length] + encoded;
num = Math.floor(num / length);
} while (num > 0);
return encoded;
}
/**
* Return the integer value specified by the given string.
*
* @param {String} str The string to convert.
* @returns {Number} The integer value represented by the string.
* @api public
*/
function decode(str) {
var decoded = 0;
for (i = 0; i < str.length; i++) {
decoded = decoded * length + map[str.charAt(i)];
}
return decoded;
}
/**
* Yeast: A tiny growing id generator.
*
* @returns {String} A unique id.
* @api public
*/
function yeast() {
var now = encode(+new Date());
if (now !== prev) return seed = 0, prev = now;
return now +'.'+ encode(seed++);
}
//
// Map each character to its index.
//
for (; i < length; i++) map[alphabet[i]] = i;
//
// Expose the `yeast`, `encode` and `decode` functions.
//
yeast.encode = encode;
yeast.decode = decode;
module.exports = yeast;
},{}],228:[function(require,module,exports){
//'use babel'
// const p5lib = require('p5')
class P5 extends p5{
constructor ({
width = window.innerWidth,
height = window.innerHeight,
mode = 'P2D'
} = {}) {
//console.log('createing canvas', width, height, window.innerWidth, window.innerHeight)
super(( p ) => {
p.setup = () => { p.createCanvas(width, height, p[mode]) }
// p.setup = () => { p.createCanvas() }
p.draw = () => { }
}, 'hydra-ui')
this.width = width
this.height = height
this.mode = mode
this.canvas.style.position = "absolute"
this.canvas.style.top = "0px"
this.canvas.style.left = "0px"
this.canvas.style.zIndex = -1
// console.log('p5', this)
// return this.p5
}
show() {
this.canvas.style.visibility = "visible"
}
hide() {
this.canvas.style.visibility = "hidden"
}
// p5 clear function not covering canvas
clear() {
this.drawingContext.clearRect(0, 0, this.canvas.width, this.canvas.height)
}
}
module.exports = P5
},{}],229:[function(require,module,exports){
/* globals sessionStorage */
// Extends rtc-patch-bay to include support for nicknames and persistent session storage
var PatchBay = require('./rtc-patch-bay.js')
//var PatchBay = require('./../../../../rtc-patch-bay')
var inherits = require('inherits')
var PBLive = function () {
this.session = {}
// lookup tables for converting id to nickname
this.nickFromId = {}
this.idFromNick = {}
this.loadFromStorage()
}
// inherits from PatchBay module
inherits(PBLive, PatchBay)
PBLive.prototype.init = function (stream, opts) {
this.settings = {
server: opts.server || 'https://patch-bay.glitch.me/',
room: opts.room || 'patch-bay',
stream: stream
}
// console.log('initializing patch-bay', stream, opts)
this.makeGlobal = opts.makeGlobal || true
this.setPageTitle = opts.setTitle || true
if (this.session.id) this.settings.id = this.session.id
PatchBay.call(this, this.settings)
if (this.makeGlobal) window.pb = this
this.on('ready', () => {
if (!this.nick) {
if (this.session.nick) {
this.setName(this.session.nick)
} else {
this.session.id = this.id
this.setName(this.session.id)
}
}
// console.log('connected to server ' + this.settings.server + ' with name ' + this.settings.id)
})
// received a broadcast
this.on('broadcast', this._processBroadcast.bind(this))
this.on('new peer', this.handleNewPeer.bind(this))
window.onbeforeunload = () => {
this.session.id = window.pb.id
this.session.nick = this.nick
sessionStorage.setItem('pb', JSON.stringify(this.session))
}
var self = this
this.on('stream', function (id, stream) {
console.log('got stream!', id, stream)
const video = document.createElement('video')
if ('srcObject' in video) {
video.srcObject = stream
} else {
// Avoid using this in new browsers, as it is going away.
video.src = window.URL.createObjectURL(stream)
}
// video.src = window.URL.createObjectURL(stream)
video.addEventListener('loadedmetadata', () => {
// console.log("loaded meta22")
video.play()
self.video = video
self.emit('got video', self.nickFromId[id], video)
})
})
}
PBLive.prototype.loadFromStorage = function () {
if (sessionStorage.getItem('pb') !== null) {
this.session = JSON.parse(sessionStorage.getItem('pb'))
}
}
PBLive.prototype.initSource = function (nick, callback) {
this.initConnectionFromId(this.idFromNick[nick], callback)
// this.peers[this.idFromNick[nick]].streamCallback = callback
}
// default nickname is just peer id.
// to do: save nickname information between sessions
PBLive.prototype.handleNewPeer = function (peer) {
// console.log("new peer", peer)
this.nickFromId[peer] = peer
this.idFromNick[peer] = peer
// console.log("THIS IS THE PEER", peer)
// to do: only send to new peer, not to all
if (this.nick) {
this.broadcast({
type: 'update-nick',
id: this.id,
nick: this.nick
})
}
}
PBLive.prototype.list = function () {
var l = Object.keys(this.idFromNick)
console.log(l)
return Object.keys(this.idFromNick)
}
// choose an identifying name
PBLive.prototype.setName = function (nick) {
this.broadcast({
type: 'update-nick',
id: this.id,
nick: nick,
previous: this.nick
})
this.nick = nick
if (this.setPageTitle) document.title = nick
}
PBLive.prototype._processBroadcast = function (data) {
if (data.type === 'update-nick') {
if (data.previous !== data.nick) {
delete this.idFromNick[this.nickFromId[data.id]]
this.nickFromId[data.id] = data.nick
this.idFromNick[data.nick] = data.id
if (data.previous) {
//console.log(data.previous + ' changed to ' + data.nick)
} else {
//console.log('connected to ' + data.nick)
}
}
}
}
// PBExtended.prototype.
module.exports = PBLive
},{"./rtc-patch-bay.js":230,"inherits":102}],230:[function(require,module,exports){
// Module for handling connections to multiple peers.
var io = require('socket.io-client')
var SimplePeer = require('simple-peer')
var extend = Object.assign
var events = require('events').EventEmitter
var inherits = require('inherits')
const shortid = require('shortid')
var PatchBay = function (options) {
// connect to websocket signalling server. To DO: error validation
this.signaller = io(options.server)
//assign unique id to this peer, or use id passed in
this.id = options.id || shortid.generate()
this.stream = options.stream || null
//options to be sent to simple peer
this._peerOptions = options.peerOptions || {}
this._room = options.room
this.settings['shareMediaWhenRequested'] = true
this.settings['shareMediaWhenInitiating'] = false
this.settings['requestMediaWhenInitiating'] = true
this.settings['autoconnect'] = false
//object containing ALL peers in room
this.peers = {}
//object containing peers connected via webrtc
this.rtcPeers = {}
// Handle events from signalling server
this.signaller.on('ready', this._readyForSignalling.bind(this))
// this.signaller.on('peers', )
// this.signaller.on('signal', this._handleSignal.bind(this))
this.signaller.on('message', this._handleMessage.bind(this))
// Received message via websockets to all peers in room
this.signaller.on('broadcast', this._receivedBroadcast.bind(this))
// emit 'join' event to signalling server
this.signaller.emit('join', this._room, {uuid: this.id})
// console.log('emitting join')
this.signaller.on('new peer', this._newPeer.bind(this))
}
// inherits from events module in order to trigger events
inherits(PatchBay, events)
// send data to all connected peers via data channels
PatchBay.prototype.sendToAll = function (data) {
Object.keys(this.rtcPeers).forEach(function (id) {
this.rtcPeers[id].send(data)
}, this)
}
// sends to peer specified b
PatchBay.prototype.sendToPeer = function (peerId, data) {
if (peerId in this.rtcPeers) {
this.rtcPeers[peerId].send(data)
}
}
PatchBay.prototype.reinitAll = function(){
Object.keys(this.rtcPeers).forEach(function (id) {
this.reinitPeer(id)
}.bind(this))
// this._connectToPeers.bind(this)
}
PatchBay.prototype.initRtcPeer = function(id, opts) {
this.emit('new peer', {id: id})
var newOptions = opts
// console.log()
if(this.iceServers) {
opts['config'] = {
iceServers: this.iceServers
}
}
if(opts.initiator === true) {
if (this.stream != null) {
if(this.settings.shareMediaWhenInitiating === true){
newOptions.stream = this.stream
}
}
if(this.settings.requestMediaWhenInitiating === true){
newOptions.offerConstraints = {
offerToReceiveVideo: true,
offerToReceiveAudio: true
}
}
} else {
if(this.settings.shareMediaWhenRequested === true){
if (this.stream != null) {
newOptions.stream = this.stream
}
}
}
var options = extend(this._peerOptions, newOptions)
//console.log("OPTIONS", options)
this.rtcPeers[id] = new SimplePeer(options)
this._attachPeerEvents(this.rtcPeers[id], id)
}
PatchBay.prototype.reinitRtcConnection = function(id, opts){
// Because renegotiation is not implemeneted in SimplePeer, reinitiate connection when configuration has changed
this.rtcPeers[id]._destroy(null, function(e){
this.initRtcPeer(id, {
stream: this.stream,
initiator: true
})
}.bind(this))
}
// //new peer connected to signalling server
PatchBay.prototype._newPeer = function (peer){
// this.connectedIds.push(peer)
// Configuration for specified peer.
// Individual configuration controls whether will receive media from
// and/or send media to a specific peer.
this.peers[peer] = {
rtcPeer: null
}
this.emit('new peer', peer)
// this.emit('updated peer list', this.connectedIds)
}
// // Once the new peer receives a list of connected peers from the server,
// // creates new simple peer object for each connected peer.
PatchBay.prototype._readyForSignalling = function ({ peers, servers }) {
//console.log("received peer list", _t, this.peers)
peers.forEach((peer) => {
this._newPeer(peer)
})
// if received ice and turn server information from signalling server, use in establishing
if(servers) {
this.iceServers = servers
}
// this.peers = peers
this.emit('ready')
}
// Init connection to RECEIVE video
PatchBay.prototype.initConnectionFromId = function(id, callback){
// console.log("initianing connection")
if(id in this.rtcPeers){
console.log("Already connected to..", id, this.rtcPeers)
//if this peer was originally only sending a stream (not receiving), recreate connecting but this time two-way
if(this.rtcPeers[id].initiator===false){
this.reinitRtcConnection(id)
} else {
//already connected, do nothing
}
} else {
this.initRtcPeer(id, {
initiator: true
})
}
}
// receive signal from signalling server, forward to simple-peer
PatchBay.prototype._handleMessage = function (data) {
// if there is currently no peer object for a peer id, that peer is initiating a new connection.
if (data.type === 'signal'){
this._handleSignal(data)
} else {
this.emit('message', data)
}
}
// receive signal from signalling server, forward to simple-peer
PatchBay.prototype._handleSignal = function (data) {
// if there is currently no peer object for a peer id, that peer is initiating a new connection.
if (!this.rtcPeers[data.id]) {
// this.emit('new peer', data)
// var options = extend({stream: this.stream}, this._peerOptions)
// this.rtcPeers[data.id] = new SimplePeer(options)
// this._attachPeerEvents(this.rtcPeers[data.id], data.id)
this.initRtcPeer(data.id, {initiator: false})
}
this.rtcPeers[data.id].signal(data.message)
}
// sendToAll send through rtc connections, whereas broadcast
// send through the signalling server. Useful in cases where
// not all peers are connected via webrtc with other peers
PatchBay.prototype._receivedBroadcast = function(data) {
//console.log("RECEIVED BROADCAST", data)
this.emit('broadcast', data)
}
//sends via signalling server
PatchBay.prototype.broadcast = function (data) {
this.signaller.emit('broadcast', data)
}
// handle events for each connected peer
PatchBay.prototype._attachPeerEvents = function (p, _id) {
p.on('signal', function (id, signal) {
// console.log('signal', id, signal)
// console.log("peer signal sending over sockets", id, signal)
// this.signaller.emit('signal', {id: id, signal: signal})
this.signaller.emit('message', {id: id, message: signal, type: 'signal'})
}.bind(this, _id))
p.on('stream', function (id, stream) {
this.rtcPeers[id].stream = stream
// console.log('E: stream', id, stream)
// console.log("received a stream", stream)
this.emit('stream', id, stream)
}.bind(this, _id))
p.on('connect', function (id) {
// console.log("connected to ", id)
this.emit('connect', id)
}.bind(this, _id))
p.on('data', function (id, data) {
// console.log('data', id)
this.emit('data', {id: id, data: JSON.parse(data)})
}.bind(this, _id))
p.on('close', function (id) {
//console.log('CLOSED')
delete (this.rtcPeers[id])
this.emit('close', id)
}.bind(this, _id))
p.on('error', function(e){
console.warn("simple peer error", e)
})
}
PatchBay.prototype._destroy = function () {
Object.values(this.rtcPeers).forEach( function (peer) {
peer.destroy()
})
this.signaller.close()
}
module.exports = PatchBay
},{"events":81,"inherits":102,"shortid":171,"simple-peer":181,"socket.io-client":200}],231:[function(require,module,exports){
module.exports=[
{
"sketch_id": "example_0",
"code": "JTJGJTJGRmxvciUyMGRlJTIwRnVlZ28lMEElMEFzaGFwZSgyMDAlMkMwLjUlMkMxLjUpJTBBLnNjYWxlKDAuNSUyQzAuNSklMEEuY29sb3IoJTVCMC41JTJDMiU1RC5zbW9vdGgoMSklMkMwLjMlMkMwKSUwQS5yZXBlYXQoMiUyQzIpJTBBLm1vZHVsYXRlU2NhbGUob3NjKDMlMkMwLjUpJTJDLTAuNiklMEEuYWRkKG8wJTJDMC41KSUwQS5zY2FsZSgwLjkpJTBBLm91dCgp"
},{
"sketch_id": "example_3",
"code":"JTJGJTJGJTIwYnklMjBPbGl2aWElMjBKYWNrJTBBJTBBb3NjKDIwJTJDJTIwMC4wMyUyQyUyMDEuNykua2FsZWlkKCkubXVsdChvc2MoMjAlMkMlMjAwLjAwMSUyQyUyMDApLnJvdGF0ZSgxLjU4KSkuYmxlbmQobzAlMkMlMjAwLjk0KS5tb2R1bGF0ZVNjYWxlKG9zYygxMCUyQyUyMDApJTJDLTAuMDMpLnNjYWxlKDAuOCUyQyUyMCgpJTIwJTNEJTNFJTIwKDEuMDUlMjAlMkIlMjAwLjElMjAqJTIwTWF0aC5zaW4oMC4wNSp0aW1lKSkpLm91dChvMCk="
},{
"sketch_id": "example_4",
"code":"JTJGJTJGJTIwYnklMjBOZWxzb24lMjBWZXJhJTBBJTJGJTJGJTIwdHdpdHRlciUzQSUyMCU0MG5lbF9zb25vbG9naWElMEElMEFvc2MoOCUyQy0wLjUlMkMlMjAxKS5jb2xvcigtMS41JTJDJTIwLTEuNSUyQyUyMC0xLjUpLmJsZW5kKG8wKS5yb3RhdGUoLTAuNSUyQyUyMC0wLjUpLm1vZHVsYXRlKHNoYXBlKDQpLnJvdGF0ZSgwLjUlMkMlMjAwLjUpLnNjYWxlKDIpLnJlcGVhdFgoMiUyQyUyMDIpLm1vZHVsYXRlKG8wJTJDJTIwKCklMjAlM0QlM0UlMjBtb3VzZS54JTIwKiUyMDAuMDAwNSkucmVwZWF0WSgyJTJDJTIwMikpLm91dChvMCklMEElMEElMEElMEElMEElMEE="
},{
"sketch_id": "example_6",
"code":"JTJGJTJGJTIwYnklMjBEJUMzJUE5Ym9yYSUyMEZhbGxlaXJvcyUyMEdvbnphbGVzJTBBJTJGJTJGJTIwaHR0cHMlM0ElMkYlMkZ3d3cuZ29uemFsZXNkZWJvcmEuY29tJTJGJTBBJTBBb3NjKDUpLmFkZChub2lzZSg1JTJDJTIwMikpLmNvbG9yKDAlMkMlMjAwJTJDJTIwMykuY29sb3JhbWEoMC40KS5vdXQoKSUwQSUwQSUwQSUwQQ=="
},{
"sketch_id": "example_8",
"code":"JTJGJTJGJTIwYnklMjBSb2RyaWdvJTIwVmVsYXNjbyUwQSUyRiUyRiUyMGh0dHBzJTNBJTJGJTJGeWVjdG8uZ2l0aHViLmlvJTJGJTBBJTBBb3NjKDEwNyUyQyUyMDAlMkMlMjAwLjcpLmNvbG9yKDElMkMlMjAwJTJDJTIwMSkucm90YXRlKDAlMkMlMjAtMC4wOCkubW9kdWxhdGVSb3RhdGUobzElMkMlMjAwLjQpLm91dChvMCklMEFvc2MoMzMpLnJvdGF0ZSgyJTJDJTIwMC44KS5tb2R1bGF0ZVJvdGF0ZShvMCUyQyUyMCgpJTIwJTNEJTNFJTIwKGEuZmZ0JTVCMCU1RCoyKSkub3V0KG8xKSUwQQ=="
},{
"sketch_id": "example_9",
"code":"JTJGJTJGJTIwYnklMjBSb2RyaWdvJTIwVmVsYXNjbyUwQSUyRiUyRiUyMGh0dHBzJTNBJTJGJTJGeWVjdG8uZ2l0aHViLmlvJTJGJTBBJTBBb3NjKDE4JTJDJTIwMC4xJTJDJTIwMCkuY29sb3IoMiUyQyUyMDAuMSUyQyUyMDIpJTBBLm11bHQob3NjKDIwJTJDJTIwMC4wMSUyQyUyMDApKS5yZXBlYXQoMiUyQyUyMDIwKS5yb3RhdGUoMC41KS5tb2R1bGF0ZShvMSklMEEuc2NhbGUoMSUyQyUyMCgpJTIwJTNEJTNFJTIwJTIwKGEuZmZ0JTVCMCU1RCowLjklMjAlMkIlMjAyKSkuZGlmZihvMSkub3V0KG8wKSUwQW9zYygyMCUyQyUyMDAuMiUyQyUyMDApLmNvbG9yKDIlMkMlMjAwLjclMkMlMjAwLjEpLm11bHQob3NjKDQwKSkubW9kdWxhdGVSb3RhdGUobzAlMkMlMjAwLjIpJTBBLnJvdGF0ZSgwLjIpLm91dChvMSk="
},{
"sketch_id": "example_10",
"code":"JTJGJTJGJTIwYnklMjBaYWNoJTIwS3JhbGwlMEElMkYlMkYlMjBodHRwJTNBJTJGJTJGemFjaGtyYWxsLm9ubGluZSUyRiUwQSUwQW9zYyglMjAyMTUlMkMlMjAwLjElMkMlMjAyJTIwKSUwQS5tb2R1bGF0ZSglMEElMjAlMjBvc2MoJTIwMiUyQyUyMC0wLjMlMkMlMjAxMDAlMjApJTBBJTIwJTIwLnJvdGF0ZSgxNSklMEEpJTBBLm11bHQoJTBBJTIwJTIwb3NjKCUyMDIxNSUyQyUyMC0wLjElMkMlMjAyKSUwQSUyMCUyMC5waXhlbGF0ZSglMjA1MCUyQyUyMDUwJTIwKSUwQSklMEEuY29sb3IoJTIwMC45JTJDJTIwMC4wJTJDJTIwMC45JTIwKSUwQS5tb2R1bGF0ZSglMEElMjAlMjBvc2MoJTIwNiUyQyUyMC0wLjElMjApJTBBJTIwJTIwLnJvdGF0ZSglMjA5JTIwKSUwQSklMEEuYWRkKCUwQSUyMCUyMG9zYyglMjAxMCUyQyUyMC0wLjklMkMlMjA5MDAlMjApJTBBJTIwJTIwLmNvbG9yKDElMkMwJTJDMSklMEEpJTBBLm11bHQoJTBBJTIwJTIwc2hhcGUoOTAwJTJDJTIwMC4yJTJDJTIwMSklMEElMjAlMjAubHVtYSgpJTBBJTIwJTIwLnJlcGVhdFgoMiklMEElMjAlMjAucmVwZWF0WSgyKSUwQSUyMCUyMC5jb2xvcmFtYSgxMCklMEEpJTBBLm1vZHVsYXRlKCUwQSUyMCUyMG9zYyglMjA5JTJDJTIwLTAuMyUyQyUyMDkwMCUyMCklMEElMjAlMjAucm90YXRlKCUyMDYlMjApJTBBKSUwQS5hZGQoJTBBJTIwJTIwb3NjKDQlMkMlMjAxJTJDJTIwOTApJTBBJTIwJTIwLmNvbG9yKDAuMiUyQzAlMkMxKSUwQSklMEEub3V0KCklMEE="
},{
"sketch_id": "example_11",
"code": "JTJGJTJGJTIwYnklMjBaYWNoJTIwS3JhbGwlMEElMkYlMkYlMjBodHRwJTNBJTJGJTJGemFjaGtyYWxsLm9ubGluZSUyRiUwQSUwQW9zYygxMCUyQyUyMDAuOSUyQyUyMDMwMCklMEEuY29sb3IoMC45JTJDJTIwMC43JTJDJTIwMC44KSUwQS5kaWZmKCUwQSUyMCUyMG9zYyg0NSUyQyUyMDAuMyUyQyUyMDEwMCklMEElMjAlMjAuY29sb3IoMC45JTJDJTIwMC45JTJDJTIwMC45KSUwQSUyMCUyMC5yb3RhdGUoMC4xOCklMEElMjAlMjAucGl4ZWxhdGUoMTIpJTBBJTIwJTIwLmthbGVpZCgpJTBBKSUwQS5zY3JvbGxYKDEwKSUwQS5jb2xvcmFtYSgpJTBBLmx1bWEoKSUwQS5yZXBlYXRYKDQpJTBBLnJlcGVhdFkoNCklMEEubW9kdWxhdGUoJTBBJTIwJTIwb3NjKDElMkMlMjAtMC45JTJDJTIwMzAwKSUwQSklMEEuc2NhbGUoMiklMEEub3V0KCklMEE="
},{
"sketch_id": "example_13",
"code":"JTJGJTJGJTIwYWNpZCUyMGJ1cyUyMHNlYXQlMEElMkYlMkYlMjBieSUyMFdpbGwlMjBIdW1waHJleXMlMEElMkYlMkYlMjBodHRwcyUzQSUyRiUyRmdpdGh1Yi5jb20lMkZUaGVXaXNweSUwQSUwQW9zYygxMDUpLmNvbG9yKDAuNSUyQzAuMSUyQzAuOCkucm90YXRlKDAuMTElMkMlMjAwLjEpLm1vZHVsYXRlKG9zYygxMCkucm90YXRlKDAuMykuYWRkKG8wJTJDJTIwMC4xKSkuYWRkKG9zYygyMCUyQzAuMDElMkMxKS5jb2xvcigwJTJDMC44JTJDMSkpLm91dChvMCklMEFvc2MoNTAlMkMwLjA1JTJDJTIwMC43KS5jb2xvcigxJTJDMC43JTJDMC41KS5kaWZmKG8wKS5tb2R1bGF0ZShvMSUyQzAuMDUpLm91dChvMSklMEFyZW5kZXIobzEp"
},
{
"sketch_id": "example_14",
"code": "JTJGJTJGJTIwYnklMjBPbGl2aWElMjBKYWNrJTBBJTJGJTJGJTIwJTQwX29qYWNrXyUwQSUwQW9zYygyMCUyQyUyMDAuMDElMkMlMjAxLjEpJTBBJTA5LmthbGVpZCg1KSUwQSUwOS5jb2xvcigyLjgzJTJDMC45MSUyQzAuMzkpJTBBJTA5LnJvdGF0ZSgwJTJDJTIwMC4xKSUwQSUwOS5tb2R1bGF0ZShvMCUyQyUyMCgpJTIwJTNEJTNFJTIwbW91c2UueCUyMColMjAwLjAwMDMpJTBBJTA5LnNjYWxlKDEuMDEpJTBBJTIwJTIwJTA5Lm91dChvMCk="
},
{
"sketch_id": "example_15",
"code": "JTJGJTJGJTIwYnklMjBPbGl2aWElMjBKYWNrJTBBJTJGJTJGJTIwaHR0cHMlM0ElMkYlMkZvamFjay5naXRodWIuaW8lMEElMEFvc2MoMTAwJTJDJTIwMC4wMSUyQyUyMDEuNCklMEElMDkucm90YXRlKDAlMkMlMjAwLjEpJTBBJTA5Lm11bHQob3NjKDEwJTJDJTIwMC4xKS5tb2R1bGF0ZShvc2MoMTApLnJvdGF0ZSgwJTJDJTIwLTAuMSklMkMlMjAxKSklMEElMDkuY29sb3IoMi44MyUyQzAuOTElMkMwLjM5KSUwQSUyMCUyMC5vdXQobzAp"
},
{
"sketch_id": "example_16",
"code": "JTJGJTJGJTIwYnklMjBPbGl2aWElMjBKYWNrJTBBJTJGJTJGJTIwaHR0cHMlM0ElMkYlMkZvamFjay5naXRodWIuaW8lMEElMEFvc2MoNCUyQyUyMDAuMSUyQyUyMDAuOCkuY29sb3IoMS4wNCUyQzAlMkMlMjAtMS4xKS5yb3RhdGUoMC4zMCUyQyUyMDAuMSkucGl4ZWxhdGUoMiUyQyUyMDIwKS5tb2R1bGF0ZShub2lzZSgyLjUpJTJDJTIwKCklMjAlM0QlM0UlMjAxLjUlMjAqJTIwTWF0aC5zaW4oMC4wOCUyMColMjB0aW1lKSkub3V0KG8wKQ=="
},
{
"sketch_id": "example_17",
"code": "JTJGJTJGJTIwbW9pcmUlMEElMkYlMkYlMjBieSUyME9saXZpYSUyMEphY2slMEElMkYlMkYlMjB0d2l0dGVyJTNBJTIwJTQwX29qYWNrXyUwQSUwQXBhdHRlcm4lMjAlM0QlMjAoKSUyMCUzRCUzRSUyMG9zYygyMDAlMkMlMjAwKS5rYWxlaWQoMjAwKS5zY2FsZSgxJTJDJTIwMC40KSUwQSUyRiUyRiUwQXBhdHRlcm4oKSUwQSUyMCUyMC5zY3JvbGxYKDAuMSUyQyUyMDAuMDEpJTBBJTIwJTIwLm11bHQocGF0dGVybigpKSUwQSUyMCUyMC5vdXQoKQ=="
},
{
"sketch_id": "example_18",
"code": "JTJGJTJGJTIwYnklMjBPbGl2aWElMjBKYWNrJTBBJTJGJTJGJTIwaHR0cHMlM0ElMkYlMkZvamFjay5naXRodWIuaW8lMEElMEFvc2MoNiUyQyUyMDAlMkMlMjAwLjgpJTBBJTIwJTIwLmNvbG9yKDEuMTQlMkMlMjAwLjYlMkMuODApJTBBJTIwJTIwLnJvdGF0ZSgwLjkyJTJDJTIwMC4zKSUwQSUyMCUyMC5waXhlbGF0ZSgyMCUyQyUyMDEwKSUwQSUyMCUyMC5tdWx0KG9zYyg0MCUyQyUyMDAuMDMpLnRocmVzaCgwLjQpLnJvdGF0ZSgwJTJDJTIwLTAuMDIpKSUwQSUyMCUyMC5tb2R1bGF0ZVJvdGF0ZShvc2MoMjAlMkMlMjAwKS50aHJlc2goMC4zJTJDJTIwMC42KSUyQyUyMCgpJTIwJTNEJTNFJTIwMC4xJTIwJTJCJTIwbW91c2UueCUyMColMjAwLjAwMiklMEElMjAlMjAub3V0KG8wKQ=="
},
{
"sketch_id": "rangga_0",
"code": "JTJGJTJGJTIwRHJlYW15JTIwRGlhbW9uZCUwQSUyRiUyRiUyMGJ5JTIwUmFuZ2dhJTIwUHVybmFtYSUyMEFqaSUwQSUyRiUyRiUyMGh0dHBzJTNBJTJGJTJGcmFuZ2dhcHVybmFtYWFqaTEud2l4c2l0ZS5jb20lMkZwb3J0Zm9saW8lMEElMEFvc2MoNyUyQy0wLjEyNSkubW9kdWxhdGUodm9yb25vaSgxKSkuZGlmZih2b3Jvbm9pKDEpLm11bHQoZ3JhZGllbnQoLTEpLmx1bWEoMC4xMjUpKSklMEElMjAlMjAubHVtYSgwLjEyNSklMEElMjAlMjAuYWRkKHNoYXBlKDclMkMlMjAwLjUpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwLm11bHQodm9yb25vaSgxMCUyQzIpLmJsZW5kKG8wKS5kaWZmKGdyYWRpZW50KDEpKS5tb2R1bGF0ZSh2b3Jvbm9pKCkpKSklMEElMjAlMjAuc2Nyb2xsWSgtMC4xKSUwQSUyMCUyMC5zY3JvbGxYKDAuMTI1KSUwQSUyMCUyMC5ibGVuZChvMCklMEElMjAlMjAuYmxlbmQobzApJTBBJTIwJTIwLm91dCgpJTBB"
},
{
"sketch_id": "rangga_1",
"code": "JTJGJTJGJTIwVGFnJTIwJTI2JTIwU3dlZXAlMEElMkYlMkYlMjBieSUyMFJhbmdnYSUyMFB1cm5hbWElMjBBamklMEElMkYlMkYlMjBodHRwcyUzQSUyRiUyRnJhbmdnYXB1cm5hbWFhamkxLndpeHNpdGUuY29tJTJGcG9ydGZvbGlvJTBBJTBBb3NjKDUlMkMwLjEyNSkuY29sb3JhbWEoMSklMEElMjAlMjAubHVtYSgwLjEyNSkuYWRkKHNoYXBlKDElMkMwLjUpLmx1bWEoMikuZGlmZihncmFkaWVudCgxKSkpJTBBJTIwJTIwLmRpZmYob3NjKC0xJTJDLTAuMjUpKS5ibGVuZChvMCkuY29sb3IoMCUyQzIuNSUyQzEuNzUpJTBBJTIwJTIwLm91dCgp"
},
{
"sketch_id": "rangga_2",
"code": "JTJGJTJGJTIwTW9ub2Nocm9tZSUyME1lbW9hciUwQSUyRiUyRiUyMGJ5JTIwUmFuZ2dhJTIwUHVybmFtYSUyMEFqaSUwQSUyRiUyRiUyMGh0dHBzJTNBJTJGJTJGcmFuZ2dhcHVybmFtYWFqaTEud2l4c2l0ZS5jb20lMkZwb3J0Zm9saW8lMEElMEF2b3Jvbm9pKDUwJTJDMSklMEElMjAlMjAubHVtYSgwLjUpLmFkZChzaGFwZSgxJTJDMSkubHVtYSgxKSklMEElMjAlMjAubW9kdWxhdGUob3NjKC0xMDAwJTJDLTEpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwLm1vZHVsYXRlKG9zYygpLmx1bWEoKSkpJTBBJTIwJTIwLmJsZW5kKG8wKSUwQSUyMCUyMC5ibGVuZChvMCklMEElMjAlMjAuYmxlbmQobzApJTBBJTIwJTIwLmJsZW5kKG8wKSUwQSUyMCUyMC5vdXQoKQ=="
},
{
"sketch_id": "rangga_3",
"code": "JTJGJTJGJTIwR2FsYXh5JTIwVHJpcCUwQSUyRiUyRiUyMGJ5JTIwUmFuZ2dhJTIwUHVybmFtYSUyMEFqaSUwQSUyRiUyRiUyMGh0dHBzJTNBJTJGJTJGcmFuZ2dhcHVybmFtYWFqaTEud2l4c2l0ZS5jb20lMkZwb3J0Zm9saW8lMEElMEFzaGFwZSgxJTJDMSklMEElMjAlMjAubXVsdCh2b3Jvbm9pKDEwMDAlMkMyKSUwQSUyMCUyMC5ibGVuZChvMCkubHVtYSgpKSUwQSUyMCUyMC5hZGQoc2hhcGUoMyUyQzAuMTI1KSUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMC5yb3RhdGUoMSUyQzEpLm11bHQodm9yb25vaSgxMDAwJTJDMSkubHVtYSgpKSUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMC5yb3RhdGUoMS41KSkuc2Nyb2xsWCglNUIwLjElMkMtMC4wNjI1JTJDMC4wMDUlMkMwLjAwMDAxJTVEJTJDMCklMEElMjAlMjAuc2Nyb2xsWSglNUIwLjElMkMtMC4wNjI1JTJDMC4wMDUlMkMwLjAwMDAxJTVEJTJDMCklMEElMjAlMjAub3V0KCk="
},
{
"sketch_id": "rangga_4",
"code": "JTJGJTJGJTIwU3VtZXQlMEElMkYlMkYlMjBieSUyMFJhbmdnYSUyMFB1cm5hbWElMjBBamklMEElMkYlMkYlMjBodHRwcyUzQSUyRiUyRnJhbmdnYXB1cm5hbWFhamkxLndpeHNpdGUuY29tJTJGcG9ydGZvbGlvJTBBJTBBb3NjKDAuNSUyQzEuMjUpLm11bHQoc2hhcGUoMSUyQzAuMDkpLnJvdGF0ZSgxLjUpKSUwQSUyMCUyMC5kaWZmKGdyYWRpZW50KCkpJTBBJTIwJTIwLmFkZChzaGFwZSgyJTJDMikuYmxlbmQoZ3JhZGllbnQoMSkpKSUwQSUyMCUyMC5tb2R1bGF0ZShub2lzZSgpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwLm1vZHVsYXRlKG5vaXNlKCkuc2Nyb2xsWSgxJTJDMC4wNjI1KSkpJTBBJTIwJTIwLmJsZW5kKG8wKSUwQSUyMCUyMC5jb2xvcigxJTJDLTAuNSUyQy0wLjc1KSUwQSUyMCUyMC5vdXQoKQ=="
},
{
"sketch_id": "marianne_0",
"code": "JTJGJTJGcG9ydCUwQSUyRiUyRmJ5JTIwTWFyaWFubmUlMjBUZWl4aWRvJTBBJTJGJTJGaHR0cHMlM0ElMkYlMkZtYXJpYW5uZXRlaXhpZG8uZ2l0aHViLmlvJTJGJTBBJTBBb3NjKDUlMkMlMjAwLjklMkMlMjAwLjAwMSklMEElMjAlMjAlMjAlMjAua2FsZWlkKCU1QjMlMkM0JTJDNSUyQzclMkM4JTJDOSUyQzEwJTVELmZhc3QoMC4xKSklMEElMjAlMjAlMjAlMjAuY29sb3IoMC41JTJDJTIwMC4zKSUwQSUyMCUyMCUyMCUyMC5jb2xvcmFtYSgwLjQpJTBBJTIwJTIwJTIwJTIwLnJvdGF0ZSgwLjAwOSUyQygpJTNEJTNFTWF0aC5zaW4odGltZSkqJTIwLTAuMDAxJTIwKSUwQSUyMCUyMCUyMCUyMC5tb2R1bGF0ZVJvdGF0ZShvMCUyQygpJTNEJTNFTWF0aC5zaW4odGltZSklMjAqJTIwMC4wMDMpJTBBJTIwJTIwJTIwJTIwLm1vZHVsYXRlKG8wJTJDJTIwMC45KSUwQSUyMCUyMCUyMCUyMC5zY2FsZSgwLjkpJTBBJTIwJTIwJTIwJTIwLm91dChvMCklMEElMEE="
},
{
"sketch_id": "marianne_1",
"code": "JTJGJTJGUGl4ZWxzY2FwZSUwQSUyRiUyRk1hcmlhbm5lJTIwVGVpeGlkbyUwQSUyRiUyRmh0dHBzJTNBJTJGJTJGZ2l0aHViLmNvbSUyRk1hcmlhbm5lVGVpeGlkbyUwQSUwQXNyYyhvMCklMEElMjAuc2F0dXJhdGUoMS4wMSklMEElMjAuc2NhbGUoLjk5OSklMEElMjAuY29sb3IoMS4wMSUyQzEuMDElMkMxLjAxKSUwQSUyMC5odWUoLjAxKSUwQSUyMC5tb2R1bGF0ZUh1ZShzcmMobzEpLmh1ZSguMykucG9zdGVyaXplKC0xKS5jb250cmFzdCguNyklMkMyKSUwQSUyMCUyMC5sYXllcihzcmMobzEpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwLmx1bWEoKSUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMC5tdWx0KGdyYWRpZW50KDEpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwLnNhdHVyYXRlKC45KSkpJTBBJTIwJTIwLm91dChvMCklMEElMEFub2lzZSgxJTJDJTIwLjIpJTBBJTIwJTIwLnJvdGF0ZSgyJTJDLjUpJTBBJTIwJTIwLmxheWVyKHNyYyhvMCklMEElMjAlMjAuc2Nyb2xsWCguMikpJTBBJTIwJTIwLm91dChvMSklMEElMEFyZW5kZXIobzAp"
},
{
"sketch_id": "naoto_0",
"code": "JTJGJTJGJTIwJTQwbmFvdG9faGllZGElMEFvc2MoMjAlMkMlMjAwLjElMkMlMjAwKS5jb2xvcigwJTJDJTIwMSUyQyUyMDIpLnJvdGF0ZSgxLjU3JTJGMikub3V0KG8xKSUwQW9zYygzMCUyQyUyMDAuMDElMkMlMjAwKS5jb2xvcigyJTJDJTIwMC43JTJDJTIwMSkubW9kdWxhdGUobzElMkMlMjAwKS5hZGQobzElMkMxKS5tb2R1bGF0ZVBpeGVsYXRlKG8xJTJDMSUyQzEwKS5vdXQobzAp"
},
{
"sketch_id": "naoto_1",
"code": "JTJGJTJGJTIwJTQwbmFvdG9faGllZGElMEFzb2xpZCgwLjIlMkMwLjYlMkMwLjkpLmxheWVyKG9zYygzMS40JTJDMCkudGhyZXNoKDAuNykubHVtYSgpLm1vZHVsYXRlKG9zYyg0JTJDMSkucm90YXRlKDEpJTJDMC4wNSkuY29sb3IoMCUyQzAlMkMwKSkubGF5ZXIob3NjKDMxLjQlMkMwKS50aHJlc2goMC43KS5sdW1hKCkubW9kdWxhdGUob3NjKDQlMkMxKS5yb3RhdGUoMSklMkMwLjEpKS5vdXQoKQ=="
},
{
"sketch_id": "ritchse_0",
"code": "JTJGJTJGcmFuZG9tJTIwdHJ5cG9waG9iaWElMjAtJTIwY2hhbmdlcyUyMGV2ZXJ5dGltZSUyMHlvdSUyMGxvYWQlMjBpdCElMEElMkYlMkZieSUyMFJpdGNoc2UlMEElMkYlMkZpbnN0YWdyYW0uY29tJTJGcml0Y2hzZSUwQSUyMCUwQWZ1bmN0aW9uJTIwcihtaW4lM0QwJTJDbWF4JTNEMSklMjAlN0IlMjByZXR1cm4lMjBNYXRoLnJhbmRvbSgpKihtYXgtbWluKSUyQm1pbiUzQiUyMCU3RCUwQSUyMCUwQXNvbGlkKDElMkMxJTJDMSklMEElMjAlMjAlMDkuZGlmZihzaGFwZSglNUI0JTJDNCUyQzQlMkMyNCU1RC5zbW9vdGgoKS5mYXN0KC41KSUyQ3IoMC42JTJDMC45MyklMkMuMDkpLnJlcGVhdCgyMCUyQzEwKSklMEElMDkubW9kdWxhdGVTY2FsZShvc2MoOCkucm90YXRlKHIoLS41JTJDLjUpKSUyQy41MiklMEElMDkuYWRkKCUwQSUyMCUyMCUwOSUwOXNyYyhvMCkuc2NhbGUoMC45NjUpLnJvdGF0ZSguMDEyKihNYXRoLnJvdW5kKHIoLTIlMkMxKSkpKSUwQSUyMCUyMCUwOSUwOS5jb2xvcihyKCklMkNyKCklMkNyKCkpJTBBJTIwJTIwJTIwJTIwJTA5Lm1vZHVsYXRlUm90YXRlKG8wJTJDcigwJTJDMC41KSklMEElMjAlMjAlMDklMDkuYnJpZ2h0bmVzcyguMTUpJTBBJTIwJTIwJTA5JTA5JTJDLjcpJTBBJTA5Lm91dCgp"
},
{
"sketch_id": "ritchse_1",
"code": "JTJGJTJGY29ycnVwdGVkJTIwc2NyZWVuc2F2ZXIlMEElMkYlMkZieSUyMFJpdGNoc2UlMEElMkYlMkZpbnN0YWdyYW0uY29tJTJGcml0Y2hzZSUwQSUyMCUwQXZvcm9ub2koMzUwJTJDMC4xNSklMEElMjAlMjAlMDkubW9kdWxhdGVTY2FsZShvc2MoOCkucm90YXRlKE1hdGguc2luKHRpbWUpKSUyQy41KSUwQSUyMCUyMCUwOS50aHJlc2goLjgpJTBBJTA5Lm1vZHVsYXRlUm90YXRlKG9zYyg3KSUyQy40KSUwQSUwOS50aHJlc2goLjcpJTBBJTIwJTIwJTA5LmRpZmYoc3JjKG8wKS5zY2FsZSgxLjgpKSUwQSUwOS5tb2R1bGF0ZVNjYWxlKG9zYygyKS5tb2R1bGF0ZVJvdGF0ZShvMCUyQy43NCkpJTBBJTA5LmRpZmYoc3JjKG8wKS5yb3RhdGUoJTVCLS4wMTIlMkMuMDElMkMtLjAwMiUyQzAlNUQpLnNjcm9sbFkoMCUyQyU1Qi0xJTJGMTk5ODAwJTJDMCU1RC5mYXN0KDAuNykpKSUwQSUwOS5icmlnaHRuZXNzKCU1Qi0uMDIlMkMtLjE3JTVELnNtb290aCgpLmZhc3QoLjUpKSUwQSUwOS5vdXQoKQ=="
},
{
"sketch_id": "ritchse_2",
"code": "JTJGJTJGdHJvcGljYWwlMjBqdWljZSUwQSUyRiUyRmJ5JTIwUml0Y2hzZSUwQSUyRiUyRmluc3RhZ3JhbS5jb20lMkZyaXRjaHNlJTBBJTIwJTBBdm9yb25vaSgyJTJDMC4zJTJDMC4yKS5zaGlmdCgwLjUpJTBBLm1vZHVsYXRlUGl4ZWxhdGUodm9yb25vaSg0JTJDMC4yKSUyQzMyJTJDMiklMEEuc2NhbGUoKCklM0QlM0UxJTJCKE1hdGguc2luKHRpbWUqMi41KSowLjA1KSklMEEuZGlmZih2b3Jvbm9pKDMpLnNoaWZ0KDAuNikpJTBBLmRpZmYob3NjKDIlMkMwLjE1JTJDMS4xKS5yb3RhdGUoKSklMEEuYnJpZ2h0bmVzcygwLjEpLmNvbnRyYXN0KDEuMikuc2F0dXJhdGUoMS4yKSUwQSUwOS5vdXQoKSUwQXNwZWVkJTIwJTNEJTIwMC44"
},
{
"sketch_id": "ritchse_3",
"code": "JTJGJTJGdHJ5aW5nJTIwdG8lMjBnZXQlMjBjbG9zZXIlMEElMkYlMkZieSUyMFJpdGNoc2UlMEElMkYlMkZpbnN0YWdyYW0uY29tJTJGcml0Y2hzZSUwQSUyMCUwQW9zYyg2MCUyQy0wLjAxNSUyQzAuMykuZGlmZihvc2MoNjAlMkMwLjA4KS5yb3RhdGUoTWF0aC5QSSUyRjIpKSUwQSUwOS5tb2R1bGF0ZVNjYWxlKG5vaXNlKDMuNSUyQzAuMjUpLm1vZHVsYXRlU2NhbGUob3NjKDE1KS5yb3RhdGUoKCklM0QlM0VNYXRoLnNpbih0aW1lJTJGMikpKSUyQzAuNiklMEElMDkuY29sb3IoMSUyQzAuNSUyQzAuNCkuY29udHJhc3QoMS40KSUwQSUwOS5hZGQoc3JjKG8wKS5tb2R1bGF0ZShvMCUyQy4wNCklMkMuNiklMEElMDkuaW52ZXJ0KCkuYnJpZ2h0bmVzcygwLjEpLmNvbnRyYXN0KDEuMiklMEElMDkubW9kdWxhdGVTY2FsZShvc2MoMiklMkMtMC4yKSUwQSUyMCUyMC5vdXQoKQ=="
},
{
"sketch_id": "ritchse_4",
"code": "JTJGJTJGJTIwZGlzaW50ZWdyYXRpb24lMEElMkYlMkYlMjBieSUyMFJpdGNoc2UlMEElMkYlMkYlMjBpbnN0YWdyYW0uY29tJTJGcml0Y2hzZSUwQSUyMCUwQW9zYyg1JTJDLjEpLm1vZHVsYXRlKG5vaXNlKDYpJTJDLjIyKS5kaWZmKG8wKSUwQSUyMCUyMCUwOS5tb2R1bGF0ZVNjcm9sbFkob3NjKDIpLm1vZHVsYXRlKG9zYygpLnJvdGF0ZSgpJTJDLjExKSklMEElMDkuc2NhbGUoLjcyKS5jb2xvcigwLjk5JTJDMS4wMTQlMkMxKSUwQSUyMCUyMCUwOS5vdXQoKQ== "
},
{
"sketch_id": "flor_0",
"code": "JTJGJTJGRmxvciUyMGRlJTIwRnVlZ28lMEElMkYlMkZodHRwcyUzQSUyRiUyRmZsb3JkZWZ1ZWdvLmdpdGh1Yi5pbyUyRiUwQW9zYygzMCUyQzAuMDElMkMxKSUwQS5tdWx0KG9zYygyMCUyQy0wLjElMkMxKS5tb2R1bGF0ZShub2lzZSgzJTJDMSkpLnJvdGF0ZSgwLjcpKSUwQS5wb3N0ZXJpemUoJTVCMyUyQzEwJTJDMiU1RC5mYXN0KDAuNSkuc21vb3RoKDEpKSUwQS5tb2R1bGF0ZVJvdGF0ZShvMCUyQygpJTNEJTNFbW91c2UueCowLjAwMyklMEEub3V0KCk= "
},
{
"sketch_id": "mahalia_0",
"code": "JTJGJTJGJTIwTWFoYWxpYSUyMEgtUiUwQSUyRiUyRiUyMElHJTNBJTIwJTQwbW1faHJfJTBBJTBBc2hhcGUoMjAlMkMwLjElMkMwLjAxKSUwQSUyMCUyMC5zY2FsZSgoKSUyMCUzRCUzRSUyME1hdGguc2luKHRpbWUpKjMpJTBBJTIwJTIwLnJlcGVhdCgoKSUyMCUzRCUzRSUyME1hdGguc2luKHRpbWUpKjEwKSUwQSUyMCUyMC5tb2R1bGF0ZVJvdGF0ZShvMCklMEElMjAlMjAuc2NhbGUoKCklMjAlM0QlM0UlMjBNYXRoLnNpbih0aW1lKSoyKSUwQSUyMCUyMC5tb2R1bGF0ZShub2lzZSgyJTJDMCkpJTBBJTIwJTIwLnJvdGF0ZSgwLjElMkMlMjAwLjkpJTBBLm91dChvMCklMEElMEFzcmMobzApJTBBLm1vZHVsYXRlKG9zYyg1MDAlMkMwJTJDMCkpJTBBLm91dChvMSklMEElMEFzcmMobzEpJTBBLm1vZHVsYXRlS2FsZWlkKHZvcm9ub2koKCklMjAlM0QlM0UlMjBNYXRoLnNpbih0aW1lKSozJTJDMC4xJTJDMC4wMSklMkMoKSUyMCUzRCUzRSUyME1hdGguc2luKHRpbWUpKjMpJTBBLnNjYWxlKCgpJTIwJTNEJTNFJTIwTWF0aC5zaW4odGltZSkqMyklMEEub3V0KG8yKSUwQSUwQXJlbmRlcihvMik="
},
{
"sketch_id": "mahalia_1",
"code": "JTJGJTJGJTIwTWFoYWxpYSUyMEgtUiUwQSUyRiUyRiUyMElHJTNBJTIwJTQwbW1faHJfJTBBJTBBc2hhcGUoKCklMjAlM0QlM0UlMjBNYXRoLnNpbih0aW1lKSUyQjEqMiklMEEucm90YXRlKCgpJTIwJTNEJTNFJTIwTWF0aC5QSSUyMColMjBtb3VzZS54JTIwJTJGMTgwKSUwQS5yZXBlYXRYKDMpJTBBLnJlcGVhdFkoKCklM0QlM0VNYXRoLnNpbih0aW1lKSo1KSUwQS5zY2FsZSgoKSUyMCUzRCUzRSUyME1hdGguUEklMkY0KSUwQS5ibGVuZChzcmMobzApLmNvbG9yKDElMkMwJTJDMCkpJTBBLm1vZHVsYXRlKG9zYygyMCUyQyUyMDAlMkMuNCkpJTBBLmthbGVpZCgyKSUwQSUyMC5vdXQobzApJTBBJTBBcmVuZGVyKG8wKQ=="
},
{
"sketch_id": "mahalia_2",
"code": "JTJGJTJGJTIwVmVsdmV0JTIwUG9vbCUwQSUyRiUyRiUyMGJ5JTIwTWFoYWxpYSUyMEgtUiUwQSUyRiUyRiUyMElHJTNBJTIwbW1faHJfJTBBJTBBJTBBbm9pc2UoKSUwQS5jb2xvcigoKSUyMCUzRCUzRSUyMGEuZmZ0JTVCMiU1RCoyJTJDMCUyQy42KSUwQS5tb2R1bGF0ZShub2lzZSgoKSUyMCUzRCUzRSUyMGEuZmZ0JTVCMCU1RCoxMCkpJTBBLnNjYWxlKCgpJTNEJTNFJTIwYS5mZnQlNUIyJTVEKjUpJTBBLmxheWVyKCUwQSUyMCUyMHNyYyhvMCklMEElMjAlMjAubWFzayhvc2MoMTApLm1vZHVsYXRlUm90YXRlKG9zYygpJTJDOTAlMkMwKSklMEElMjAlMjAuc2NhbGUoKCklMjAlM0QlM0UlMjBhLmZmdCU1QjAlNUQqMiklMEElMjAlMjAubHVtYSgwLjIlMkMwLjMpJTBBKSUwQS5ibGVuZChvMCklMEEub3V0KG8wKSUwQSUwQW9zYygpJTBBLm1vZHVsYXRlKG5vaXNlKCgpJTIwJTNEJTNFJTIwYS5mZnQlNUIxJTVEJTJCNSkpJTBBLmNvbG9yKDElMkMwJTJDMCklMEEub3V0KG8xKSUwQSUwQXNyYyhvMCklMEEubW9kdWxhdGUobzEpJTBBLmxheWVyKCUwQSUyMCUyMHNyYyhvMSklMEElMjAlMjAubWFzayhvMSklMEElMjAlMjAuc2F0dXJhdGUoNyklMEEpJTBBLm1vZHVsYXRlUm90YXRlKG8xKSUwQS5yb3RhdGUoKCU3QnRpbWUlN0QpJTIwJTNEJTNFJTIwdGltZSUyNTM2MCowLjA1KSUwQS5vdXQobzIpJTBBJTBBcmVuZGVyKG8yKQ=="
},
{
"sketch_id": "mahalia_3",
"code": "JTJGJTJGJTIwYnklMjBNYWhhbGlhJTIwSC1SJTBBJTJGJTJGJTIwSUclM0ElMjBtbV9ocl8lMEElMEFzaGFwZSgoKSUzRCUzRU1hdGguc2luKHRpbWUpJTJCMSozJTJDJTIwLjUlMkMuMDEpJTBBLnJlcGVhdCg1JTJDMyUyQyUyMCgpJTNEJTNFYS5mZnQlNUIwJTVEKjIlMkMlMjAoKSUzRCUzRWEuZmZ0JTVCMSU1RCoyKSUwQS5zY3JvbGxZKC41JTJDMC4xKSUwQS5sYXllciglMEElMjAlMjBzcmMobzEpJTBBJTIwJTIwLm1hc2sobzApJTBBJTIwJTIwLmx1bWEoLjAxJTJDJTIwLjEpJTBBJTIwJTIwLmludmVydCguMiklMEEpJTBBLm1vZHVsYXRlKG8xJTJDLjAyKSUwQS5vdXQobzApJTBBJTBBb3NjKDQwJTJDJTIwMC4wOSUyQyUyMDAuOSklMEEuY29sb3IoLjklMkMwJTJDNSklMEEubW9kdWxhdGUob3NjKDEwKS5yb3RhdGUoMSUyQyUyMDAuNSkpJTBBLnJvdGF0ZSgxJTJDJTIwMC4yKSUwQS5vdXQobzEpJTBBJTBBcmVuZGVyKG8wKSUwQSUwQQ=="
},
{
"sketch_id": "mahalia_4",
"code": "JTJGJTJGJTIwQ2VsbHVsYXIlMjAlMjYlMjBCbG9idWxhciUwQSUyRiUyRiUyMGJ5JTIwTWFoYWxpYSUyMEgtUiUwQSUyRiUyRiUyMElHJTNBJTIwbW1faHJfJTBBJTBBc3BlZWQlMjAlM0QlMjAwLjMlMEElMEFzaGFwZSgyMCUyQzAuMiUyQzAuMyklMEEuY29sb3IoMC41JTJDMC44JTJDNTApJTBBJTIwJTIwLnNjYWxlKCgpJTIwJTNEJTNFJTIwTWF0aC5zaW4odGltZSklMkIxKjIpJTBBJTIwJTIwLnJlcGVhdCgoKSUyMCUzRCUzRSUyME1hdGguc2luKHRpbWUpKjEwKSUwQSUyMCUyMC5tb2R1bGF0ZVJvdGF0ZShvMCklMEElMjAlMjAuc2NhbGUoKCklMjAlM0QlM0UlMjBNYXRoLnNpbih0aW1lKSUyQjElMjAqMS41KSUwQSUyMCUyMC5tb2R1bGF0ZShub2lzZSgyJTJDMikpJTBBJTIwJTIwLnJvdGF0ZSgxJTJDJTIwLjIpJTBBJTIwJTIwJTJGJTJGJTIwLmludmVydCgyLjQpJTBBLm91dChvMCklMEE="
},
{
"sketch_id": "andromeda_0",
"code": "JTJGJTJGJTIwMy4wJTBBJTJGJTJGJTIwYnklMjAlQ0UlOTRORFIwTTNEJUNFJTk0JTBBJTJGJTJGJTIwaHR0cHMlM0ElMkYlMkZ3d3cuaW5zdGFncmFtLmNvbSUyRmFuZHJvbTNfZGElMkYlMEElMEElMEFub2lzZSgzJTJDMC4zJTJDMykudGhyZXNoKDAuMyUyQzAuMDMpLmRpZmYobzMlMkMwLjMpLm91dChvMSklMEFncmFkaWVudCglNUIwLjMlMkMwLjMlMkMzJTVEKS5kaWZmKG8wKS5ibGVuZChvMSkub3V0KG8zKSUwQXZvcm9ub2koMzMlMkMzJTJDMzApLnJvdGF0ZSgzJTJDMC4zJTJDMCkubW9kdWxhdGVTY2FsZShvMiUyQzAuMykuY29sb3IoLTMlMkMzJTJDMCkuYnJpZ2h0bmVzcygzKS5vdXQobzApJTBBc2hhcGUoMzAlMkMwLjMlMkMxKS5pbnZlcnQoKCU3QnRpbWUlN0QpJTNEJTNFTWF0aC5zaW4odGltZSkqMykub3V0KG8yKSUwQSUwQXJlbmRlcihvMyklMEE="
},
{
"sketch_id": "andromeda_1",
"code": "JTJGJTJGJTIwMy4zJTBBJTJGJTJGJTIwYnklMjAlQ0UlOTRORFIwTTNEJUNFJTk0JTBBJTJGJTJGJTIwaHR0cHMlM0ElMkYlMkZ3d3cuaW5zdGFncmFtLmNvbSUyRmFuZHJvbTNfZGElMkYlMEElMEFvc2MoKS5tb2R1bGF0ZVJvdGF0ZShvMCUyQzAuMykub3V0KCklMEFvc2MoMzMlMkMwLjMlMkMwLjMpLmRpZmYobzMlMkMzKS5vdXQobzEpJTBBb3NjKDMlMkMwLjMlMkMzMykubW9kdWxhdGVLYWxlaWQobzMlMkMzKS5kaWZmKG8wKS5vdXQobzIpJTBBc3JjKG8wJTJDMykubXVsdChvMSUyQzMpLmthbGVpZCgzKS5vdXQobzMpJTBBcmVuZGVyKG8yKQ=="
},
{
"sketch_id": "asdrubal_0",
"code": "JTJGJTJGQXNkciVDMyVCQWJhbCUyMEdvbWV6JTBBJTBBbm9pc2UoMyUyQzAuMSUyQzcpJTBBLnJvdGF0ZSgxJTJDLTElMkMtMikubWFzayhzaGFwZSgyMCkpJTBBLmNvbG9yYW1hKDAuNSklMEEubW9kdWxhdGVTY2FsZShvMCklMEEubW9kdWxhdGVTY2FsZShvMCUyQzElMkMpJTBBLmJsZW5kKG8wKSUwQS5ibGVuZChvMCklMEEuYmxlbmQobzApJTBBLmJsZW5kKG8wKSUwQS5vdXQobzApJTBB"
},
{
"sketch_id": "flor_1",
"code": "JTJGJTJGSHlkcmElMjBHbGl0Y2h5JTIwU2xpdCUyMFNjYW4lMEElMkYlMkZGbG9yJTIwZGUlMjBGdWVnbyUwQSUyRiUyRmh0dHBzJTNBJTJGJTJGZmxvcmRlZnVlZ28uZ2l0aHViLmlvJTJGJTIwJTBBczAuaW5pdENhbSgpJTBBc3JjKHMwKS5zYXR1cmF0ZSgyKS5jb250cmFzdCgxLjMpLmxheWVyKHNyYyhvMCkubWFzayhzaGFwZSg0JTJDMikuc2NhbGUoMC41JTJDMC43KS5zY3JvbGxYKDAuMjUpKS5zY3JvbGxYKDAuMDAxKSkubW9kdWxhdGUobzAlMkMwLjAwMSkub3V0KG8wKSUwQSUwQQ=="
},
{
"sketch_id": "flor_2",
"code": "JTJGJTJGR2xpdGNoJTIwUml2ZXIlMEElMkYlMkZGbG9yJTIwZGUlMjBGdWVnbyUwQSUyRiUyRmh0dHBzJTNBJTJGJTJGZmxvcmRlZnVlZ28uZ2l0aHViLmlvJTJGJTBBdm9yb25vaSg4JTJDMSklMEEubXVsdChvc2MoMTAlMkMwLjElMkMoKSUzRCUzRU1hdGguc2luKHRpbWUpKjMpLnNhdHVyYXRlKDMpLmthbGVpZCgyMDApKSUwQS5tb2R1bGF0ZShvMCUyQzAuNSklMEEuYWRkKG8wJTJDMC44KSUwQS5zY3JvbGxZKC0wLjAxKSUwQS5zY2FsZSgwLjk5KSUwQS5tb2R1bGF0ZSh2b3Jvbm9pKDglMkMxKSUyQzAuMDA4KSUwQS5sdW1hKDAuMyklMEEub3V0KCklMEElMEElMEFzcGVlZCUyMCUzRCUyMDAuMSUwQSUwQSUwQSUwQQ=="
},
{
"sketch_id": "nesso_0",
"code": "JTBBJTJGJTJGY2xvdWRzJTIwb2YlMjBwYXNzYWdlJTBBJTJGJTJGYnklMjBOZXNzbyUwQSUyRiUyRnd3dy5uZXNzby54eXolMEElMEFzaGFwZSglNUI0JTJDNSUyQzYlNUQuZmFzdCgwLjEpLnNtb290aCgxKSUyQzAuMDAwMDAxJTJDJTVCMC4yJTJDMC43JTVELnNtb290aCgxKSklMEEuY29sb3IoMC4yJTJDMC40JTJDMC4zKSUwQS5zY3JvbGxYKCgpJTNEJTNFTWF0aC5zaW4odGltZSowLjI3KSklMEEuYWRkKCUwQSUyMCUyMHNoYXBlKCU1QjQlMkM1JTJDNiU1RC5mYXN0KDAuMSkuc21vb3RoKDEpJTJDMC4wMDAwMDElMkMlNUIwLjIlMkMwLjclMkMwLjUlMkMwLjMlNUQuc21vb3RoKDEpKSUwQSUyMCUyMC5jb2xvcigwLjYlMkMwLjIlMkMwLjUpJTBBJTIwJTIwLnNjcm9sbFkoMC4zNSklMEElMjAlMjAuc2Nyb2xsWCgoKSUzRCUzRU1hdGguc2luKHRpbWUqMC4zMykpKSUwQS5hZGQoJTBBJTIwJTIwc2hhcGUoJTVCNCUyQzUlMkM2JTVELmZhc3QoMC4xKS5zbW9vdGgoMSklMkMwLjAwMDAwMSUyQyU1QjAuMiUyQzAuNyUyQzAuMyU1RC5zbW9vdGgoMSkpJTBBJTIwJTIwLmNvbG9yKDAuMiUyQzAuNCUyQzAuNiklMEElMjAlMjAuc2Nyb2xsWSgtMC4zNSklMEElMjAlMjAuc2Nyb2xsWCgoKSUzRCUzRU1hdGguc2luKHRpbWUqMC40MSkqLTEpKSUwQS5hZGQoJTBBJTIwJTIwJTIwJTIwJTIwJTIwc3JjKG8wKS5zaGlmdCgwLjAwMSUyQzAuMDElMkMwLjAwMSklMEElMjAlMjAlMjAlMjAlMjAlMjAuc2Nyb2xsWCglNUIwLjA1JTJDLTAuMDUlNUQuZmFzdCgwLjEpLnNtb290aCgxKSklMEElMjAlMjAlMjAlMjAlMjAlMjAuc2NhbGUoJTVCMS4wNSUyQzAuOSU1RC5mYXN0KDAuMykuc21vb3RoKDEpJTJDJTVCMS4wNSUyQzAuOSUyQzElNUQuZmFzdCgwLjI5KS5zbW9vdGgoMSkpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTJDMC44NSklMEEubW9kdWxhdGUodm9yb25vaSgxMCUyQzIlMkMyKSklMEEub3V0KCk="
},
{
"sketch_id": "malitzin_0",
"code": "JTJGJTJGQ05EU0QlMEElMkYlMkZodHRwJTNBJTJGJTJGbWFsaXR6aW5jb3J0ZXMubmV0JTJGJTBBJTJGJTJGJTIwc2FuZCUyMHNwaXJhbHMlMEElMEFvc2MoMyUyQyUyMDAuMDElMkMlMjAwLjQpJTBBLmNvbG9yKDEuMiUyQzEuMiUyQzEuMyklMEEuc2F0dXJhdGUoMC40KSUwQS5tb2R1bGF0ZVJlcGVhdChvc2MoMiklMkMxJTJDJTIwMiUyQyUyMDQlMkMlMjAzKSUwQS5tb2R1bGF0ZUthbGVpZChvc2MoMTIlMkMwLjA1JTJDMCklMkMxKSUwQS5sdW1hJTIwKDAuNCklMEEucm90YXRlKDQlMkMlMjAwLjElMkMwKSUwQS5tb2R1bGF0ZShvMCUyQyUyMCgpJTIwJTNEJTNFJTIwbW91c2UueSUyMCowLjAwMDIlMjApJTBBLnNjYWxlKDEpLmRpZmYobzEpJTBBLm91dChvMCk="
},
{
"sketch_id": "malitzin_1",
"code": "JTJGJTJGQ05EU0QlMEElMkYlMkZodHRwJTNBJTJGJTJGbWFsaXR6aW5jb3J0ZXMubmV0JTJGJTBBJTJGJTJGYW1lYmElMEElMEFvc2MoMTUlMkMlMjAwLjAxJTJDJTIwMC4xKS5tdWx0KG9zYygxJTJDJTIwLTAuMSkubW9kdWxhdGUob3NjKDIpLnJvdGF0ZSg0JTJDMSklMkMlMjAyMCkpJTBBLmNvbG9yKDAlMkMyLjQlMkM1KSUwQS5zYXR1cmF0ZSgwLjQpJTBBLmx1bWEoMSUyQzAuMSUyQyUyMCg2JTJDJTIwKCklM0QlM0UlMjAxJTIwJTJCJTIwYS5mZnQlNUIzJTVEKSklMEEuc2NhbGUoMC43JTJDJTIwKCklM0QlM0UlMjAwLjclMjAlMkIlMjBhLmZmdCU1QjMlNUQpJTBBLmRpZmYobzApJTJGJTJGJTIwbzAlMEEub3V0KG8wKSUyRiUyRiUyMG8x"
},
{
"sketch_id": "malitzin_2",
"code": "JTJGJTJGQ05EU0QlMEElMkYlMkZodHRwJTNBJTJGJTJGbWFsaXR6aW5jb3J0ZXMubmV0JTJGJTBBJTJGJTJGY3JhenklMjBzcXVhcmVzJTBBJTBBc2hhcGUoNCUyQyUyMCgwLjAxJTJDJTIwKCklM0QlM0UlMjAwLjIlMjAlMkIlMjBhLmZmdCU1QjIlNUQpJTJDMSklMEEubXVsdChvc2MoMSUyQyUyMDEpLm1vZHVsYXRlKG9zYyg1KS5yb3RhdGUoMS40JTJDMSklMkMzKSklMEEuY29sb3IoMSUyQzIlMkM0KSUwQS5zYXR1cmF0ZSgwLjIpJTBBLmx1bWEoMS4yJTJDMC4wNSUyQyUyMCg1JTJDJTIwKCklM0QlM0UlMjAyJTIwJTJCJTIwYS5mZnQlNUIzJTVEKSklMEEuc2NhbGUoMC42JTJDJTIwKCklM0QlM0UlMjAwLjklMjAlMkIlMjBhLmZmdCU1QjMlNUQpJTBBLmRpZmYobzApJTJGJTJGJTIwbzAlMEEub3V0KG8wKSUyRiUyRiUyMG8x"
},
{
"sketch_id": "khoparzi_0",
"code": "JTJGJTJGJTIwSGFwcHklMjBNYW5kYWxhJTBBJTJGJTJGJTIwQnklMjBBYmhpbmF5JTIwS2hvcGFyemklMEElMkYlMkYlMjB0d2l0dGVyJTJGZ2l0aHViJTJGaW5zdGFncmFtJTNBJTIwJTQwa2hvcGFyemklMEF2b3Jvbm9pKDUlMkMtMC4xJTJDNSklMEEuYWRkKG9zYygxJTJDMCUyQzEpKS5rYWxlaWQoMjEpJTBBLnNjYWxlKDElMkMxJTJDMikuY29sb3JhbWEoKS5vdXQobzEpJTBBc3JjKG8xKS5tdWx0KHNyYyhzMCkubW9kdWxhdGVSb3RhdGUobzElMkMxMDApJTJDJTIwLTAuNSklMEElMjAlMjAub3V0KG8wKSUwQSUwQQ=="
},
{
"sketch_id": "khoparzi_1",
"code": "JTJGJTJGJTIwUGVycGV0dWFsJTIwZWxldmF0b3IlMjBidXR0b25zJTBBJTJGJTJGJTIwQnklMjBLaG9wYXJ6aSUwQSUyRiUyRiUyMGh0dHAlM0ElMkYlMkZraG9wYXJ6aS5jb20lMEElMEFzaGFwZSgzKS5hZGQob3NjKDElMkMwLjUlMkMxKSUyQyUyMDEpJTBBJTA5LmFkZChvMSUyQyUyMCgpJTIwJTNEJTNFJTIwKE1hdGguc2luKHRpbWUlMkY0KSUyMColMjAwLjclMjAlMkIlMjAwLjEpKSUwQSUwOSUyRiUyRi5yZXBlYXQoNSklMEElMjAlMjAlMDkuc2NhbGUoKCklM0QlM0VNYXRoLnNpbih0aW1lJTIwJTJGJTIwMTYpKS5yb3RhdGUoMCUyQyUyMC0wLjEpJTBBJTA5Lm91dChvMSklMEElMEFzcmMobzEpJTBBJTIwJTIwLnJvdGF0ZSgwJTJDMC4xKSUwQSUyMCUyMC5vdXQoKQ=="
},
{
"sketch_id": "khoparzi_2",
"code": "JTJGJTJGJTIwUmVhbGx5JTIwTG92ZSUwQSUyRiUyRiUyMGJ5JTIwQWJoaW5heSUyMEtob3BhcnppJTBBJTJGJTJGJTIwaHR0cCUzQSUyRiUyRmtob3BhcnppLmNvbSUwQW9zYygxMDAlMkMtMC4wMTI0NSUyQzEpLnBpeGVsYXRlKDUwKS5rYWxlaWQoKCklM0QlM0UoTWF0aC5zaW4odGltZSUyRjgpKjklMkIzKSkucm90YXRlKDAlMkMwLjEyNSklMEEubW9kdWxhdGVSb3RhdGUoc2hhcGUoMykuc2NhbGUoKCklM0QlM0UoTWF0aC5jb3ModGltZSkqMikpLnJvdGF0ZSgwJTJDLTAuMjUpKS5kaWZmKHNyYyhvMCkuYnJpZ2h0bmVzcygwLjMpKSUwQSUyMCUyMC5vdXQoKQ=="
},
{
"sketch_id": "khoparzi_3",
"code": "JTJGJTJGJTIwQXFhdXRpYyUyMGJsdWJzJTBBJTJGJTJGJTIwQnklMjBLaG9wYXJ6aSUwQSUyRiUyRiUyMGh0dHBzJTNBJTJGJTJGa2hvcGFyemkuY29tJTBBJTBBZ3JhZGllbnQoMC4yNSklMEEuYWRkKG5vaXNlKCklMkMlMjAoKSUzRCUzRU1hdGguY29zKHRpbWUpKSUwQS5tb2R1bGF0ZVJvdGF0ZShzcmMobzApLnJvdGF0ZSgwJTJDJTIwLTAuNTIpJTJDJTIwMC4yKS5tdWx0KHNoYXBlKDM2MCklMkMlMjAwLjgpJTBBLnJlcGVhdCgxMCUyQzUpLm11bHQoc2hhcGUoMzYwKS5zY2FsZSgoKSUzRCUzRU1hdGguc2luKHRpbWUpKSUyQyUyMDAuOCkucm90YXRlKDAlMkMlMjAwLjIpJTBBLmRpZmYoc3JjKG8wKS5yb3RhdGUoMCUyQyUyMC0wLjIpJTJDJTIwMC4yKSUwQS5vdXQoKQ=="
},
{
"sketch_id": "celeste_0",
"code": "JTBBJTIwJTJGJTJGJTIwUHVlcnRhcyUyMElJJTBBJTJGJTJGJTIwcG9yJTIwQ2VsZXN0ZSUyMEJldGFuY3VyJTBBJTJGJTJGJTIwaHR0cHMlM0ElMkYlMkZnaXRodWIuY29tJTJGZXNzdGViYW4lMEElMEFvc2MoMTMlMkMwJTJDMSklMEElMjAlMjAua2FsZWlkKCklMEElMjAlMjAubWFzayhzaGFwZSg0JTJDMC4zJTJDMSkpJTBBJTIwJTIwLm1vZHVsYXRlUm90YXRlKHNoYXBlKDQlMkMwLjElMkMxKSklMEElMjAlMjAubW9kdWxhdGVSb3RhdGUoc2hhcGUoNCUyQzAuMSUyQzAuOSkpJTBBJTIwJTIwLm1vZHVsYXRlUm90YXRlKHNoYXBlKDQlMkMwLjElMkMwLjgpKSUwQSUyMCUyMC5zY2FsZSgwLjMpJTBBJTIwJTIwLmFkZChzaGFwZSg0JTJDMC4yJTJDMSkuY29sb3IoMC4zJTJDMSUyQzElMkMwLjUpKSUwQSUyMCUyMC5yb3RhdGUoKCklM0QlM0V0aW1lKSUwQSUyMCUyMC5vdXQoKQ=="
},
{
"sketch_id": "celeste_1",
"code": "JTJGJTJGJTIwUHVlcnRhcyUyMElJSSUwQSUyRiUyRiUyMHBvciUyMENlbGVzdGUlMjBCZXRhbmN1ciUwQSUyRiUyRiUyMGh0dHBzJTNBJTJGJTJGZ2l0aHViLmNvbSUyRmVzc3RlYmFuJTBBJTIwJTBBb3NjKDQwJTJDMC4yJTJDMSklMEElMjAlMjAubW9kdWxhdGVTY2FsZShvc2MoNDAlMkMwJTJDMSkua2FsZWlkKDgpKSUwQSUyMCUyMC5yZXBlYXQoMiUyQzQpJTBBJTIwJTIwLm1vZHVsYXRlKG8wJTJDMC4wNSklMEElMjAlMjAubW9kdWxhdGVLYWxlaWQoc2hhcGUoNCUyQzAuMSUyQzEpKSUwQSUyMCUyMC5vdXQobzAp"
},
{
"sketch_id": "celeste_2",
"code": "JTBBJTIwJTJGJTJGJTIwUHVlcnRhcyUwQSUyRiUyRiUyMHBvciUyMENlbGVzdGUlMjBCZXRhbmN1ciUwQSUyRiUyRiUyMGh0dHBzJTNBJTJGJTJGZ2l0aHViLmNvbSUyRmVzc3RlYmFuJTBBJTBBb3NjKDEzJTJDMCUyQzEpJTBBJTIwJTIwLm1vZHVsYXRlKG9zYygyMSUyQzAuMjUlMkMwKSklMEElMjAlMjAubW9kdWxhdGVTY2FsZShvc2MoMzQpKSUwQSUyMCUyMC5tb2R1bGF0ZUthbGVpZChvc2MoNTUpJTJDMC4xJTJDMSklMEElMjAlMjAub3V0KCk="
},
{
"sketch_id": "alexandre_0",
"code": "JTJGJTJGJTIwJTIydGhlLXdhbGwlMjIlMEElMkYlMkYlMjBBbGV4YW5kcmUlMjBSYW5nZWwlMEElMkYlMkYlMjB3d3cuYWxleGFuZHJlcmFuZ2VsLmFydC5iciUyRmh5ZHJhLmh0bWwlMEElMEFzcGVlZCUzRC4wMjIyJTBBb3NjKDQ4JTJDLS4xJTJDMCkudGhyZXNoKCU1Qi4zJTJDLjclNUQuZmFzdCguNzUpJTJDMCkuY29sb3IoMCUyQzAlMkMxKSUwQSUwQS5hZGQoJTBBJTIwJTIwJTIwJTIwb3NjKDI4JTJDLjElMkMwKS50aHJlc2goJTVCLjMlMkMuNyU1RC5mYXN0KC43NSklMkMwKS5yb3RhdGUoMy4xNCUyRjQpJTBBJTIwJTIwJTIwJTIwLmNvbG9yKDElMkMwJTJDMCklMEElMjAlMjAlMjAlMjAubW9kdWxhdGVTY2FsZSglMjBvc2MoNjQlMkMtLjAxJTJDMCkudGhyZXNoKCU1Qi4zJTJDLjclNUQuZmFzdCguNzUpJTJDMCklMjApJTBBKSUwQS5kaWZmKCUwQSUyMCUyMCUyMCUyMG9zYygyOCUyQy4xJTJDMCkudGhyZXNoKCU1Qi4zJTJDLjclNUQuZmFzdCguNSklMkMwKS5yb3RhdGUoMy4xNCUyRjIpJTBBJTIwJTIwJTIwJTIwLmNvbG9yKDElMkMwJTJDMSklMEElMjAlMjAlMjAlMjAubW9kdWxhdGVTY2FsZSglMjBvc2MoNjQlMkMtLjAxNSUyQzApLnRocmVzaCglNUIuMyUyQy43JTVELmZhc3QoLjUpJTJDMCklMjApJTBBKSUwQS5tb2R1bGF0ZVJvdGF0ZSglMjBvc2MoNTQlMkMtLjAwNSUyQzApLnRocmVzaCglNUIuMyUyQy43JTVELmZhc3QoLjI1KSUyQzApJTIwKSUwQS5tb2R1bGF0ZVNjYWxlKCUyMG9zYyg0NCUyQy0uMDIwJTJDMCkudGhyZXNoKCU1Qi4zJTJDLjclNUQuZmFzdCguMjUpJTJDMCklMjApJTBBLmNvbG9yYW1hKCUyMCgpJTNEJTNFTWF0aC5zaW4odGltZSUyRjI3KSouMDEyMjIlMkI5Ljg5KSUwQS5zY2FsZSgyLjEyMiklMEElMEEub3V0KCk="
},
{
"sketch_id": "alexandre_1",
"code": "JTBBJTIwJTJGJTJGJTIwJTIyZXllJTIwb2YlMjB0aGUlMjBiZWhvbGRlciUyMiUwQSUyRiUyRiUyMEFsZXhhbmRyZSUyMFJhbmdlbCUwQSUyRiUyRiUyMHd3dy5hbGV4YW5kcmVyYW5nZWwuYXJ0LmJyJTJGaHlkcmEuaHRtbCUwQSUwQW5vaXNlKDYlMkMuMDUpJTBBLm11bHQoJTIwb3NjKDklMkMwJTJDJTIwKCklM0QlM0VNYXRoLnNpbih0aW1lJTJGMS41KSUyQjIlMjApJTIwKSUwQS5tdWx0KCUwQSUyMCUyMCUyMCUyMG5vaXNlKDklMkMuMDMpLmJyaWdodG5lc3MoMS4yKS5jb250cmFzdCgyKSUwQSUyMCUyMCUyMCUyMC5tdWx0KCUyMG9zYyg5JTJDMCUyQyUyMCgpJTNEJTNFTWF0aC5zaW4odGltZSUyRjMpJTJCMTMlMjApJTIwKSUwQSklMEEuZGlmZiglMEElMjAlMjAlMjAlMjBub2lzZSgxNSUyQy4wNCkuYnJpZ2h0bmVzcyguMikuY29udHJhc3QoMS4zKSUwQSUyMCUyMCUyMCUyMC5tdWx0KCUyMG9zYyg5JTJDMCUyQyUyMCgpJTNEJTNFTWF0aC5zaW4odGltZSUyRjUpJTJCMTMlMjApJTIwKSUwQSUyMCUyMCUyMCUyMC5yb3RhdGUoJTIwKCklM0QlM0V0aW1lJTJGMzMlMjApJTBBKSUwQS5zY2FsZSglMjAoKSUzRCUzRU1hdGguc2luKHRpbWUlMkY2LjIpKi4xMiUyQi4xNSUyMCklMEEubW9kdWxhdGVTY2FsZSglMEElMjAlMjAlMjAlMjBvc2MoMyUyQzAlMkMwKS5tdWx0KCUyMG9zYygzJTJDMCUyQzApLnJvdGF0ZSgzLjE0JTJGMiklMjApJTBBJTIwJTIwJTIwJTIwLnJvdGF0ZSglMjAoKSUzRCUzRXRpbWUlMkYyNSUyMCkuc2NhbGUoLjM5KS5zY2FsZSgxJTJDLjYlMkMxKS5pbnZlcnQoKSUwQSUyMCUyMCUyMCUyMCUyQyUyMCgpJTNEJTNFTWF0aC5zaW4odGltZSUyRjUuMykqMS41JTJCMyUyMCUyMCklMEEucm90YXRlKCUyMCgpJTNEJTNFdGltZSUyRjIyJTIwKSUwQS5tdWx0KCUyMHNoYXBlKDEwMCUyQy45JTJDLjAxKS5zY2FsZSgxJTJDLjYlMkMxKSUyMCklMEEub3V0KCk="
},
{
"sketch_id": "alexandre_2",
"code": "JTJGJTJGJTIwJTIyZWdnJTIwb2YlMjB0aGUlMjBwaG9lbml4JTIyJTBBJTJGJTJGJTIwQWxleGFuZHJlJTIwUmFuZ2VsJTBBJTJGJTJGJTIwd3d3LmFsZXhhbmRyZXJhbmdlbC5hcnQuYnIlMkZoeWRyYS5odG1sJTBBJTBBc3BlZWQlM0QxLjIlMEFzaGFwZSg5OSUyQy4xNSUyQy41KS5jb2xvcigwJTJDMSUyQzIpJTBBJTBBLmRpZmYoJTIwc2hhcGUoMjQwJTJDLjUlMkMwKS5zY3JvbGxYKC4wNSkucm90YXRlKCUyMCgpJTNEJTNFdGltZSUyRjEwJTIwKS5jb2xvcigxJTJDMCUyQy43NSklMjApJTBBLmRpZmYoJTIwc2hhcGUoOTklMkMuNCUyQy4wMDIpLnNjcm9sbFgoLjEwKS5yb3RhdGUoJTIwKCklM0QlM0V0aW1lJTJGMjAlMjApLmNvbG9yKDElMkMwJTJDLjc1KSUyMCklMEEuZGlmZiglMjBzaGFwZSg5OSUyQy4zJTJDLjAwMikuc2Nyb2xsWCguMTUpLnJvdGF0ZSglMjAoKSUzRCUzRXRpbWUlMkYzMCUyMCkuY29sb3IoMSUyQzAlMkMuNzUpJTIwKSUwQS5kaWZmKCUyMHNoYXBlKDk5JTJDLjIlMkMuMDAyKS5zY3JvbGxYKC4yMCkucm90YXRlKCUyMCgpJTNEJTNFdGltZSUyRjQwJTIwKS5jb2xvcigxJTJDMCUyQy43NSklMjApJTBBLmRpZmYoJTIwc2hhcGUoOTklMkMuMSUyQy4wMDIpLnNjcm9sbFgoLjI1KS5yb3RhdGUoJTIwKCklM0QlM0V0aW1lJTJGNTAlMjApLmNvbG9yKDElMkMwJTJDLjc1KSUyMCklMEElMEEubW9kdWxhdGVTY2FsZSglMEElMjAlMjBzaGFwZSgyNDAlMkMuNSUyQzApLnNjcm9sbFgoLjA1KS5yb3RhdGUoJTIwKCklM0QlM0V0aW1lJTJGMTAlMjApJTBBJTIwJTIwJTJDJTIwKCklM0QlM0UoTWF0aC5zaW4odGltZSUyRjMpKi4yKSUyQi4yJTIwKSUwQSUwQS5zY2FsZSgxLjYlMkMuNiUyQzEpJTBBLm91dCgp"
},{
"sketch_id": "afalfl_0",
"code": "JTJGJTJGZmlsZXQlMjBtaWdub24lMEElMkYlMkYlMjBBRkFMRkwlMEElMkYlMkYlMjBpbnN0YWdyYW0lMkZhX2ZfYWxmbCUyMCUwQSUwQW9zYygxMDAlMkMtMC4wMDE4JTJDMC4xNykuZGlmZihvc2MoMjAlMkMwLjAwMDA4KS5yb3RhdGUoTWF0aC5QSSUyRjAuMDAwMDMpKSUwQS5tb2R1bGF0ZVNjYWxlKG5vaXNlKDEuNSUyQzAuMTgpLm1vZHVsYXRlU2NhbGUob3NjKDEzKS5yb3RhdGUoKCklM0QlM0VNYXRoLnNpbih0aW1lJTJGMjIpKSklMkMzKSUwQS5jb2xvcigxMSUyQzAuNSUyQzAuNCUyQyUyMDAuOSUyQyUyMDAuMiUyQyUyMDAuMDExJTJDJTIwNSUyQyUyMDIyJTJDJTIwJTIwMC41JTJDJTIwLTEpLmNvbnRyYXN0KDEuNCklMEEuYWRkKHNyYyhvMCkubW9kdWxhdGUobzAlMkMuMDQpJTJDLjYlMkMlMjAuOSklMEElMjAlMjAlMkYlMkYucGl4ZWxhdGUoMC40JTJDJTIwMC4yJTJDJTIwMC4xKSUwQS5pbnZlcnQoKS5icmlnaHRuZXNzKDAuMDAwMyUyQyUyMDIpLmNvbnRyYXN0KCUyMDAuNSUyQyUyMDIlMkMlMjAwLjElMkMlMjAyKS5jb2xvcig0JTJDJTIwLTIlMkMlMjAwLjEpJTBBLm1vZHVsYXRlU2NhbGUob3NjKDIpJTJDLTAuMiUyQyUyMDIlMkMlMjAxJTJDJTIwMC4zKSUwQSUyMC5wb3N0ZXJpemUoMjAwKSUyMC5yb3RhdGUoMSUyQyUyMDAuMiUyQyUyMDAuMDElMkMlMjAwLjAwMSklMEElMjAuY29sb3IoMjIlMkMlMjAtMiUyQyUyMDAuNSUyQyUyMDAuNSUyQyUyMDAuMDAwMSUyQyUyMCUyMDAuMSUyQyUyMDAuMiUyQyUyMDgpLmNvbnRyYXN0KDAuMTglMkMlMjAwLjMlMkMlMjAwLjElMkMlMjAwLjIlMkMlMjAwLjAzJTJDJTIwMSklMjAuJTIwYnJpZ2h0bmVzcygwLjAwMDElMkMlMjAtMSUyQyUyMDEwKSUwQSUwOS5vdXQoKQ=="
},
{
"sketch_id": "eerie_ear_0",
"code": "JTJGJTJGJTIwZWVfMiUyMC4lMjBNVUxUSVZFUlNFJTIwLiUyMHRpbWUlMjBhbmQlMjBmZWVkYmFjayUwQSUyRiUyRiUyMGVfZSUyMCUyRiUyRiUyMCU0MGVlcmllX2VhciUwQXBhdCUyMCUzRCUyMCgpJTNEJTNFJTBBc29saWQoKSUwQS5sYXllcihzb2xpZCgpLmRpZmYoJTBBJTIwJTIwb3NjKCh0aW1lJTJGMTYpJTIwKiUyMDElMkMlMjAodGltZSUyRjEwMDApJTIwKiUyMDAuMiUyMCUyMCklMEElMjAlMjAlMjAlMjAubXVsdChvc2MoKHRpbWUlMkY4KSUyMColMjAxJTJDJTIwKHRpbWUlMkYxMDA2KSUyMColMjAwLjIlMjAlMjApLnJvdGF0ZSgxLjU3KSklMEElMjAlMjAlMjAlMjAubW9kdWxhdGUoKHNoYXBlKDEwNiUyQzElMkMwLjA1KSkpJTBBJTIwJTIwJTIwJTIwLm11bHQoc2hhcGUoMTA2JTJDMSUyQzAuMDUpKSUwQSUyMCUyMCkpJTBBJTIwJTIwLm1vZHVsYXRlU2NhbGUob3NjKDIlMkMwLjEyNSklMkMwLjEyNSklMEElMkYlMkYlMEFzb2xpZCgpJTBBLmxheWVyKHNvbGlkKDElMkMxJTJDMSklMEElMjAlMjAubXVsdChwYXQoKSUwQSUyMCUyMC5kaWZmKHNyYyhvMCkuc2NhbGUoMC4yKS5tdWx0KHNvbGlkKCklMkMlNUIwLjclMkMwLjYlMkMwLjQlMkMwLjYlNUQpLmthbGVpZCgxLjAxKS5zYXR1cmF0ZSgwLjMpKSUwQSklMEEubGF5ZXIoc29saWQoMSUyQzElMkMxKSUwQSUyMCUyMCUyMCUyMC5tYXNrKCUwQSUyMCUyMCUyMCUyMCUyMCUyMG5vaXNlKDIlMkMwLjA1KSUwQSUyMCUyMCUyMCUyMCUyMCUyMC5pbnZlcnQoKS5jb2xvcmFtYSgyKS5wb3N0ZXJpemUoOCUyQzQpLmx1bWEoMC4yNSkudGhyZXNoKDAuNSklMEElMjAlMjAlMjAlMjAlMjAlMjAubW9kdWxhdGVSb3RhdGUob3NjKDElMkMwLjUpKSUwQSUyMCUyMCUyMCUyMCklMEElMjAlMjAlMjAlMjAubXVsdChncmFkaWVudCgwLjUpLmthbGVpZCgxKS5jb2xvcmFtYSgyKS5zYXR1cmF0ZSgxLjEpLmNvbnRyYXN0KDEuNikubXVsdChzb2xpZCgpJTJDMC40NSkpJTBBJTIwJTIwKSklMEElMjAlMjAub3V0KCklMEElMkYlMkYlMEFzcGVlZCUzRCUyMDAuNSUwQQ=="
},
{
"sketch_id": "eerie_ear_1",
"code": "JTJGJTJGJTIwZWVfMyUyMCUyRiUyRkxJTkVTJTBBJTJGJTJGJTIwZV9lJTIwJTJGJTJGJTIwJTQwZWVyaWVfZWFyJTBBJTJGJTJGJTBBJTJGJTJGYmFzZWQlMjBvbiUwQSUyRiUyRiU0MG5hb3RvX2hpZWRhJTBBJTJGJTJGaHR0cHMlM0ElMkYlMkZuYW90b2hpZWRhLmNvbSUyRmJsb2clMkZoeWRyYS1ib29rJTJGJTBBJTJGJTJGJTBBbiUyMCUzRCUyMDglMEFhJTIwJTNEJTIwKCklMjAlM0QlM0UlMjBzaGFwZSg0JTJDMC4yNSUyQzAuMDA5KS5yb3RhdGUoKCklM0QlM0V0aW1lJTJGLTQwKS5yZXBlYXQobiUyQ24pJTBBYSgpLmFkZChhKCkuc2Nyb2xsWCgwLjUlMkZuKS5zY3JvbGxZKDAuNSUyRm4pJTJDMSkubW9kdWxhdGUobzElMkMwLjEpLm1vZHVsYXRlKHNyYyhvMSkuY29sb3IoMTAlMkMxMCkuYWRkKHNvbGlkKC0xNCUyQy0xNCkpLnJvdGF0ZSgoKSUzRCUzRXRpbWUlMkY0MCklMkMwLjAwNSkuYWRkKHNyYyhvMSkuc2Nyb2xsWSgwLjAxMiUyQzAuMDIpJTJDMC41KS5vdXQobzEpJTBBc3JjKG8xKS5jb2xvcmFtYSgxLjIpLnBvc3Rlcml6ZSg0KS5zYXR1cmF0ZSgwLjcpLmNvbnRyYXN0KDYpLm11bHQoc29saWQoKSUyQzAuMTUpLm91dChvMCklMEElMEElMEE="
},
{
"sketch_id": "eerie_ear_2",
"code": "JTJGJTJGZWVfNSUyMC4lMjBGVUdJVElWRSUyMEdFT01FVFJZJTIwVkhTJTIwLiUyMGF1ZGlvcmVhY3RpdmUlMjBzaGFwZXMlMjBhbmQlMjBncmFkaWVudHMlMEElMkYlMkYlMjBlX2UlMjAlMkYlMkYlMjAlNDBlZXJpZV9lYXIlMEElMkYlMkYlMEFzJTNEJTIwKCklM0QlM0UlMEElMjAlMjBzaGFwZSg0KSUwQS5zY3JvbGxYKCU1Qi0wLjUlMkMtMC4yJTJDMC4zJTJDLTAuMSUyQy0wLjElNUQuc21vb3RoKDAuMSkuZmFzdCgwLjMpKSUwQS5zY3JvbGxZKCU1QjAuMjUlMkMtMC4yJTJDMC4zJTJDLTAuMSUyQzAuMiU1RC5zbW9vdGgoMC45KS5mYXN0KDAuMTUpKSUwQSUyRiUyRiUwQXNvbGlkKCklMEEuYWRkKGdyYWRpZW50KDMlMkMwLjA1KS5yb3RhdGUoMC4wNSUyQy0wLjIpLnBvc3Rlcml6ZSgyKS5jb250cmFzdCgwLjYpJTJDJTVCMSUyQzAlMkMxJTJDMC41JTJDMCUyQzAuNiU1RC5zbW9vdGgoMC45KSklMEEuYWRkKHMoKSklMEEubXVsdChzKCkuc2NhbGUoMC44KS5zY3JvbGxYKDAuMDEpLnNjcm9sbFkoLTAuMDEpLnJvdGF0ZSgwLjIlMkMwLjA2KS5hZGQoZ3JhZGllbnQoMykuY29udHJhc3QoMC42KSUyQyU1QjElMkMwJTJDMSUyQzAuNSU1RC5zbW9vdGgoMC45KSUyQzAuNSkubXVsdChzcmMobzApLnNjYWxlKDAuOTgpJTJDKCklM0QlM0VhLmZmdCU1QjAlNUQqOSklMEElMjAlMjAlMjAlMjAlMjApJTBBLmRpZmYocygpLm1vZHVsYXRlKHNoYXBlKDUwMCkpLnNjYWxlKCU1QjEuNyUyQzEuMiU1RC5zbW9vdGgoMC45KS5mYXN0KDAuMDUpKSklMEEuYWRkKGdyYWRpZW50KDIpLmludmVydCgpJTJDKCklM0QlM0VhLmZmdCU1QjIlNUQpJTBBLm11bHQoZ3JhZGllbnQoKCklM0QlM0VhLmZmdCU1QjMlNUQqOCkpJTBBLmJsZW5kKHNyYygobzApJTJDKCklM0QlM0VhLmZmdCU1QjElNUQqNDApKSUwQS5hZGQodm9yb25vaSgoKSUzRCUzRWEuZmZ0JTVCMSU1RCUyQygpJTNEJTNFYS5mZnQlNUIzJTVEJTJDKCklM0QlM0VhLmZmdCU1QjAlNUQpLnRocmVzaCgwLjcpLnBvc3Rlcml6ZSgyJTJDNCkubHVtYSgwLjkpLnNjcm9sbFkoMSUyQygpJTNEJTNFYS5mZnQlNUIwJTVEJTJGMzApLmNvbG9yYW1hKDMpLnRocmVzaCgoKSUzRCUzRWEuZmZ0JTVCMSU1RCkuc2NhbGUoKCklM0QlM0VhLmZmdCU1QjMlNUQqMiklMkMoKSUzRCUzRWEuZmZ0JTVCMCU1RCUyRjIpJTBBJTIwJTIwLm91dCgpJTBBJTJGJTJGJTBBc3BlZWQlM0QlMjAxJTBBJTBBYS5zZXRTbW9vdGgoMC45Nik="
},
{
"sketch_id": "eerie_ear_3",
"code": "JTJGJTJGJTIwZWVfMSUyMC4lMjBFWUUlMjBJTiUyMFRIRSUyMFNLWSUwQSUyRiUyRmV4YW1wbGUlMjBvZiUyMG1hc2slMjBhbmQlMjBmdW5jdGlvbiUyMG1vZHVsYXRpb24lMEElMkYlMkYlMjBlX2UlMjAlMkYlMkYlMjAlNDBlZXJpZV9lYXIlMEFub2lzZSgxOCklMEElMjAlMjAuY29sb3JhbWEoMSklMEElMjAlMjAucG9zdGVyaXplKDIpJTBBJTIwJTIwLmthbGVpZCg1MCklMEElMjAlMjAubWFzayglMEElMjAlMjAlMjAlMjBzaGFwZSgyNSUyQyUyMDAuMjUpLm1vZHVsYXRlU2NhbGUoJTBBJTIwJTIwJTIwJTIwJTIwJTIwbm9pc2UoNDAwLjUlMkMlMjAwLjUpJTBBJTIwJTIwJTIwJTIwKSUwQSUyMCUyMCklMEElMjAlMjAubWFzayhzaGFwZSg0MDAlMkMlMjAxJTJDJTIwMi4xMjUpKSUwQSUyMCUyMC5tb2R1bGF0ZVNjYWxlKG9zYyg2JTJDJTIwMC4xMjUlMkMlMjAwLjA1KS5rYWxlaWQoNTApKSUwQSUyMCUyMC5tdWx0KG9zYygyMCUyQyUyMDAuMDUlMkMlMjAyLjQpLmthbGVpZCg1MCklMkMlMjAwLjI1KSUwQSUyMCUyMC5zY2FsZSgxLjc1JTJDJTIwMC42NSUyQyUyMDAuNSklMEElMjAlMjAubW9kdWxhdGUobm9pc2UoMC41KSklMEElMjAlMjAuc2F0dXJhdGUoNiklMEElMjAlMjAucG9zdGVyaXplKDQlMkMlMjAwLjIpJTBBJTIwJTIwLnNjYWxlKDEuNSklMEElMjAlMjAub3V0KCklM0IlMEE="
}
]
},{}],232:[function(require,module,exports){
const request = require('superagent')
const examples = require('./examples.json')
const sketches = []
const license = `// licensed with CC BY-NC-SA 4.0 https://creativecommons.org/licenses/by-nc-sa/4.0/`
class Gallery {
constructor(callback, state, emitter) {
this.sketches = []
this.examples = []
this.current = null
this.code = null
this.exampleIndex = null
this.state = state
this.emitter = emitter
this.serverURL = this.state.serverURL === null ? '' : this.state.serverURL
// request.get('/sketches').end((err, res) => {
// console.log('got sketches', res.text, err)
// if(err) {
// console.log('err getting sketches', err)
// } else {
// this.sketches = JSON.parse(res.text)
// }
this.examples = examples
this.setSketchFromURL(callback)
// callback(this.code, this.foundSketch)
// })
window.addEventListener('popstate', (event) => {
this.setSketchFromURL(callback)
// console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
});
this.setRandomSketch = this.setRandomSketch.bind(this)
}
clear() {
this.current = null
this.code = null
//this.exampleIndex = null
let newurl = window.location.protocol + '//' + window.location.host + window.location.pathname
window.history.pushState({ path: newurl }, '', newurl)
this.url = newurl
}
setSketchFromURL(callback) {
hush()
render(o0)
let searchParams = new URLSearchParams(window.location.search)
this.searchParams = searchParams
let base64Code = searchParams.get('code')
// if(!base64Code) base64Code = searchParams.get('id') // backwards compatibility with earlier form of naming. id is now called code
let sketch_id = searchParams.get('sketch_id')
let showCode = searchParams.get('showCode')
let code = ''
//console.log("id", sketch_id, "code", base64Code)
// boolean to determine whether a sketch was found based on the URL, either through looking through the database or rendering the code
this.foundSketch = false
// if contains a sketch id, set sketch from id
if (sketch_id) {
var sketch = this.getExampleById(sketch_id)
if (sketch) {
// console.log('found', sketch)
this.setSketch(sketch)
callback(this.code, false)
} else {
request
// .get('/sketchById')
.get(`${this.state.serverURL}/sketchById`)
.query({ sketch_id: sketch_id })
.end((err, res) => {
// console.log('got sketches', res.text, err)
if (err) {
console.log('err getting sketches', err)
this.setSketchFromCode(base64Code, callback)
} else {
this.sketches = JSON.parse(res.text)
if (this.sketches.length > 0) {
this.setSketch(this.sketches[0])
//this.code = this.decodeBase64(this.sketches[0].code)
this.foundSketch = true
callback(this.code, this.foundSketch)
} else {
this.setSketchFromCode(base64Code, callback)
}
}
})
}
} else {
this.setSketchFromCode(base64Code, callback)
}
if (showCode === 'false') {
this.emitter.emit('hideAll')
this.emitter.emit('hide info')
}
//
// // console.log('found ', sketch)
// // if(sketch) {
// // this.setSketch(sketch)
// // this. = true0
// // } else if (base64Code){
// // this.code = this.decodeBase64(base64Code)
// // this.foundSketch = true
// // } else {
// // console.log('id not found', sketch_id)
// // this.setRandomSketch()
// // }
//
// // // backwards combaitbility with earlier shareable URLS
// } else {
//
// if (base64Code) {
// this.code = this.decodeBase64(base64Code)
// this.foundSketch = true
// } else {
// this.setRandomSketch()
// }
// }
}
setSketchFromCode(base64Code, callback) {
if (base64Code) {
this.code = this.decodeBase64(base64Code)
this.foundSketch = true
} else {
this.setRandomSketch()
}
callback(this.code, this.foundSketch)
}
saveImage() {
}
setToURL(params) {
// console.log(base64)
// console.log('params', params)
// keep code in url for backwards compatibility / compatibility between local and public versions
this.searchParams.delete('sketch_id')
this.searchParams.delete('code')
let url_params
if (params.sketch_id) {
url_params = `sketch_id=${params.sketch_id}`
this.searchParams.append('sketch_id', params.sketch_id)
} else {
url_params = `sketch_id=${params.sketch_id}&code=${params.code}`
this.searchParams.append('sketch_id', params.sketch_id)
this.searchParams.append('code', params.code)
}
let newurl = window.location.protocol + '//' +
window.location.host + window.location.pathname + '?' + this.searchParams.toString()
window.history.replaceState({ path: newurl }, '', newurl)
this.url = newurl
}
encodeBase64(text) {
return btoa(encodeURIComponent(text))
}
decodeBase64(base64Code) {
return decodeURIComponent(atob(base64Code))
}
setSketch(sketch) {
let code = this.decodeBase64(sketch.code)
if (code.indexOf(license) < 0)
code =
`${license}
${code}
`
this.code = code
this.current = sketch
// this.setToURL('sketch_id', sketch._id)
// let params = Object.keys(sketch).map( (key) => {
// return {label: key, value: sketch[key]}
// })
this.setToURL(sketch)
}
setRandomSketch() {
// if there are sketches, set code from sketch, otherwise generate random
//console.log("examples length", this.examples, this.exampleIndex)
if (this.examples.length > 0) {
let index
// if(this.exampleIndex === null) {
index = Math.floor(Math.random() * this.examples.length)
while (index === this.exampleIndex) {
index = Math.floor(Math.random() * this.examples.length)
}
// } else {
// index = this.exampleIndex +1
// if(index >= this.examples.length) index = 0
// }
this.exampleIndex = index
// console.log('example is', this.examples[rand])
this.setSketch(this.examples[index])
} else {
var startString = 'osc(' + 2 + Math.floor(Math.pow(10, Math.random() * 2)) + ')'
startString += '.color(' + Math.random().toFixed(2) + ',' + Math.random().toFixed(2) + ',' + Math.random().toFixed(2) + ')'
startString += '.rotate(' + Math.random().toFixed(2) + ')'
startString += '.out(o0)'
this.code = startString
}
}
// shares via twitter
shareSketch(code, hydra, name) {
this.saveSketch(code, () => {
console.log("URL is", this.url, 'sketch is', this.current)
hydra.getScreenImage((img) => {
request
// .post('/image')
.post(`${this.state.serverURL}/image`)
.attach('previewImage', img)
.query({
url: this.url,
sketch_id: this.current.sketch_id,
name: name
})
// .send({
// code: base64
// })
// .query(query)
.end((err, res) => {
if (err) {
console.log('error postingimage', err)
} else {
console.log('image response', res.text)
// self.setToURL([ { label: 'sketch_id', value: res.text}, {label: 'code', value: base64} ])
}
})
// var oReq = new XMLHttpRequest();
// oReq.open("POST", "https://localhost:8000/image", true);
// oReq.onload = function (oEvent) {
// // Uploaded.
// console.log("uploaded", oEvent)
// };
// oReq.send(img);
// console.log('got image', img)
})
})
}
saveSketch(code, callback) {
let self = this
//console.log('saving in gallery', code)
let base64 = this.encodeBase64(code)
// console.log('code is', base64)
let query = {
code: base64,
parent: this.current ? this.current.sketch_id : null
}
console.log('saving in gallery', query)
request
// .post('/sketch')
.post(`${this.state.serverURL}/sketch`)
// .send({
// code: base64
// })
.query(query)
.end((err, res) => {
if (err) {
console.log('error posting sketch', err)
if (callback) callback(err)
} else {
console.log('response', res.text)
// self.setToURL([ { label: 'sketch_id', value: res.text}, {label: 'code', value: base64} ])
self.setSketch({
sketch_id: res.text,
code: base64
})
if (callback) callback(null)
}
})
}
saveLocally(code) {
let base64 = this.encodeBase64(code)
this.searchParams.delete('sketch_id')
this.searchParams.delete('code')
this.searchParams.append('code', base64)
// keep code in url for backwards compatibility / compatibility between local and public versions
var url_params = this.searchParams.toString()
let newurl = window.location.protocol + '//' +
window.location.host + window.location.pathname + '?' + url_params
window.history.pushState({ path: newurl }, '', newurl)
this.url = newurl
}
getExampleById(id) {
//console.log('looking for', id, this.examples, this.sketches)
var sketches = this.examples.filter((sketch) => sketch.sketch_id === id)
if (sketches.length <= 0) sketches = this.sketches.filter((sketch) => sketch.sketch_id === id)
return sketches[0]
}
}
module.exports = Gallery
},{"./examples.json":231,"superagent":218}],233:[function(require,module,exports){
const i18next = require('i18next')
const i18nextBrowserLanguageDetector = require('i18next-browser-languagedetector')
// const i18nextHttpBackend = require('i18next-http-backend')
const languageResources = require('./text-elements.js')
const availableLanguages = ['ja', 'es', 'ar', 'id', 'pt-br', 'ch', 'ko', 'fr'] // localizations available in repository at /hydra-synth/l10n
const languagePath = (lang) => `https://raw.githubusercontent.com/hydra-synth/l10n/main/${lang}/editor.json`
i18next
// .use(i18nextHttpBackend)
.use(i18nextBrowserLanguageDetector)
.init({
debug: true,
fallbackLng: 'en',
partialBundledLanguages: true,
// backend: {
// loadPath: `${window.location.origin}/locales/{{lng}}.json`,
// crossDomain: true
// },
resources: languageResources
})
module.exports = function store(state, emitter) {
const languages = {}
let searchParams = new URLSearchParams(window.location.search)
let lang = searchParams.get('l10n-lang')
// if(!base64Code) base64Code = searchParams.get('id') // backwards compatibility with earlier form of naming. id is now called code
let path = searchParams.get('l10n-url')
availableLanguages.forEach((lang) => {
loadLanguageFromURL(lang, languagePath(lang))
})
// console.log('%c', "color:purple", 'tttt', lang, path)
if (lang !== null && path !== null) {
loadLanguageFromURL(lang, path)
}
updateAvailableLanguages()
emitter.on('set language', (lang) => {
// console.log('setting language to', lang)
i18next.changeLanguage(lang, (err, t) => {
// console.log(err, t)
state.translation.selectedLanguage = lang
emitter.emit('render')
})
})
function updateAvailableLanguages() {
Object.keys(languageResources).forEach((key) => {
// for some reason, 'pt-br' was not working, use just pt instead
const k = key.split('-')[0]
languages[k] = i18next.getFixedT(k)('language-name')
})
state.translation = {
t: i18next.t,
languages: languages,
// languages: ['en', 'ja'],
selectedLanguage: i18next.language
}
}
// loadLanguageFromURL('es', 'https://raw.githubusercontent.com/hydra-synth/l10n/main/es/editor.json')
//loadLanguageFromURL('es','https://hackmd.io/baEnGh7gRt2iHTvt-TT8Fw/download')
function loadLanguageFromURL(lang = 'es', path) {
const css = "color: purple; background: orange; font-size: 14px;padding:10px"
console.log(`%cloading translation for ${lang} from ${path}`, css);
fetch(path)
.then(res => {
if (!res.ok) {
return res.text().then(text => { throw new Error(text) })
}
else {
// console.log('returning json')
return res.json();
}
}).then(json => {
// console.log(json)
window.i18n = i18next
console.log('adding language', lang, json)
// for some reason, 'pt-br' was not working, use just pt instead
const k = lang.split('-')[0]
i18next.addResourceBundle(k, 'translation', json)
const languages = {}
updateAvailableLanguages()
emitter.emit('render')
})
}
// const path = `${window.location.origin}/locales/es.json`
}
},{"./text-elements.js":235,"i18next":99,"i18next-browser-languagedetector":98}],234:[function(require,module,exports){
const Gallery = require('./gallery.js')
const repl = require('../views/editor/repl.js')
// console.log('ENVIRONMENT IS', process.env.NODE_ENV)
module.exports = function store(state, emitter) {
state.showInfo = true
state.showUI = true
const SERVER_URL = "http://localhost:8000"
state.serverURL = SERVER_URL !== undefined ? SERVER_URL : null
let sketches
emitter.on('DOMContentLoaded', function () {
const editor = state.editor.editor
sketches = new Gallery((code, sketchFromURL) => {
editor.setValue(code)
repl.eval(code)
if(sketchFromURL) {
state.showInfo = false
} else {
state.showInfo = true
}
emitter.emit('render')
// @todo create gallery store
// console.warn('gallery callback not let implemented')
}, state, emitter)
})
emitter.on('screencap', () => {
screencap()
const editor = state.editor.editor
const text = editor.getValue()
const data = new Blob([text], {type: 'text/plain'});
const a = document.createElement('a')
a.style.display = 'none'
let d = new Date()
a.download = `hydra-${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}-${d.getHours()}.${d.getMinutes()}.${d.getSeconds()}.js`
a.href = URL.createObjectURL(data)
a.click()
setTimeout(() => {
window.URL.revokeObjectURL(a.href);
}, 300);
})
emitter.on('editor:randomize', function (evt) {
const editor = state.editor.editor
if (evt.shiftKey) {
editor.mutator.doUndo();
} else {
editor.mutator.mutate({ reroll: false, changeTransform: evt.metaKey });
editor.formatCode()
sketches.saveLocally(editor.getValue())
}
})
function clearAll() {
const editor = state.editor.editor
hush()
speed = 1
sketches.clear()
editor.clear()
}
emitter.on('editor:clearAll', function () {
clearAll()
})
emitter.on('editor:evalAll', function () {
const editor = state.editor.editor
const code = editor.getValue()
repl.eval(code, (string, err) => {
editor.flashCode()
if (!err) sketches.saveLocally(code)
})
})
emitter.on('editor:evalLine', (line) => {
repl.eval(line)
})
emitter.on('editor:evalBlock', (block) => {
repl.eval(block)
})
emitter.on('gallery:saveToURL', function () {
let editor = state.editor.editor
const editorText = editor.getValue()
sketches.saveLocally(editorText)
})
emitter.on('gallery:shareSketch', function () {
let editor = state.editor.editor
const editorText = editor.getValue()
repl.eval(editor.getValue(), (code, error) => {
// console.log('evaluated', code, error)
if (!error) {
showConfirmation((name) => {
sketches.shareSketch(editorText, state.hydra.hydra, name)
}, () => { })
} else {
console.warn(error)
}
})
})
emitter.on('gallery:showExample', () => {
const editor = state.editor.editor
clearAll()
sketches.setRandomSketch()
editor.setValue(sketches.code)
repl.eval(editor.getValue())
})
emitter.on('show confirmation', function (count) {
})
emitter.on('clear all', function (count) {
})
emitter.on('hideAll', function () {
state.showUI = !state.showUI
emitter.emit('render')
})
emitter.on('toggle info', function (count) {
state.showInfo = !state.showInfo
emitter.emit('render')
})
emitter.on('hude info', function (count) {
state.showInfo = false
emitter.emit('render')
})
emitter.on('mutate sketch', function () {
})
}
function showConfirmation(successCallback, terminateCallback) {
var c = prompt(`
////:: ḣ̖̻͛̓y҉̃̀̋̑ḑ̴̞͛̒r̴̨̦͕̝ā̤̓̍͘ s̠҉͍͊ͅḳ̯͍̑ͦẹ̿͋̒̕t̲̂̓ͩ̑c͕͗ͤ̕̕ḣ̖̻͛̓ ĝ̽̓̀͑ā̤̓̍͘l̙͖̑̾ͣl̙͖̑̾ͣẹ̿͋̒̕r̴̨̦͕̝y҉̃̀̋̑ ::////
🎨 Click 'OK' to add your sketch and screenshot to the gallery of hydra sketches at https://botsin.space/@hydra.
‼️ Make sure you are ready to share - there is no undo button!
💖 Thank you for sharing! You are also warmly invited to join the the live coding server on the fediverse at https://social.toplap.org/.
`
, 'your name, mastodon handle, and/or a short description')
// console.log('confirm value', c)
if (c !== null) {
successCallback(c)
} else {
terminateCallback()
}
}
},{"../views/editor/repl.js":244,"./gallery.js":232}],235:[function(require,module,exports){
module.exports = {
en: {
translation: {
'language-name': 'english',
toolbar: {
run: "Run all code (ctrl+shift+enter)",
upload: "upload to gallery",
clear: "clear all",
shuffle: "show random sketch",
random: "make random change",
"show-info": "show info window",
"hide-info": "hide info window"
},
info: {
title: 'hydra',
subtitle: 'live coding video synth',
description: 'Hydra is live code-able video synth and coding environment that runs directly in the browser. It is free and open-source and made for beginners and experts alike.',
'get-started-title': 'To get started:',
'get-started-list': [
'Close this window',
'Change some numbers',
'Type Ctrl + Shift + Enter'
],
'description-detailed': 'Hydra is written in JavaScript and compiles to WebGL under the hood. The syntax is inspired by analog modular synthesis, in which chaining or patching a set of transformations together generates a visual result.',
'uses': 'Hydra can be used:',
'uses-list': [
'to mix and add effects to camera feeds, screenshares, live streams, and videos',
'to create generative and audio-reactive visuals, and share them online with others',
'in combination with other javascript libraries such as P5.js, Tone.js, THREE.js, or gibber',
'to add interactive video effects to a website',
'to experiment with and learn about video feedback, fractals, and pixel operations',
'to stream video between browsers and live-jam with others online'
],
'author': 'Created by <a {{author}}>olivia.</a>',
'more-info': 'For more information and instructions, see: <a {{docs}}>the interactive documentation</a>, <a {{functions}}>a list of hydra functions</a>, <a {{garden}}>the community database of projects and tutorials</a>, <a {{gallery}}>a gallery of user-generated sketches</a>, and <a {{repo}}>the source code on github</a>,',
'more-info-forums': 'There is also an active <a {{discord}}>Discord server</a> and <a {{facebook}}>facebook group</a> for hydra users+contributors.',
'support': 'If you enjoy using Hydra, please consider <a {{open-collective}} >supporting continued development <3 </a>.'
}
}
}
}
},{}],236:[function(require,module,exports){
const html = require('choo/html')
const Component = require('choo/component')
const HydraEditor = require('./editor/editor.js')
const log = require('./editor/log.js')
module.exports = class Editor extends Component {
constructor (id, state, emit) {
super(id)
this.local = state.components[id] = {}
state.editor = this // hacky way fo sharing editor to rest of app
this.emit = emit
}
load (element) {
log.init(this.logElement)
this.editor = new HydraEditor(this.textEl)
this.editor.on("*", (e, args) => {
this.emit(e, args)
})
// hacky, maybe not necessary
this.innerText = document.getElementsByClassName('CodeMirror')[0]
}
hide() {
this.innerText.style.opacity = 0
}
show() {
this.innerText.style.opacity = 1
this.innerText.style.pointerEvents = 'all'
}
update (state) {
if(state.showInfo === true || state.showUI === false) {
this.hide()
} else {
this.show()
}
return false
}
createElement ({ width = window.innerWidth, height = window.innerHeight} = {}) {
this.textEl = html` <textarea></textarea>`
this.logElement = html`<div class="console cm-s-tomorrow-night-eighties"></div>`
return html`<div id="editor-container" style="display:flex;flex-direction:column;">
<div style="position:relative;flex:auto;padding:15px">${this.textEl}</div>
${this.logElement}
</div>`
}
}
},{"./editor/editor.js":238,"./editor/log.js":240,"choo/component":48,"choo/html":49}],237:[function(require,module,exports){
const html = require('choo/html')
const Component = require('choo/component')
// const HydraSynth = require('hydra-synth')
// const HydraSynth = require('./../../../../../hydra-synth')
const P5 = require('./../lib/p5-wrapper.js')
const PatchBay = require('./../lib/patch-bay/pb-live.js')
let pb
// const SERVER_URL = process.env['SERVER_URL']
module.exports = class HydraCanvas extends Component {
constructor(id, state, emit) {
super(id)
this.local = state.components[id] = {}
state.hydra = this // hacky
this.state = state
this.emit = emit
}
load(element) {
let isIOS =
(/iPad|iPhone|iPod/.test(navigator.platform) ||
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) &&
!window.MSStream;
let precisionValue = isIOS ? 'highp' : 'mediump'
const hydraOptions = { detectAudio: true, canvas: element.querySelector("canvas"), precision: precisionValue }
if (this.state.serverURL === null) {
console.log('LOCAL ONLY, WILL NOT INIT webRTC and gallery')
this.hydra = new Hydra(hydraOptions)
} else {
this.pb = new PatchBay()
hydraOptions.pb = this.pb
this.hydra = new Hydra(hydraOptions)
this.pb.init(this.hydra.captureStream, {
// server: window.location.origin,
server: this.state.serverURL,
room: 'iclc'
})
window.pb = this.pb
}
window.hydraSynth = this.hydra
// if(environment !== 'local') {
// osc().out()
// }
window.P5 = P5
// window.pb = pb
this.emit('hydra loaded')
}
update(center) {
return false
}
createElement({ width = window.innerWidth, height = window.innerHeight } = {}) {
return html`<div style="width:100%;height:100%;">
<canvas id="hydra-canvas" class="bg-black" style="image-rendering:pixelated; width:100%;height:100%" width="${width}" height="${height}"></canvas></div>`
}
}
},{"./../lib/p5-wrapper.js":228,"./../lib/patch-bay/pb-live.js":229,"choo/component":48,"choo/html":49}],238:[function(require,module,exports){
/* eslint-disable no-eval */
var CodeMirror = require('codemirror-minified/lib/codemirror')
require('codemirror-minified/mode/javascript/javascript')
require('codemirror-minified/addon/hint/javascript-hint')
require('codemirror-minified/addon/hint/show-hint')
require('codemirror-minified/addon/selection/mark-selection')
require('codemirror-minified/addon/comment/comment')
const EventEmitter = require('nanobus')
const keymaps = require('./keymaps.js')
const Mutator = require('./randomizer/Mutator.js');
const beautify_js = require('js-beautify').js_beautify
var isShowing = true
module.exports = class Editor extends EventEmitter {
constructor(parent) {
super()
console.log("*** Editor class created");
var self = this
// var container = document.createElement('div')
// container.setAttribute('id', 'editor-container')
// var el = document.createElement('TEXTAREA')
// document.body.appendChild(container)
// container.appendChild(el)
this.mutator = new Mutator(this);
const extraKeys = {}
Object.entries(keymaps).forEach(([key, e]) => extraKeys[key] = () => {
if(e == 'editor:evalBlock') {
this.emit(e, this.getCurrentBlock().text)
} else if (e == 'editor:evalLine') {
this.emit(e, this.getLine())
} else if (e == 'editor:toggleComment') {
this.cm.toggleComment()
// } else if (e == 'gallery:saveToURL') {
this.emit(e, this)
} else if (e === 'editor:formatCode') {
this.formatCode()
} else {
this.emit(e, this)
}
})
const opts = {
theme: 'tomorrow-night-eighties',
value: 'hello',
mode: { name: 'javascript', globalVars: true },
lineWrapping: true,
styleSelectedText: true,
extraKeys: extraKeys
}
this.cm = CodeMirror.fromTextArea(parent, opts)
window.cm = this.cm
this.cm.refresh()
// this.show()
// // // TO DO: add show code param
// let searchParams = new URLSearchParams(window.location.search)
// let showCode = searchParams.get('show-code')
// if (showCode === "false") {
// this.hide()
// }
}
clear() {
this.cm.setValue('\n \n // Type some code on a new line (such as "osc().out()"), and press CTRL+shift+enter')
}
setValue(val) {
this.cm.setValue(val)
}
getValue() {
return this.cm.getValue()
}
formatCode() {
const formatted = beautify_js(this.cm.getValue(), { indent_size: 2, "break_chained_methods": true, "indent_with_tabs": true})
this.cm.setValue(formatted)
}
// hide() {
// console.log('hiding')
// var l = document.getElementsByClassName('CodeMirror')[0]
// var m = document.getElementById('modal-header')
// l.style.opacity = 0
// m.style.opacity = 0
// this.isShowing = false
// }
// show() {
// var l = document.getElementsByClassName('CodeMirror')[0]
// var m = document.getElementById('modal-header')
// l.style.opacity= 1
// m.style.opacity = 1
// l.style.pointerEvents = 'all'
// this.isShowing = true
// }
toggle() {
if (this.isShowing) {
this.hide()
} else {
this.show()
}
}
getLine() {
var c = this.cm.getCursor()
var s = this.cm.getLine(c.line)
// this.cm.markText({line: c.line, ch:0}, {line: c.line+1, ch:0}, {className: 'styled-background'})
this.flashCode({ line: c.line, ch: 0 }, { line: c.line + 1, ch: 0 })
return s
}
flashCode(start, end) {
if (!start) start = { line: this.cm.firstLine(), ch: 0 }
if (!end) end = { line: this.cm.lastLine() + 1, ch: 0 }
var marker = this.cm.markText(start, end, { className: 'styled-background' })
setTimeout(() => marker.clear(), 300)
}
getCurrentBlock() { // thanks to graham wakefield + gibber
var editor = this.cm
var pos = editor.getCursor()
var startline = pos.line
var endline = pos.line
while (startline > 0 && editor.getLine(startline) !== '') {
startline--
}
while (endline < editor.lineCount() && editor.getLine(endline) !== '') {
endline++
}
var pos1 = {
line: startline,
ch: 0
}
var pos2 = {
line: endline,
ch: 0
}
var str = editor.getRange(pos1, pos2)
this.flashCode(pos1, pos2)
return {
start: pos1,
end: pos2,
text: str
}
}
}
},{"./keymaps.js":239,"./randomizer/Mutator.js":241,"codemirror-minified/addon/comment/comment":54,"codemirror-minified/addon/hint/javascript-hint":55,"codemirror-minified/addon/hint/show-hint":56,"codemirror-minified/addon/selection/mark-selection":57,"codemirror-minified/lib/codemirror":58,"codemirror-minified/mode/javascript/javascript":59,"js-beautify":103,"nanobus":128}],239:[function(require,module,exports){
module.exports = {
'Ctrl-Enter': 'editor:evalLine',
'Ctrl-/': 'editor:toggleComment',
'Alt-Enter': 'editor:evalBlock',
'Shift-Ctrl-Enter': 'editor:evalAll',
'Shift-Ctrl-G': 'gallery:shareSketch',
'Shift-Ctrl-F': 'editor:formatCode',
'Shift-Ctrl-L': 'gallery:saveToURL',
'Shift-Ctrl-H': 'hideAll',
'Shift-Ctrl-S': 'screencap'
}
},{}],240:[function(require,module,exports){
var logElement
module.exports = {
init: (el) => {
// logElement = document.createElement('div')
// logElement.className = "console cm-s-tomorrow-night-eighties"
// document.body.appendChild(logElement)
logElement = el
},
log: (msg, className = "") => {
console.log('logging', msg, className)
if(logElement) logElement.innerHTML =` >> <span class=${className}> ${msg} </span> `
},
hide: () => {
if(logElement) logElement.style.display = 'none'
},
show: () => {
if(logElement) logElement.style.display = 'block'
},
toggle: () => {
if(logElement.style.display == 'none') {
logElement.style.display = 'block'
} else {
logElement.style.display = 'none'
}
}
}
},{}],241:[function(require,module,exports){
const {Parser} = require("acorn");
const {generate} = require('astring');
const { defaultTraveler, attachComments, makeTraveler } = require('astravel');
const {UndoStack} = require('./UndoStack.js');
const repl = require('./../repl.js')
// const glslTransforms = require('hydra-synth/src/glsl/glsl-functions.js')()
const glslTransforms = require('./glslTransforms.js')
class Mutator {
constructor(editor) {
this.editor = editor;
this.undoStack = new UndoStack();
this.initialVector = [];
this.funcTab = {};
this.transMap = {};
this.scanFuncs();
this.dumpDict();
}
dumpList() {
let gslTab = glslTransforms;
gslTab.forEach (v => {
var argList = "";
v.inputs.forEach((a) => {
if (argList != "") argList += ", ";
let argL = a.name + ": " + a.type + " {" + a.default + "}";
argList = argList + argL;
});
// console.log(v.name + " [" + v.type + "] ("+ argList + ")");
});
}
scanFuncs() {
let gslTab = glslTransforms;
gslTab.forEach (f => {
this.transMap[f.name] = f;
if (this.funcTab[f.type] === undefined) {this.funcTab[f.type] = []}
this.funcTab[f.type].push(f);
});
}
dumpDict() {
for(let tn in this.funcTab)
{
this.funcTab[tn].forEach(f => {
var argList = "";
f.inputs.forEach((a) => {
if (argList != "") argList += ", ";
let argL = a.name + ": " + a.type + " {" + a.default + "}";
argList = argList + argL;
});
//console.log(f.name + " [" + f.type + "] ("+ argList + ")");
});
}
}
mutate(options) {
// Get text from CodeMirror.
let text = this.editor.cm.getValue();
this.undoStack.push({text, lastLitX: this.lastLitX});
let needToRun = true;
let tryCounter = 5;
while (needToRun && tryCounter-- >= 0) {
// Parse to AST
var comments = [];
let ast = Parser.parse(text, {
locations: true,
onComment: comments}
);
// Modify the AST.
this.transform(ast, options);
// Put the comments back.
attachComments(ast, comments);
// Generate JS from AST and set back into CodeMirror editor.
let regen = generate(ast, {comments: true});
this.editor.cm.setValue(regen);
try {
// Evaluate the updated expression.
repl.eval(regen, (code, error) => {
// If we got an error, keep trying something else.
if (error) {
console.log("Eval error: " + regen);
}
needToRun = error;
});
} catch (err) {
console.log("Exception caught: " + err);
needToRun = err;
}
}
}
doUndo() {
// If the current text is unsaved, save it so we can redo if need be.
if (this.undoStack.atTop()) {
let text = this.editor.cm.getValue();
this.undoStack.push({text, lastLitX: this.lastLitX});
}
// Then pop-off the info to restore.
if (this.undoStack.canUndo()) {
let {text, lastLitX} = this.undoStack.undo();
this.setText(text);
this.lastLitX = lastLitX;
}
}
doRedo() {
if(this.undoStack.canRedo()) {
let {text, lastLitX} = this.undoStack.redo();
this.setText(text);
this.lastLitX = lastLitX;
}
}
setText(text) {
this.editor.cm.setValue(text);
repl.eval(text, (code, error) => {
});
}
// The options object contains a flag that controls how the
// Literal to mutate is determined. If reroll is false, we
// pick one at random. If reroll is true, we use the same field
// we did last time.
transform(ast, options) {
// An AST traveler that accumulates a list of Literal nodes.
let traveler = makeTraveler({
go: function(node, state) {
if (node.type === 'Literal') {
state.literalTab.push(node);
} else if (node.type === 'MemberExpression') {
if (node.property && node.property.type === 'Literal') {
// numeric array subscripts are ineligable
return;
}
} else if (node.type === 'CallExpression') {
if (node.callee && node.callee.property && node.callee.property.name && node.callee.property.name !== 'out') {
state.functionTab.push(node);
}
}
// Call the parent's `go` method
this.super.go.call(this, node, state);
}
});
let state = {};
state.literalTab = [];
state.functionTab = [];
traveler.go(ast, state);
this.litCount = state.literalTab.length;
this.funCount = state.functionTab.length;
if (this.litCount !== this.initialVector.length) {
let nextVect = [];
for(let i = 0; i < this.litCount; ++i) {
nextVect.push(state.literalTab[i].value);
}
this.initialVector = nextVect;
}
if (options.changeTransform) {
this.glitchTrans(state, options);
}
else this.glitchLiteral(state, options);
}
glitchLiteral(state, options)
{
let litx = 0;
if (options.reroll) {
if (this.lastLitX !== undefined) {
litx = this.lastLitX;
}
} else {
litx = Math.floor(Math.random() * this.litCount);
this.lastLitX = litx;
}
let modLit = state.literalTab[litx];
if (modLit) {
// let glitched = this.glitchNumber(modLit.value);
let glitched = this.glitchRelToInit(modLit.value, this.initialVector[litx]);
let was = modLit.raw;
modLit.value = glitched;
modLit.raw = "" + glitched;
console.log("Literal: " + litx + " changed from: " + was + " to: " + glitched);
}
}
glitchNumber(num) {
if (num === 0) {
num = 1;
}
let range = num * 2;
let rndVal = Math.round(Math.random() * range * 1000) / 1000;
return rndVal;
}
glitchRelToInit(num, initVal) {
if (initVal === undefined) {
return glitchNumber(num);
} if (initVal === 0) {
initVal = 0.5;
}
let rndVal = Math.round(Math.random() * initVal * 2 * 1000) / 1000;
return rndVal;
}
glitchTrans(state, options)
{
/*
state.functionTab.forEach((f)=>{
console.log(f.callee.property.name);
});
*/
let funx = Math.floor(Math.random() * this.funCount);
if (state.functionTab[funx] === undefined || state.functionTab[funx].callee === undefined || state.functionTab[funx].callee.property === undefined) {
console.log("No valid functionTab for index: " + funx);
return;
}
let oldName = state.functionTab[funx].callee.property.name;
if (oldName == undefined) {
console.log("No name for callee");
return;
}
let ftype = this.transMap[oldName].type;
if (ftype == undefined) {
console.log("ftype undefined for: " + oldName);
return;
}
let others = this.funcTab[ftype];
if (others == undefined) {
console.log("no funcTab entry for: " + ftype);
return;
}
let changeX = Math.floor(Math.random() * others.length);
let become = others[changeX].name;
// check blacklisted combinations.
if (oldName === "modulate" && become === "modulateScrollX")
{
console.log("Function: " + funx + " changing from: " + oldName + " can't change to: " + become);
return;
}
state.functionTab[funx].callee.property.name = become;
console.log("Function: " + funx + " changed from: " + oldName + " to: " + become);
}
} // End of class Mutator.
module.exports = Mutator
},{"./../repl.js":244,"./UndoStack.js":242,"./glslTransforms.js":243,"acorn":19,"astravel":26,"astring":29}],242:[function(require,module,exports){
// A generalized 'Undo stack' which can keep N levels of revertable state.
class UndoStack {
constructor(limit) {
this.stack = [];
this.index = -1;
this.limit = limit;
}
atTop() {
return this.index === -1;
}
canUndo() {
if(this.stack.length === 0) return false;
return this.index === -1 || this.index > 0;
}
canRedo() {
if(this.stack.length === 0 || this.index === -1) return false;
return this.index < this.stack.length - 1;
}
push(item) {
if (this.index >= 0) {
while (this.index < this.stack.length) this.stack.pop();
this.index = -1;
}
if (this.limit && this.stack.length > this.limit) {
this.stack.shift();
}
this.stack.push(item);
}
undo() {
if (this.stack.length === 0) return undefined;
if (this.index === -1) { // start one behind the redo buffer
this.index = this.stack.length - 1;
}
if (this.index > 0) this.index--;
let v = this.stack[this.index];
return v;
}
redo() {
if (this.stack.length === 0 || this.index === -1) return undefined;
let nextX = this.index + 1;
if (nextX >= this.stack.length) return undefined;
this.index = nextX;
return this.stack[this.index];
}
};
module.exports = {UndoStack}
},{}],243:[function(require,module,exports){
/*
Format for adding functions to hydra. For each entry in this file, hydra automatically generates a glsl function and javascript function with the same name. You can also ass functions dynamically using setFunction(object).
{
name: 'osc', // name that will be used to access function in js as well as in glsl
type: 'src', // can be 'src', 'color', 'combine', 'combineCoords'. see below for more info
inputs: [
{
name: 'freq',
type: 'float',
default: 0.2
},
{
name: 'sync',
type: 'float',
default: 0.1
},
{
name: 'offset',
type: 'float',
default: 0.0
}
],
glsl: `
vec2 st = _st;
float r = sin((st.x-offset*2/freq+time*sync)*freq)*0.5 + 0.5;
float g = sin((st.x+time*sync)*freq)*0.5 + 0.5;
float b = sin((st.x+offset/freq+time*sync)*freq)*0.5 + 0.5;
return vec4(r, g, b, 1.0);
`
}
// The above code generates the glsl function:
`vec4 osc(vec2 _st, float freq, float sync, float offset){
vec2 st = _st;
float r = sin((st.x-offset*2/freq+time*sync)*freq)*0.5 + 0.5;
float g = sin((st.x+time*sync)*freq)*0.5 + 0.5;
float b = sin((st.x+offset/freq+time*sync)*freq)*0.5 + 0.5;
return vec4(r, g, b, 1.0);
}`
Types and default arguments for hydra functions.
The value in the 'type' field lets the parser know which type the function will be returned as well as default arguments.
const types = {
'src': {
returnType: 'vec4',
args: ['vec2 _st']
},
'coord': {
returnType: 'vec2',
args: ['vec2 _st']
},
'color': {
returnType: 'vec4',
args: ['vec4 _c0']
},
'combine': {
returnType: 'vec4',
args: ['vec4 _c0', 'vec4 _c1']
},
'combineCoord': {
returnType: 'vec2',
args: ['vec2 _st', 'vec4 _c0']
}
}
*/
module.exports = [
{
name: 'noise',
type: 'src',
inputs: [
{
type: 'float',
name: 'scale',
default: 10,
},
{
type: 'float',
name: 'offset',
default: 0.1,
}
],
glsl:
` return vec4(vec3(_noise(vec3(_st*scale, offset*time))), 1.0);`
},
{
name: 'voronoi',
type: 'src',
inputs: [
{
type: 'float',
name: 'scale',
default: 5,
},
{
type: 'float',
name: 'speed',
default: 0.3,
},
{
type: 'float',
name: 'blending',
default: 0.3,
}
],
glsl:
` vec3 color = vec3(.0);
// Scale
_st *= scale;
// Tile the space
vec2 i_st = floor(_st);
vec2 f_st = fract(_st);
float m_dist = 10.; // minimun distance
vec2 m_point; // minimum point
for (int j=-1; j<=1; j++ ) {
for (int i=-1; i<=1; i++ ) {
vec2 neighbor = vec2(float(i),float(j));
vec2 p = i_st + neighbor;
vec2 point = fract(sin(vec2(dot(p,vec2(127.1,311.7)),dot(p,vec2(269.5,183.3))))*43758.5453);
point = 0.5 + 0.5*sin(time*speed + 6.2831*point);
vec2 diff = neighbor + point - f_st;
float dist = length(diff);
if( dist < m_dist ) {
m_dist = dist;
m_point = point;
}
}
}
// Assign a color using the closest point position
color += dot(m_point,vec2(.3,.6));
color *= 1.0 - blending*m_dist;
return vec4(color, 1.0);`
},
{
name: 'osc',
type: 'src',
inputs: [
{
type: 'float',
name: 'frequency',
default: 60,
},
{
type: 'float',
name: 'sync',
default: 0.1,
},
{
type: 'float',
name: 'offset',
default: 0,
}
],
glsl:
` vec2 st = _st;
float r = sin((st.x-offset/frequency+time*sync)*frequency)*0.5 + 0.5;
float g = sin((st.x+time*sync)*frequency)*0.5 + 0.5;
float b = sin((st.x+offset/frequency+time*sync)*frequency)*0.5 + 0.5;
return vec4(r, g, b, 1.0);`
},
{
name: 'shape',
type: 'src',
inputs: [
{
type: 'float',
name: 'sides',
default: 3,
},
{
type: 'float',
name: 'radius',
default: 0.3,
},
{
type: 'float',
name: 'smoothing',
default: 0.01,
}
],
glsl:
` vec2 st = _st * 2. - 1.;
// Angle and radius from the current pixel
float a = atan(st.x,st.y)+3.1416;
float r = (2.*3.1416)/sides;
float d = cos(floor(.5+a/r)*r-a)*length(st);
return vec4(vec3(1.0-smoothstep(radius,radius + smoothing + 0.0000001,d)), 1.0);`
},
{
name: 'gradient',
type: 'src',
inputs: [
{
type: 'float',
name: 'speed',
default: 0,
}
],
glsl:
` return vec4(_st, sin(time*speed), 1.0);`
},
{
name: 'src',
type: 'src',
inputs: [
{
type: 'sampler2D',
name: 'tex',
default: NaN,
}
],
glsl:
` // vec2 uv = gl_FragCoord.xy/vec2(1280., 720.);
return texture2D(tex, fract(_st));`
},
{
name: 'solid',
type: 'src',
inputs: [
{
type: 'float',
name: 'r',
default: 0,
},
{
type: 'float',
name: 'g',
default: 0,
},
{
type: 'float',
name: 'b',
default: 0,
},
{
type: 'float',
name: 'a',
default: 1,
}
],
glsl:
` return vec4(r, g, b, a);`
},
{
name: 'rotate',
type: 'coord',
inputs: [
{
type: 'float',
name: 'angle',
default: 10,
},
{
type: 'float',
name: 'speed',
default: 0,
}
],
glsl:
` vec2 xy = _st - vec2(0.5);
float ang = angle + speed *time;
xy = mat2(cos(ang),-sin(ang), sin(ang),cos(ang))*xy;
xy += 0.5;
return xy;`
},
{
name: 'scale',
type: 'coord',
inputs: [
{
type: 'float',
name: 'amount',
default: 1.5,
},
{
type: 'float',
name: 'xMult',
default: 1,
},
{
type: 'float',
name: 'yMult',
default: 1,
},
{
type: 'float',
name: 'offsetX',
default: 0.5,
},
{
type: 'float',
name: 'offsetY',
default: 0.5,
}
],
glsl:
` vec2 xy = _st - vec2(offsetX, offsetY);
xy*=(1.0/vec2(amount*xMult, amount*yMult));
xy+=vec2(offsetX, offsetY);
return xy;
`
},
{
name: 'pixelate',
type: 'coord',
inputs: [
{
type: 'float',
name: 'pixelX',
default: 20,
},
{
type: 'float',
name: 'pixelY',
default: 20,
}
],
glsl:
` vec2 xy = vec2(pixelX, pixelY);
return (floor(_st * xy) + 0.5)/xy;`
},
{
name: 'posterize',
type: 'color',
inputs: [
{
type: 'float',
name: 'bins',
default: 3,
},
{
type: 'float',
name: 'gamma',
default: 0.6,
}
],
glsl:
` vec4 c2 = pow(_c0, vec4(gamma));
c2 *= vec4(bins);
c2 = floor(c2);
c2/= vec4(bins);
c2 = pow(c2, vec4(1.0/gamma));
return vec4(c2.xyz, _c0.a);`
},
{
name: 'shift',
type: 'color',
inputs: [
{
type: 'float',
name: 'r',
default: 0.5,
},
{
type: 'float',
name: 'g',
default: 0,
},
{
type: 'float',
name: 'b',
default: 0,
},
{
type: 'float',
name: 'a',
default: 0,
}
],
glsl:
` vec4 c2 = vec4(_c0);
c2.r = fract(c2.r + r);
c2.g = fract(c2.g + g);
c2.b = fract(c2.b + b);
c2.a = fract(c2.a + a);
return vec4(c2.rgba);`
},
{
name: 'repeat',
type: 'coord',
inputs: [
{
type: 'float',
name: 'repeatX',
default: 3,
},
{
type: 'float',
name: 'repeatY',
default: 3,
},
{
type: 'float',
name: 'offsetX',
default: 0,
},
{
type: 'float',
name: 'offsetY',
default: 0,
}
],
glsl:
` vec2 st = _st * vec2(repeatX, repeatY);
st.x += step(1., mod(st.y,2.0)) * offsetX;
st.y += step(1., mod(st.x,2.0)) * offsetY;
return fract(st);`
},
{
name: 'modulateRepeat',
type: 'combineCoord',
inputs: [
{
type: 'float',
name: 'repeatX',
default: 3,
},
{
type: 'float',
name: 'repeatY',
default: 3,
},
{
type: 'float',
name: 'offsetX',
default: 0.5,
},
{
type: 'float',
name: 'offsetY',
default: 0.5,
}
],
glsl:
` vec2 st = _st * vec2(repeatX, repeatY);
st.x += step(1., mod(st.y,2.0)) + _c0.r * offsetX;
st.y += step(1., mod(st.x,2.0)) + _c0.g * offsetY;
return fract(st);`
},
{
name: 'repeatX',
type: 'coord',
inputs: [
{
type: 'float',
name: 'reps',
default: 3,
},
{
type: 'float',
name: 'offset',
default: 0,
}
],
glsl:
` vec2 st = _st * vec2(reps, 1.0);
// float f = mod(_st.y,2.0);
st.y += step(1., mod(st.x,2.0))* offset;
return fract(st);`
},
{
name: 'modulateRepeatX',
type: 'combineCoord',
inputs: [
{
type: 'float',
name: 'reps',
default: 3,
},
{
type: 'float',
name: 'offset',
default: 0.5,
}
],
glsl:
` vec2 st = _st * vec2(reps, 1.0);
// float f = mod(_st.y,2.0);
st.y += step(1., mod(st.x,2.0)) + _c0.r * offset;
return fract(st);`
},
{
name: 'repeatY',
type: 'coord',
inputs: [
{
type: 'float',
name: 'reps',
default: 3,
},
{
type: 'float',
name: 'offset',
default: 0,
}
],
glsl:
` vec2 st = _st * vec2(1.0, reps);
// float f = mod(_st.y,2.0);
st.x += step(1., mod(st.y,2.0))* offset;
return fract(st);`
},
{
name: 'modulateRepeatY',
type: 'combineCoord',
inputs: [
{
type: 'float',
name: 'reps',
default: 3,
},
{
type: 'float',
name: 'offset',
default: 0.5,
}
],
glsl:
` vec2 st = _st * vec2(reps, 1.0);
// float f = mod(_st.y,2.0);
st.x += step(1., mod(st.y,2.0)) + _c0.r * offset;
return fract(st);`
},
{
name: 'kaleid',
type: 'coord',
inputs: [
{
type: 'float',
name: 'nSides',
default: 4,
}
],
glsl:
` vec2 st = _st;
st -= 0.5;
float r = length(st);
float a = atan(st.y, st.x);
float pi = 2.*3.1416;
a = mod(a,pi/nSides);
a = abs(a-pi/nSides/2.);
return r*vec2(cos(a), sin(a));`
},
{
name: 'modulateKaleid',
type: 'combineCoord',
inputs: [
{
type: 'float',
name: 'nSides',
default: 4,
}
],
glsl:
` vec2 st = _st - 0.5;
float r = length(st);
float a = atan(st.y, st.x);
float pi = 2.*3.1416;
a = mod(a,pi/nSides);
a = abs(a-pi/nSides/2.);
return (_c0.r+r)*vec2(cos(a), sin(a));`
},
{
name: 'scroll',
type: 'coord',
inputs: [
{
type: 'float',
name: 'scrollX',
default: 0.5,
},
{
type: 'float',
name: 'scrollY',
default: 0.5,
},
{
type: 'float',
name: 'speedX',
default: 0,
},
{
type: 'float',
name: 'speedY',
default: 0,
}
],
glsl:
`
_st.x += scrollX + time*speedX;
_st.y += scrollY + time*speedY;
return fract(_st);`
},
{
name: 'scrollX',
type: 'coord',
inputs: [
{
type: 'float',
name: 'scrollX',
default: 0.5,
},
{
type: 'float',
name: 'speed',
default: 0,
}
],
glsl:
` _st.x += scrollX + time*speed;
return fract(_st);`
},
{
name: 'modulateScrollX',
type: 'combineCoord',
inputs: [
{
type: 'float',
name: 'scrollX',
default: 0.5,
},
{
type: 'float',
name: 'speed',
default: 0,
}
],
glsl:
` _st.x += _c0.r*scrollX + time*speed;
return fract(_st);`
},
{
name: 'scrollY',
type: 'coord',
inputs: [
{
type: 'float',
name: 'scrollY',
default: 0.5,
},
{
type: 'float',
name: 'speed',
default: 0,
}
],
glsl:
` _st.y += scrollY + time*speed;
return fract(_st);`
},
{
name: 'modulateScrollY',
type: 'combineCoord',
inputs: [
{
type: 'float',
name: 'scrollY',
default: 0.5,
},
{
type: 'float',
name: 'speed',
default: 0,
}
],
glsl:
` _st.y += _c0.r*scrollY + time*speed;
return fract(_st);`
},
{
name: 'add',
type: 'combine',
inputs: [
{
type: 'float',
name: 'amount',
default: 1,
}
],
glsl:
` return (_c0+_c1)*amount + _c0*(1.0-amount);`
},
{
name: 'sub',
type: 'combine',
inputs: [
{
type: 'float',
name: 'amount',
default: 1,
}
],
glsl:
` return (_c0-_c1)*amount + _c0*(1.0-amount);`
},
{
name: 'layer',
type: 'combine',
inputs: [
],
glsl:
` return vec4(mix(_c0.rgb, _c1.rgb, _c1.a), clamp(_c0.a + _c1.a, 0.0, 1.0));`
},
{
name: 'blend',
type: 'combine',
inputs: [
{
type: 'float',
name: 'amount',
default: 0.5,
}
],
glsl:
` return _c0*(1.0-amount)+_c1*amount;`
},
{
name: 'mult',
type: 'combine',
inputs: [
{
type: 'float',
name: 'amount',
default: 1,
}
],
glsl:
` return _c0*(1.0-amount)+(_c0*_c1)*amount;`
},
{
name: 'diff',
type: 'combine',
inputs: [
],
glsl:
` return vec4(abs(_c0.rgb-_c1.rgb), max(_c0.a, _c1.a));`
},
{
name: 'modulate',
type: 'combineCoord',
inputs: [
{
type: 'float',
name: 'amount',
default: 0.1,
}
],
glsl:
` // return fract(st+(_c0.xy-0.5)*amount);
return _st + _c0.xy*amount;`
},
{
name: 'modulateScale',
type: 'combineCoord',
inputs: [
{
type: 'float',
name: 'multiple',
default: 1,
},
{
type: 'float',
name: 'offset',
default: 1,
}
],
glsl:
` vec2 xy = _st - vec2(0.5);
xy*=(1.0/vec2(offset + multiple*_c0.r, offset + multiple*_c0.g));
xy+=vec2(0.5);
return xy;`
},
{
name: 'modulatePixelate',
type: 'combineCoord',
inputs: [
{
type: 'float',
name: 'multiple',
default: 10,
},
{
type: 'float',
name: 'offset',
default: 3,
}
],
glsl:
` vec2 xy = vec2(offset + _c0.x*multiple, offset + _c0.y*multiple);
return (floor(_st * xy) + 0.5)/xy;`
},
{
name: 'modulateRotate',
type: 'combineCoord',
inputs: [
{
type: 'float',
name: 'multiple',
default: 1,
},
{
type: 'float',
name: 'offset',
default: 0,
}
],
glsl:
` vec2 xy = _st - vec2(0.5);
float angle = offset + _c0.x * multiple;
xy = mat2(cos(angle),-sin(angle), sin(angle),cos(angle))*xy;
xy += 0.5;
return xy;`
},
{
name: 'modulateHue',
type: 'combineCoord',
inputs: [
{
type: 'float',
name: 'amount',
default: 1,
}
],
glsl:
` return _st + (vec2(_c0.g - _c0.r, _c0.b - _c0.g) * amount * 1.0/resolution);`
},
{
name: 'invert',
type: 'color',
inputs: [
{
type: 'float',
name: 'amount',
default: 1,
}
],
glsl:
` return vec4((1.0-_c0.rgb)*amount + _c0.rgb*(1.0-amount), _c0.a);`
},
{
name: 'contrast',
type: 'color',
inputs: [
{
type: 'float',
name: 'amount',
default: 1.6,
}
],
glsl:
` vec4 c = (_c0-vec4(0.5))*vec4(amount) + vec4(0.5);
return vec4(c.rgb, _c0.a);`
},
{
name: 'brightness',
type: 'color',
inputs: [
{
type: 'float',
name: 'amount',
default: 0.4,
}
],
glsl:
` return vec4(_c0.rgb + vec3(amount), _c0.a);`
},
{
name: 'mask',
type: 'combine',
inputs: [
],
glsl:
` float a = _luminance(_c1.rgb);
return vec4(_c0.rgb*a, a*_c0.a);`
},
{
name: 'luma',
type: 'color',
inputs: [
{
type: 'float',
name: 'threshold',
default: 0.5,
},
{
type: 'float',
name: 'tolerance',
default: 0.1,
}
],
glsl:
` float a = smoothstep(threshold-(tolerance+0.0000001), threshold+(tolerance+0.0000001), _luminance(_c0.rgb));
return vec4(_c0.rgb*a, a);`
},
{
name: 'thresh',
type: 'color',
inputs: [
{
type: 'float',
name: 'threshold',
default: 0.5,
},
{
type: 'float',
name: 'tolerance',
default: 0.04,
}
],
glsl:
` return vec4(vec3(smoothstep(threshold-(tolerance+0.0000001), threshold+(tolerance+0.0000001), _luminance(_c0.rgb))), _c0.a);`
},
{
name: 'color',
type: 'color',
inputs: [
{
type: 'float',
name: 'r',
default: 1,
},
{
type: 'float',
name: 'g',
default: 1,
},
{
type: 'float',
name: 'b',
default: 1,
},
{
type: 'float',
name: 'a',
default: 1,
}
],
glsl:
` vec4 c = vec4(r, g, b, a);
vec4 pos = step(0.0, c); // detect whether negative
// if > 0, return r * _c0
// if < 0 return (1.0-r) * _c0
return vec4(mix((1.0-_c0)*abs(c), c*_c0, pos));`
},
{
name: 'saturate',
type: 'color',
inputs: [
{
type: 'float',
name: 'amount',
default: 2,
}
],
glsl:
` const vec3 W = vec3(0.2125, 0.7154, 0.0721);
vec3 intensity = vec3(dot(_c0.rgb, W));
return vec4(mix(intensity, _c0.rgb, amount), _c0.a);`
},
{
name: 'hue',
type: 'color',
inputs: [
{
type: 'float',
name: 'hue',
default: 0.4,
}
],
glsl:
` vec3 c = _rgbToHsv(_c0.rgb);
c.r += hue;
// c.r = fract(c.r);
return vec4(_hsvToRgb(c), _c0.a);`
},
{
name: 'colorama',
type: 'color',
inputs: [
{
type: 'float',
name: 'amount',
default: 0.005,
}
],
glsl:
` vec3 c = _rgbToHsv(_c0.rgb);
c += vec3(amount);
c = _hsvToRgb(c);
c = fract(c);
return vec4(c, _c0.a);`
},
{
name: 'prev',
type: 'src',
inputs: [
],
glsl:
` return texture2D(prevBuffer, fract(_st));`
},
{
name: 'sum',
type: 'color',
inputs: [
{
type: 'vec4',
name: 'scale',
default: 1,
}
],
glsl:
` vec4 v = _c0 * s;
return v.r + v.g + v.b + v.a;
}
float sum(vec2 _st, vec4 s) { // vec4 is not a typo, because argument type is not overloaded
vec2 v = _st.xy * s.xy;
return v.x + v.y;`
},
{
name: 'r',
type: 'color',
inputs: [
{
type: 'float',
name: 'scale',
default: 1,
},
{
type: 'float',
name: 'offset',
default: 0,
}
],
glsl:
` return vec4(_c0.r * scale + offset);`
},
{
name: 'g',
type: 'color',
inputs: [
{
type: 'float',
name: 'scale',
default: 1,
},
{
type: 'float',
name: 'offset',
default: 0,
}
],
glsl:
` return vec4(_c0.g * scale + offset);`
},
{
name: 'b',
type: 'color',
inputs: [
{
type: 'float',
name: 'scale',
default: 1,
},
{
type: 'float',
name: 'offset',
default: 0,
}
],
glsl:
` return vec4(_c0.b * scale + offset);`
},
{
name: 'a',
type: 'color',
inputs: [
{
type: 'float',
name: 'scale',
default: 1,
},
{
type: 'float',
name: 'offset',
default: 0,
}
],
glsl:
` return vec4(_c0.a * scale + offset);`
}
]
},{}],244:[function(require,module,exports){
const log = require('./log.js').log
module.exports = {
eval: (arg, callback) => {
var self = this
// wrap everything in an async function
var jsString = `(async() => {
${arg}
})().catch(${(err) => log(err.message, "log-error")})`
var isError = false
try {
eval(jsString)
// log(jsString)
log('')
} catch (e) {
isError = true
console.log("logging", e)
// var err = e.constructor('Error in Evaled Script: ' + e.message);
// console.log(err.lineNumber)
log(e.message, "log-error")
//console.log('ERROR', JSON.stringify(e))
}
// console.log('callback is', callback)
if(callback) callback(jsString, isError)
}
}
},{"./log.js":240}],245:[function(require,module,exports){
const html = require('choo/html')
const raw = require('choo/html/raw')
const toolbar = require('./toolbar.js')
const link = (url) => `href=${url} target=_blank`
module.exports = function mainView(state, emit) {
const { t, languages } = state.translation
const textDirection = state.translation.selectedLanguage === 'ar' && state.showInfo === true ? 'rtl': 'ltr'
const langArray = Object.entries(languages)
return html`
<div id="info-container" class="${state.showInfo ? "" : "hidden"}" style="direction:${textDirection}">
<div id="modal">
<div id="modal-header" style="opacity:${state.showUI === true? 1: 0}">
${state.showInfo && langArray.length > 1 ? html`<div style="display:flex;flex-wrap:wrap">${langArray.map(([key, val]) => html`
<div class="language-select" onclick=${() => emit('set language', key)}>${val}</div>
`)}</div>` : html`<div></div>` }
${toolbar(state, emit)}
</div>
<div id="modal-body">
<div id="modal-content">
<h1>${t('info.title')}</h1>
<h3>${t('info.subtitle')}</h3>
<br> ///////////////////////////////////////////////////////////<br>
<h4>${t('info.description')}</h4>
<h4>${t('info.get-started-title')}<ol>
<li>${t('info.get-started-list.0')}</li>
<li>${t('info.get-started-list.1')}</li>
<li>${t('info.get-started-list.2')}</li>
</ol>
</h4>
<p> ///////////////////////////////////////////////////////////<br><br><br>
${t('info.description-detailed')}
</p>
<p>${t('info.uses')}<ul>
${t('info.uses-list', { returnObjects: true }).map((text) => html`<li>${text}</li>`)}
</ul></p>
<p class="align-right">${raw(t('info.author', { author: `href=https://ojack.xyz class=olivia target=_blank`}))}</p>
<p>${raw(t('info.more-info', {
docs: link("https://hydra.ojack.xyz/docs"),
functions: link("https://hydra.ojack.xyz/api"),
gallery: link("https://twitter.com/hydra_patterns"),
repo: link("https://github.com/hydra-synth/hydra"),
pixeljam: link("http://pixeljam.glitch.me/"),
garden: link("https://hydra.ojack.xyz/garden"),
'hydra-book': link("https://hydra-book.glitch.me/"),
"tutorials": link("https://github.com/ojack/hydra/blob/master/examples/README.md")
}))}</p>
<p>${raw(t('info.more-info-forums', {
discord: link("https://discord.gg/ZQjfHkNHXC"),
facebook: link("https://www.facebook.com/groups/1084288351771117/")
}))}</p>
<p>${raw(t('info.support', {
"open-collective": link("https://opencollective.com/hydra-synth")
}))}</p>
</div>
</div>
</div>
</div>
`
}
// <!---<p>${t('info.features')}<ul>
// ${t('info.features-list', { returnObjects: true }).map((text) => html`<li>${text}</li>`)}
// </ul></p>--->
// module.exports = function mainView(state, emit) {
// return html`
// <div id="info-container" class="${state.showInfo ? "" : "hidden"}">
// <div id="modal">
// <div id="modal-header" style="opacity:${state.showUI === true? 1: 0}">
// <div><!--<i class="fas fa-bars icon"></i>--></div>
// ${toolbar(state, emit)}
// </div>
// <div id="modal-body">
// <div id="modal-content">
// <h1> hydra</h1>
// <h3> live coding networked visuals </h3>
// <br> ///////////////////////////////////////////////////////////<br>
// <h4> Hydra is a platform for live coding visuals, in which each connected browser window can be used as a node of a modular and distributed video synthesizer.</h4>
// <h4> To get started: <ol>
// <li>Close this window </li>
// <li>Change some numbers </li>
// <li>Type Ctrl + Shift + Enter </li>
// </ol>
// </h4>
// <p> ///////////////////////////////////////////////////////////<br><br><br>Built using WebRTC (peer-to-peer web streaming) and WebGL, hydra allows each connected browser/device/person to output a video signal or stream, and receive and modify streams from other browsers/devices/people. The API is inspired by analog modular synthesis, in which multiple visual sources (oscillators, cameras, application windows, other connected windows) can be transformed, modulated, and composited via combining sequences of functions. </p>
// <p>Features: <ul>
// <li>Written in javascript and compatible with other javascript libraries</li>
// <li>Available as a platform as well as a set of standalone modules </li>
// <li>Cross-platform and requires no installation (runs in the browser)</li>
// <li>Also available as a package for live coding from within atom text editor</li>
// <li>Experimental and forever evolving !! </li>
// </ul>
// <p class="align-right"> Created by <a class="olivia" href="https://twitter.com/_ojack_" target="_blank">olivia.</a> </p>
// <p> For more information and instructions, see:
// <a href="https://github.com/ojack/hydra#Getting-Started" target="_blank">the documentation on github</a>,
// <a href="https://ojack.xyz/hydra-functions/" target="_blank">a list of hydra functions</a>,
// <!-- <a href="https://github.com/ojack/hydra/blob/master/docs/funcs.md" target="_blank">documentation</a>, -->
// <a href="https://twitter.com/hydra_patterns" target="_blank">a gallery of user-generated sketches</a>,
// <a href="http://pixeljam.glitch.me/" target="_blank">PIXELJAM collaborative editor</a>,
// <a href="https://hydra-book.naotohieda.com/#/" target="_blank">Hydra Book</a>, and more <a href="https://github.com/ojack/hydra/blob/master/examples/README.md">tutorials and examples.</a></p>
// <p>There is also an active <a href="https://discord.gg/ZQjfHkNHXC" target="_blank">Discord server</a> and <a href="https://www.facebook.com/groups/1084288351771117/" target="_blank">facebook group</a> for hydra users+contributors.</p>
// <p> If you enjoy using Hydra, please consider <a href="https://opencollective.com/hydra-synth" target="_blank">supporting continued development ${'<3 <3'} </a></p>
// </div>
// </div>
// </div>
// </div>
// `
// }
},{"./toolbar.js":247,"choo/html":49,"choo/html/raw":50}],246:[function(require,module,exports){
const html = require('choo/html')
const info = require('./info.js')
const Hydra = require('./Hydra.js')
const Editor = require('./EditorComponent.js')
module.exports = function mainView(state, emit) {
return html`
<body>
<div id="hydra-ui">
${state.cache(Hydra, 'hydra-canvas').render(state, emit)}
<!---<canvas id="audio-canvas">
</canvas>--->
</div>
${info(state, emit)}
${state.cache(Editor, 'editor').render(state, emit)}
</body>
`
}
},{"./EditorComponent.js":236,"./Hydra.js":237,"./info.js":245,"choo/html":49}],247:[function(require,module,exports){
const html = require('choo/html')
module.exports = function toolbar(state, emit) {
const hidden = state.showInfo ? 'hidden' : ''
const { t } = state.translation
const dispatch = (eventName) => (e) => emit(eventName, e)
const icon = (id, className, title, event) => html`
<i id="${id}-icon" class="fas icon ${className}" title="${title}" onclick=${dispatch(event)} aria-hidden="true"></i>`
const toggleInfo = state.showInfo ? icon("close", "fa-times", t('toolbar.hide-info'), 'toggle info') : icon("close", "fa-question-circle", t('toolbar.show-info'), 'toggle info')
return html`<div id="toolbar-container">
${icon("run", `fa-play-circle ${hidden}`, t('toolbar.run'), 'editor:evalAll')}
${icon("clear", `fa fa-trash ${hidden}`, t('toolbar.clear'), 'editor:clearAll')}
${icon("shuffle", `fa-random`, t('toolbar.shuffle'), 'gallery:showExample')}
${icon("mutator", `fa-dice ${hidden}`, t('toolbar.random'), 'editor:randomize')}
${state.serverURL === null ? '' : icon("share", `fa-upload ${hidden}`, t('toolbar.upload'), 'gallery:shareSketch')}
${toggleInfo}
</div>`
// ${icon("share", `fa-upload ${hidden}`, t('toolbar.upload'), 'gallery:shareSketch')}
}
},{"choo/html":49}]},{},[1]);