Files
hydra/frontend/web-editor/public/bundle.js
2022-02-11 16:30:40 +01:00

28708 lines
1.1 MiB

(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/store.js')
const mainView = require('./src/views/main.js')
const app = choo()
app.use(devtools())
app.use(store)
app.route('/', mainView)
app.mount('body')
},{"./src/store.js":111,"./src/views/main.js":121,"choo":22,"choo-devtools":9}],2:[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';
// 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
// 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.
// Generated by `bin/generate-identifier-regex.js`.
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";
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\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-\u0ecd\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";
var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
// 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. They were
// generated by bin/generate-identifier-regex.js
// eslint-disable-next-line comma-spacing
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,85,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,190,0,80,921,103,110,18,195,2637,96,16,1070,4050,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,46,2,18,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,482,44,11,6,17,0,322,29,19,43,1269,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,4152,8,221,3,5761,15,7472,3104,541,1507,4938];
// eslint-disable-next-line comma-spacing
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,154,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,161,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,19306,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,262,6,10,9,357,0,62,13,1495,6,110,6,6,9,4759,9,787719,239];
// 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 }
}
}
// 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, "|") + ")$")
}
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), 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.
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 (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) {
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");
};
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, "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 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral
if (context) { return false }
if (nextCh === 123) { return true } // '{'
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.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.parseBindingAtom();
var simple = clause.param.type === "Identifier";
this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
this.expect(types$1.parenR);
} 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) {
this.next();
this.parseVar(node, false, kind);
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) {
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 (kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
this.unexpected();
} else if (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.raise(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(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.parseExport = function(node, exports) {
this.next();
// export * from '...'
if (this.eat(types$1.star)) {
if (this.options.ecmaVersion >= 11) {
if (this.eatContextual("as")) {
node.exported = this.parseModuleExportName();
this.checkExport(exports, node.exported.name, 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")
}
if (this.eat(types$1._default)) { // export default ...
this.checkExport(exports, "default", this.lastTokStart);
var isAsync;
if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
var fNode = this.startNode();
this.next();
if (isAsync) { this.next(); }
node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
} else if (this.type === types$1._class) {
var cNode = this.startNode();
node.declaration = this.parseClass(cNode, "nullableID");
} else {
node.declaration = this.parseMaybeAssign();
this.semicolon();
}
return this.finishNode(node, "ExportDefaultDeclaration")
}
// export var|const|let|function|class ...
if (this.shouldParseExportStatement()) {
node.declaration = this.parseStatement(null);
if (node.declaration.type === "VariableDeclaration")
{ this.checkVariableExport(exports, node.declaration.declarations); }
else
{ this.checkExport(exports, node.declaration.id.name, 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.checkExport = function(exports, name, pos) {
if (!exports) { return }
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.name, 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.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; }
var node = this.startNode();
node.local = this.parseModuleExportName();
node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
this.checkExport(
exports,
node.exported[node.exported.type === "Identifier" ? "name" : "value"],
node.exported.start
);
nodes.push(this.finishNode(node, "ExportSpecifier"));
}
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.parseImportSpecifiers = function() {
var nodes = [], first = true;
if (this.type === types$1.name) {
// import defaultObj, { x, y as z } from '...'
var node = this.startNode();
node.local = this.parseIdent();
this.checkLValSimple(node.local, BIND_LEXICAL);
nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
if (!this.eat(types$1.comma)) { return nodes }
}
if (this.type === types$1.star) {
var node$1 = this.startNode();
this.next();
this.expectContextual("as");
node$1.local = this.parseIdent();
this.checkLValSimple(node$1.local, BIND_LEXICAL);
nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
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; }
var node$2 = this.startNode();
node$2.imported = this.parseModuleExportName();
if (this.eatContextual("as")) {
node$2.local = this.parseIdent();
} else {
this.checkUnreserved(node$2.imported);
node$2.local = node$2.imported;
}
this.checkLValSimple(node$2.local, BIND_LEXICAL);
nodes.push(this.finishNode(node$2, "ImportSpecifier"));
}
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 (
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) {
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.raise(this.start, "Comma is not permitted after the rest element"); }
this.expect(close);
break
} else {
var elem = this.parseMaybeDefault(this.start, this.startLoc);
this.parseBindingListItem(elem);
elts.push(elem);
}
}
return elts
};
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
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 case when token context could not be inferred correctly in tokenize 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
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.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.canInsertSemicolon() && this.eat(types$1.arrow)) {
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.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, 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) {
// 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()
} else {
return this.unexpected()
}
default:
this.unexpected();
}
};
pp$5.parseExprImport = function() {
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);
switch (this.type) {
case types$1.parenL:
return this.parseDynamicImport(node)
case types$1.dot:
node.meta = meta;
return this.parseImportMeta(node)
default:
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.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.raise(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.canInsertSemicolon() && 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, isImport = this.type === types$1._import;
node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false);
if (isImport && node.callee.type === "ImportExpression") {
this.raise(startPos, "Cannot use new with import()");
}
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.raise(this.start, "Comma is not permitted after the rest element");
}
return this.finishNode(prop, "RestElement")
}
// To disallow parenthesized identifier via `this.toAssignable()`.
if (this.type === types$1.parenL && refDestructuringErrors) {
if (refDestructuringErrors.parenthesizedAssign < 0) {
refDestructuringErrors.parenthesizedAssign = this.start;
}
if (refDestructuringErrors.parenthesizedBind < 0) {
refDestructuringErrors.parenthesizedBind = this.start;
}
}
// 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, refDestructuringErrors);
} else {
isAsync = false;
}
this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
return this.finishNode(prop, "Property")
};
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(); }
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"); }
}
} 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, isBinding) {
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();
}
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.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 unicodeBinaryProperties = {
9: ecma9BinaryProperties,
10: ecma10BinaryProperties,
11: ecma11BinaryProperties,
12: ecma12BinaryProperties,
13: ecma13BinaryProperties
};
// #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 unicodeScriptValues = {
9: ecma9ScriptValues,
10: ecma10ScriptValues,
11: ecma11ScriptValues,
12: ecma12ScriptValues,
13: ecma13ScriptValues
};
var data = {};
function buildUnicodeData(ecmaVersion) {
var d = data[ecmaVersion] = {
binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
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]; 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" : "");
this.unicodeProperties = data[parser.options.ecmaVersion >= 13 ? 13 : parser.options.ecmaVersion];
this.source = "";
this.flags = "";
this.start = 0;
this.switchU = 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 unicode = flags.indexOf("u") !== -1;
this.start = start | 0;
this.source = pattern + "";
this.flags = flags;
this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
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
};
function codePointToString$1(ch) {
if (ch <= 0xFFFF) { return String.fromCharCode(ch) }
ch -= 0x10000;
return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00)
}
/**
* 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;
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");
}
}
};
/**
* 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$1(state.lastIntValue);
while (this.regexp_eatRegExpIdentifierPart(state)) {
state.lastStringValue += codePointToString$1(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
};
// 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 true
}
if (
state.switchU &&
this.options.ecmaVersion >= 9 &&
(ch === 0x50 /* P */ || ch === 0x70 /* p */)
) {
state.lastIntValue = -1;
state.advance();
if (
state.eat(0x7B /* { */) &&
this.regexp_eatUnicodePropertyValueExpression(state) &&
state.eat(0x7D /* } */)
) {
return true
}
state.raise("Invalid property name");
}
return false
};
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 true
}
}
state.pos = start;
// LoneUnicodePropertyNameOrValue
if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
var nameOrValue = state.lastStringValue;
this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
return true
}
return false
};
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))
{ 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$1(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$1(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 /* [ */)) {
state.eat(0x5E /* ^ */);
this.regexp_classRanges(state);
if (state.eat(0x5D /* ] */)) {
return true
}
// Unreachable since it threw "unterminated regular expression" error before.
state.raise("Unterminated character class");
}
return false
};
// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
// 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_classRanges = 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://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
};
function codePointToString(code) {
// UTF-16 Decoding
if (code <= 0xFFFF) { return String.fromCharCode(code) }
code -= 0x10000;
return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
}
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"
);
return null
}
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.
var version = "8.7.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;
Object.defineProperty(exports, '__esModule', { value: true });
}));
},{}],3:[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":4,"./defaultTraveler":5}],4:[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":5}],5:[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);
}
};
});
},{}],6:[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 = {
'||': 3,
'&&': 4,
'|': 5,
'??': 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 (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 ');
}
this[node.key.type](node.key, state);
state.write(' = ');
this[node.value.type](node.value, state);
},
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;
}
},{}],7:[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;
};
},{"./":8,"get-intrinsic":36}],8:[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":35,"get-intrinsic":36}],9:[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":10,"./lib/debug":11,"./lib/help":12,"./lib/log":13,"./lib/logger":14,"./lib/perf":15,"./lib/storage":16,"events":130,"wayfarer/get-all-routes":106}],10:[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":89,"state-copy":99}],11:[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":123,"nanologger":75,"object-change-callsite":85}],12:[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 () {}
},{}],13:[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":24,"nanologger":75,"nanoscheduler":83,"remove-array-items":17}],14:[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":18,"nanologger":75,"nanoscheduler":83}],15:[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":88}],16:[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":90}],17:[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;
},{}],18:[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":123,"nanoscheduler":83,"on-performance":88}],19:[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":64,"nanolru":76}],20:[function(require,module,exports){
module.exports = require('nanocomponent')
},{"nanocomponent":66}],21:[function(require,module,exports){
module.exports = require('nanohtml')
},{"nanohtml":71}],22:[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":19,"assert":64,"document-ready":32,"nanobus":65,"nanohref":68,"nanomorph":77,"nanoquery":80,"nanoraf":81,"nanorouter":82,"nanotiming":84,"scroll-to-anchor":97}],23:[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'))
}
},{}],24:[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":129}],25:[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(w);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={},w=/[^\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),u=null==a.padding?" ":a.padding,k=a.commentBlankLines||c.line==d.line;b.operation(function(){if(a.indent){for(var p=null,h=c.line;h<m;++h){var q=b.getLine(h);q=q.slice(0,I(q));if(null==p||p.length>q.length)p=q}for(h=c.line;h<m;++h){q=b.getLine(h);var t=p.length;if(k||w.test(q))q.slice(0,t)!=p&&(t=I(q)),b.replaceRange(p+f+u,l(h,0),l(h,t))}}else for(h=c.line;h<m;++h)(k||w.test(b.getLine(h)))&&b.replaceRange(f+u,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&&w.test(b.getLine(m))&&--m;var u=null==a.padding?" ":a.padding;c.line>m||b.operation(function(){if(0!=
a.fullLines){var k=w.test(b.getLine(m));b.replaceRange(u+f,l(m));b.replaceRange(g+u,l(c.line,0));var p=a.blockCommentLead||e.blockCommentLead;if(null!=p)for(var h=c.line+1;h<=m;++h)(h!=m||k)&&b.replaceRange(p+u,l(h,0))}else k=0==K(b.getCursor("to"),d),p=!b.somethingSelected(),b.replaceRange(f,d),k&&b.setSelection(p?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,u=[],k=null==a.padding?" ":a.padding,p;a:if(m){for(var h=f;h<=g;++h){var q=b.getLine(h),t=q.indexOf(m);-1<t&&!/comment/.test(b.getTokenTypeAt(l(h,t+1)))&&(t=-1);if(-1==t&&w.test(q))break a;if(-1<t&&w.test(q.slice(0,t)))break a;u.push(q)}b.operation(function(){for(var n=f;n<=g;++n){var A=u[n-f],x=A.indexOf(m),v=x+m.length;0>x||(A.slice(v,v+k.length)==k&&(v+=k.length),p=!0,b.replaceRange("",l(n,x),l(n,v)))}});if(p)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 n=D+y.length;k&&C.slice(n,n+k.length)==k&&(n+=k.length);b.replaceRange("",l(f,D),l(f,n));if(H)for(n=f+1;n<=g;++n){var A=b.getLine(n),x=A.indexOf(H);if(-1!=x&&!w.test(A.slice(0,x))){var v=x+H.length;k&&A.slice(v,v+k.length)==k&&(v+=k.length);b.replaceRange("",l(n,x),l(n,v))}}});return!0})});
},{"../../lib/codemirror":29}],26:[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":29}],27:[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 J(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],l="CodeMirror-hint"+(g!=this.selectedHint?"":" CodeMirror-hint-active");null!=k.className&&(l=k.className+" "+l);m.className=l;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}l=a.options.container||e.body;g=d.cursorCoords(a.options.alignWithWord?b.from:null);var v=g.left,w=g.bottom,E=!0,q=m=0;if(l!==e.body){k=-1!==["absolute","relative","fixed"].indexOf(p.getComputedStyle(l).position)?l:l.offsetParent;var t=k.getBoundingClientRect();q=e.body.getBoundingClientRect();m=t.left-q.left-k.scrollLeft;q=t.top-q.top-k.scrollTop}f.style.left=
v-m+"px";f.style.top=w-q+"px";k=p.innerWidth||Math.max(e.body.offsetWidth,e.documentElement.offsetWidth);var y=p.innerHeight||Math.max(e.body.offsetHeight,e.documentElement.offsetHeight);l.appendChild(f);d.getInputField().setAttribute("aria-autocomplete","list");d.getInputField().setAttribute("aria-owns",this.id);d.getInputField().setAttribute("aria-activedescendant",this.id+"-"+this.selectedHint);l=a.options.moveOnOverlap?f.getBoundingClientRect():new DOMRect;t=a.options.paddingForScrollbar?f.scrollHeight>
f.clientHeight+1:!1;var u;setTimeout(function(){u=d.getScrollInfo()});if(0<l.bottom-y){var z=l.bottom-l.top;0<g.top-(g.bottom-l.top)-z?(f.style.top=(w=g.top-z-q)+"px",E=!1):z>y&&(f.style.height=y-5+"px",f.style.top=(w=g.bottom-l.top-q)+"px",q=d.getCursor(),b.from.ch!=q.ch&&(g=d.cursorCoords(q),f.style.left=(v=g.left-m)+"px",l=f.getBoundingClientRect()))}q=l.right-k;t&&(q+=d.display.nativeBarWidth);0<q&&(l.right-l.left>k&&(f.style.width=k-5+"px",q-=l.right-l.left-k),f.style.left=(v=g.left-q-m)+"px");
if(t)for(g=f.firstChild;g;g=g.nextSibling)g.style.paddingRight=d.display.nativeBarWidth+"px";d.addKeyMap(this.keyMap=J(a,{moveFocus:function(n,x){c.changeActive(c.selectedHint+n,x)},setFocus:function(n){c.changeActive(n)},menuSize:function(){return c.screenAmount()},length:r.length,close:function(){a.close()},pick:function(){c.pick()},data:b}));if(a.options.closeOnUnfocus){var F;d.on("blur",this.onBlur=function(){F=setTimeout(function(){a.close()},100)});d.on("focus",this.onFocus=function(){clearTimeout(F)})}d.on("scroll",
this.onScroll=function(){var n=d.getScrollInfo(),x=d.getWrapperElement().getBoundingClientRect();u||(u=d.getScrollInfo());var G=w+u.top-n.top,A=G-(p.pageYOffset||(e.documentElement||e.body).scrollTop);E||(A+=f.offsetHeight);if(A<=x.top||A>=x.bottom)return a.close();f.style.top=G+"px";f.style.left=v+u.left-n.left+"px"});h.on(f,"dblclick",function(n){(n=C(f,n.target||n.srcElement))&&null!=n.hintId&&(c.changeActive(n.hintId),c.pick())});h.on(f,"click",function(n){(n=C(f,n.target||n.srcElement))&&null!=
n.hintId&&(c.changeActive(n.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 K(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 H(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 I)d[e]=I[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 L=window.requestAnimationFrame||function(a){return setTimeout(a,1E3/60)},M=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&&(M(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=L(function(){d.update()});
this.widget&&this.widget.disable()}},update:function(a){if(null!=this.tick){var b=this,c=++this.tick;H(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);
H(g[m],e,f,function(k){k&&0<k.list.length?p(k):r(m+1)})}var g=K(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 I={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":29}],28:[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":29}],29:[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(){try{var a=document.activeElement}catch(b){a=document.body||null}for(;a&&a.shadowRoot&&a.shadowRoot.activeElement;)a=a.shadowRoot.activeElement;return a}function Wa(a,b){var d=a.className;y(b).test(d)||
(a.className+=(d?" ":"")+b)}function ed(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 fd(a){var b=Array.prototype.slice.call(arguments,1);return function(){return a.apply(null,b)}}function Xa(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 va(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 gd(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 hd(a){for(;tc.length<=a;)tc.push(J(tc)+" ");return tc[a]}function J(a){return a[a.length-1]}function uc(a,b){for(var d=[],c=0;c<a.length;c++)d[c]=b(a[c],c);return d}function wg(a,b,d){for(var c=0,e=d(b);c<a.length&&
d(a[c])<=e;)c++;a.splice(c,0,b)}function oe(){}function pe(a,b){Object.create?a=Object.create(a):(oe.prototype=a,a=new oe);b&&Xa(b,a);return a}function id(a){return/\w/.test(a)||"\u0080"<a&&(a.toUpperCase()!=a.toLowerCase()||xg.test(a))}function vc(a,b){return b?-1<b.source.indexOf("\\w")&&id(a)?!0:b.test(a):id(a)}function qe(a){for(var b in a)if(a.hasOwnProperty(b)&&a[b])return!1;return!0}function jd(a){return 768<=a.charCodeAt(0)&&yg.test(a)}function re(a,b,d){for(;(0>d?0<b:b<a.length)&&jd(a.charAt(b));)b+=
d;return b}function Hb(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 zg(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 Ib(a,b,d){var c;Jb=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:Jb=e);f.from==b&&(f.from!=f.to&&"before"!=d?c=e:Jb=e)}return null!=c?c:Jb}function Ia(a,b){var d=a.order;null==d&&(d=a.order=Ag(a.text,b));return d}function sa(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]||wc;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 kd(b)||b.codemirrorIgnore}function se(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 wa(a,b){return 0<(a._handlers&&a._handlers[b]||wc).length}function nb(a){a.prototype.on=function(b,d){z(this,b,d)};a.prototype.off=function(b,
d){sa(this,b,d)}}function la(a){a.preventDefault?a.preventDefault():a.returnValue=!1}function te(a){a.stopPropagation?a.stopPropagation():a.cancelBubble=!0}function kd(a){return null!=a.defaultPrevented?a.defaultPrevented:0==a.returnValue}function Kb(a){la(a);te(a)}function ue(a){var b=a.which;null==b&&(a.button&1?b=1:a.button&2?b=3:a.button&4&&(b=2));xa&&a.ctrlKey&&1==b&&(b=3);return b}function Bg(a,b){2<arguments.length&&(b.dependencies=Array.prototype.slice.call(arguments,2));ld[a]=b}function xc(a){if("string"==
typeof a&&ob.hasOwnProperty(a))a=ob[a];else if(a&&"string"==typeof a.name&&ob.hasOwnProperty(a.name)){var b=ob[a.name];"string"==typeof b&&(b={name:b});a=pe(b,a);a.name=b.name}else{if("string"==typeof a&&/^[\w\-]+\/[\w\-]+\+xml$/.test(a))return xc("application/xml");if("string"==typeof a&&/^[\w\-]+\/[\w\-]+\+json$/.test(a))return xc("application/json")}return"string"==typeof a?{name:a}:a||{name:"null"}}function md(a,b){b=xc(b);var d=ld[b.name];if(!d)return md(a,"text/plain");a=d(a,b);if(pb.hasOwnProperty(b.name)){d=
pb[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 Cg(a,b){a=pb.hasOwnProperty(a)?pb[a]:pb[a]={};Xa(b,a)}function Ya(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 nd(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 ve(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 Za(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 od(a,b,d){var c=[];a.iter(b,d,function(e){c.push(e.text)});return c}function Ca(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 $a(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 Lb(a,b){return b>=a.first&&b<a.first+a.size}function pd(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 qd(a,b){return a.sticky==b.sticky&&0==B(a,b)}function rd(a){return t(a.line,a.ch)}function yc(a,b){return 0>B(a,b)?b:a}
function zc(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 we(a,b){for(var d=[],c=0;c<b.length;c++)d[c]=C(a,b[c]);return d}function xe(a,b,d,c){var e=[a.state.modeGen],f={};ye(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;ye(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 ze(a,b,d){if(!b.styles||b.styles[0]!=a.state.modeGen){var c=Mb(a,N(b)),e=b.text.length>a.options.maxHighlightLength&&
Ya(a.doc.mode,c.state),f=xe(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 Mb(a,b,d){var c=a.doc,e=a.display;if(!c.mode.startState)return new Da(c,!0,b);var f=Dg(a,b,d),g=f>c.first&&w(c,f-1).stateAfter,h=g?Da.fromSaved(c,g,f):new Da(c,ve(c.mode),f);c.iter(f,b,function(k){sd(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 sd(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&&Ae(e,d.state);!a.eol();)td(e,a,d.state),a.start=a.pos}function Ae(a,b){if(a.blankLine)return a.blankLine(b);if(a.innerMode&&(a=nd(a,b),a.mode.blankLine))return a.mode.blankLine(a.state)}function td(a,b,d,c){for(var e=0;10>e;e++){c&&(c[0]=nd(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 Be(a,b,d,c){var e=a.doc,f=e.mode;b=C(e,b);var g=w(e,b.line);d=Mb(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=td(f,a,d.state);c&&h.push(new Ce(a,k,Ya(e.mode,d.state)))}return c?h:new Ce(a,k,d.state)}function De(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 ye(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&&De(Ae(d,c.state),f);!m.eol();){if(m.pos>a.options.maxHighlightLength){h=!1;g&&sd(a,b,c,m.pos);m.pos=b.length;var p=null}else p=De(td(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 Dg(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 Ac?k.lookAhead:0)<=f.modeFrontier))return b;h=va(h.text,null,a.options.tabSize);if(null==e||c>h)e=b-1,c=h}return e}function Eg(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 Ac)||c+e.lookAhead<b)){d=c+1;break}}a.highlightFrontier=Math.min(a.highlightFrontier,d)}}function Bc(a,b,d){this.marker=a;this.from=b;this.to=d}function Nb(a,b){if(a)for(var d=0;d<a.length;++d){var c=a[d];if(c.marker==b)return c}}function ud(a,b){if(b.full)return null;var d=Lb(a,b.from.line)&&w(a,b.from.line).markedSpans,c=Lb(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 Bc(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 Bc(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=Nb(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?Nb(d,f.marker)||(f.from=e,c&&(d||(d=[])).push(f)):(f.from+=e,c&&(d||(d=[])).push(f));d&&(d=Ee(d));n&&n!=d&&(n=Ee(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 Bc(d[c].marker,null,null));for(d=0;d<b;++d)a.push(p);a.push(n)}return a}function Ee(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 Fg(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 Fe(a){var b=a.markedSpans;if(b){for(var d=0;d<b.length;++d)b[d].marker.detachLine(a);a.markedSpans=null}}function Ge(a,b){if(b){for(var d=0;d<b.length;++d)b[d].marker.attachLine(a);a.markedSpans=
b}}function vd(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 qb(a,b){a=Ja&&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>vd(e,d.marker)))var e=d.marker;return e}function He(a,b,d,c,e){a=w(a,b);if(a=Ja&&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 Ea(a){for(var b;b=qb(a,!0);)a=b.find(-1,!0).line;return a}function wd(a,b){a=w(a,b);var d=Ea(a);return a==d?b:N(d)}
function Ie(a,b){if(b>a.lastLine())return b;var d=w(a,b);if(!Oa(a,d))return b;for(;a=qb(d,!1);)d=a.find(1,!0).line;return N(d)+1}function Oa(a,b){var d=Ja&&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&&xd(a,b,c)))return!0}function xd(a,b,d){if(null==d.to)return b=d.marker.find(1,!0),xd(a,b.line,Nb(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)&&xd(a,b,c))return!0}function Fa(a){a=Ea(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 Cc(a){if(0==a.height)return 0;for(var b=a.text.length,d,c=
a;d=qb(c,!0);)d=d.find(0,!0),c=d.from.line,b+=d.from.ch-d.to.ch;for(c=a;d=qb(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 yd(a){var b=a.display;a=a.doc;b.maxLine=w(a,a.first);b.maxLineLength=Cc(b.maxLine);b.maxLineChanged=!0;a.iter(function(d){var c=Cc(d);c>b.maxLineLength&&(b.maxLineLength=c,b.maxLine=d)})}function Je(a,b){if(!a||/^\s*$/.test(a))return null;b=b.addModeClass?Gg:Hg;return b[a]||(b[a]=a.replace(/\S+/g,"cm-$&"))}function Ke(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=Ig;var g=a.display.measure;if(null!=zd)g=zd;else{var h=D(g,document.createTextNode("A\u062eA")),k=Ob(h,0,1).getBoundingClientRect();h=Ob(h,1,2).getBoundingClientRect();E(g);g=k&&k.left!=k.right?zd=3>h.right-
k.right:!1}g&&(f=Ia(e,a.doc.direction))&&(d.addToken=Jg(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=ze(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>vd(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)Le(f,0,S[F]);
if(k&&(k.from||0)==x){Le(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=Je(l[P++],f.cm.options)}}else for(g=1;g<l.length;g+=2)f.addToken(f,u.slice(A,A=l[g]),Je(l[g+1],f.cm.options))}e.styleClasses&&(e.styleClasses.bgClass&&(d.bgClass=ed(e.styleClasses.bgClass,
d.bgClass||"")),e.styleClasses.textClass&&(d.textClass=ed(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==Ad&&(m=v("span","\u200b"),D(h,v("span",[m,document.createTextNode("x")])),0!=h.firstChild.offsetHeight&&(Ad=1>=m.offsetWidth&&2<m.offsetHeight&&!(G&&8>T))),h=Ad?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=ed(d.pre.className,d.textClass||""));return d}function Kg(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 Ig(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",hd(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 Jg(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 Le(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 Me(a,b,d){for(var c=this.line=b,e;c=qb(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=Oa(a,b)}function Dc(a,b,d){var c=[],e;for(e=b;e<d;)b=new Me(a.doc,w(a.doc,e),e),e+=b.size,c.push(b);return c}function Lg(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{rb=null,b(a)}}function aa(a,b){var d=a._handlers&&a._handlers[b]||wc;if(d.length){var c=Array.prototype.slice.call(arguments,2);if(rb)var e=rb.delayedCallbacks;else Pb?e=Pb:(e=Pb=[],setTimeout(Mg,0));for(var f=function(h){e.push(function(){return d[h].apply(null,c)})},g=0;g<d.length;++g)f(g)}}function Mg(){var a=Pb;Pb=null;for(var b=0;b<a.length;++b)a[b]()}function Ne(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=Oe(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,Bd(f,g)):h&&(g.text.className=h)}else if("gutter"==f)Pe(a,b,d,c);else if("class"==f)Bd(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);Qe(f,g,h)}}b.changes=null}function Qb(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 Oe(a,b){var d=a.display.externalMeasured;return d&&d.line==b.line?(a.display.externalMeasured=null,b.measure=d.measure,d.built):Ke(a,b)}function Bd(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=Qb(b);b.background=c.insertBefore(v("div",null,d),c.firstChild);a.display.input.setUneditable(b.background)}b.line.wrapClass?Qb(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 Pe(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=Qb(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=Qb(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",pd(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 Ng(a,b,d,c){var e=Oe(a,b);b.text=b.node=e.pre;e.bgClass&&(b.bgClass=e.bgClass);e.textClass&&(b.textClass=e.textClass);Bd(a,b);Pe(a,b,d,c);Qe(a,b,c);return b.node}function Qe(a,b,d){Re(a,b.line,b,d,!0);if(b.rest)for(var c=0;c<b.rest.length;c++)Re(a,
b.rest[c],b,d,!1)}function Re(a,b,d,c,e){if(b.widgets){var f=Qb(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 Rb(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 Ka(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 Cd(a){return a.mover.offsetHeight-a.lineSpace.offsetHeight}function Se(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 Ga(a){return 50-a.display.nativeBarWidth}function ab(a){return a.display.scroller.clientWidth-Ga(a)-a.display.barWidth}function Dd(a){return a.display.scroller.clientHeight-Ga(a)-a.display.barHeight}function Te(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 Ed(a,b){if(b>=a.display.viewFrom&&b<a.display.viewTo)return a.display.view[bb(a,b)];if((a=a.display.externalMeasured)&&b>=a.lineN&&b<a.lineN+a.size)return a}function cb(a,b){var d=N(b),c=Ed(a,d);c&&!c.text?c=null:c&&c.changes&&(Ne(a,c,d,Fd(a)),a.curOp.forceUpdate=!0);if(!c){var e=Ea(b);c=N(e);e=a.display.externalMeasured=new Me(a.doc,e,c);e.lineN=c;c=e.built=Ke(a,e);e.text=c.pre;D(a.display.lineMeasure,
c.pre);c=e}a=Te(c,b,d);return{line:b,view:c,rect:null,map:a.map,cache:a.cache,before:a.before,hasHeights:!1}}function ya(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&&ab(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=Ue(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&&jd(b.line.text.charAt(g.coverStart+h));)--h;for(;g.coverStart+k<g.coverEnd&&jd(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=Ob(c,h,k).getClientRects();k=Ve;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!=Gd?p=Gd:(m=D(a.display.measure,v("span","x")),p=m.getBoundingClientRect(),m=Ob(m,0,1).getBoundingClientRect(),p=Gd=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+sb(a.display),top:q.top,bottom:q.bottom}:Ve);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 Ue(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 We(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 Xe(a){a.display.externalMeasure=null;E(a.display.lineMeasure);for(var b=0;b<a.display.view.length;b++)We(a.display.view[b])}
function Sb(a){Xe(a);a.display.cachedCharWidth=a.display.cachedTextHeight=a.display.cachedPaddingH=null;a.options.lineWrapping||(a.display.maxLineChanged=!0);a.display.lineNumChars=null}function Ye(){return Ec&&Fc?-(document.body.getBoundingClientRect().left-parseInt(getComputedStyle(document.body).marginLeft)):window.pageXOffset||(document.documentElement||document.body).scrollLeft}function Ze(){return Ec&&Fc?-(document.body.getBoundingClientRect().top-parseInt(getComputedStyle(document.body).marginTop)):
window.pageYOffset||(document.documentElement||document.body).scrollTop}function Hd(a){var b=0;if(a.widgets)for(var d=0;d<a.widgets.length;++d)a.widgets[d].above&&(b+=Rb(a.widgets[d]));return b}function Gc(a,b,d,c,e){e||(e=Hd(b),d.top+=e,d.bottom+=e);if("line"==c)return d;c||(c="local");b=Fa(b);b="local"==c?b+a.display.lineSpace.offsetTop:b-a.display.viewOffset;if("page"==c||"window"==c)a=a.display.lineSpace.getBoundingClientRect(),b+=a.top+("window"==c?0:Ze()),c=a.left+("window"==c?0:Ye()),d.left+=
c,d.right+=c;d.top+=b;d.bottom+=b;return d}function $e(a,b,d){if("div"==d)return b;var c=b.left;b=b.top;"page"==d?(c-=Ye(),b-=Ze()):"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 Hc(a,b,d,c,e){c||(c=w(a.doc,b.line));var f=c;b=b.ch;c=ya(a,cb(a,c),b,e);return Gc(a,f,c,d)}function za(a,b,d,c,e,f){function g(p,q){p=ya(a,e,p,q?"right":"left",f);q?p.left=p.right:p.right=p.left;return Gc(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=cb(a,c));var k=Ia(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=Ib(k,l,b),n=Jb;m=h(l,m,"before"==b);null!=n&&(m.other=h(l,n,"before"!=b));return m}function af(a,b){var d=0;b=C(a.doc,b);a.options.lineWrapping||(d=sb(a.display)*b.ch);b=w(a.doc,b.line);a=Fa(b)+a.display.lineSpace.offsetTop;return{left:d,right:d,
top:a,bottom:a+b.height}}function Id(a,b,d,c,e){a=t(a,b,d);a.xRel=e;c&&(a.outside=c);return a}function Jd(a,b,d){var c=a.doc;d+=a.display.viewOffset;if(0>d)return Id(c.first,0,null,-1,-1);var e=$a(c,d),f=c.first+c.size-1;if(e>f)return Id(c.first+c.size-1,w(c,f).text.length,null,1,1);0>b&&(b=0);for(var g=w(c,e);;){f=Og(a,g,e,b,d);var h=void 0;var k=f.ch+(0<f.xRel||0<f.outside?1:0);if(g=Ja&&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>vd(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 bf(a,b,d,c){c-=Hd(b);b=b.text.length;var e=Hb(function(f){return ya(a,d,f-1).bottom<=c},b,0);b=Hb(function(f){return ya(a,d,f).top>c},e,b);return{begin:e,end:b}}function cf(a,b,d,c){d||(d=cb(a,b));c=Gc(a,b,ya(a,d,c),"line").top;return bf(a,b,d,c)}function Kd(a,b,d,c){return a.bottom<=d?!1:a.top>d?!0:(c?a.left:a.right)>b}function Og(a,b,d,c,e){e-=Fa(b);var f=cb(a,b),g=Hd(b),h=0,
k=b.text.length,l=!0,m=Ia(b,a.doc.direction);m&&(m=(a.options.lineWrapping?Pg:Qg)(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=Hb(function(r){var u=ya(a,f,r);u.top+=g;u.bottom+=g;if(!Kd(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":ya(a,f,m-(l?1:0)).bottom+g<=e==l?"after":"before",q=za(a,
t(d,m,l),"line",b,f),h=q.left,q=e<q.top?-1:e>=q.bottom?1:0);m=re(b.text,m,1);return Id(d,m,l,q,c-h)}function Qg(a,b,d,c,e,f,g){var h=Hb(function(m){m=e[m];var n=1!=m.level;return Kd(za(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=za(a,t(d,l?k.from:k.to,l?"after":"before"),"line",b,c);Kd(l,f,g,!0)&&l.top>g&&(k=e[h-1])}return k}function Pg(a,b,d,c,e,f,g){g=bf(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=ya(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 tb(a){if(null!=a.cachedTextHeight)return a.cachedTextHeight;if(null==db){db=v("pre",null,"CodeMirror-line-like");for(var b=0;49>b;++b)db.appendChild(document.createTextNode("x")),db.appendChild(v("br"));db.appendChild(document.createTextNode("x"))}D(a.measure,
db);b=db.offsetHeight/50;3<b&&(a.cachedTextHeight=b);E(a.measure);return b||1}function sb(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 Fd(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:Ld(b),gutterTotalWidth:b.gutters.offsetWidth,gutterLeft:d,gutterWidth:c,wrapperWidth:b.wrapper.clientWidth}}function Ld(a){return a.scroller.getBoundingClientRect().left-a.sizer.getBoundingClientRect().left}function df(a){var b=tb(a.display),d=a.options.lineWrapping,c=d&&Math.max(5,a.display.scroller.clientWidth/sb(a.display)-3);return function(e){if(Oa(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 Md(a){var b=a.doc,d=df(a);b.iter(function(c){var e=d(c);e!=c.height&&Ca(c,e)})}function eb(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=Jd(a,f,g);var h;c&&0<b.xRel&&(h=w(a.doc,b.line).text).length==b.ch&&(c=va(h,h.length,a.options.tabSize)-h.length,b=t(b.line,Math.max(0,
Math.round((f-Se(a.display).left)/sb(a.display))-c)));return b}function bb(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)Ja&&wd(a.doc,b)<e.viewTo&&Pa(a);else if(d<=
e.viewFrom)Ja&&Ie(a.doc,d+c)>e.viewFrom?Pa(a):(e.viewFrom+=c,e.viewTo+=c);else if(b<=e.viewFrom&&d>=e.viewTo)Pa(a);else if(b<=e.viewFrom){var f=Ic(a,d,d+c,1);f?(e.view=e.view.slice(f.index),e.viewFrom=f.lineN,e.viewTo+=c):Pa(a)}else if(d>=e.viewTo)(f=Ic(a,b,b,-1))?(e.view=e.view.slice(0,f.index),e.viewTo=f.lineN):Pa(a);else{f=Ic(a,b,b,-1);var g=Ic(a,d,d+c,1);f&&g?(e.view=e.view.slice(0,f.index).concat(Dc(a,f.lineN,g.lineN)).concat(e.view.slice(g.index)),e.viewTo+=c):Pa(a)}if(a=e.externalMeasured)d<
a.lineN?a.lineN+=c:b<a.lineN+a.size&&(e.externalMeasured=null)}function Qa(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[bb(a,b)],null!=a.node&&(a=a.changes||(a.changes=[]),-1==ea(a,d)&&a.push(d)))}function Pa(a){a.display.viewFrom=a.display.viewTo=a.doc.first;a.display.view=[];a.display.viewOffset=0}function Ic(a,b,d,c){var e=bb(a,b),f=a.display.view;if(!Ja||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(;wd(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 ef(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 Tb(a){a.display.input.showSelection(a.display.input.prepareSelection())}function ff(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&&Nd(a,m,e)}else(l||a.options.showCursorWhenSelecting)&&Nd(a,k.head,e);l||Rg(a,k,f)}}return c}function Nd(a,b,d){var c=za(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=Hc(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 Jc(a,b){return a.top-b.top||a.left-b.left}function Rg(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 Hc(a,t(q,F),"div",x,R)}function Y(F,R,H){F=cf(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=Ia(x,g.direction);zg(S,r||0,null==u?P:u,function(F,R,H,L){var ha="ltr"==H,na=A(F,ha?"left":"right"),ta=A(R-1,ha?"right":"left"),fb=null==r&&0==F,gb=null==u&&R==P,Od=0==L;L=!S||L==S.length-1;3>=ta.top-na.top?(R=(n?fb:gb)&&Od?l:(ha?na:ta).left,c(R,na.top,((n?gb:fb)&&L?m:(ha?ta:na).right)-R,na.bottom)):(ha?(ha=n&&fb&&Od?l:na.left,fb=n?m:Y(F,H,"before"),F=n?l:Y(R,H,
"after"),gb=n&&gb&&L?m:ta.right):(ha=n?Y(F,H,"before"):l,fb=!n&&fb&&Od?m:na.right,F=!n&&gb&&L?l:ta.left,gb=n?Y(R,H,"after"):m),c(ha,na.top,fb-ha,na.bottom),na.bottom<ta.top&&c(l,na.bottom,null,ta.top),c(F,ta.top,gb-F,ta.bottom));if(!K||0>Jc(na,K))K=na;0>Jc(ta,K)&&(K=ta);if(!Q||0>Jc(na,Q))Q=na;0>Jc(ta,Q)&&(Q=ta)});return{start:K,end:Q}}var f=a.display,g=a.doc,h=document.createDocumentFragment(),k=Se(a.display),l=k.left,m=Math.max(f.sizerWidth,ab(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=Ea(p)==Ea(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 Pd(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()||ub(a);b.cursorDiv.style.visibility=(d=!d)?"":"hidden"},a.options.cursorBlinkRate):0>a.options.cursorBlinkRate&&(b.cursorDiv.style.visibility="hidden")}}function gf(a){a.hasFocus()||(a.display.input.focus(),a.state.focused||Qd(a))}function Rd(a){a.state.delayingBlurEvent=!0;setTimeout(function(){a.state.delayingBlurEvent&&(a.state.delayingBlurEvent=!1,a.state.focused&&ub(a))},100)}function Qd(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,Wa(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()),Pd(a))}function ub(a,b){a.state.delayingBlurEvent||(a.state.focused&&(W(a,"blur",a,b),a.state.focused=!1,hb(a.display.wrapper,"CodeMirror-focused")),clearInterval(a.display.blinker),setTimeout(function(){a.state.focused||
(a.display.shift=!1)},150))}function Kc(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),Ca(h.line,m),hf(h.line),h.rest)for(m=0;m<h.rest.length;m++)hf(h.rest[m]);l>a.display.sizerWidth&&(l=Math.ceil(l/sb(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 hf(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 Lc(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=$a(b,c);e=$a(b,e);if(d&&d.ensure){var f=d.ensure.from.line;d=d.ensure.to.line;f<c?(c=f,e=$a(b,Fa(w(b,f))+a.wrapper.clientHeight)):Math.min(d,b.lastLine())>=e&&(c=$a(b,Fa(w(b,d))-a.wrapper.clientHeight),e=d)}return{from:c,to:Math.max(e,c+1)}}function Sd(a,b){var d=a.display,c=tb(a.display);0>b.top&&(b.top=0);var e=a.curOp&&null!=a.curOp.scrollTop?a.curOp.scrollTop:d.scroller.scrollTop,
f=Dd(a),g={};b.bottom-b.top>f&&(b.bottom=b.top+f);var h=a.doc.height+Cd(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=ab(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 Mc(a,b){null!=b&&(Nc(a),a.curOp.scrollTop=(null==a.curOp.scrollTop?a.doc.scrollTop:a.curOp.scrollTop)+b)}function vb(a){Nc(a);var b=a.getCursor();a.curOp.scrollToPos={from:b,to:b,margin:a.options.cursorScrollMargin}}function Ub(a,b,d){null==b&&null==d||Nc(a);null!=b&&(a.curOp.scrollLeft=b);null!=d&&(a.curOp.scrollTop=d)}function Nc(a){var b=a.curOp.scrollToPos;if(b){a.curOp.scrollToPos=null;var d=af(a,b.from),c=af(a,b.to);jf(a,d,c,b.margin)}}function jf(a,b,d,
c){b=Sd(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});Ub(a,b.scrollLeft,b.scrollTop)}function Vb(a,b){2>Math.abs(a.doc.scrollTop-b)||(La||Td(a,{top:b}),kf(a,b,!0),La&&Td(a),Wb(a,100))}function kf(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 ib(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,lf(a),a.display.scroller.scrollLeft!=b&&(a.display.scroller.scrollLeft=b),a.display.scrollbars.setScrollLeft(b))}function Xb(a){var b=a.display,d=b.gutters.offsetWidth,c=Math.round(a.doc.height+Cd(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+Ga(a)+b.barHeight,nativeBarWidth:b.nativeBarWidth,gutterWidth:d}}function wb(a,b){b||(b=Xb(a));var d=a.display.barWidth,c=a.display.barHeight;mf(a,b);for(b=0;4>b&&d!=a.display.barWidth||c!=a.display.barHeight;b++)d!=a.display.barWidth&&a.options.lineWrapping&&Kc(a),mf(a,Xb(a)),d=a.display.barWidth,c=a.display.barHeight}function mf(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 nf(a){a.display.scrollbars&&(a.display.scrollbars.clear(),a.display.scrollbars.addClass&&hb(a.display.wrapper,a.display.scrollbars.addClass));a.display.scrollbars=new of[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?ib(a,b):Vb(a,b)},a);a.display.scrollbars.addClass&&Wa(a.display.wrapper,a.display.scrollbars.addClass)}function jb(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:++Sg,markArrays:null};a=a.curOp;rb?rb.ops.push(a):a.ownsGroup=
rb={ops:[a],delayedCallbacks:[]}}function kb(a){(a=a.curOp)&&Lg(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=Ga(e)+"px",g.sizer.style.marginBottom=-g.nativeBarWidth+"px",g.sizer.style.borderRightWidth=Ga(e)+"px",g.scrollbarsClipped=!0);c.updateMaxLine&&yd(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 Oc(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&&Ud(c.cm,c.update);for(d=0;d<b.length;d++)if(c=b[d],e=c.cm,f=e.display,c.updatedDisplay&&Kc(e),c.barMeasure=Xb(e),f.maxLineChanged&&!e.options.lineWrapping&&(g=f.maxLine.text.length,
g=ya(e,cb(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+Ga(e)+e.display.barWidth),c.maxScrollLeft=Math.max(0,f.sizer.offsetLeft+c.adjustWidthTo-ab(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&&
ib(e,Math.min(e.display.scroller.scrollLeft,c.maxScrollLeft),!0),e.display.maxLineChanged=!1),f=c.focus&&c.focus==ka(),c.preparedSelection&&e.display.input.showSelection(c.preparedSelection,f),(c.updatedDisplay||c.startHeight!=e.doc.height)&&wb(e,c.barMeasure),c.updatedDisplay&&Vd(e,c.barMeasure),c.selectionChanged&&Pd(e),e.state.focused&&c.updateInput&&e.display.input.reset(c.typing),f&&gf(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&&pf(e,c.update);
null==f.wheelStartX||null==c.scrollTop&&null==c.scrollLeft&&!c.scrollToPos||(f.wheelStartX=f.wheelStartY=null);null!=c.scrollTop&&kf(e,c.scrollTop,c.forceScroll);null!=c.scrollLeft&&ib(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=za(e,
k);var q=l&&l!=k?za(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=Sd(e,h);var r=e.doc.scrollTop,u=e.doc.scrollLeft;null!=q.scrollTop&&(Vb(e,q.scrollTop),1<Math.abs(e.doc.scrollTop-r)&&(p=!0));null!=q.scrollLeft&&(ib(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,0>l.top+n.top?k=!0:l.bottom+n.top>(window.innerHeight||
document.documentElement.clientHeight)&&(k=!1),null==k||Tg||(l=v("div","\u200b",null,"position: absolute;\n top: "+(l.top-m.viewOffset-e.display.lineSpace.offsetTop)+"px;\n height: "+(l.bottom-l.top+Ga(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 qa(a,b){if(a.curOp)return b();jb(a);try{return b()}finally{kb(a)}}function ba(a,b){return function(){if(a.curOp)return b.apply(a,arguments);jb(a);try{return b.apply(a,arguments)}finally{kb(a)}}}function ia(a){return function(){if(this.curOp)return a.apply(this,
arguments);jb(this);try{return a.apply(this,arguments)}finally{kb(this)}}}function ca(a){return function(){var b=this.cm;if(!b||b.curOp)return a.apply(this,arguments);jb(b);try{return a.apply(this,arguments)}finally{kb(b)}}}function Wb(a,b){a.doc.highlightFrontier<a.display.viewTo&&a.state.highlight.set(b,fd(Ug,a))}function Ug(a){var b=a.doc;if(!(b.highlightFrontier>=a.display.viewTo)){var d=+new Date+a.options.workTime,c=Mb(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?Ya(b.mode,c.state):null,k=xe(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&&sd(a,f.text,c),
f.stateAfter=0==c.line%5?c.save():null;c.nextLine();if(+new Date>d)return Wb(a,a.options.workDelay),!0});b.highlightFrontier=c.line;b.modeFrontier=Math.max(b.modeFrontier,c.line);e.length&&qa(a,function(){for(var f=0;f<e.length;f++)Qa(a,e[f],"text")})}}function Ud(a,b){var d=a.display,c=a.doc;if(b.editorIsHidden)return Pa(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==ef(a))return!1;qf(a)&&
(Pa(a),b.dims=Fd(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));Ja&&(f=wd(a.doc,f),g=Ie(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=Dc(a,f,g),e.viewFrom=f):(e.viewFrom>
f?e.view=Dc(a,f,e.viewFrom).concat(e.view):e.viewFrom<f&&(e.view=e.view.slice(bb(a,f))),e.viewFrom=f,e.viewTo<g?e.view=e.view.concat(Dc(a,e.viewTo,g)):e.viewTo>g&&(e.view=e.view.slice(0,bb(a,g))));e.viewTo=g;d.viewOffset=Fa(w(a.doc,d.viewFrom));a.display.mover.style.top=d.viewOffset+"px";g=ef(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())&&ja(a.display.lineDiv,f)?(f={activeElt:f},window.getSelection&&
(e=window.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");Vg(a,d.updateLineNumbers,b.dims);4<g&&(d.lineDiv.style.display="");d.renderedView=d.view;(g=f)&&g.activeElt&&g.activeElt!=ka()&&(g.activeElt.focus(),!/^(INPUT|TEXTAREA)$/.test(g.activeElt.nodeName)&&g.anchorNode&&ja(document.body,g.anchorNode)&&ja(document.body,
g.focusNode)&&(f=window.getSelection(),e=document.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,Wb(a,400));d.updateLineNumbers=null;return!0}function pf(a,b){for(var d=b.viewport,c=!0;;c=!1){if(c&&a.options.lineWrapping&&b.oldDisplayWidth!=ab(a))c&&(b.visible=
Lc(a.display,a.doc,d));else if(d&&null!=d.top&&(d={top:Math.min(a.doc.height+Cd(a.display)-Dd(a),d.top)}),b.visible=Lc(a.display,a.doc,d),b.visible.from>=a.display.viewFrom&&b.visible.to<=a.display.viewTo)break;if(!Ud(a,b))break;Kc(a);c=Xb(a);Tb(a);wb(a,c);Vd(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 Td(a,b){b=new Oc(a,b);if(Ud(a,b)){Kc(a);pf(a,b);var d=Xb(a);Tb(a);wb(a,d);Vd(a,d);b.finish()}}function Vg(a,b,d){function c(p){var q=p.nextSibling;fa&&xa&&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),Ne(a,m,e,d));h&&(E(m.lineNumber),m.lineNumber.appendChild(document.createTextNode(pd(a.options,e))));h=m.node.nextSibling}else{var n=Ng(a,m,e,d);g.insertBefore(n,h)}e+=m.size}for(;h;)h=c(h)}function Wd(a){a.sizer.style.marginLeft=a.gutters.offsetWidth+"px";aa(a,"gutterChanged",a)}function Vd(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+Ga(a)+"px"}function lf(a){var b=a.display,d=b.view;if(b.alignWidgets||b.gutters.firstChild&&a.options.fixedGutter){for(var c=Ld(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 qf(a){if(!a.options.lineNumbers)return!1;var b=a.doc;b=pd(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";Wd(a.display);return!0}return!1}function Xd(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 rf(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";Wd(a)}function Yb(a){rf(a.display);ma(a);lf(a)}function Wg(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");this.wrapper.setAttribute("translate","no");G&&8>T&&(this.gutters.style.zIndex=-1,this.scroller.style.paddingRight=
0);fa||La&&Zb||(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=Xd(c.gutters,c.lineNumbers);rf(this);d.init(this)}function sf(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 Xg(a){a=sf(a);a.x*=Ma;a.y*=Ma;return a}function tf(a,b){var d=sf(b),c=d.x;d=d.y;var e=Ma;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&&xa&&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||La||Aa||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),Td(a,{top:k,bottom:h})),20>Pc&&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&&(Ma=(Ma*Pc+n)/(Pc+1),++Pc)}},200)):(f.wheelDX+=c,f.wheelDY+=d))):(d&&k&&Vb(a,Math.max(0,g.scrollTop+d*e)),ib(a,Math.max(0,
g.scrollLeft+c*e)),(!d||d&&k)&&la(b),f.wheelStartX=null)}}function Ba(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=zc(f.from(),e.from());var h=yc(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 ua(b,d)}function Na(a,b){return new ua([new I(a,b||a)],0)}function Ra(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 uf(a,b){if(0>B(a,b.from))return a;if(0>=B(a,b.to))return Ra(b);var d=a.line+b.text.length-(b.to.line-b.from.line)-1,c=a.ch;a.line==b.to.line&&(c+=Ra(b).ch-b.to.ch);return t(d,c)}function Yd(a,b){for(var d=[],c=0;c<a.sel.ranges.length;c++){var e=a.sel.ranges[c];d.push(new I(uf(e.anchor,b),uf(e.head,b)))}return Ba(a.cm,d,a.sel.primIndex)}function vf(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 Zd(a){a.doc.mode=md(a.options,a.doc.modeOption);$b(a)}function $b(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;Wb(a,100);a.state.modeGen++;a.curOp&&ma(a)}function wf(a,b){return 0==b.from.ch&&0==b.to.ch&&""==J(b.text)&&(!a.cm||a.cm.options.wholeLineUpdateBefore)}function $d(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);Fe(r);Ge(r,A);u=c?c(r):1;u!=r.height&&Ca(r,u);aa(r,"change",r,b)}function f(r,u){for(var A=[];r<u;++r)A.push(new xb(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)):wf(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 xb(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 Sa(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 xf(a,b){if(b.cm)throw Error("This document is already in use.");a.doc=b;b.cm=a;Md(a);Zd(a);yf(a);a.options.direction=b.direction;a.options.lineWrapping||yd(a);a.options.mode=b.modeOption;ma(a)}function yf(a){("rtl"==a.doc.direction?Wa:hb)(a.display.lineDiv,"CodeMirror-rtl")}function Yg(a){qa(a,function(){yf(a);ma(a)})}function Qc(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 ae(a,b){var d={from:rd(b.from),to:Ra(b),text:Za(a,b.from,b.to)};zf(a,d,b.from.line,b.to.line+1);Sa(a,function(c){return zf(c,d,b.from.line,b.to.line+1)},!0);return d}function Af(a){for(;a.length;)if(J(a).ranges)a.pop();else break}function Bf(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){Af(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=Ra(b):h.changes.push(ae(a,b))}else for((h=J(e.done))&&h.ranges||Rc(a.sel,e.done),h={changes:[ae(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 Rc(a,b){var d=J(b);d&&d.ranges&&d.equals(a)||b.push(a)}function zf(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 Cf(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=ud(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 yb(a,b,d){for(var c=[],e=0;e<a.length;++e){var f=a[e];
if(f.ranges)c.push(d?ua.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 be(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 Sc(a,b,d,c,e){null==e&&(e=a.cm&&(a.cm.display.shift||a.extend));da(a,new ua([be(a.sel.primary(),
b,d,e)],0),c)}function Df(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]=be(a.sel.ranges[f],b[f],null,e);b=Ba(a.cm,c,a.sel.primIndex);da(a,b,d)}function ce(a,b,d,c){var e=a.sel.ranges.slice(0);e[b]=d;da(a,Ba(a.cm,e,a.sel.primIndex),c)}function Zg(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?Ba(a.cm,d.ranges,d.ranges.length-1):b}function Ef(a,b,d){var c=a.history.done,e=J(c);e&&e.ranges?(c[c.length-1]=b,Tc(a,b,d)):da(a,b,d)}function da(a,b,d){Tc(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:Rc(b,e.done);e.lastSelTime=+new Date;e.lastSelOrigin=f;e.lastSelOp=c;d&&!1!==d.clearRedo&&Af(e.undone)}function Tc(a,b,d){if(wa(a,"beforeSelectionChange")||a.cm&&wa(a.cm,"beforeSelectionChange"))b=Zg(a,b,d);var c=d&&d.bias||(0>B(b.primary().head,a.sel.primary().head)?-1:1);Ff(a,Gf(a,b,c,!0));d&&!1===d.scroll||!a.cm||"nocursor"==a.cm.getOption("readOnly")||vb(a.cm)}function Ff(a,b){b.equals(a.sel)||
(a.sel=b,a.cm&&(a.cm.curOp.updateInput=1,a.cm.curOp.selectionChanged=!0,se(a.cm)),aa(a,"cursorActivity",a))}function Hf(a){Ff(a,Gf(a,a.sel,null,!1))}function Gf(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=Uc(a,g.anchor,h&&h.anchor,d,c);h=Uc(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?Ba(a.cm,e,b.primIndex):b}function zb(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=If(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 zb(a,
g,b,c,e)}d=k.find(0>c?-1:1);if(0>c?l:m)d=If(a,d,c,d.line==b.line?f:null);return d?zb(a,d,b,c,e):null}}}return b}function Uc(a,b,d,c,e){c=c||1;b=zb(a,b,d,c,e)||!e&&zb(a,b,d,c,!0)||zb(a,b,d,-c,e)||!e&&zb(a,b,d,-c,!0);return b?b:(a.cantEdit=!0,t(a.first,0))}function If(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 Jf(a){a.setSelection(t(a.firstLine(),0),t(a.lastLine()),
Ha)}function Kf(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 Ab(a,b,d){if(a.cm){if(!a.cm.curOp)return ba(a.cm,Ab)(a,b,d);if(a.cm.state.suppressEdits)return}if(wa(a,
"beforeChange")||a.cm&&wa(a.cm,"beforeChange"))if(b=Kf(a,b,!0),!b)return;if(d=Lf&&!d&&Fg(a,b.from,b.to))for(var c=d.length-1;0<=c;--c)Mf(a,{from:d[c].from,to:d[c].to,text:c?[""]:b.text,origin:b.origin});else Mf(a,b)}function Mf(a,b){if(1!=b.text.length||""!=b.text[0]||0!=B(b.from,b.to)){var d=Yd(a,b);Bf(a,b,d,a.cm?a.cm.curOp.id:NaN);ac(a,b,d,ud(a,b));var c=[];Sa(a,function(e,f){f||-1!=ea(c,e.history)||(Nf(e.history,b),c.push(e.history));ac(e,b,null,ud(e,b))})}}function Vc(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){Rc(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=[];Rc(g,k);k.push({changes:m,generation:e.generation});e.generation=f.generation||++e.maxGeneration;var n=wa(a,"beforeChange")||a.cm&&wa(a.cm,"beforeChange");
d=function(p){var q=f.changes[p];q.origin=b;if(n&&!Kf(a,q,!1))return h.length=0,{};m.push(ae(a,q));var r=p?Yd(a,q):J(h);ac(a,q,r,Cf(a,q));!p&&a.cm&&a.cm.scrollIntoView({from:q.from,to:Ra(q)});var u=[];Sa(a,function(A,Y){Y||-1!=ea(u,A.history)||(Nf(A.history,q),u.push(A.history));ac(A,q,null,Cf(A,q))})};for(c=f.changes.length-1;0<=c;--c)if(e=d(c))return e.v}}}function Of(a,b){if(0!=b&&(a.first+=b,a.sel=new ua(uc(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++)Qa(a.cm,c,"gutter")}}function ac(a,b,d,c){if(a.cm&&!a.cm.curOp)return ba(a.cm,ac)(a,b,d,c);if(b.to.line<a.first)Of(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);Of(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=Za(a,b.from,b.to);d||(d=Yd(a,b));a.cm?$g(a.cm,b,c):$d(a,b,c);Tc(a,d,Ha);a.cantEdit&&Uc(a,t(a.firstLine(),0))&&(a.cantEdit=!1)}}function $g(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(Ea(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)&&se(a);$d(c,b,d,df(a));a.options.lineWrapping||(c.iter(k,f.line+b.text.length,function(l){var m=Cc(l);
m>e.maxLineLength&&(e.maxLine=l,e.maxLineLength=m,e.maxLineChanged=!0,h=!1)}),h&&(a.curOp.updateMaxLine=!0));Eg(c,f.line);Wb(a,400);d=b.text.length-(g.line-f.line)-1;b.full?ma(a):f.line!=g.line||1!=b.text.length||wf(a.doc,b)?ma(a,f.line,g.line+1,d):Qa(a,f.line,"text");d=wa(a,"changes");if((c=wa(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 Bb(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));Ab(a,{from:d,to:c,text:b,origin:e})}function Pf(a,b,d,c){d<a.line?a.line+=c:b<a.line&&(a.line=b,a.ch=0)}function Qf(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++)Pf(f.ranges[g].anchor,b,d,c),Pf(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 Nf(a,b){var d=b.from.line,c=b.to.line;b=b.text.length-(c-d)-1;Qf(a.done,d,c,b);Qf(a.undone,d,c,b)}function bc(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&&Qa(a.cm,e,d);return f}function cc(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 dc(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 ah(a,b,d,c){var e=new ec(a,d,c),f=a.cm;f&&e.noHScroll&&(f.display.alignWidgets=!0);bc(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&&!Oa(a,g)&&(h=Fa(g)<a.scrollTop,Ca(g,g.height+Rb(e)),h&&Mc(f,e.height),f.curOp.forceUpdate=
!0);return!0});f&&aa(f,"lineWidgetAdded",f,e,"number"==typeof b?b:N(b));return e}function Cb(a,b,d,c,e){if(c&&c.shared)return bh(a,b,d,c,e);if(a.cm&&!a.cm.curOp)return ba(a.cm,Cb)(a,b,d,c,e);var f=new Ta(a,e);e=B(b,d);c&&Xa(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(He(a,
b.line,b,d,f)||b.line!=d.line&&He(a,d.line,b,d,f))throw Error("Inserting collapsed marker partially overlapping an existing one");Ja=!0}f.addToHistory&&Bf(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&&Ea(l)==h.display.maxLine&&(k=!0);f.collapsed&&g!=b.line&&Ca(l,0);var m=new Bc(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)))&&
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){Oa(a,l)&&Ca(l,0)});f.clearOnEnter&&z(f,"beforeCursorEnter",function(){return f.clear()});f.readOnly&&(Lf=!0,(a.history.done.length||a.history.undone.length)&&a.clearHistory());f.collapsed&&(f.id=++Rf,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++)Qa(h,c,"text");f.atomic&&Hf(h.doc);aa(h,"markerAdded",h,f)}return f}function bh(a,b,d,c,e){c=Xa(c);c.shared=!1;var f=[Cb(a,b,d,c,e)],g=f[0],h=c.widgetNode;Sa(a,function(k){h&&(c.widgetNode=h.cloneNode(!0));f.push(Cb(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 fc(f,g)}function Sf(a){return a.findMarks(t(a.first,0),a.clipPos(t(a.lastLine())),function(b){return b.parent})}
function ch(a){for(var b=function(c){c=a[c];var e=[c.primary.doc];Sa(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 dh(a){var b=this;Tf(b);if(!Z(b,a)&&!Ka(b.display,a)){la(a);G&&(Uf=+new Date);var d=eb(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"};Ab(b.doc,m);Ef(b.doc,Na(C(b.doc,d),C(b.doc,Ra(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());Tc(b.doc,Na(d,d));if(l)for(c=0;c<l.length;++c)Bb(b.doc,"",l[c].anchor,l[c].head,"drag");b.replaceSelection(k,"around","paste");b.display.input.focus()}}catch(m){}}}function Tf(a){a.display.dragCursor&&(a.display.lineSpace.removeChild(a.display.dragCursor),a.display.dragCursor=
null)}function Vf(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 eh(){var a;z(window,"resize",function(){null==a&&(a=setTimeout(function(){a=null;Vf(fh)},100))});z(window,"blur",function(){return Vf(ub)})}function fh(a){var b=a.display;b.cachedCharWidth=b.cachedTextHeight=b.cachedPaddingH=null;b.scrollbarsClipped=
!1;a.setSize()}function gh(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 hh(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=uc(d.split(" "),gh),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 Db(a,b,d,c){b=Wc(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 Db(a,
b.fallthrough,d,c);for(e=0;e<b.fallthrough.length;e++){var f=Db(a,b.fallthrough[e],d,c);if(f)return f}}}function Wf(a){a="string"==typeof a?a:Ua[a.keyCode];return"Ctrl"==a||"Alt"==a||"Shift"==a||"Mod"==a}function Xf(a,b,d){var c=a;b.altKey&&"Alt"!=c&&(a="Alt-"+a);(Yf?b.metaKey:b.ctrlKey)&&"Ctrl"!=c&&(a="Ctrl-"+a);(Yf?b.ctrlKey:b.metaKey)&&"Mod"!=c&&(a="Cmd-"+a);!d&&b.shiftKey&&"Shift"!=c&&(a="Shift-"+a);return a}function Zf(a,b){if(Aa&&34==a.keyCode&&a["char"])return!1;var d=Ua[a.keyCode];if(null==
d||a.altGraphKey)return!1;3==a.keyCode&&a.code&&(d=a.code);return Xf(d,a,b)}function Wc(a){return"string"==typeof a?gc[a]:a}function Eb(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)}qa(a,function(){for(var h=c.length-1;0<=h;h--)Bb(a.doc,"",c[h].from,c[h].to,"+delete");vb(a)})}function de(a,b,d){b=re(a.text,b+d,d);return 0>b||b>a.text.length?null:b}function ee(a,b,d){a=
de(a,b.ch,d);return null==a?null:new t(b.line,a,0>d?"after":"before")}function fe(a,b,d,c,e){if(a&&("rtl"==b.doc.direction&&(e=-e),a=Ia(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=cb(b,d);var h=0>e?d.text.length-1:0;var k=ya(b,g,h).top;h=Hb(function(l){return ya(b,g,l).top==k},0>e==(1==a.level)?a.from:a.to-1,h);"before"==f&&(h=de(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 ih(a,b,d,c){var e=Ia(b,a.doc.direction);if(!e)return ee(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=Ib(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 ee(b,d,c);var h=function(q,r){return de(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||cb(a,b);return cf(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 $f(a,b){var d=w(a.doc,b),c=Ea(d);c!=d&&(b=N(c));return fe(!0,a,c,b,1)}function ag(a,b){var d=$f(a,b.line),c=w(a.doc,d.line);a=Ia(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 Xc(a,b,d){if("string"==typeof b&&(b=hc[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)!=Yc}finally{a.display.shift=c,a.state.suppressEdits=!1}return e}function ic(a,b,d,c){var e=a.state.keySeq;if(e){if(Wf(b))return"handled";/'$/.test(b)?a.state.keySeq=null:jh.set(50,function(){a.state.keySeq==e&&(a.state.keySeq=null,a.display.input.reset())});if(bg(a,e+" "+b,d,c))return!0}return bg(a,b,d,c)}function bg(a,b,d,c){a:{for(var e=0;e<a.state.keyMaps.length;e++){var f=Db(b,a.state.keyMaps[e],c,a);if(f){c=f;break a}}c=a.options.extraKeys&&Db(b,a.options.extraKeys,
c,a)||Db(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),Pd(a);return!!c}function cg(a,b){var d=Zf(b,!0);return d?b.shiftKey&&!a.state.keySeq?ic(a,"Shift-"+d,b,function(c){return Xc(a,c,!0)})||ic(a,d,b,function(c){if("string"==typeof c?/^go[A-Z]/.test(c):c.motion)return Xc(a,c)}):ic(a,d,b,function(c){return Xc(a,c)}):!1}function kh(a,b,d){return ic(a,"'"+d+"'",b,function(c){return Xc(a,c,!0)})}function dg(a){if(!a.target||
a.target==this.display.input.getField())if(this.curOp.focus=ka(),!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=cg(this,a);Aa&&(ge=d?b:null,!d&&88==b&&!lh&&(xa?a.metaKey:a.ctrlKey)&&this.replaceSelection("",null,"cut"));La&&!xa&&!d&&46==b&&a.shiftKey&&!a.ctrlKey&&document.execCommand&&document.execCommand("cut");18!=b||/\bCodeMirror-crosshair\b/.test(this.display.lineDiv.className)||mh(this)}}function mh(a){function b(c){18!=c.keyCode&&
c.altKey||(hb(d,"CodeMirror-crosshair"),sa(document,"keyup",b),sa(document,"mouseover",b))}var d=a.display.lineDiv;Wa(d,"CodeMirror-crosshair");z(document,"keyup",b);z(document,"mouseover",b)}function eg(a){16==a.keyCode&&(this.doc.sel.shift=!1);Z(this,a)}function fg(a){if(!(a.target&&a.target!=this.display.input.getField()||Ka(this.display,a)||Z(this,a)||a.ctrlKey&&!a.altKey||xa&&a.metaKey)){var b=a.keyCode,d=a.charCode;if(Aa&&b==ge)ge=null,la(a);else if(!Aa||a.which&&!(10>a.which)||!cg(this,a))if(b=
String.fromCharCode(null==d?b:d),"\b"!=b&&!kh(this,a,b))this.display.input.onKeyPress(a)}}function nh(a,b){var d=+new Date;if(jc&&jc.compare(d,a,b))return kc=jc=null,"triple";if(kc&&kc.compare(d,a,b))return jc=new he(d,a,b),kc=null,"double";kc=new he(d,a,b);jc=null;return"single"}function gg(a){var b=this.display;if(!(Z(this,a)||b.activeTouch&&b.input.supportsTouch()))if(b.input.ensurePolled(),b.shift=a.shiftKey,Ka(b,a))fa||(b.scroller.draggable=!1,setTimeout(function(){return b.scroller.draggable=
!0},100));else if(!Zc(this,a,"gutterClick",!0)){var d=eb(this,a),c=ue(a),e=d?nh(d,c):"single";window.focus();1==c&&this.state.selectingText&&this.state.selectingText(a);if(!d||!oh(this,c,d,e,a))if(1==c)d?ph(this,d,e,a):(a.target||a.srcElement)==b.scroller&&la(a);else if(2==c)d&&Sc(this.doc,d),setTimeout(function(){return b.input.focus()},20);else if(3==c)if(ie)this.display.input.onContextMenu(a);else Rd(this)}}function oh(a,b,d,c,e){var f="Click";"double"==c?f="Double"+f:"triple"==c&&(f="Triple"+
f);return ic(a,Xf((1==b?"Left":2==b?"Middle":"Right")+f,e),e,function(g){"string"==typeof g&&(g=hc[g]);if(!g)return!1;var h=!1;try{a.isReadOnly()&&(a.state.suppressEdits=!0),h=g(a,d)!=Yc}finally{a.state.suppressEdits=!1}return h})}function ph(a,b,d,c){G?setTimeout(fd(gf,a),0):a.curOp.focus=ka();var e=a.getOption("configureMouse");e=e?e(a,d,c):{};null==e.unit&&(e.unit=(qh?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=xa?c.metaKey:c.ctrlKey);null==e.moveOnDrag&&(e.moveOnDrag=!(xa?c.altKey:c.ctrlKey));var f=a.doc.sel,g;a.options.dragDrop&&rh&&!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)?sh(a,c,b,e):th(a,c,b,e)}function sh(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:Rd(a));sa(e.wrapper.ownerDocument,"mouseup",g);sa(e.wrapper.ownerDocument,"mousemove",h);sa(e.scroller,"dragstart",k);sa(e.scroller,"drop",g);f||(la(l),c.addNew||Sc(a.doc,d,null,null,c.extend),fa&&!$c||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 hg(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 th(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=va(w(k,d.line).text,d.ch,K),S=va(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=gd(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,gd(H,Q,K))))}P.length||P.push(new I(d,d));da(k,Ba(a,l.ranges.slice(0,n).concat(P),n),{origin:"*mouse",scroll:!1});a.scrollIntoView(x)}else P=p,F=hg(a,x,c.unit),x=P.anchor,0<B(F.anchor,
x)?(K=F.head,x=zc(P.from(),F.anchor)):(K=F.anchor,x=yc(P.to(),F.head)),P=l.ranges.slice(0),P[n]=uh(a,new I(C(k,x),K)),da(k,Ba(a,P,n),je)}function f(x){var P=++u,K=eb(a,x,!0,"rectangle"==c.unit);if(K)if(0!=B(K,q)){a.curOp.focus=ka();e(K);var Q=Lc(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());sa(h.wrapper.ownerDocument,"mousemove",A);sa(h.wrapper.ownerDocument,"mouseup",Y);k.history.lastSelOrigin=null}G&&Rd(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=eb(a,b,!0,!0),n=-1):(b=hg(a,d,c.unit),p=c.extend?be(p,b.anchor,b.head,c.extend):b);c.addNew?-1==n?(n=m.length,da(k,Ba(a,m.concat([p]),n),
{scroll:!1,origin:"*mouse"})):1<m.length&&m[n].empty()&&"char"==c.unit&&!c.extend?(da(k,Ba(a,m.slice(0,n).concat(m.slice(n+1)),0),{scroll:!1,origin:"*mouse"}),l=k.sel):ce(k,n,p,je):(n=0,da(k,new ua([p],0),je),l=k.sel);var q=d,r=h.wrapper.getBoundingClientRect(),u=0,A=ba(a,function(x){0!==x.buttons&&ue(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 uh(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=Ia(e);if(!e)return b;var f=Ib(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=Ib(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 Zc(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||!wa(a,d))return kd(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=$a(a.doc,f),W(a,d,a,e,a.display.gutterSpecs[g].className,b),kd(b)}}function ig(a,b){var d;
(d=Ka(a.display,b))||(d=wa(a,"gutterContextMenu")?Zc(a,b,"gutterContextMenu",!1):!1);if(!d&&!Z(a,b,"contextmenu")&&!ie)a.display.input.onContextMenu(b)}function jg(a){a.display.wrapper.className=a.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+a.options.theme.replace(/(^|\s)\s*/g," cm-s-");Sb(a)}function vh(a,b,d){!b!=!(d&&d!=Fb)&&(d=a.display.dragFunctions,b=b?z:sa,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 wh(a){a.options.lineWrapping?(Wa(a.display.wrapper,"CodeMirror-wrap"),a.display.sizer.style.minWidth="",a.display.sizerWidth=null):(hb(a.display.wrapper,"CodeMirror-wrap"),yd(a));Md(a);ma(a);Sb(a);setTimeout(function(){return wb(a)},100)}function U(a,b){var d=this;if(!(this instanceof U))return new U(a,b);this.options=b=b?Xa(b):{};Xa(kg,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 Wg(a,c,e,b);a.wrapper.CodeMirror=this;jg(this);b.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap");nf(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 Va,keySeq:null,specialChars:null};b.autofocus&&!Zb&&a.input.focus();G&&11>T&&setTimeout(function(){return d.display.input.reset(!0)},
20);xh(this);lg||(eh(),lg=!0);jb(this);this.curOp.forceUpdate=!0;xf(this,c);b.autofocus&&!Zb||this.hasFocus()?setTimeout(function(){d.hasFocus()&&!d.state.focused&&Qd(d)},20):ub(this);for(var f in ad)if(ad.hasOwnProperty(f))ad[f](this,b[f],Fb);qf(this);b.finishInit&&b.finishInit(this);for(c=0;c<ke.length;++c)ke[c](this);kb(this);fa&&b.lineWrapping&&"optimizelegibility"==getComputedStyle(a.lineDiv).textRendering&&(a.lineDiv.style.textRendering="auto")}function xh(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,gg));G&&11>T?z(c.scroller,"dblclick",ba(a,function(h){if(!Z(a,h)){var k=eb(a,h);!k||Zc(a,h,"gutterClick",!0)||Ka(a.display,h)||(la(h),h=a.findWordAt(k),Sc(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 ig(a,
h)});z(c.input.getField(),"contextmenu",function(h){c.scroller.contains(h.target)||ig(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&&!Zc(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&&!Ka(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&&(Vb(a,c.scroller.scrollTop),
ib(a,c.scroller.scrollLeft,!0),W(a,"scroll",a))});z(c.scroller,"mousewheel",function(h){return tf(a,h)});z(c.scroller,"DOMMouseScroll",function(h){return tf(a,h)});z(c.wrapper,"scroll",function(){return c.wrapper.scrollTop=c.wrapper.scrollLeft=0});c.dragFunctions={enter:function(h){Z(a,h)||Kb(h)},over:function(h){if(!Z(a,h)){var k=eb(a,h);if(k){var l=document.createDocumentFragment();Nd(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)}Kb(h)}},start:function(h){if(G&&(!a.state.draggingText||100>+new Date-Uf))Kb(h);else if(!Z(a,h)&&!Ka(a.display,h)&&(h.dataTransfer.setData("Text",a.getSelection()),h.dataTransfer.effectAllowed="copyMove",h.dataTransfer.setDragImage&&!$c)){var k=v("img",null,null,"position: fixed; left: 0; top: 0;");k.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";Aa&&(k.width=k.height=1,a.display.wrapper.appendChild(k),k._top=k.offsetTop);
h.dataTransfer.setDragImage(k,0,0);Aa&&k.parentNode.removeChild(k)}},drop:ba(a,dh),leave:function(h){Z(a,h)||Tf(a)}};var g=c.input.getField();z(g,"keyup",function(h){return eg.call(a,h)});z(g,"keydown",ba(a,dg));z(g,"keypress",ba(a,fg));z(g,"focus",function(h){return Qd(a,h)});z(g,"blur",function(h){return ub(a,h)})}function lc(a,b,d,c){var e=a.doc,f;null==d&&(d="add");"smart"==d&&(e.mode.indent?f=Mb(a,b).state:d="prev");var g=a.options.tabSize,h=w(e,b),k=va(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==Yc||150<m)){if(!c)return;d="prev"}"prev"==d?m=b>e.first?va(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+=hd(m-c));if(d!=l)return Bb(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);ce(e,g,new I(b,b));break}}function le(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=me(b),l=null;if(h&&1<c.ranges.length)if(ra&&ra.text.join("\n")==b){if(0==c.ranges.length%ra.text.length){l=[];for(var m=0;m<ra.text.length;m++)l.push(f.splitLines(ra.text[m]))}}else k.length==c.ranges.length&&a.options.pasteLinesPerSelection&&
(l=uc(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&&ra&&ra.lineWise&&ra.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")};Ab(a.doc,p);aa(a,"inputRead",a,p)}b&&!h&&mg(a,b);vb(a);2>a.curOp.updateInput&&
(a.curOp.updateInput=m);a.curOp.typing=!0;a.state.pasteIncoming=a.state.cutIncoming=-1}function ng(a,b){var d=a.clipboardData&&a.clipboardData.getData("Text");if(d)return a.preventDefault(),b.isReadOnly()||b.options.disableInput||qa(b,function(){return le(b,d,0,null,"paste")}),!0}function mg(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=lc(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=lc(a,e.head.line,"smart"));g&&aa(a,"electricInput",a,e.head.line)}}}function og(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 pg(a,b,d,c){a.setAttribute("autocorrect",d?"":"off");a.setAttribute("autocapitalize",c?"":"off");a.setAttribute("spellcheck",!!b)}function qg(){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");mc&&(a.style.border="1px solid black");pg(a);return b}function ne(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?ih(a.cm,k,b,d):ee(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=fe(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=vc(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=Uc(a,b,g,h,!0);qd(g,h)&&(h.hitSide=!0);return h}function rg(a,b,d,c){var e=a.doc,f=b.left;if("page"==c){var g=Math.max(Math.min(a.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight)-
.5*tb(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=Jd(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 sg(a,b){var d=Ed(a,b.line);if(!d||d.hidden)return null;var c=w(a.doc,b.line);d=Te(d,c,b.line);a=Ia(c,a.doc.direction);c="left";a&&(c=Ib(a,b.ch)%2?"right":"left");b=Ue(d.map,b.ch,c);b.offset="right"==b.collapse?b.end:b.start;return b}function yh(a){for(;a;a=a.parentNode)if(/CodeMirror-gutter-wrapper/.test(a.className))return!0;
return!1}function Gb(a,b){b&&(a.bad=!0);return a}function zh(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(Za(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 bd(a,b,d){if(b==a.display.lineDiv){var c=a.display.lineDiv.childNodes[d];if(!c)return Gb(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 Ah(f,b,d)}}function Ah(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 Gb(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,Gb(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 Gb(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 Gb(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 Gb(t(b.line,b.ch+d),f);d+=h.textContent.length}}var pa=navigator.userAgent,tg=navigator.platform,La=/gecko\/\d/i.test(pa),ug=/MSIE \d/.test(pa),vg=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(pa),cd=/Edge\/(\d+)/.exec(pa),G=ug||vg||cd,T=G&&(ug?document.documentMode||6:+(cd||vg)[1]),fa=!cd&&/WebKit\//.test(pa),Bh=fa&&/Qt\/\d+\.\d+/.test(pa),Ec=!cd&&/Chrome\//.test(pa),Aa=/Opera\//.test(pa),$c=/Apple Computer/.test(navigator.vendor),Ch=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(pa),
Tg=/PhantomJS/.test(pa),mc=$c&&(/Mobile\/\w+/.test(pa)||2<navigator.maxTouchPoints),Fc=/Android/.test(pa),Zb=mc||Fc||/webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(pa),xa=mc||/Mac/.test(tg),qh=/\bCrOS\b/.test(pa),Dh=/win/i.test(tg),lb=Aa&&pa.match(/Version\/(\d*\.\d*)/);lb&&(lb=Number(lb[1]));lb&&15<=lb&&(Aa=!1,fa=!0);var Yf=xa&&(Bh||Aa&&(null==lb||12.11>lb)),ie=La||G&&9<=T,hb=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 Ob=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 nc=function(a){a.select()};mc?nc=function(a){a.selectionStart=0;a.selectionEnd=a.value.length}:G&&(nc=function(a){try{a.select()}catch(b){}});var Va=function(){this.f=this.id=null;
this.time=0;this.handler=fd(this.onTimeout,this)};Va.prototype.onTimeout=function(a){a.id=0;a.time<=+new Date?a.f():setTimeout(a.handler,a.time-+new Date)};Va.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 Yc={toString:function(){return"CodeMirror.Pass"}},Ha={scroll:!1},je={origin:"*mouse"},oc={origin:"+move"},tc=[""],xg=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,
yg=/[\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]/,
Jb=null,Ag=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}}(),wc=[],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]||wc).concat(d))},rh=function(){if(G&&9>T)return!1;var a=v("div");return"draggable"in a||"dragDrop"in a}(),Ad,zd,me=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/)},Eh=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},lh=function(){var a=v("div");if("oncopy"in a)return!0;a.setAttribute("oncopy","return;");return"function"==typeof a.oncopy}(),Gd=null,ld={},ob={},pb={},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=va(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue),this.lastColumnPos=this.start);return this.lastColumnValue-(this.lineStart?va(this.string,this.lineStart,this.tabSize):0)};X.prototype.indentation=function(){return va(this.string,null,this.tabSize)-(this.lineStart?va(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 Ac=function(a,b){this.state=a;this.lookAhead=b},Da=function(a,b,d,c){this.state=b;this.doc=a;this.line=d;this.maxLookAhead=c||0;this.baseTokens=null;this.baseTokenPos=1};Da.prototype.lookAhead=function(a){var b=this.doc.getLine(this.line+a);null!=b&&a>this.maxLookAhead&&(this.maxLookAhead=a);return b};Da.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}};Da.prototype.nextLine=function(){this.line++;0<this.maxLookAhead&&this.maxLookAhead--};Da.fromSaved=function(a,b,d){return b instanceof Ac?new Da(a,Ya(a.mode,b.state),d,b.lookAhead):new Da(a,Ya(a.mode,b),d)};Da.prototype.save=function(a){a=!1!==a?Ya(this.doc.mode,this.state):this.state;return 0<this.maxLookAhead?new Ac(a,this.maxLookAhead):a};var Ce=function(a,b,d){this.start=a.start;this.end=a.pos;this.string=
a.current();this.type=b||null;this.state=d},Lf=!1,Ja=!1,xb=function(a,b,d){this.text=a;Ge(this,b);this.height=d?d(this):1};xb.prototype.lineNo=function(){return N(this)};nb(xb);var Hg={},Gg={},rb=null,Pb=null,Ve={left:0,right:0,top:0,bottom:0},db,mb=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")};mb.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}};mb.prototype.setScrollLeft=function(a){this.horiz.scrollLeft!=a&&(this.horiz.scrollLeft=a);this.disableHoriz&&this.enableZeroWidthBar(this.horiz,this.disableHoriz,"horiz")};mb.prototype.setScrollTop=function(a){this.vert.scrollTop!=a&&(this.vert.scrollTop=a);this.disableVert&&this.enableZeroWidthBar(this.vert,this.disableVert,"vert")};mb.prototype.zeroWidthHack=function(){this.horiz.style.height=this.vert.style.width=xa&&!Ch?"12px":"18px";this.horiz.style.pointerEvents=this.vert.style.pointerEvents=
"none";this.disableHoriz=new Va;this.disableVert=new Va};mb.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.pointerEvents="none":b.set(1E3,c)}a.style.pointerEvents="auto";b.set(1E3,c)};mb.prototype.clear=function(){var a=this.horiz.parentNode;a.removeChild(this.horiz);a.removeChild(this.vert)};var pc=function(){};pc.prototype.update=
function(){return{bottom:0,right:0}};pc.prototype.setScrollLeft=function(){};pc.prototype.setScrollTop=function(){};pc.prototype.clear=function(){};var of={"native":mb,"null":pc},Sg=0,Oc=function(a,b,d){var c=a.display;this.viewport=b;this.visible=Lc(c,a.doc,b);this.editorIsHidden=!c.wrapper.offsetWidth;this.wrapperHeight=c.wrapper.clientHeight;this.wrapperWidth=c.wrapper.clientWidth;this.oldDisplayWidth=ab(a);this.force=d;this.dims=Fd(a);this.events=[]};Oc.prototype.signal=function(a,b){wa(a,b)&&
this.events.push(arguments)};Oc.prototype.finish=function(){for(var a=0;a<this.events.length;a++)W.apply(null,this.events[a])};var Pc=0,Ma=null;G?Ma=-.53:La?Ma=15:Ec?Ma=-.7:$c&&(Ma=-1/3);var ua=function(a,b){this.ranges=a;this.primIndex=b};ua.prototype.primary=function(){return this.ranges[this.primIndex]};ua.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(!qd(d.anchor,c.anchor)||!qd(d.head,c.head))return!1}return!0};ua.prototype.deepCopy=function(){for(var a=[],b=0;b<this.ranges.length;b++)a[b]=new I(rd(this.ranges[b].anchor),rd(this.ranges[b].head));return new ua(a,this.primIndex)};ua.prototype.somethingSelected=function(){for(var a=0;a<this.ranges.length;a++)if(!this.ranges[a].empty())return!0;return!1};ua.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 zc(this.anchor,this.head)};I.prototype.to=function(){return yc(this.anchor,this.head)};I.prototype.empty=function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch};cc.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;Fe(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}};dc.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 cc))&&(a=[],this.collapse(a),this.children=[new cc(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 cc(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 dc(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 dc(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 ec=function(a,b,d){if(d)for(var c in d)d.hasOwnProperty(c)&&(this[c]=d[c]);this.doc=a;this.node=b};ec.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=Rb(this);Ca(d,Math.max(0,d.height-f));a&&(qa(a,function(){var g=-f;Fa(d)<(a.curOp&&a.curOp.scrollTop||a.doc.scrollTop)&&Mc(a,g);Qa(a,c,"widget")}),aa(a,"lineWidgetCleared",a,this,c))}};ec.prototype.changed=function(){var a=this,b=this.height,d=this.doc.cm,c=this.line;this.height=null;var e=Rb(this)-b;e&&(Oa(this.doc,c)||Ca(c,c.height+e),d&&qa(d,function(){d.curOp.forceUpdate=!0;Fa(c)<(d.curOp&&d.curOp.scrollTop||d.doc.scrollTop)&&Mc(d,e);aa(d,"lineWidgetChanged",d,a,N(c))}))};
nb(ec);var Rf=0,Ta=function(a,b){this.lines=[];this.type=b;this.doc=a;this.id=++Rf};Ta.prototype.clear=function(){if(!this.explicitlyCleared){var a=this.doc.cm,b=a&&!a.curOp;b&&jb(a);if(wa(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=Nb(f.markedSpans,this);a&&!this.collapsed?Qa(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&&!Oa(this.doc,f)&&a&&Ca(f,tb(a.display))}if(a&&this.collapsed&&!a.options.lineWrapping)for(e=0;e<this.lines.length;++e)f=Ea(this.lines[e]),g=Cc(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&&Hf(a.doc));a&&aa(a,"markerCleared",a,this,d,
c);b&&kb(a);this.parent&&this.parent.clear()}};Ta.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=Nb(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}};Ta.prototype.changed=function(){var a=this,b=this.find(-1,!0),d=this,c=this.doc.cm;b&&c&&qa(c,function(){var e=b.line,f=N(b.line);if(f=Ed(c,f))We(f),c.curOp.selectionChanged=
c.curOp.forceUpdate=!0;c.curOp.updateMaxLine=!0;Oa(d.doc,e)||null==d.height||(f=d.height,d.height=null,(f=Rb(d)-f)&&Ca(e,e.height+f));aa(c,"markerChanged",c,a)})};Ta.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)};Ta.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))};nb(Ta);var fc=function(a,b){this.markers=a;this.primary=b;for(b=0;b<a.length;++b)a[b].parent=this};fc.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")}};fc.prototype.find=function(a,b){return this.primary.find(a,b)};nb(fc);var Fh=0,oa=function(a,b,d,c,e){if(!(this instanceof oa))return new oa(a,b,d,c,e);null==
d&&(d=0);dc.call(this,[new cc([new xb("",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=Na(d);this.history=new Qc(null);this.id=++Fh;this.modeOption=b;this.lineSep=c;this.direction="rtl"==e?"rtl":"ltr";this.extend=!1;"string"==typeof a&&(a=this.splitLines(a));$d(this,{from:d,to:d,text:a});da(this,Na(d),Ha)};oa.prototype=pe(dc.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=od(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;Ab(this,{from:b,to:t(d,w(this,d).text.length),text:this.splitLines(a),origin:"setValue",full:!0},!0);this.cm&&
Ub(this.cm,0,0);da(this,Na(b),Ha)}),replaceRange:function(a,b,d,c){b=C(this,b);d=d?C(this,d):b;Bb(this,a,b,d,c)},getRange:function(a,b,d){a=Za(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(Lb(this,a))return w(this,a)},getLineNumber:function(a){return N(a)},getLineHandleVisualStart:function(a){"number"==typeof a&&(a=w(this,a));return Ea(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,Na(a,null),d)}),setSelection:ca(function(a,
b,d){var c=C(this,a);a=C(this,b||a);da(this,Na(c,a),d)}),extendSelection:ca(function(a,b,d){Sc(this,C(this,a),b&&C(this,b),d)}),extendSelections:ca(function(a,b){Df(this,we(this,a),b)}),extendSelectionsBy:ca(function(a,b){a=uc(this.sel.ranges,a);Df(this,we(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,Ba(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,Ba(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=Za(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=Za(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=vf(h.from,d,e);var k=vf(Ra(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 ua(a,this.sel.primIndex)}b=
a;for(a=c.length-1;0<=a;a--)Ab(this,c[a]);b?Ef(this,b):this.cm&&vb(this.cm)}),undo:ca(function(){Vc(this,"undo")}),redo:ca(function(){Vc(this,"redo")}),undoSelection:ca(function(){Vc(this,"undo",!0)}),redoSelection:ca(function(){Vc(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 Qc(this.history);Sa(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:yb(this.history.done),undone:yb(this.history.undone)}},
setHistory:function(a){var b=this.history=new Qc(this.history);b.done=yb(a.done.slice(0),null,!0);b.undone=yb(a.undone.slice(0),null,!0)},setGutterMarker:ca(function(a,b,d){return bc(this,a,"gutter",function(c){var e=c.gutterMarkers||(c.gutterMarkers={});e[b]=d;!d&&qe(e)&&(c.gutterMarkers=null);return!0})}),clearGutter:ca(function(a){var b=this;this.iter(function(d){d.gutterMarkers&&d.gutterMarkers[a]&&bc(b,d,"gutter",function(){d.gutterMarkers[a]=null;qe(d.gutterMarkers)&&(d.gutterMarkers=null);
return!0})})}),lineInfo:function(a){if("number"==typeof a){if(!Lb(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 bc(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 bc(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 ah(this,a,b,d)}),removeLineWidget:function(a){a.clear()},
markText:function(a,b,d){return Cb(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 Cb(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(od(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(od(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=Sf(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=Cb(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);ch(Sf(this));break}if(a.history==this.history){var d=[a.id];Sa(a,function(c){return d.push(c.id)},!0);a.history=new Qc(null);a.history.done=yb(this.history.done,d);
a.history.undone=yb(this.history.undone,d)}},iterLinkedDocs:function(a){Sa(this,a)},getMode:function(){return this.mode},getEditor:function(){return this.cm},splitLines:function(a){return this.lineSep?a.split(this.lineSep):me(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&&Yg(this.cm))})});oa.prototype.eachLine=oa.prototype.iter;for(var Uf=0,lg=!1,Ua={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"},qc=0;10>qc;qc++)Ua[qc+48]=Ua[qc+96]=String(qc);for(var dd=65;90>=dd;dd++)Ua[dd]=String.fromCharCode(dd);for(var rc=1;12>=rc;rc++)Ua[rc+111]=Ua[rc+63235]="F"+rc;var gc={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"]}};gc["default"]=xa?gc.macDefault:gc.pcDefault;var hc={selectAll:Jf,singleSelection:function(a){return a.setSelection(a.getCursor("anchor"),a.getCursor("head"),Ha)},killLine:function(a){return Eb(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 Eb(a,function(b){return{from:t(b.from().line,0),to:C(a.doc,t(b.to().line+1,0))}})},delLineLeft:function(a){return Eb(a,function(b){return{from:t(b.from().line,0),to:b.from()}})},delWrappedLineLeft:function(a){return Eb(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 Eb(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 $f(a,b.head.line)},{origin:"+move",bias:1})},goLineStartSmart:function(a){return a.extendSelectionsBy(function(b){return ag(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=qb(c,!1);)c=e.find(1,!0).line;c!=d&&(b=N(c));return fe(!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")},oc)},goLineLeft:function(a){return a.extendSelectionsBy(function(b){b=a.cursorCoords(b.head,"div").top+5;return a.coordsChar({left:0,top:b},"div")},oc)},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/)?ag(a,b.head):d},oc)},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=va(a.getLine(f.line),f.ch,c);b.push(hd(c-f%c))}a.replaceSelections(b)},defaultTab:function(a){a.somethingSelected()?a.indentSelection("add"):a.execCommand("insertTab")},transposeChars:function(a){return qa(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 qa(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);vb(a)})},openLine:function(a){return a.replaceSelection("\n","start")},toggleOverwrite:function(a){return a.toggleOverwrite()}},jh=new Va,ge=null,he=function(a,b,d){this.time=a;this.pos=b;this.button=d};he.prototype.compare=function(a,b,d){return this.time+400>a&&0==B(b,this.pos)&&d==this.button};var kc,jc,Fb={toString:function(){return"CodeMirror.Init"}},
kg={},ad={};U.defaults=kg;U.optionHandlers=ad;var ke=[];U.defineInitHook=function(a){return ke.push(a)};var ra=null,O=function(a){this.cm=a;this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null;this.polling=new Va;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())ra={lineWise:!1,text:f.getSelections()},"cut"==h.type&&f.replaceSelection("",null,"cut");else if(f.options.lineWiseCopyCut){var k=og(f);ra={lineWise:!0,text:k.text};"cut"==h.type&&f.operation(function(){f.setSelections(k.ranges,0,Ha);f.replaceSelection("",null,"cut")})}else return;if(h.clipboardData){h.clipboardData.clearData();var l=ra.text.join("\n");h.clipboardData.setData("Text",l);if(h.clipboardData.getData("Text")==l){h.preventDefault();return}}var m=qg();h=m.firstChild;
f.display.lineSpace.insertBefore(m,f.display.lineSpace.firstChild);h.value=ra.text.join("\n");var n=ka();nc(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;pg(g,f.options.spellcheck,f.options.autocorrect,f.options.autocapitalize);z(g,"paste",function(h){!b(h)||Z(f,h)||ng(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=ff(this.cm,!1);a.focus=ka()==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=bd(b,a.anchorNode,a.anchorOffset),f=bd(b,a.focusNode,a.focusOffset);if(!e||e.bad||!f||f.bad||0!=B(zc(e,f),c)||0!=B(yc(e,f),d))if(e=b.display.view,c=c.line>=b.display.viewFrom&&sg(b,c)||{node:e[0].measure.map[2],offset:0},d=d.line<b.display.viewTo&&sg(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=Ob(c.node,c.offset,d.offset,d.node)}catch(h){}g&&(!La&&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):La&&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||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):qa(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(Fc&&Ec&&this.cm.display.gutterSpecs.length&&
yh(a.anchorNode))this.cm.triggerOnKeyDown({type:"keydown",keyCode:8,preventDefault:Math.abs}),this.blur(),this.focus();else if(!this.composing){this.rememberSelection();var d=bd(b,a.anchorNode,a.anchorOffset),c=bd(b,a.focusNode,a.focusOffset);d&&c&&qa(b,function(){da(b.doc,Na(d,c),Ha);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=bb(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=bb(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(zh(a,f,b,d,e));for(f=Za(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 Bb(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()||qa(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,le)(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 Va;this.hasSelection=!1;this.composing=null};
V.prototype.init=function(a){function b(g){if(!Z(e,g)){if(e.somethingSelected())ra={lineWise:!1,text:e.getSelections()};else if(e.options.lineWiseCopyCut){var h=og(e);ra={lineWise:!0,text:h.text};"cut"==g.type?e.setSelections(h.ranges,null,Ha):(c.prevInput="",f.value=h.text.join("\n"),nc(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);mc&&(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)||ng(g,e)||(e.state.pasteIncoming=+new Date,c.fastPoll())});z(f,"cut",b);z(f,"copy",b);z(a.scroller,"paste",function(g){if(!Ka(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){Ka(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=qg();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=ff(a);if(a.options.moveInputWithCursor){a=za(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){var b=this.cm;b.somethingSelected()?(this.prevInput="",a=b.getSelection(),this.textarea.value=a,b.state.focused&&nc(this.textarea),G&&9<=T&&(this.hasSelection=a)):a||(this.prevInput=this.textarea.value="",G&&9<=T&&(this.hasSelection=null))}};V.prototype.getField=function(){return this.textarea};V.prototype.supportsTouch=function(){return!1};V.prototype.focus=function(){if("nocursor"!=
this.cm.options.readOnly&&(!Zb||ka()!=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||!b.state.focused||Eh(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||xa&&/[\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;qa(b,function(){le(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,Jf)(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=eb(e,
a),k=f.scroller.scrollTop;if(h&&!Aa){e.options.resetSelectionOnContextMenu&&-1==e.doc.sel.contains(h)&&ba(e,da)(e.doc,Na(h),Ha);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=window.scrollY;f.input.focus();fa&&window.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(ie){Kb(a);var p=function(){sa(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!=Fb&&f(h,k,l)}:f)}var d=a.optionHandlers;a.defineOption=b;a.Init=Fb;b("value","",function(c,e){return c.setValue(e)},!0);b("mode",null,function(c,e){c.doc.modeOption=e;Zd(c)},!0);b("indentUnit",2,Zd,!0);b("indentWithTabs",!1);b("smartIndent",!0);b("tabSize",4,function(c){$b(c);Sb(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--)Bb(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\ufeff\ufff9-\ufffc]/g,function(c,e,f){c.state.specialChars=new RegExp(e.source+(e.test("\t")?"":"|\t"),"g");f!=Fb&&c.refresh()});b("specialCharPlaceholder",Kg,function(c){return c.refresh()},!0);b("electricChars",!0);b("inputStyle",
Zb?"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",!Dh);b("wholeLineUpdateBefore",!0);b("theme","default",function(c){jg(c);Yb(c)},!0);b("keyMap","default",function(c,e,f){e=Wc(e);
(f=f!=Fb&&Wc(f))&&f.detach&&f.detach(c,e);e.attach&&e.attach(c,f||null)});b("extraKeys",null);b("configureMouse",null);b("lineWrapping",!1,wh,!0);b("gutters",[],function(c,e){c.display.gutterSpecs=Xd(e,c.options.lineNumbers);Yb(c)},!0);b("fixedGutter",!0,function(c,e){c.display.gutters.style.left=e?Ld(c.display)+"px":"0";c.refresh()},!0);b("coverGutterNextToScrollbar",!1,function(c){return wb(c)},!0);b("scrollbarStyle","native",function(c){nf(c);wb(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=Xd(c.options.gutters,e);Yb(c)},!0);b("firstLineNumber",1,Yb,!0);b("lineNumberFormatter",function(c){return c},Yb,!0);b("showCursorWhenSelecting",!1,Tb,!0);b("resetSelectionOnContextMenu",!0);b("lineWiseCopyCut",!0);b("pasteLinesPerSelection",!0);b("selectionsMayTouch",!1);b("readOnly",!1,function(c,e){"nocursor"==e&&(ub(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,vh);b("allowDropFileTypes",null);b("cursorBlinkRate",530);b("cursorScrollMargin",0);b("cursorHeight",1,Tb,!0);b("singleCursorHeightPerLine",!0,Tb,!0);b("workTime",100);b("workDelay",100);b("flattenSpans",!0,$b,!0);b("addModeClass",!1,$b,!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,$b,!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(){window.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"](Wc(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.");
wg(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");Lb(this.doc,c)&&
lc(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&&(lc(this,h.head.line,c,!0),f=h.head.line,g==this.doc.sel.primIndex&&vb(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)lc(this,h,c);h=this.doc.sel.ranges;0==k.ch&&e.length==h.length&&0<h[g].from().ch&&ce(this.doc,g,new I(k,h[g].to()),Ha)}}}),getTokenAt:function(c,e){return Be(this,
c,e)},getLineTokens:function(c,e){return Be(this,t(c),e,!0)},getTokenTypeAt:function(c){c=C(this.doc,c);var e=ze(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 Mb(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 za(this,c,e||"page")},charCoords:function(c,e){return Hc(this,C(this.doc,c),e||"page")},coordsChar:function(c,e){c=$e(this,c,e||"page");return Jd(this,c.left,c.top)},lineAtHeight:function(c,e){c=$e(this,{top:c,left:0},e||"page").top;return $a(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 Gc(this,c,{top:0,left:0},e||"page",f||g).top+(g?this.doc.height-Fa(c):0)},defaultTextHeight:function(){return tb(this.display)},defaultCharWidth:function(){return sb(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=za(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=Sd(this,{left:m,top:l,right:m+e.offsetWidth,bottom:l+e.offsetHeight}),null!=c.scrollTop&&Vb(this,c.scrollTop),null!=c.scrollLeft&&ib(this,c.scrollLeft))},triggerOnKeyDown:ia(dg),triggerOnKeyPress:ia(fg),triggerOnKeyUp:eg,triggerOnMouseDown:ia(gg),execCommand:function(c){if(hc.hasOwnProperty(c))return hc[c].call(null,this)},triggerElectric:ia(function(c){mg(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=ne(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()?ne(f.doc,g.head,c,e,f.options.rtlMoveVisually):0>c?g.from():g.to()},oc)}),deleteH:ia(function(c,e){var f=this.doc;this.doc.sel.somethingSelected()?f.replaceSelection("",null,"+delete"):Eb(this,function(g){var h=ne(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=za(this,k,"div"),null==g?g=k.left:k.left=g,k=rg(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=za(f,m.head,"div");null!=m.goalColumn&&(n.left=m.goalColumn);h.push(n.left);var p=rg(f,n,c,e);"page"==e&&
m==g.sel.primary()&&Mc(f,Hc(f,p,"div").top-n.top);return p},oc);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=vc(k,h)?function(l){return vc(l,h)}:/\s/.test(k)?function(l){return/\s/.test(l)}:function(l){return!/\s/.test(l)&&!vc(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)?Wa(this.display.cursorDiv,"CodeMirror-overwrite"):hb(this.display.cursorDiv,"CodeMirror-overwrite"),W(this,"overwriteToggle",this,this.state.overwrite)},hasFocus:function(){return this.display.input.getField()==ka()},isReadOnly:function(){return!(!this.options.readOnly&&!this.doc.cantEdit)},scrollTo:ia(function(c,e){Ub(this,c,e)}),getScrollInfo:function(){var c=this.display.scroller;
return{left:c.scrollLeft,top:c.scrollTop,height:c.scrollHeight-Ga(this)-this.display.barHeight,width:c.scrollWidth-Ga(this)-this.display.barWidth,clientHeight:Dd(this),clientWidth:ab(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?(Nc(this),this.curOp.scrollToPos=c):jf(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&&Xe(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){Qa(f,h,"widget");break}++h});this.curOp.forceUpdate=!0;W(this,"refresh",this)}),operation:function(c){return qa(this,
c)},startOperation:function(){return jb(this)},endOperation:function(){return kb(this)},refresh:ia(function(){var c=this.display.cachedTextHeight;ma(this);this.curOp.forceUpdate=!0;Sb(this);Ub(this,this.doc.scrollLeft,this.doc.scrollTop);Wd(this.display);(null==c||.5<Math.abs(c-tb(this.display))||this.options.lineWrapping)&&Md(this);W(this,"refresh",this)}),swapDoc:ia(function(c){var e=this.doc;e.cm=null;this.state.selectingText&&this.state.selectingText();xf(this,c);Sb(this);this.display.input.reset();
Ub(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}};nb(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 Gh="iter insert remove copy getEditor constructor".split(" "),sc;for(sc in oa.prototype)oa.prototype.hasOwnProperty(sc)&&0>ea(Gh,sc)&&(U.prototype[sc]=function(a){return function(){return a.apply(this.doc,arguments)}}(oa.prototype[sc]));nb(oa);U.inputStyles={textarea:V,contenteditable:O};U.defineMode=function(a){U.defaults.mode||"null"==a||(U.defaults.mode=
a);Bg.apply(this,arguments)};U.defineMIME=function(a,b){ob[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?Xa(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();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&&(sa(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=sa;a.on=z;a.wheelEventPixels=Xg;a.Doc=oa;a.splitLines=me;a.countColumn=va;a.findColumn=gd;a.isWordChar=id;a.Pass=Yc;a.signal=W;a.Line=xb;a.changeEnd=Ra;a.scrollbarModel=of;a.Pos=t;a.cmpPos=B;a.modes=ld;a.mimeModes=ob;a.resolveMode=xc;a.getMode=md;a.modeExtensions=pb;a.extendMode=Cg;a.copyState=Ya;a.startState=ve;a.innerMode=nd;a.commands=hc;a.keyMap=gc;
a.keyName=Zf;a.isModifierKey=Wf;a.lookupKey=Db;a.normalizeKeyMap=hh;a.StringStream=X;a.SharedTextMarker=fc;a.TextMarker=Ta;a.LineWidget=ec;a.e_preventDefault=la;a.e_stopPropagation=te;a.e_stop=Kb;a.addClass=Wa;a.contains=ja;a.rmClass=hb;a.keyNames=Ua})(U);U.version="5.65.0";return U});
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],30:[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 pa(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;qa=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--)qa.push(arguments[a])}function c(){k.apply(null,arguments);return!0}function ra(a,b){for(;b;b=b.next)if(b.name==a)return!0;return!1}function N(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(!ra(a,b.localVars)){b.localVars=new Y(a,b.localVars);return}A.globalVars&&!ra(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:ra(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 O(){p.context=new Z(p.context,p.localVars,!1);p.localVars=Xa}function sa(){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("}"),sa,ia,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"),sa,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("}"),ia,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"),sa,ia,g,g,C):"case"==a?c(t,n(":")):"default"==a?c(n(":")):"catch"==a?c(l("form"),O,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(K,
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(O,l(")"),z(K,")"),g,n("=>"),e,C);if("variable"==a)return k(O,D,n("=>"),e,C)}e=d?Q:L;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(ja,"}",null,e):"quasi"==a?k(ka,e):"new"==a?c(eb(d)):c()}function P(a){return a.match(/[;\}\)\],]/)?k():k(t)}function L(a,b){return","==a?c(P):Q(a,b,!1)}function Q(a,b,d){var e=0==d?L:Q,h=0==d?t:B;if("=>"==a)return c(O,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(ka,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 ka(a,b){return"quasi"!=a?k():"${"!=b.slice(b.length-2)?c(ka):c(P,gb)}function gb(a){if("}"==a)return f="string-2",p.tokenize=W,c(ka)}function Oa(a){pa(w,p);return k("{"==a?x:t)}function Na(a){pa(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:L):k(a?B:t)}}
function ib(a,b){if("target"==b)return f="keyword",c(L)}function hb(a,b){if("target"==b)return f="keyword",c(Q)}function Ya(a){return":"==a?c(g,x):k(L,n(";"),g)}function fb(a){if("variable"==a)return f="property",c()}function ja(a,b){if("async"==a)return f="property",c(ja);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(M)}if("number"==a||"string"==a)return f=fa?"property":
X+" property",c(M);if("jsonld-keyword"==a)return c(M);if(r&&ha(b))return f="keyword",c(ja);if("["==a)return c(t,R,n("]"),M);if("spread"==a)return c(B,M);if("*"==b)return f="keyword",c(ja);if(":"==a)return k(M)}function kb(a){if("variable"!=a)return k(M);f="property";return c(G)}function M(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++)qa.push(arguments[e]);return c(l(b,d),z(a,b),g)}function ia(a){return"}"==a?c():k(x,ia)}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 la(){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 N(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 N(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 N(b),c(G);if("("==a)return c(O,l(")"),z(K,")"),g,Pa,x,C);if(r&&"<"==b)return c(l(">"),z(la,">"),g,G)}function S(a,b){if("*"==b)return f="keyword",c(S);if("variable"==a)return N(b),c(S);if("("==a)return c(O,l(")"),z(K,")"),g,Pa,C);if(r&&"<"==b)return c(l(">"),z(la,">"),
g,S)}function La(a,b){if("keyword"==a||"variable"==a)return f="type",c(La);if("<"==b)return c(l(">"),z(la,">"),g)}function K(a,b){"@"==b&&c(t,K);return"spread"==a?c(K):r&&ha(b)?(f="keyword",c(K)):r&&"this"==a?c(R,H):k(D,R,H)}function cb(a,b){return"variable"==a?Ja(a,b):ma(a,b)}function Ja(a,b){if("variable"==a)return N(b),c(ma)}function ma(a,b){if("<"==b)return c(l(">"),z(la,">"),g,ma);if("extends"==b||"implements"==b||r&&","==a)return"implements"==b&&(f="keyword"),c(r?q:t,ma);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(na,F);if("number"==a||"string"==a)return c(na,F);if("["==a)return c(t,R,n("]"),na,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 na(a,b){if("!"==b||"?"==b)return c(na);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(L):k(oa,Sa,za)}function oa(a,b){if("{"==a)return aa(oa,"}");"variable"==a&&N(b);"*"==b&&(f="keyword");return c(tb)}function Sa(a){if(","==a)return c(oa,
Sa)}function tb(a,b){if("as"==b)return f="keyword",c(oa)}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 qa=f=p=null;var X=w=void 0;var Xa=new Y("this",new Y("arguments",null));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(),pa(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!=L&&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":29}],31:[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;
};
},{}],32:[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()
})
}
},{}],33:[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)
}
}
},{}],34:[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;
};
},{}],35:[function(require,module,exports){
'use strict';
var implementation = require('./implementation');
module.exports = Function.prototype.bind || implementation;
},{"./implementation":34}],36:[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 getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);
var INTRINSICS = {
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols ? 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,
'%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([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? 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 ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols ? 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
};
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) {
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);
/* 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');
}
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":35,"has":41,"has-symbols":39}],37:[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":128}],38:[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 : {})
},{}],39:[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":40}],40:[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;
};
},{}],41:[function(require,module,exports){
'use strict';
var bind = require('function-bind');
module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);
},{"function-bind":35}],42:[function(require,module,exports){
const Output = require('./src/output.js')
const loop = require('raf-loop')
const Source = require('./src/hydra-source.js')
const Mouse = require('./src/lib/mouse.js')()
const Audio = require('./src/lib/audio.js')
const VidRecorder = require('./src/lib/video-recorder.js')
const ArrayUtils = require('./src/lib/array-utils.js')
const Sandbox = require('./src/eval-sandbox.js')
const Generator = require('./src/generator-factory.js')
// to do: add ability to pass in certain uniforms and transforms
class HydraRenderer {
constructor ({
pb = null,
width = 1280,
height = 720,
numSources = 4,
numOutputs = 4,
makeGlobal = true,
autoLoop = true,
detectAudio = true,
enableStreamCapture = true,
canvas,
precision,
extendTransforms = {} // add your own functions on init
} = {}) {
ArrayUtils.init()
this.pb = pb
this.width = width
this.height = height
this.renderAll = false
this.detectAudio = detectAudio
this._initCanvas(canvas)
// object that contains all properties that will be made available on the global context and during local evaluation
this.synth = {
time: 0,
bpm: 30,
width: this.width,
height: this.height,
fps: undefined,
stats: {
fps: 0
},
speed: 1,
mouse: Mouse,
render: this._render.bind(this),
setResolution: this.setResolution.bind(this),
update: (dt) => {},// user defined update function
hush: this.hush.bind(this)
}
if (makeGlobal) window.loadScript = this.loadScript
this.timeSinceLastUpdate = 0
this._time = 0 // for internal use, only to use for deciding when to render frames
// only allow valid precision options
let precisionOptions = ['lowp','mediump','highp']
if(precision && precisionOptions.includes(precision.toLowerCase())) {
this.precision = precision.toLowerCase()
//
// if(!precisionValid){
// console.warn('[hydra-synth warning]\nConstructor was provided an invalid floating point precision value of "' + precision + '". Using default value of "mediump" instead.')
// }
} else {
let isIOS =
(/iPad|iPhone|iPod/.test(navigator.platform) ||
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) &&
!window.MSStream;
this.precision = isIOS ? 'highp' : 'mediump'
}
this.extendTransforms = extendTransforms
// boolean to store when to save screenshot
this.saveFrame = false
// if stream capture is enabled, this object contains the capture stream
this.captureStream = null
this.generator = undefined
this._initRegl()
this._initOutputs(numOutputs)
this._initSources(numSources)
this._generateGlslTransforms()
this.synth.screencap = () => {
this.saveFrame = true
}
if (enableStreamCapture) {
try {
this.captureStream = this.canvas.captureStream(25)
// to do: enable capture stream of specific sources and outputs
this.synth.vidRecorder = new VidRecorder(this.captureStream)
} catch (e) {
console.warn('[hydra-synth warning]\nnew MediaSource() is not currently supported on iOS.')
console.error(e)
}
}
if(detectAudio) this._initAudio()
if(autoLoop) loop(this.tick.bind(this)).start()
// final argument is properties that the user can set, all others are treated as read-only
this.sandbox = new Sandbox(this.synth, makeGlobal, ['speed', 'update', 'bpm', 'fps'])
}
eval(code) {
this.sandbox.eval(code)
}
getScreenImage(callback) {
this.imageCallback = callback
this.saveFrame = true
}
hush() {
this.s.forEach((source) => {
source.clear()
})
this.o.forEach((output) => {
this.synth.solid(0, 0, 0, 0).out(output)
})
this.synth.render(this.o[0])
}
loadScript(url = "") {
const p = new Promise((res, rej) => {
var script = document.createElement("script");
script.onload = function () {
console.log(`loaded script ${url}`);
res();
};
script.onerror = (err) => {
console.log(`error loading script ${url}`, "log-error");
res()
};
script.src = url;
document.head.appendChild(script);
});
return p;
}
setResolution(width, height) {
// console.log(width, height)
this.canvas.width = width
this.canvas.height = height
this.width = width // is this necessary?
this.height = height // ?
this.sandbox.set('width', width)
this.sandbox.set('height', height)
console.log(this.width)
this.o.forEach((output) => {
output.resize(width, height)
})
this.s.forEach((source) => {
source.resize(width, height)
})
this.regl._refresh()
console.log(this.canvas.width)
}
canvasToImage (callback) {
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()}.png`
document.body.appendChild(a)
var self = this
this.canvas.toBlob( (blob) => {
if(self.imageCallback){
self.imageCallback(blob)
delete self.imageCallback
} else {
a.href = URL.createObjectURL(blob)
console.log(a.href)
a.click()
}
}, 'image/png')
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(a.href);
}, 300);
}
_initAudio () {
const that = this
this.synth.a = new Audio({
numBins: 4,
// changeListener: ({audio}) => {
// that.a = audio.bins.map((_, index) =>
// (scale = 1, offset = 0) => () => (audio.fft[index] * scale + offset)
// )
//
// if (that.makeGlobal) {
// that.a.forEach((a, index) => {
// const aname = `a${index}`
// window[aname] = a
// })
// }
// }
})
}
// create main output canvas and add to screen
_initCanvas (canvas) {
if (canvas) {
this.canvas = canvas
this.width = canvas.width
this.height = canvas.height
} else {
this.canvas = document.createElement('canvas')
this.canvas.width = this.width
this.canvas.height = this.height
this.canvas.style.width = '100%'
this.canvas.style.height = '100%'
this.canvas.style.imageRendering = 'pixelated'
document.body.appendChild(this.canvas)
}
}
_initRegl () {
this.regl = require('regl')({
// profile: true,
canvas: this.canvas,
pixelRatio: 1//,
// extensions: [
// 'oes_texture_half_float',
// 'oes_texture_half_float_linear'
// ],
// optionalExtensions: [
// 'oes_texture_float',
// 'oes_texture_float_linear'
//]
})
// This clears the color buffer to black and the depth buffer to 1
this.regl.clear({
color: [0, 0, 0, 1]
})
this.renderAll = this.regl({
frag: `
precision ${this.precision} float;
varying vec2 uv;
uniform sampler2D tex0;
uniform sampler2D tex1;
uniform sampler2D tex2;
uniform sampler2D tex3;
void main () {
vec2 st = vec2(1.0 - uv.x, uv.y);
st*= vec2(2);
vec2 q = floor(st).xy*(vec2(2.0, 1.0));
int quad = int(q.x) + int(q.y);
st.x += step(1., mod(st.y,2.0));
st.y += step(1., mod(st.x,2.0));
st = fract(st);
if(quad==0){
gl_FragColor = texture2D(tex0, st);
} else if(quad==1){
gl_FragColor = texture2D(tex1, st);
} else if (quad==2){
gl_FragColor = texture2D(tex2, st);
} else {
gl_FragColor = texture2D(tex3, st);
}
}
`,
vert: `
precision ${this.precision} float;
attribute vec2 position;
varying vec2 uv;
void main () {
uv = position;
gl_Position = vec4(1.0 - 2.0 * position, 0, 1);
}`,
attributes: {
position: [
[-2, 0],
[0, -2],
[2, 2]
]
},
uniforms: {
tex0: this.regl.prop('tex0'),
tex1: this.regl.prop('tex1'),
tex2: this.regl.prop('tex2'),
tex3: this.regl.prop('tex3')
},
count: 3,
depth: { enable: false }
})
this.renderFbo = this.regl({
frag: `
precision ${this.precision} float;
varying vec2 uv;
uniform vec2 resolution;
uniform sampler2D tex0;
void main () {
gl_FragColor = texture2D(tex0, vec2(1.0 - uv.x, uv.y));
}
`,
vert: `
precision ${this.precision} float;
attribute vec2 position;
varying vec2 uv;
void main () {
uv = position;
gl_Position = vec4(1.0 - 2.0 * position, 0, 1);
}`,
attributes: {
position: [
[-2, 0],
[0, -2],
[2, 2]
]
},
uniforms: {
tex0: this.regl.prop('tex0'),
resolution: this.regl.prop('resolution')
},
count: 3,
depth: { enable: false }
})
}
_initOutputs (numOutputs) {
const self = this
this.o = (Array(numOutputs)).fill().map((el, index) => {
var o = new Output({
regl: this.regl,
width: this.width,
height: this.height,
precision: this.precision,
label: `o${index}`
})
// o.render()
o.id = index
self.synth['o'+index] = o
return o
})
// set default output
this.output = this.o[0]
}
_initSources (numSources) {
this.s = []
for(var i = 0; i < numSources; i++) {
this.createSource(i)
}
}
createSource (i) {
let s = new Source({regl: this.regl, pb: this.pb, width: this.width, height: this.height, label: `s${i}`})
this.synth['s' + this.s.length] = s
this.s.push(s)
return s
}
_generateGlslTransforms () {
var self = this
this.generator = new Generator({
defaultOutput: this.o[0],
defaultUniforms: this.o[0].uniforms,
extendTransforms: this.extendTransforms,
changeListener: ({type, method, synth}) => {
if (type === 'add') {
self.synth[method] = synth.generators[method]
if(self.sandbox) self.sandbox.add(method)
} else if (type === 'remove') {
// what to do here? dangerously deleting window methods
//delete window[method]
}
// }
}
})
this.synth.setFunction = this.generator.setFunction.bind(this.generator)
}
_render (output) {
if (output) {
this.output = output
this.isRenderingAll = false
} else {
this.isRenderingAll = true
}
}
// dt in ms
tick (dt, uniforms) {
this.sandbox.tick()
if(this.detectAudio === true) this.synth.a.tick()
// let updateInterval = 1000/this.synth.fps // ms
if(this.synth.update) {
try { this.synth.update(dt) } catch (e) { console.log(error) }
}
this.sandbox.set('time', this.synth.time += dt * 0.001 * this.synth.speed)
this.timeSinceLastUpdate += dt
if(!this.synth.fps || this.timeSinceLastUpdate >= 1000/this.synth.fps) {
// console.log(1000/this.timeSinceLastUpdate)
this.synth.stats.fps = Math.ceil(1000/this.timeSinceLastUpdate)
// console.log(this.synth.speed, this.synth.time)
for (let i = 0; i < this.s.length; i++) {
this.s[i].tick(this.synth.time)
}
// console.log(this.canvas.width, this.canvas.height)
for (let i = 0; i < this.o.length; i++) {
this.o[i].tick({
time: this.synth.time,
mouse: this.synth.mouse,
bpm: this.synth.bpm,
resolution: [this.canvas.width, this.canvas.height]
})
}
if (this.isRenderingAll) {
this.renderAll({
tex0: this.o[0].getCurrent(),
tex1: this.o[1].getCurrent(),
tex2: this.o[2].getCurrent(),
tex3: this.o[3].getCurrent(),
resolution: [this.canvas.width, this.canvas.height]
})
} else {
this.renderFbo({
tex0: this.output.getCurrent(),
resolution: [this.canvas.width, this.canvas.height]
})
}
this.timeSinceLastUpdate = 0
}
if(this.saveFrame === true) {
this.canvasToImage()
this.saveFrame = false
}
// this.regl.poll()
}
}
module.exports = HydraRenderer
},{"./src/eval-sandbox.js":44,"./src/generator-factory.js":47,"./src/hydra-source.js":51,"./src/lib/array-utils.js":52,"./src/lib/audio.js":53,"./src/lib/mouse.js":56,"./src/lib/video-recorder.js":59,"./src/output.js":61,"raf-loop":137,"regl":139}],43:[function(require,module,exports){
const Synth = require('./hydra-synth.js')
//const ShaderGenerator = require('./shader-generator.js')
module.exports = Synth
},{"./hydra-synth.js":42}],44:[function(require,module,exports){
// handles code evaluation and attaching relevant objects to global and evaluation contexts
const Sandbox = require('./lib/sandbox.js')
const ArrayUtils = require('./lib/array-utils.js')
class EvalSandbox {
constructor(parent, makeGlobal, userProps = []) {
this.makeGlobal = makeGlobal
this.sandbox = Sandbox(parent)
this.parent = parent
var properties = Object.keys(parent)
properties.forEach((property) => this.add(property))
this.userProps = userProps
}
add(name) {
if(this.makeGlobal) window[name] = this.parent[name]
this.sandbox.addToContext(name, `parent.${name}`)
}
// sets on window as well as synth object if global (not needed for objects, which can be set directly)
set(property, value) {
if(this.makeGlobal) {
window[property] = value
}
this.parent[property] = value
}
tick() {
if(this.makeGlobal) {
this.userProps.forEach((property) => {
this.parent[property] = window[property]
})
// this.parent.speed = window.speed
} else {
}
}
eval(code) {
this.sandbox.eval(code)
}
}
module.exports = EvalSandbox
},{"./lib/array-utils.js":52,"./lib/sandbox.js":57}],45:[function(require,module,exports){
const arrayUtils = require('./lib/array-utils.js')
// [WIP] how to treat different dimensions (?)
const DEFAULT_CONVERSIONS = {
float: {
'vec4': { name: 'sum', args: [[1, 1, 1, 1]] },
'vec2': { name: 'sum', args: [[1, 1]] }
}
}
function fillArrayWithDefaults(arr, len) {
// fill the array with default values if it's too short
while (arr.length < len) {
if (arr.length === 3) { // push a 1 as the default for .a in vec4
arr.push(1.0)
} else {
arr.push(0.0)
}
}
return arr.slice(0, len)
}
const ensure_decimal_dot = (val) => {
val = val.toString()
if (val.indexOf('.') < 0) {
val += '.'
}
return val
}
module.exports = function formatArguments(transform, startIndex, synthContext) {
const defaultArgs = transform.transform.inputs
const userArgs = transform.userArgs
const { generators } = transform.synth
const { src } = generators // depends on synth having src() function
return defaultArgs.map((input, index) => {
const typedArg = {
value: input.default,
type: input.type, //
isUniform: false,
name: input.name,
vecLen: 0
// generateGlsl: null // function for creating glsl
}
if (typedArg.type === 'float') typedArg.value = ensure_decimal_dot(input.default)
if (input.type.startsWith('vec')) {
try {
typedArg.vecLen = Number.parseInt(input.type.substr(3))
} catch (e) {
console.log(`Error determining length of vector input type ${input.type} (${input.name})`)
}
}
// if user has input something for this argument
if (userArgs.length > index) {
typedArg.value = userArgs[index]
// do something if a composite or transform
if (typeof userArgs[index] === 'function') {
// if (typedArg.vecLen > 0) { // expected input is a vector, not a scalar
// typedArg.value = (context, props, batchId) => (fillArrayWithDefaults(userArgs[index](props), typedArg.vecLen))
// } else {
typedArg.value = (context, props, batchId) => {
try {
return userArgs[index](props)
} catch (e) {
console.log('ERROR', e)
return input.default
}
}
// }
typedArg.isUniform = true
} else if (userArgs[index].constructor === Array) {
// if (typedArg.vecLen > 0) { // expected input is a vector, not a scalar
// typedArg.isUniform = true
// typedArg.value = fillArrayWithDefaults(typedArg.value, typedArg.vecLen)
// } else {
// console.log("is Array")
typedArg.value = (context, props, batchId) => arrayUtils.getValue(userArgs[index])(props)
typedArg.isUniform = true
// }
}
}
if (startIndex < 0) {
} else {
if (typedArg.value && typedArg.value.transforms) {
const final_transform = typedArg.value.transforms[typedArg.value.transforms.length - 1]
if (final_transform.transform.glsl_return_type !== input.type) {
const defaults = DEFAULT_CONVERSIONS[input.type]
if (typeof defaults !== 'undefined') {
const default_def = defaults[final_transform.transform.glsl_return_type]
if (typeof default_def !== 'undefined') {
const { name, args } = default_def
typedArg.value = typedArg.value[name](...args)
}
}
}
typedArg.isUniform = false
} else if (typedArg.type === 'float' && typeof typedArg.value === 'number') {
typedArg.value = ensure_decimal_dot(typedArg.value)
} else if (typedArg.type.startsWith('vec') && typeof typedArg.value === 'object' && Array.isArray(typedArg.value)) {
typedArg.isUniform = false
typedArg.value = `${typedArg.type}(${typedArg.value.map(ensure_decimal_dot).join(', ')})`
} else if (input.type === 'sampler2D') {
// typedArg.tex = typedArg.value
var x = typedArg.value
typedArg.value = () => (x.getTexture())
typedArg.isUniform = true
} else {
// if passing in a texture reference, when function asks for vec4, convert to vec4
if (typedArg.value.getTexture && input.type === 'vec4') {
var x1 = typedArg.value
typedArg.value = src(x1)
typedArg.isUniform = false
}
}
// add tp uniform array if is a function that will pass in a different value on each render frame,
// or a texture/ external source
if (typedArg.isUniform) {
typedArg.name += startIndex
// shaderParams.uniforms.push(typedArg)
}
}
return typedArg
})
}
},{"./lib/array-utils.js":52}],46:[function(require,module,exports){
const formatArguments = require('./format-arguments.js')
// Add extra functionality to Array.prototype for generating sequences in time
const arrayUtils = require('./lib/array-utils.js')
// converts a tree of javascript functions to a shader
module.exports = function (transforms) {
var shaderParams = {
uniforms: [], // list of uniforms used in shader
glslFunctions: [], // list of functions used in shader
fragColor: ''
}
var gen = generateGlsl(transforms, shaderParams)('st')
shaderParams.fragColor = gen
// remove uniforms with duplicate names
let uniforms = {}
shaderParams.uniforms.forEach((uniform) => uniforms[uniform.name] = uniform)
shaderParams.uniforms = Object.values(uniforms)
return shaderParams
}
// recursive function for generating shader string from object containing functions and user arguments. Order of functions in string depends on type of function
// to do: improve variable names
function generateGlsl (transforms, shaderParams) {
// transform function that outputs a shader string corresponding to gl_FragColor
var fragColor = () => ''
// var uniforms = []
// var glslFunctions = []
transforms.forEach((transform) => {
var inputs = formatArguments(transform, shaderParams.uniforms.length)
inputs.forEach((input) => {
if(input.isUniform) shaderParams.uniforms.push(input)
})
// add new glsl function to running list of functions
if(!contains(transform, shaderParams.glslFunctions)) shaderParams.glslFunctions.push(transform)
// current function for generating frag color shader code
var f0 = fragColor
if (transform.transform.type === 'src') {
fragColor = (uv) => `${shaderString(uv, transform.name, inputs, shaderParams)}`
} else if (transform.transform.type === 'coord') {
fragColor = (uv) => `${f0(`${shaderString(uv, transform.name, inputs, shaderParams)}`)}`
} else if (transform.transform.type === 'color') {
fragColor = (uv) => `${shaderString(`${f0(uv)}`, transform.name, inputs, shaderParams)}`
} else if (transform.transform.type === 'combine') {
// combining two generated shader strings (i.e. for blend, mult, add funtions)
var f1 = inputs[0].value && inputs[0].value.transforms ?
(uv) => `${generateGlsl(inputs[0].value.transforms, shaderParams)(uv)}` :
(inputs[0].isUniform ? () => inputs[0].name : () => inputs[0].value)
fragColor = (uv) => `${shaderString(`${f0(uv)}, ${f1(uv)}`, transform.name, inputs.slice(1), shaderParams)}`
} else if (transform.transform.type === 'combineCoord') {
// combining two generated shader strings (i.e. for modulate functions)
var f1 = inputs[0].value && inputs[0].value.transforms ?
(uv) => `${generateGlsl(inputs[0].value.transforms, shaderParams)(uv)}` :
(inputs[0].isUniform ? () => inputs[0].name : () => inputs[0].value)
fragColor = (uv) => `${f0(`${shaderString(`${uv}, ${f1(uv)}`, transform.name, inputs.slice(1), shaderParams)}`)}`
}
})
// console.log(fragColor)
// break;
return fragColor
}
// assembles a shader string containing the arguments and the function name, i.e. 'osc(uv, frequency)'
function shaderString (uv, method, inputs, shaderParams) {
const str = inputs.map((input) => {
if (input.isUniform) {
return input.name
} else if (input.value && input.value.transforms) {
// this by definition needs to be a generator, hence we start with 'st' as the initial value for generating the glsl fragment
return `${generateGlsl(input.value.transforms, shaderParams)('st')}`
}
return input.value
}).reduce((p, c) => `${p}, ${c}`, '')
return `${method}(${uv}${str})`
}
// merge two arrays and remove duplicates
function mergeArrays (a, b) {
return a.concat(b.filter(function (item) {
return a.indexOf(item) < 0;
}))
}
// check whether array
function contains(object, arr) {
for(var i = 0; i < arr.length; i++){
if(object.name == arr[i].name) return true
}
return false
}
},{"./format-arguments.js":45,"./lib/array-utils.js":52}],47:[function(require,module,exports){
const GlslSource = require('./glsl-source.js')
class GeneratorFactory {
constructor ({
defaultUniforms,
defaultOutput,
extendTransforms = [],
changeListener = (() => {})
} = {}
) {
this.defaultOutput = defaultOutput
this.defaultUniforms = defaultUniforms
this.changeListener = changeListener
this.extendTransforms = extendTransforms
this.generators = {}
this.init()
}
init () {
this.glslTransforms = {}
this.generators = Object.entries(this.generators).reduce((prev, [method, transform]) => {
this.changeListener({type: 'remove', synth: this, method})
return prev
}, {})
this.sourceClass = (() => {
return class extends GlslSource {
}
})()
let functions = require('./glsl/glsl-functions.js')()
// add user definied transforms
if (Array.isArray(this.extendTransforms)) {
functions.concat(this.extendTransforms)
} else if (typeof this.extendTransforms === 'object' && this.extendTransforms.type) {
functions.push(this.extendTransforms)
}
return functions.map((transform) => this.setFunction(transform))
}
_addMethod (method, transform) {
const self = this
this.glslTransforms[method] = transform
if (transform.type === 'src') {
const func = (...args) => new this.sourceClass({
name: method,
transform: transform,
userArgs: args,
defaultOutput: this.defaultOutput,
defaultUniforms: this.defaultUniforms,
synth: self
})
this.generators[method] = func
this.changeListener({type: 'add', synth: this, method})
return func
} else {
this.sourceClass.prototype[method] = function (...args) {
this.transforms.push({name: method, transform: transform, userArgs: args, synth: self})
return this
}
}
return undefined
}
setFunction(obj) {
var processedGlsl = processGlsl(obj)
if(processedGlsl) this._addMethod(obj.name, processedGlsl)
}
}
const typeLookup = {
'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']
}
}
// expects glsl of format
// {
// name: 'osc', // name that will be used to access function as well as within glsl
// type: 'src', // can be src: vec4(vec2 _st), coord: vec2(vec2 _st), color: vec4(vec4 _c0), combine: vec4(vec4 _c0, vec4 _c1), combineCoord: vec2(vec2 _st, vec4 _c0)
// inputs: [
// {
// name: 'freq',
// type: 'float', // 'float' //, 'texture', 'vec4'
// 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);
// `
// }
// // generates 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);
// }`
function processGlsl(obj) {
let t = typeLookup[obj.type]
if(t) {
let baseArgs = t.args.map((arg) => arg).join(", ")
// @todo: make sure this works for all input types, add validation
let customArgs = obj.inputs.map((input) => `${input.type} ${input.name}`).join(', ')
let args = `${baseArgs}${customArgs.length > 0 ? ', '+ customArgs: ''}`
// console.log('args are ', args)
let glslFunction =
`
${t.returnType} ${obj.name}(${args}) {
${obj.glsl}
}
`
// add extra input to beginning for backward combatibility @todo update compiler so this is no longer necessary
if(obj.type === 'combine' || obj.type === 'combineCoord') obj.inputs.unshift({
name: 'color',
type: 'vec4'
})
return Object.assign({}, obj, { glsl: glslFunction})
} else {
console.warn(`type ${obj.type} not recognized`, obj)
}
}
module.exports = GeneratorFactory
},{"./glsl-source.js":48,"./glsl/glsl-functions.js":49}],48:[function(require,module,exports){
const generateGlsl = require('./generate-glsl.js')
// const formatArguments = require('./glsl-utils.js').formatArguments
// const glslTransforms = require('./glsl/composable-glsl-functions.js')
const utilityGlsl = require('./glsl/utility-functions.js')
var GlslSource = function (obj) {
this.transforms = []
this.transforms.push(obj)
this.defaultOutput = obj.defaultOutput
this.synth = obj.synth
this.type = 'GlslSource'
this.defaultUniforms = obj.defaultUniforms
return this
}
GlslSource.prototype.addTransform = function (obj) {
this.transforms.push(obj)
}
GlslSource.prototype.out = function (_output) {
var output = _output || this.defaultOutput
var glsl = this.glsl(output)
this.synth.currentFunctions = []
// output.renderPasses(glsl)
if(output) try{
output.render(glsl)
} catch (error) {
console.log('shader could not compile', error)
}
}
GlslSource.prototype.glsl = function () {
//var output = _output || this.defaultOutput
var self = this
// uniforms included in all shaders
// this.defaultUniforms = output.uniforms
var passes = []
var transforms = []
// console.log('output', output)
this.transforms.forEach((transform) => {
if(transform.transform.type === 'renderpass'){
// if (transforms.length > 0) passes.push(this.compile(transforms, output))
// transforms = []
// var uniforms = {}
// const inputs = formatArguments(transform, -1)
// inputs.forEach((uniform) => { uniforms[uniform.name] = uniform.value })
//
// passes.push({
// frag: transform.transform.frag,
// uniforms: Object.assign({}, self.defaultUniforms, uniforms)
// })
// transforms.push({name: 'prev', transform: glslTransforms['prev'], synth: this.synth})
console.warn('no support for renderpass')
} else {
transforms.push(transform)
}
})
if (transforms.length > 0) passes.push(this.compile(transforms))
return passes
}
GlslSource.prototype.compile = function (transforms) {
var shaderInfo = generateGlsl(transforms, this.synth)
var uniforms = {}
shaderInfo.uniforms.forEach((uniform) => { uniforms[uniform.name] = uniform.value })
var frag = `
precision ${this.defaultOutput.precision} float;
${Object.values(shaderInfo.uniforms).map((uniform) => {
let type = uniform.type
switch (uniform.type) {
case 'texture':
type = 'sampler2D'
break
}
return `
uniform ${type} ${uniform.name};`
}).join('')}
uniform float time;
uniform vec2 resolution;
varying vec2 uv;
uniform sampler2D prevBuffer;
${Object.values(utilityGlsl).map((transform) => {
// console.log(transform.glsl)
return `
${transform.glsl}
`
}).join('')}
${shaderInfo.glslFunctions.map((transform) => {
return `
${transform.transform.glsl}
`
}).join('')}
void main () {
vec4 c = vec4(1, 0, 0, 1);
vec2 st = gl_FragCoord.xy/resolution.xy;
gl_FragColor = ${shaderInfo.fragColor};
}
`
return {
frag: frag,
uniforms: Object.assign({}, this.defaultUniforms, uniforms)
}
}
module.exports = GlslSource
},{"./generate-glsl.js":46,"./glsl/utility-functions.js":50}],49:[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);`
}
]
},{}],50:[function(require,module,exports){
// functions that are only used within other functions
module.exports = {
_luminance: {
type: 'util',
glsl: `float _luminance(vec3 rgb){
const vec3 W = vec3(0.2125, 0.7154, 0.0721);
return dot(rgb, W);
}`
},
_noise: {
type: 'util',
glsl: `
// Simplex 3D Noise
// by Ian McEwan, Ashima Arts
vec4 permute(vec4 x){return mod(((x*34.0)+1.0)*x, 289.0);}
vec4 taylorInvSqrt(vec4 r){return 1.79284291400159 - 0.85373472095314 * r;}
float _noise(vec3 v){
const vec2 C = vec2(1.0/6.0, 1.0/3.0) ;
const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);
// First corner
vec3 i = floor(v + dot(v, C.yyy) );
vec3 x0 = v - i + dot(i, C.xxx) ;
// Other corners
vec3 g = step(x0.yzx, x0.xyz);
vec3 l = 1.0 - g;
vec3 i1 = min( g.xyz, l.zxy );
vec3 i2 = max( g.xyz, l.zxy );
// x0 = x0 - 0. + 0.0 * C
vec3 x1 = x0 - i1 + 1.0 * C.xxx;
vec3 x2 = x0 - i2 + 2.0 * C.xxx;
vec3 x3 = x0 - 1. + 3.0 * C.xxx;
// Permutations
i = mod(i, 289.0 );
vec4 p = permute( permute( permute(
i.z + vec4(0.0, i1.z, i2.z, 1.0 ))
+ i.y + vec4(0.0, i1.y, i2.y, 1.0 ))
+ i.x + vec4(0.0, i1.x, i2.x, 1.0 ));
// Gradients
// ( N*N points uniformly over a square, mapped onto an octahedron.)
float n_ = 1.0/7.0; // N=7
vec3 ns = n_ * D.wyz - D.xzx;
vec4 j = p - 49.0 * floor(p * ns.z *ns.z); // mod(p,N*N)
vec4 x_ = floor(j * ns.z);
vec4 y_ = floor(j - 7.0 * x_ ); // mod(j,N)
vec4 x = x_ *ns.x + ns.yyyy;
vec4 y = y_ *ns.x + ns.yyyy;
vec4 h = 1.0 - abs(x) - abs(y);
vec4 b0 = vec4( x.xy, y.xy );
vec4 b1 = vec4( x.zw, y.zw );
vec4 s0 = floor(b0)*2.0 + 1.0;
vec4 s1 = floor(b1)*2.0 + 1.0;
vec4 sh = -step(h, vec4(0.0));
vec4 a0 = b0.xzyw + s0.xzyw*sh.xxyy ;
vec4 a1 = b1.xzyw + s1.xzyw*sh.zzww ;
vec3 p0 = vec3(a0.xy,h.x);
vec3 p1 = vec3(a0.zw,h.y);
vec3 p2 = vec3(a1.xy,h.z);
vec3 p3 = vec3(a1.zw,h.w);
//Normalise gradients
vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));
p0 *= norm.x;
p1 *= norm.y;
p2 *= norm.z;
p3 *= norm.w;
// Mix final noise value
vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);
m = m * m;
return 42.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1),
dot(p2,x2), dot(p3,x3) ) );
}
`
},
_rgbToHsv: {
type: 'util',
glsl: `vec3 _rgbToHsv(vec3 c){
vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));
float d = q.x - min(q.w, q.y);
float e = 1.0e-10;
return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
}`
},
_hsvToRgb: {
type: 'util',
glsl: `vec3 _hsvToRgb(vec3 c){
vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}`
}
}
},{}],51:[function(require,module,exports){
const Webcam = require('./lib/webcam.js')
const Screen = require('./lib/screenmedia.js')
class HydraSource {
constructor ({ regl, width, height, pb, label = ""}) {
this.label = label
this.regl = regl
this.src = null
this.dynamic = true
this.width = width
this.height = height
this.tex = this.regl.texture({
// shape: [width, height]
shape: [ 1, 1 ]
})
this.pb = pb
}
init (opts, params) {
if ('src' in opts) {
this.src = opts.src
this.tex = this.regl.texture({ data: this.src, ...params })
}
if ('dynamic' in opts) this.dynamic = opts.dynamic
}
initCam (index, params) {
const self = this
Webcam(index)
.then(response => {
self.src = response.video
self.dynamic = true
self.tex = self.regl.texture({ data: self.src, ...params })
})
.catch(err => console.log('could not get camera', err))
}
initVideo (url = '', params) {
// const self = this
const vid = document.createElement('video')
vid.crossOrigin = 'anonymous'
vid.autoplay = true
vid.loop = true
vid.muted = true // mute in order to load without user interaction
const onload = vid.addEventListener('loadeddata', () => {
this.src = vid
vid.play()
this.tex = this.regl.texture({ data: this.src, ...params})
this.dynamic = true
})
vid.src = url
}
initImage (url = '', params) {
const img = document.createElement('img')
img.crossOrigin = 'anonymous'
img.src = url
img.onload = () => {
this.src = img
this.dynamic = false
this.tex = this.regl.texture({ data: this.src, ...params})
}
}
initStream (streamName, params) {
// console.log("initing stream!", streamName)
let self = this
if (streamName && this.pb) {
this.pb.initSource(streamName)
this.pb.on('got video', function (nick, video) {
if (nick === streamName) {
self.src = video
self.dynamic = true
self.tex = self.regl.texture({ data: self.src, ...params})
}
})
}
}
// index only relevant in atom-hydra + desktop apps
initScreen (index = 0, params) {
const self = this
Screen()
.then(function (response) {
self.src = response.video
self.tex = self.regl.texture({ data: self.src, ...params})
self.dynamic = true
// console.log("received screen input")
})
.catch(err => console.log('could not get screen', err))
}
resize (width, height) {
this.width = width
this.height = height
}
clear () {
if (this.src && this.src.srcObject) {
if (this.src.srcObject.getTracks) {
this.src.srcObject.getTracks().forEach(track => track.stop())
}
}
this.src = null
this.tex = this.regl.texture({ shape: [ 1, 1 ] })
}
tick (time) {
// console.log(this.src, this.tex.width, this.tex.height)
if (this.src !== null && this.dynamic === true) {
if (this.src.videoWidth && this.src.videoWidth !== this.tex.width) {
console.log(
this.src.videoWidth,
this.src.videoHeight,
this.tex.width,
this.tex.height
)
this.tex.resize(this.src.videoWidth, this.src.videoHeight)
}
if (this.src.width && this.src.width !== this.tex.width) {
this.tex.resize(this.src.width, this.src.height)
}
this.tex.subimage(this.src)
}
}
getTexture () {
return this.tex
}
}
module.exports = HydraSource
},{"./lib/screenmedia.js":58,"./lib/webcam.js":60}],52:[function(require,module,exports){
// WIP utils for working with arrays
// Possibly should be integrated with lfo extension, etc.
// to do: transform time rather than array values, similar to working with coordinates in hydra
var easing = require('./easing-functions.js')
var map = (num, in_min, in_max, out_min, out_max) => {
return (num - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
module.exports = {
init: () => {
Array.prototype.fast = function(speed = 1) {
this._speed = speed
return this
}
Array.prototype.smooth = function(smooth = 1) {
this._smooth = smooth
return this
}
Array.prototype.ease = function(ease = 'linear') {
if (typeof ease == 'function') {
this._smooth = 1
this._ease = ease
}
else if (easing[ease]){
this._smooth = 1
this._ease = easing[ease]
}
return this
}
Array.prototype.offset = function(offset = 0.5) {
this._offset = offset%1.0
return this
}
// Array.prototype.bounce = function() {
// this.modifiers.bounce = true
// return this
// }
Array.prototype.fit = function(low = 0, high =1) {
let lowest = Math.min(...this)
let highest = Math.max(...this)
var newArr = this.map((num) => map(num, lowest, highest, low, high))
newArr._speed = this._speed
newArr._smooth = this._smooth
newArr._ease = this._ease
return newArr
}
},
getValue: (arr = []) => ({time, bpm}) =>{
let speed = arr._speed ? arr._speed : 1
let smooth = arr._smooth ? arr._smooth : 0
let index = time * speed * (bpm / 60) + (arr._offset || 0)
if (smooth!==0) {
let ease = arr._ease ? arr._ease : easing['linear']
let _index = index - (smooth / 2)
let currValue = arr[Math.floor(_index % (arr.length))]
let nextValue = arr[Math.floor((_index + 1) % (arr.length))]
let t = Math.min((_index%1)/smooth,1)
return ease(t) * (nextValue - currValue) + currValue
}
else {
return arr[Math.floor(index % (arr.length))]
}
}
}
},{"./easing-functions.js":54}],53:[function(require,module,exports){
const Meyda = require('meyda')
class Audio {
constructor ({
numBins = 4,
cutoff = 2,
smooth = 0.4,
max = 15,
scale = 10,
isDrawing = false
}) {
this.vol = 0
this.scale = scale
this.max = max
this.cutoff = cutoff
this.smooth = smooth
this.setBins(numBins)
// beat detection from: https://github.com/therewasaguy/p5-music-viz/blob/gh-pages/demos/01d_beat_detect_amplitude/sketch.js
this.beat = {
holdFrames: 20,
threshold: 40,
_cutoff: 0, // adaptive based on sound state
decay: 0.98,
_framesSinceBeat: 0 // keeps track of frames
}
this.onBeat = () => {
// console.log("beat")
}
this.canvas = document.createElement('canvas')
this.canvas.width = 100
this.canvas.height = 80
this.canvas.style.width = "100px"
this.canvas.style.height = "80px"
this.canvas.style.position = 'absolute'
this.canvas.style.right = '0px'
this.canvas.style.bottom = '0px'
document.body.appendChild(this.canvas)
this.isDrawing = isDrawing
this.ctx = this.canvas.getContext('2d')
this.ctx.fillStyle="#DFFFFF"
this.ctx.strokeStyle="#0ff"
this.ctx.lineWidth=0.5
if(window.navigator.mediaDevices) {
window.navigator.mediaDevices.getUserMedia({video: false, audio: true})
.then((stream) => {
// console.log('got mic stream', stream)
this.stream = stream
this.context = new AudioContext()
// this.context = new AudioContext()
let audio_stream = this.context.createMediaStreamSource(stream)
// console.log(this.context)
this.meyda = Meyda.createMeydaAnalyzer({
audioContext: this.context,
source: audio_stream,
featureExtractors: [
'loudness',
// 'perceptualSpread',
// 'perceptualSharpness',
// 'spectralCentroid'
]
})
})
.catch((err) => console.log('ERROR', err))
}
}
detectBeat (level) {
//console.log(level, this.beat._cutoff)
if (level > this.beat._cutoff && level > this.beat.threshold) {
this.onBeat()
this.beat._cutoff = level *1.2
this.beat._framesSinceBeat = 0
} else {
if (this.beat._framesSinceBeat <= this.beat.holdFrames){
this.beat._framesSinceBeat ++;
} else {
this.beat._cutoff *= this.beat.decay
this.beat._cutoff = Math.max( this.beat._cutoff, this.beat.threshold);
}
}
}
tick() {
if(this.meyda){
var features = this.meyda.get()
if(features && features !== null){
this.vol = features.loudness.total
this.detectBeat(this.vol)
// reduce loudness array to number of bins
const reducer = (accumulator, currentValue) => accumulator + currentValue;
let spacing = Math.floor(features.loudness.specific.length/this.bins.length)
this.prevBins = this.bins.slice(0)
this.bins = this.bins.map((bin, index) => {
return features.loudness.specific.slice(index * spacing, (index + 1)*spacing).reduce(reducer)
}).map((bin, index) => {
// map to specified range
// return (bin * (1.0 - this.smooth) + this.prevBins[index] * this.smooth)
return (bin * (1.0 - this.settings[index].smooth) + this.prevBins[index] * this.settings[index].smooth)
})
// var y = this.canvas.height - scale*this.settings[index].cutoff
// this.ctx.beginPath()
// this.ctx.moveTo(index*spacing, y)
// this.ctx.lineTo((index+1)*spacing, y)
// this.ctx.stroke()
//
// var yMax = this.canvas.height - scale*(this.settings[index].scale + this.settings[index].cutoff)
this.fft = this.bins.map((bin, index) => (
// Math.max(0, (bin - this.cutoff) / (this.max - this.cutoff))
Math.max(0, (bin - this.settings[index].cutoff)/this.settings[index].scale)
))
if(this.isDrawing) this.draw()
}
}
}
setCutoff (cutoff) {
this.cutoff = cutoff
this.settings = this.settings.map((el) => {
el.cutoff = cutoff
return el
})
}
setSmooth (smooth) {
this.smooth = smooth
this.settings = this.settings.map((el) => {
el.smooth = smooth
return el
})
}
setBins (numBins) {
this.bins = Array(numBins).fill(0)
this.prevBins = Array(numBins).fill(0)
this.fft = Array(numBins).fill(0)
this.settings = Array(numBins).fill(0).map(() => ({
cutoff: this.cutoff,
scale: this.scale,
smooth: this.smooth
}))
// to do: what to do in non-global mode?
this.bins.forEach((bin, index) => {
window['a' + index] = (scale = 1, offset = 0) => () => (a.fft[index] * scale + offset)
})
// console.log(this.settings)
}
setScale(scale){
this.scale = scale
this.settings = this.settings.map((el) => {
el.scale = scale
return el
})
}
setMax(max) {
this.max = max
console.log('set max is deprecated')
}
hide() {
this.isDrawing = false
this.canvas.style.display = 'none'
}
show() {
this.isDrawing = true
this.canvas.style.display = 'block'
}
draw () {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
var spacing = this.canvas.width / this.bins.length
var scale = this.canvas.height / (this.max * 2)
// console.log(this.bins)
this.bins.forEach((bin, index) => {
var height = bin * scale
this.ctx.fillRect(index * spacing, this.canvas.height - height, spacing, height)
// console.log(this.settings[index])
var y = this.canvas.height - scale*this.settings[index].cutoff
this.ctx.beginPath()
this.ctx.moveTo(index*spacing, y)
this.ctx.lineTo((index+1)*spacing, y)
this.ctx.stroke()
var yMax = this.canvas.height - scale*(this.settings[index].scale + this.settings[index].cutoff)
this.ctx.beginPath()
this.ctx.moveTo(index*spacing, yMax)
this.ctx.lineTo((index+1)*spacing, yMax)
this.ctx.stroke()
})
/*var y = this.canvas.height - scale*this.cutoff
this.ctx.beginPath()
this.ctx.moveTo(0, y)
this.ctx.lineTo(this.canvas.width, y)
this.ctx.stroke()
var yMax = this.canvas.height - scale*this.max
this.ctx.beginPath()
this.ctx.moveTo(0, yMax)
this.ctx.lineTo(this.canvas.width, yMax)
this.ctx.stroke()*/
}
}
module.exports = Audio
},{"meyda":133}],54:[function(require,module,exports){
// from https://gist.github.com/gre/1650294
module.exports = {
// no easing, no acceleration
linear: function (t) { return t },
// accelerating from zero velocity
easeInQuad: function (t) { return t*t },
// decelerating to zero velocity
easeOutQuad: function (t) { return t*(2-t) },
// acceleration until halfway, then deceleration
easeInOutQuad: function (t) { return t<.5 ? 2*t*t : -1+(4-2*t)*t },
// accelerating from zero velocity
easeInCubic: function (t) { return t*t*t },
// decelerating to zero velocity
easeOutCubic: function (t) { return (--t)*t*t+1 },
// acceleration until halfway, then deceleration
easeInOutCubic: function (t) { return t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1 },
// accelerating from zero velocity
easeInQuart: function (t) { return t*t*t*t },
// decelerating to zero velocity
easeOutQuart: function (t) { return 1-(--t)*t*t*t },
// acceleration until halfway, then deceleration
easeInOutQuart: function (t) { return t<.5 ? 8*t*t*t*t : 1-8*(--t)*t*t*t },
// accelerating from zero velocity
easeInQuint: function (t) { return t*t*t*t*t },
// decelerating to zero velocity
easeOutQuint: function (t) { return 1+(--t)*t*t*t*t },
// acceleration until halfway, then deceleration
easeInOutQuint: function (t) { return t<.5 ? 16*t*t*t*t*t : 1+16*(--t)*t*t*t*t },
// sin shape
sin: function (t) { return (1 + Math.sin(Math.PI*t-Math.PI/2))/2 }
}
},{}],55:[function(require,module,exports){
// https://github.com/mikolalysenko/mouse-event
'use strict'
function mouseButtons(ev) {
if(typeof ev === 'object') {
if('buttons' in ev) {
return ev.buttons
} else if('which' in ev) {
var b = ev.which
if(b === 2) {
return 4
} else if(b === 3) {
return 2
} else if(b > 0) {
return 1<<(b-1)
}
} else if('button' in ev) {
var b = ev.button
if(b === 1) {
return 4
} else if(b === 2) {
return 2
} else if(b >= 0) {
return 1<<b
}
}
}
return 0
}
exports.buttons = mouseButtons
function mouseElement(ev) {
return ev.target || ev.srcElement || window
}
exports.element = mouseElement
function mouseRelativeX(ev) {
if(typeof ev === 'object') {
if('pageX' in ev) {
return ev.pageX
}
}
return 0
}
exports.x = mouseRelativeX
function mouseRelativeY(ev) {
if(typeof ev === 'object') {
if('pageY' in ev) {
return ev.pageY
}
}
return 0
}
exports.y = mouseRelativeY
},{}],56:[function(require,module,exports){
// based on https://github.com/mikolalysenko/mouse-change
'use strict'
module.exports = mouseListen
var mouse = require('./mouse-event.js')
function mouseListen (element, callback) {
if (!callback) {
callback = element
element = window
}
var buttonState = 0
var x = 0
var y = 0
var mods = {
shift: false,
alt: false,
control: false,
meta: false
}
var attached = false
function updateMods (ev) {
var changed = false
if ('altKey' in ev) {
changed = changed || ev.altKey !== mods.alt
mods.alt = !!ev.altKey
}
if ('shiftKey' in ev) {
changed = changed || ev.shiftKey !== mods.shift
mods.shift = !!ev.shiftKey
}
if ('ctrlKey' in ev) {
changed = changed || ev.ctrlKey !== mods.control
mods.control = !!ev.ctrlKey
}
if ('metaKey' in ev) {
changed = changed || ev.metaKey !== mods.meta
mods.meta = !!ev.metaKey
}
return changed
}
function handleEvent (nextButtons, ev) {
var nextX = mouse.x(ev)
var nextY = mouse.y(ev)
if ('buttons' in ev) {
nextButtons = ev.buttons | 0
}
if (nextButtons !== buttonState ||
nextX !== x ||
nextY !== y ||
updateMods(ev)) {
buttonState = nextButtons | 0
x = nextX || 0
y = nextY || 0
callback && callback(buttonState, x, y, mods)
}
}
function clearState (ev) {
handleEvent(0, ev)
}
function handleBlur () {
if (buttonState ||
x ||
y ||
mods.shift ||
mods.alt ||
mods.meta ||
mods.control) {
x = y = 0
buttonState = 0
mods.shift = mods.alt = mods.control = mods.meta = false
callback && callback(0, 0, 0, mods)
}
}
function handleMods (ev) {
if (updateMods(ev)) {
callback && callback(buttonState, x, y, mods)
}
}
function handleMouseMove (ev) {
if (mouse.buttons(ev) === 0) {
handleEvent(0, ev)
} else {
handleEvent(buttonState, ev)
}
}
function handleMouseDown (ev) {
handleEvent(buttonState | mouse.buttons(ev), ev)
}
function handleMouseUp (ev) {
handleEvent(buttonState & ~mouse.buttons(ev), ev)
}
function attachListeners () {
if (attached) {
return
}
attached = true
element.addEventListener('mousemove', handleMouseMove)
element.addEventListener('mousedown', handleMouseDown)
element.addEventListener('mouseup', handleMouseUp)
element.addEventListener('mouseleave', clearState)
element.addEventListener('mouseenter', clearState)
element.addEventListener('mouseout', clearState)
element.addEventListener('mouseover', clearState)
element.addEventListener('blur', handleBlur)
element.addEventListener('keyup', handleMods)
element.addEventListener('keydown', handleMods)
element.addEventListener('keypress', handleMods)
if (element !== window) {
window.addEventListener('blur', handleBlur)
window.addEventListener('keyup', handleMods)
window.addEventListener('keydown', handleMods)
window.addEventListener('keypress', handleMods)
}
}
function detachListeners () {
if (!attached) {
return
}
attached = false
element.removeEventListener('mousemove', handleMouseMove)
element.removeEventListener('mousedown', handleMouseDown)
element.removeEventListener('mouseup', handleMouseUp)
element.removeEventListener('mouseleave', clearState)
element.removeEventListener('mouseenter', clearState)
element.removeEventListener('mouseout', clearState)
element.removeEventListener('mouseover', clearState)
element.removeEventListener('blur', handleBlur)
element.removeEventListener('keyup', handleMods)
element.removeEventListener('keydown', handleMods)
element.removeEventListener('keypress', handleMods)
if (element !== window) {
window.removeEventListener('blur', handleBlur)
window.removeEventListener('keyup', handleMods)
window.removeEventListener('keydown', handleMods)
window.removeEventListener('keypress', handleMods)
}
}
// Attach listeners
attachListeners()
var result = {
element: element
}
Object.defineProperties(result, {
enabled: {
get: function () { return attached },
set: function (f) {
if (f) {
attachListeners()
} else {
detachListeners()
}
},
enumerable: true
},
buttons: {
get: function () { return buttonState },
enumerable: true
},
x: {
get: function () { return x },
enumerable: true
},
y: {
get: function () { return y },
enumerable: true
},
mods: {
get: function () { return mods },
enumerable: true
}
})
return result
}
},{"./mouse-event.js":55}],57:[function(require,module,exports){
// attempt custom evaluation sandbox for hydra functions
// for now, just avoids polluting the global namespace
// should probably be replaced with an abstract syntax tree
module.exports = (parent) => {
var initialCode = ``
var sandbox = createSandbox(initialCode)
var addToContext = (name, object) => {
initialCode += `
var ${name} = ${object}
`
sandbox = createSandbox(initialCode)
}
return {
addToContext: addToContext,
eval: (code) => sandbox.eval(code)
}
function createSandbox (initial) {
eval(initial)
// optional params
var localEval = function (code) {
eval(code)
}
// API/data for end-user
return {
eval: localEval
}
}
}
},{}],58:[function(require,module,exports){
module.exports = function (options) {
return new Promise(function(resolve, reject) {
// async function startCapture(displayMediaOptions) {
navigator.mediaDevices.getDisplayMedia(options).then((stream) => {
const video = document.createElement('video')
video.srcObject = stream
video.addEventListener('loadedmetadata', () => {
video.play()
resolve({video: video})
})
}).catch((err) => reject(err))
})
}
},{}],59:[function(require,module,exports){
class VideoRecorder {
constructor(stream) {
this.mediaSource = new MediaSource()
this.stream = stream
// testing using a recording as input
this.output = document.createElement('video')
this.output.autoplay = true
this.output.loop = true
let self = this
this.mediaSource.addEventListener('sourceopen', () => {
console.log('MediaSource opened');
self.sourceBuffer = self.mediaSource.addSourceBuffer('video/webm; codecs="vp8"');
console.log('Source buffer: ', sourceBuffer);
})
}
start() {
// let options = {mimeType: 'video/webm'};
// let options = {mimeType: 'video/webm;codecs=h264'};
let options = {mimeType: 'video/webm;codecs=vp9'};
this.recordedBlobs = []
try {
this.mediaRecorder = new MediaRecorder(this.stream, options)
} catch (e0) {
console.log('Unable to create MediaRecorder with options Object: ', e0)
try {
options = {mimeType: 'video/webm,codecs=vp9'}
this.mediaRecorder = new MediaRecorder(this.stream, options)
} catch (e1) {
console.log('Unable to create MediaRecorder with options Object: ', e1)
try {
options = 'video/vp8' // Chrome 47
this.mediaRecorder = new MediaRecorder(this.stream, options)
} catch (e2) {
alert('MediaRecorder is not supported by this browser.\n\n' +
'Try Firefox 29 or later, or Chrome 47 or later, ' +
'with Enable experimental Web Platform features enabled from chrome://flags.')
console.error('Exception while creating MediaRecorder:', e2)
return
}
}
}
console.log('Created MediaRecorder', this.mediaRecorder, 'with options', options);
this.mediaRecorder.onstop = this._handleStop.bind(this)
this.mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this)
this.mediaRecorder.start(100) // collect 100ms of data
console.log('MediaRecorder started', this.mediaRecorder)
}
stop(){
this.mediaRecorder.stop()
}
_handleStop() {
//const superBuffer = new Blob(recordedBlobs, {type: 'video/webm'})
// const blob = new Blob(this.recordedBlobs, {type: 'video/webm;codecs=h264'})
const blob = new Blob(this.recordedBlobs, {type: this.mediaRecorder.mimeType})
const url = window.URL.createObjectURL(blob)
this.output.src = url
const a = document.createElement('a')
a.style.display = 'none'
a.href = url
let d = new Date()
a.download = `hydra-${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}-${d.getHours()}.${d.getMinutes()}.${d.getSeconds()}.webm`
document.body.appendChild(a)
a.click()
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 300);
}
_handleDataAvailable(event) {
if (event.data && event.data.size > 0) {
this.recordedBlobs.push(event.data);
}
}
}
module.exports = VideoRecorder
},{}],60:[function(require,module,exports){
//const enumerateDevices = require('enumerate-devices')
module.exports = function (deviceId) {
return navigator.mediaDevices.enumerateDevices()
.then(devices => devices.filter(devices => devices.kind === 'videoinput'))
.then(cameras => {
let constraints = { audio: false, video: true}
if (cameras[deviceId]) {
constraints['video'] = {
deviceId: { exact: cameras[deviceId].deviceId }
}
}
// console.log(cameras)
return window.navigator.mediaDevices.getUserMedia(constraints)
})
.then(stream => {
const video = document.createElement('video')
video.setAttribute('autoplay', '')
video.setAttribute('muted', '')
video.setAttribute('playsinline', '')
// video.src = window.URL.createObjectURL(stream)
video.srcObject = stream
return new Promise((resolve, reject) => {
video.addEventListener('loadedmetadata', () => {
video.play().then(() => resolve({video: video}))
})
})
})
.catch(console.log.bind(console))
}
},{}],61:[function(require,module,exports){
//const transforms = require('./glsl-transforms.js')
var Output = function ({ regl, precision, label = "", width, height}) {
this.regl = regl
this.precision = precision
this.label = label
this.positionBuffer = this.regl.buffer([
[-2, 0],
[0, -2],
[2, 2]
])
this.draw = () => {}
this.init()
this.pingPongIndex = 0
// for each output, create two fbos for pingponging
this.fbos = (Array(2)).fill().map(() => this.regl.framebuffer({
color: this.regl.texture({
mag: 'nearest',
width: width,
height: height,
format: 'rgba'
}),
depthStencil: false
}))
// array containing render passes
// this.passes = []
}
Output.prototype.resize = function(width, height) {
this.fbos.forEach((fbo) => {
fbo.resize(width, height)
})
// console.log(this)
}
Output.prototype.getCurrent = function () {
return this.fbos[this.pingPongIndex]
}
Output.prototype.getTexture = function () {
var index = this.pingPongIndex ? 0 : 1
return this.fbos[index]
}
Output.prototype.init = function () {
// console.log('clearing')
this.transformIndex = 0
this.fragHeader = `
precision ${this.precision} float;
uniform float time;
varying vec2 uv;
`
this.fragBody = ``
this.vert = `
precision ${this.precision} float;
attribute vec2 position;
varying vec2 uv;
void main () {
uv = position;
gl_Position = vec4(2.0 * position - 1.0, 0, 1);
}`
this.attributes = {
position: this.positionBuffer
}
this.uniforms = {
time: this.regl.prop('time'),
resolution: this.regl.prop('resolution')
}
this.frag = `
${this.fragHeader}
void main () {
vec4 c = vec4(0, 0, 0, 0);
vec2 st = uv;
${this.fragBody}
gl_FragColor = c;
}
`
return this
}
Output.prototype.render = function (passes) {
let pass = passes[0]
//console.log('pass', pass, this.pingPongIndex)
var self = this
var uniforms = Object.assign(pass.uniforms, { prevBuffer: () => {
//var index = this.pingPongIndex ? 0 : 1
// var index = self.pingPong[(passIndex+1)%2]
// console.log('ping pong', self.pingPongIndex)
return self.fbos[self.pingPongIndex]
}
})
self.draw = self.regl({
frag: pass.frag,
vert: self.vert,
attributes: self.attributes,
uniforms: uniforms,
count: 3,
framebuffer: () => {
self.pingPongIndex = self.pingPongIndex ? 0 : 1
return self.fbos[self.pingPongIndex]
}
})
}
Output.prototype.tick = function (props) {
// console.log(props)
this.draw(props)
}
module.exports = Output
},{}],62:[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)
}
}
},{}],63:[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":62}],64:[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')
}
},{}],65:[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":64,"nanotiming":84,"remove-array-items":96}],66:[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":67,"global/document":37,"nanomorph":77,"nanotiming":84,"on-load":87}],67:[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
}
}
},{}],68:[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":64}],69:[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)
}
}
}
},{}],70:[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'
]
},{}],71:[function(require,module,exports){
module.exports = require('./dom')(document)
},{"./dom":73}],72:[function(require,module,exports){
'use strict'
module.exports = [
'indeterminate'
]
},{}],73:[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":69,"./bool-props":70,"./direct-props":72,"./svg-tags":74,"hyperx":63}],74:[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'
]
},{}],75:[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":123}],76:[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)
}
},{}],77:[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":79,"nanoassert":64}],78:[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'
]
},{}],79:[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":78}],80:[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":64}],81:[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":64}],82:[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":64,"wayfarer":107}],83:[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":64}],84:[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":64,"nanoscheduler":83}],85:[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":123}],86:[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 inspectCustom = require('./util.inspect').custom;
var inspectSymbol = inspectCustom && 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') {
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 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') {
return obj[inspectSymbol]();
} else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') {
return obj.inspect();
}
}
if (isMap(obj)) {
var mapParts = [];
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 = [];
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":128}],87:[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":37,"global/window":38}],88:[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":64,"nanoscheduler":83}],89:[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
}
}
},{}],90:[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
}
}
},{}],91:[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
};
},{}],92:[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":91,"./parse":93,"./stringify":94}],93:[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 = {};
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 {
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":95}],94:[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 split = String.prototype.split;
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,
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)) !== 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);
if (generateArrayPrefix === 'comma' && encodeValuesOnly) {
var valuesArray = split.call(String(obj), ',');
var valuesJoined = '';
for (var i = 0; i < valuesArray.length; ++i) {
valuesJoined += (i === 0 ? '' : ',') + formatter(encoder(valuesArray[i], defaults.encoder, charset, 'value', format));
}
return [formatter(keyValue) + '=' + valuesJoined];
}
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
objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : undefined }];
} else if (isArray(filter)) {
objKeys = filter;
} else {
var keys = Object.keys(obj);
objKeys = sort ? keys.sort(sort) : keys;
}
for (var j = 0; j < objKeys.length; ++j) {
var key = objKeys[j];
var value = typeof key === 'object' && key.value !== undefined ? key.value : obj[key];
if (skipNulls && value === null) {
continue;
}
var keyPrefix = isArray(obj)
? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix
: prefix + (allowDots ? '.' + key : '[' + key + ']');
sideChannel.set(object, step);
var valueSideChannel = getSideChannel();
valueSideChannel.set(sentinel, sideChannel);
pushToArray(values, stringify(
value,
keyPrefix,
generateArrayPrefix,
strictNullHandling,
skipNulls,
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 && 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 (!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,
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":91,"./utils":95,"side-channel":98}],95:[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":91}],96:[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
}
},{}],97:[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) {}
}
}
},{}],98:[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":7,"get-intrinsic":36,"object-inspect":86}],99:[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":23,"fast-safe-stringify":33}],100:[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;
},{}],101:[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 isObject = require('./is-object');
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 (Object.prototype.hasOwnProperty.call(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 (Object.prototype.hasOwnProperty.call(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);
}
} // eslint-disable-next-line new-cap
ResponseBase(Response.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 (error_) {
error = new Error('Parser is unable to parse the response');
error.parse = true;
error.original = error_; // 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); // eslint-disable-next-line new-cap
RequestBase(Request.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 = function encoder(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 (Object.prototype.hasOwnProperty.call(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":100,"./is-object":102,"./request-base":103,"./response-base":104,"component-emitter":31,"fast-safe-stringify":33,"qs":92}],102:[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); }
/**
* Check if `obj` is an object.
*
* @param {Object} obj
* @return {Boolean}
* @api private
*/
function isObject(object) {
return object !== null && _typeof(object) === 'object';
}
module.exports = isObject;
},{}],103:[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 isObject = require('./is-object');
/**
* Expose `RequestBase`.
*/
module.exports = RequestBase;
/**
* Initialize a new `RequestBase`.
*
* @api public
*/
function RequestBase(object) {
if (object) return mixin(object);
}
/**
* Mixin the prototype properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(object) {
for (var key in RequestBase.prototype) {
if (Object.prototype.hasOwnProperty.call(RequestBase.prototype, key)) object[key] = RequestBase.prototype[key];
}
return object;
}
/**
* 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 (Object.prototype.hasOwnProperty.call(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 (error_) {
console.error(error_);
}
} // 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 (cb) {
return this.then(undefined, cb);
};
/**
* Allow for extension
*/
RequestBase.prototype.use = function (fn) {
fn(this);
return this;
};
RequestBase.prototype.ok = function (cb) {
if (typeof cb !== 'function') throw new Error('Callback required');
this._okCallback = cb;
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 (Object.prototype.hasOwnProperty.call(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
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.field = function (name, value) {
// 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 (Object.prototype.hasOwnProperty.call(name, key)) this.field(key, name[key]);
}
return this;
}
if (Array.isArray(value)) {
for (var i in value) {
if (Object.prototype.hasOwnProperty.call(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);
}
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 (Object.prototype.hasOwnProperty.call(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'))
},{"./is-object":102,"_process":136,"semver":128}],104:[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(object) {
if (object) return mixin(object);
}
/**
* Mixin the prototype properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(object) {
for (var key in ResponseBase.prototype) {
if (Object.prototype.hasOwnProperty.call(ResponseBase.prototype, key)) object[key] = ResponseBase.prototype[key];
}
return object;
}
/**
* 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":105}],105:[function(require,module,exports){
"use strict";
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;
};
},{}],106:[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":64}],107:[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":108,"assert":64}],108:[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":64}],109:[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="
}
]
},{}],110:[function(require,module,exports){
const request = require('superagent')
const examples = require('./examples.json')
const sketches = []
class Gallery {
constructor (callback) {
this.sketches = []
this.examples = []
this.current = null
this.code = null
this.exampleIndex = null
// 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)
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 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')
.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)
}
//
// // 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
var url_params
if(params.sketch_id) {
url_params = `sketch_id=${params.sketch_id}`
} else {
url_params = `sketch_id=${params.sketch_id}&code=${params.code}`
}
// } else {
// url_params = params.map( (param, index) => `${param.label}=${param.value}`).join('&')
// }
// console.log('url params', url_params)
let newurl = window.location.protocol + '//' +
window.location.host + window.location.pathname + '?' + url_params
// window.location.href = newurl
window.history.replaceState({ path: newurl }, '', newurl)
this.url = newurl
}
encodeBase64(text) {
return btoa(encodeURIComponent(text))
}
decodeBase64(base64Code) {
return decodeURIComponent(atob(base64Code))
}
setSketch(sketch) {
this.code = this.decodeBase64(sketch.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')
.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')
// .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)
// keep code in url for backwards compatibility / compatibility between local and public versions
var url_params = `code=${base64}`
// } else {
// url_params = params.map( (param, index) => `${param.label}=${param.value}`).join('&')
// }
//console.log('url params', url_params)
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":109,"superagent":101}],111:[function(require,module,exports){
const Gallery = require('./gallery.js')
const repl = require('./views/editor/repl.js')
module.exports = function store (state, emitter) {
state.showInfo = true
state.showUI = true
const sketches = new Gallery(() => {
// @todo create gallery store
console.warn('gallery callback not let implemented')
})
emitter.on('shuffle sketches', function (count) {
})
emitter.on('format code', function (count) {
})
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('gallery:shareSketch', function (editor) {
console.log('waiting to share', state.editor.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('mutate sketch', function () {
})
}
},{"./gallery.js":110,"./views/editor/repl.js":119}],112:[function(require,module,exports){
const html = require('choo/html')
const Component = require('choo/component')
const HydraEditor = require('./editor/editor.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) {
this.editor = new HydraEditor(this.textEl)
this.editor.on("*", (e, t) => {
this.emit(e)
})
// 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>`
return html`<div id="editor-container">
${this.textEl}
</div>`
}
}
},{"./editor/editor.js":114,"choo/component":20,"choo/html":21}],113:[function(require,module,exports){
const html = require('choo/html')
const Component = require('choo/component')
const HydraSynth = require('hydra-synth')
module.exports = class Hydra extends Component {
constructor (id, state, emit) {
super(id)
this.local = state.components[id] = {}
}
load (element) {
const hydra = new HydraSynth({ detectAudio: true, canvas: element.querySelector("canvas")})
console.log(hydra)
osc().out()
}
update (center) {
return false
}
createElement ({ width = window.innerWidth, height = window.innerHeight} = {}) {
return html`<div style="width:100%;height:100%;">
<canvas class="bg-black" style="imageRendering:pixelated; width:100%;height:100%" width="${width}" height="${height}"></canvas></div>`
}
}
},{"choo/component":20,"choo/html":21,"hydra-synth":43}],114:[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')
var Mutator = require('./randomizer/Mutator.js');
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 {
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()
}
// 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":115,"./randomizer/Mutator.js":117,"codemirror-minified/addon/comment/comment":25,"codemirror-minified/addon/hint/javascript-hint":26,"codemirror-minified/addon/hint/show-hint":27,"codemirror-minified/addon/selection/mark-selection":28,"codemirror-minified/lib/codemirror":29,"codemirror-minified/mode/javascript/javascript":30,"nanobus":65}],115:[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'
}
},{}],116:[function(require,module,exports){
var logElement
module.exports = {
init: () => {
logElement = document.createElement('div')
logElement.className = "console cm-s-tomorrow-night-eighties"
document.body.appendChild(logElement)
},
log: (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'
}
}
}
},{}],117:[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')()
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":119,"./UndoStack.js":118,"acorn":2,"astravel":3,"astring":6,"hydra-synth/src/glsl/glsl-functions.js":49}],118:[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}
},{}],119:[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":116}],120:[function(require,module,exports){
const html = require('choo/html')
const toolbar = require('./toolbar.js')
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":122,"choo/html":21}],121:[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>
`
function onclick () {
emit('increment', 1)
}
}
},{"./EditorComponent.js":112,"./Hydra.js":113,"./info.js":120,"choo/html":21}],122:[function(require,module,exports){
const html = require('choo/html')
module.exports = function toolbar(state, emit) {
const hidden = state.showInfo ? 'hidden' : ''
const dispatch = (eventName, args = []) => () => emit(eventName, ...args)
const icon = (id, className, title, event) => html`
<i id="${id}-icon" class="fas icon ${className}" onclick=${dispatch(event)} aria-hidden="true"></i>`
return html`<div>
${icon("run", `fa-play-circle ${hidden}`, "Run all code (ctrl+shift+enter)", 'editor:evalAll')}
${icon("share", `fa-upload ${hidden}`, "upload to gallery", 'gallery:shareSketch')}
${icon("clear", `fa fa-trash ${hidden}`, "clear all", 'editor:clearAll')}
${icon("shuffle", `fa-random`, "show random sketch", 'gallery:showExample')}
${icon("mutator", `fa-dice ${hidden}`, "make random change", 'editor:randomize')}
${icon("close", state.showInfo? "fa-times" : "fa-question-circle", "", 'toggle info')}
</div>`
}
},{"choo/html":21}],123:[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":134,"util/":126}],124:[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
}
}
},{}],125:[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';
}
},{}],126:[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":125,"_process":136,"inherits":124}],127:[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('')
}
},{}],128:[function(require,module,exports){
},{}],129:[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":127,"buffer":129,"ieee754":131}],130:[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);
}
}
},{}],131:[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
}
},{}],132:[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
}
}
}
},{}],133:[function(require,module,exports){
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["Meyda"] = factory();
else
root["Meyda"] = factory();
})(window, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./src/index.js");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./node_modules/assert/assert.js":
/*!***************************************!*\
!*** ./node_modules/assert/assert.js ***!
\***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {
// 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:
// 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 = __webpack_require__(/*! util/ */ "./node_modules/webpack-stream/node_modules/util/util.js");
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; };
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
if (hasOwn.call(obj, key)) keys.push(key);
}
return keys;
};
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack-stream/node_modules/webpack/buildin/global.js */ "./node_modules/webpack-stream/node_modules/webpack/buildin/global.js")))
/***/ }),
/***/ "./node_modules/dct/index.js":
/*!***********************************!*\
!*** ./node_modules/dct/index.js ***!
\***********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(/*! ./src/dct.js */ "./node_modules/dct/src/dct.js");
/***/ }),
/***/ "./node_modules/dct/src/dct.js":
/*!*************************************!*\
!*** ./node_modules/dct/src/dct.js ***!
\*************************************/
/*! no static exports found */
/***/ (function(module, exports) {
/*===========================================================================*\
* Discrete Cosine Transform
*
* (c) Vail Systems. Joshua Jung and Ben Bryan. 2015
*
* This code is not designed to be highly optimized but as an educational
* tool to understand the Mel-scale and its related coefficients used in
* human speech analysis.
\*===========================================================================*/
var cosMap = null;
// Builds a cosine map for the given input size. This allows multiple input sizes to be memoized automagically
// if you want to run the DCT over and over.
var memoizeCosines = function(N) {
cosMap = cosMap || {};
cosMap[N] = new Array(N*N);
var PI_N = Math.PI / N;
for (var k = 0; k < N; k++) {
for (var n = 0; n < N; n++) {
cosMap[N][n + (k * N)] = Math.cos(PI_N * (n + 0.5) * k);
}
}
};
function dct(signal, scale) {
var L = signal.length;
scale = scale || 2;
if (!cosMap || !cosMap[L]) memoizeCosines(L);
var coefficients = signal.map(function () {return 0;});
return coefficients.map(function (__, ix) {
return scale * signal.reduce(function (prev, cur, ix_, arr) {
return prev + (cur * cosMap[L][ix_ + (ix * L)]);
}, 0);
});
};
module.exports = dct;
/***/ }),
/***/ "./node_modules/fftjs/dist/fft.js":
/*!****************************************!*\
!*** ./node_modules/fftjs/dist/fft.js ***!
\****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./utils */ "./node_modules/fftjs/dist/utils.js");
// real to complex fft
var fft = function fft(signal) {
var complexSignal = {};
if (signal.real === undefined || signal.imag === undefined) {
complexSignal = utils.constructComplexArray(signal);
} else {
complexSignal.real = signal.real.slice();
complexSignal.imag = signal.imag.slice();
}
var N = complexSignal.real.length;
var logN = Math.log2(N);
if (Math.round(logN) != logN) throw new Error('Input size must be a power of 2.');
if (complexSignal.real.length != complexSignal.imag.length) {
throw new Error('Real and imaginary components must have the same length.');
}
var bitReversedIndices = utils.bitReverseArray(N);
// sort array
var ordered = {
'real': [],
'imag': []
};
for (var i = 0; i < N; i++) {
ordered.real[bitReversedIndices[i]] = complexSignal.real[i];
ordered.imag[bitReversedIndices[i]] = complexSignal.imag[i];
}
for (var _i = 0; _i < N; _i++) {
complexSignal.real[_i] = ordered.real[_i];
complexSignal.imag[_i] = ordered.imag[_i];
}
// iterate over the number of stages
for (var n = 1; n <= logN; n++) {
var currN = Math.pow(2, n);
// find twiddle factors
for (var k = 0; k < currN / 2; k++) {
var twiddle = utils.euler(k, currN);
// on each block of FT, implement the butterfly diagram
for (var m = 0; m < N / currN; m++) {
var currEvenIndex = currN * m + k;
var currOddIndex = currN * m + k + currN / 2;
var currEvenIndexSample = {
'real': complexSignal.real[currEvenIndex],
'imag': complexSignal.imag[currEvenIndex]
};
var currOddIndexSample = {
'real': complexSignal.real[currOddIndex],
'imag': complexSignal.imag[currOddIndex]
};
var odd = utils.multiply(twiddle, currOddIndexSample);
var subtractionResult = utils.subtract(currEvenIndexSample, odd);
complexSignal.real[currOddIndex] = subtractionResult.real;
complexSignal.imag[currOddIndex] = subtractionResult.imag;
var additionResult = utils.add(odd, currEvenIndexSample);
complexSignal.real[currEvenIndex] = additionResult.real;
complexSignal.imag[currEvenIndex] = additionResult.imag;
}
}
}
return complexSignal;
};
// complex to real ifft
var ifft = function ifft(signal) {
if (signal.real === undefined || signal.imag === undefined) {
throw new Error("IFFT only accepts a complex input.");
}
var N = signal.real.length;
var complexSignal = {
'real': [],
'imag': []
};
//take complex conjugate in order to be able to use the regular FFT for IFFT
for (var i = 0; i < N; i++) {
var currentSample = {
'real': signal.real[i],
'imag': signal.imag[i]
};
var conjugateSample = utils.conj(currentSample);
complexSignal.real[i] = conjugateSample.real;
complexSignal.imag[i] = conjugateSample.imag;
}
//compute
var X = fft(complexSignal);
//normalize
complexSignal.real = X.real.map(function (val) {
return val / N;
});
complexSignal.imag = X.imag.map(function (val) {
return val / N;
});
return complexSignal;
};
module.exports = {
fft: fft,
ifft: ifft
};
/***/ }),
/***/ "./node_modules/fftjs/dist/utils.js":
/*!******************************************!*\
!*** ./node_modules/fftjs/dist/utils.js ***!
\******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// memoization of the reversal of different lengths.
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var memoizedReversal = {};
var memoizedZeroBuffers = {};
var constructComplexArray = function constructComplexArray(signal) {
var complexSignal = {};
complexSignal.real = signal.real === undefined ? signal.slice() : signal.real.slice();
var bufferSize = complexSignal.real.length;
if (memoizedZeroBuffers[bufferSize] === undefined) {
memoizedZeroBuffers[bufferSize] = Array.apply(null, Array(bufferSize)).map(Number.prototype.valueOf, 0);
}
complexSignal.imag = memoizedZeroBuffers[bufferSize].slice();
return complexSignal;
};
var bitReverseArray = function bitReverseArray(N) {
if (memoizedReversal[N] === undefined) {
var maxBinaryLength = (N - 1).toString(2).length; //get the binary length of the largest index.
var templateBinary = '0'.repeat(maxBinaryLength); //create a template binary of that length.
var reversed = {};
for (var n = 0; n < N; n++) {
var currBinary = n.toString(2); //get binary value of current index.
//prepend zeros from template to current binary. This makes binary values of all indices have the same length.
currBinary = templateBinary.substr(currBinary.length) + currBinary;
currBinary = [].concat(_toConsumableArray(currBinary)).reverse().join(''); //reverse
reversed[n] = parseInt(currBinary, 2); //convert to decimal
}
memoizedReversal[N] = reversed; //save
}
return memoizedReversal[N];
};
// complex multiplication
var multiply = function multiply(a, b) {
return {
'real': a.real * b.real - a.imag * b.imag,
'imag': a.real * b.imag + a.imag * b.real
};
};
// complex addition
var add = function add(a, b) {
return {
'real': a.real + b.real,
'imag': a.imag + b.imag
};
};
// complex subtraction
var subtract = function subtract(a, b) {
return {
'real': a.real - b.real,
'imag': a.imag - b.imag
};
};
// euler's identity e^x = cos(x) + sin(x)
var euler = function euler(kn, N) {
var x = -2 * Math.PI * kn / N;
return { 'real': Math.cos(x), 'imag': Math.sin(x) };
};
// complex conjugate
var conj = function conj(a) {
a.imag *= -1;
return a;
};
module.exports = {
bitReverseArray: bitReverseArray,
multiply: multiply,
add: add,
subtract: subtract,
euler: euler,
conj: conj,
constructComplexArray: constructComplexArray
};
/***/ }),
/***/ "./node_modules/inherits/inherits_browser.js":
/*!***************************************************!*\
!*** ./node_modules/inherits/inherits_browser.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(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
}
}
/***/ }),
/***/ "./node_modules/process/browser.js":
/*!*****************************************!*\
!*** ./node_modules/process/browser.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ }),
/***/ "./node_modules/webpack-stream/node_modules/util/support/isBufferBrowser.js":
/*!**********************************************************************************!*\
!*** ./node_modules/webpack-stream/node_modules/util/support/isBufferBrowser.js ***!
\**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
/***/ }),
/***/ "./node_modules/webpack-stream/node_modules/util/util.js":
/*!***************************************************************!*\
!*** ./node_modules/webpack-stream/node_modules/util/util.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {// 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 getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||
function getOwnPropertyDescriptors(obj) {
var keys = Object.keys(obj);
var descriptors = {};
for (var i = 0; i < keys.length; i++) {
descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
}
return descriptors;
};
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) {
if (typeof process !== 'undefined' && process.noDeprecation === true) {
return fn;
}
// Allow for deprecating things in the process of starting up.
if (typeof process === 'undefined') {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
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 = __webpack_require__(/*! ./support/isBuffer */ "./node_modules/webpack-stream/node_modules/util/support/isBufferBrowser.js");
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 = __webpack_require__(/*! inherits */ "./node_modules/inherits/inherits_browser.js");
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);
}
var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;
exports.promisify = function promisify(original) {
if (typeof original !== 'function')
throw new TypeError('The "original" argument must be of type Function');
if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
var fn = original[kCustomPromisifiedSymbol];
if (typeof fn !== 'function') {
throw new TypeError('The "util.promisify.custom" argument must be of type Function');
}
Object.defineProperty(fn, kCustomPromisifiedSymbol, {
value: fn, enumerable: false, writable: false, configurable: true
});
return fn;
}
function fn() {
var promiseResolve, promiseReject;
var promise = new Promise(function (resolve, reject) {
promiseResolve = resolve;
promiseReject = reject;
});
var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
args.push(function (err, value) {
if (err) {
promiseReject(err);
} else {
promiseResolve(value);
}
});
try {
original.apply(this, args);
} catch (err) {
promiseReject(err);
}
return promise;
}
Object.setPrototypeOf(fn, Object.getPrototypeOf(original));
if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {
value: fn, enumerable: false, writable: false, configurable: true
});
return Object.defineProperties(
fn,
getOwnPropertyDescriptors(original)
);
}
exports.promisify.custom = kCustomPromisifiedSymbol
function callbackifyOnRejected(reason, cb) {
// `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
// Because `null` is a special error value in callbacks which means "no error
// occurred", we error-wrap so the callback consumer can distinguish between
// "the promise rejected with null" or "the promise fulfilled with undefined".
if (!reason) {
var newReason = new Error('Promise was rejected with a falsy value');
newReason.reason = reason;
reason = newReason;
}
return cb(reason);
}
function callbackify(original) {
if (typeof original !== 'function') {
throw new TypeError('The "original" argument must be of type Function');
}
// We DO NOT return the promise as it gives the user a false sense that
// the promise is actually somehow related to the callback's execution
// and that the callback throwing will reject the promise.
function callbackified() {
var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
var maybeCb = args.pop();
if (typeof maybeCb !== 'function') {
throw new TypeError('The last argument must be of type Function');
}
var self = this;
var cb = function() {
return maybeCb.apply(self, arguments);
};
// In true node style we process the callback on `nextTick` with all the
// implications (stack, `uncaughtException`, `async_hooks`)
original.apply(this, args)
.then(function(ret) { process.nextTick(cb, null, ret) },
function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });
}
Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
Object.defineProperties(callbackified,
getOwnPropertyDescriptors(original));
return callbackified;
}
exports.callbackify = callbackify;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../process/browser.js */ "./node_modules/process/browser.js")))
/***/ }),
/***/ "./node_modules/webpack-stream/node_modules/webpack/buildin/global.js":
/*!***********************************!*\
!*** (webpack)/buildin/global.js ***!
\***********************************/
/*! no static exports found */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || new Function("return this")();
} catch (e) {
// This works if the window reference is available
if (typeof window === "object") g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/***/ "./src/extractors/chroma.js":
/*!**********************************!*\
!*** ./src/extractors/chroma.js ***!
\**********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/* harmony default export */ __webpack_exports__["default"] = (function (args) {
if (_typeof(args.ampSpectrum) !== 'object') {
throw new TypeError('Valid ampSpectrum is required to generate chroma');
}
if (_typeof(args.chromaFilterBank) !== 'object') {
throw new TypeError('Valid chromaFilterBank is required to generate chroma');
}
var chromagram = args.chromaFilterBank.map(function (row, i) {
return args.ampSpectrum.reduce(function (acc, v, j) {
return acc + v * row[j];
}, 0);
});
var maxVal = Math.max.apply(Math, _toConsumableArray(chromagram));
return maxVal ? chromagram.map(function (v) {
return v / maxVal;
}) : chromagram;
});
/***/ }),
/***/ "./src/extractors/energy.js":
/*!**********************************!*\
!*** ./src/extractors/energy.js ***!
\**********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var assert__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! assert */ "./node_modules/assert/assert.js");
/* harmony import */ var assert__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(assert__WEBPACK_IMPORTED_MODULE_0__);
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/* harmony default export */ __webpack_exports__["default"] = (function () {
if (_typeof(arguments[0].signal) !== 'object') {
throw new TypeError();
}
var energy = 0;
for (var i = 0; i < arguments[0].signal.length; i++) {
energy += Math.pow(Math.abs(arguments[0].signal[i]), 2);
}
return energy;
});
/***/ }),
/***/ "./src/extractors/extractorUtilities.js":
/*!**********************************************!*\
!*** ./src/extractors/extractorUtilities.js ***!
\**********************************************/
/*! exports provided: mu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mu", function() { return mu; });
function mu(i, amplitudeSpect) {
var numerator = 0;
var denominator = 0;
for (var k = 0; k < amplitudeSpect.length; k++) {
numerator += Math.pow(k, i) * Math.abs(amplitudeSpect[k]);
denominator += amplitudeSpect[k];
}
return numerator / denominator;
}
/***/ }),
/***/ "./src/extractors/loudness.js":
/*!************************************!*\
!*** ./src/extractors/loudness.js ***!
\************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/* harmony default export */ __webpack_exports__["default"] = (function (args) {
if (_typeof(args.ampSpectrum) !== 'object' || _typeof(args.barkScale) !== 'object') {
throw new TypeError();
}
var NUM_BARK_BANDS = 24;
var specific = new Float32Array(NUM_BARK_BANDS);
var total = 0;
var normalisedSpectrum = args.ampSpectrum;
var bbLimits = new Int32Array(NUM_BARK_BANDS + 1);
bbLimits[0] = 0;
var currentBandEnd = args.barkScale[normalisedSpectrum.length - 1] / NUM_BARK_BANDS;
var currentBand = 1;
for (var i = 0; i < normalisedSpectrum.length; i++) {
while (args.barkScale[i] > currentBandEnd) {
bbLimits[currentBand++] = i;
currentBandEnd = currentBand * args.barkScale[normalisedSpectrum.length - 1] / NUM_BARK_BANDS;
}
}
bbLimits[NUM_BARK_BANDS] = normalisedSpectrum.length - 1; //process
for (var _i = 0; _i < NUM_BARK_BANDS; _i++) {
var sum = 0;
for (var j = bbLimits[_i]; j < bbLimits[_i + 1]; j++) {
sum += normalisedSpectrum[j];
}
specific[_i] = Math.pow(sum, 0.23);
} //get total loudness
for (var _i2 = 0; _i2 < specific.length; _i2++) {
total += specific[_i2];
}
return {
specific: specific,
total: total
};
});
/***/ }),
/***/ "./src/extractors/mfcc.js":
/*!********************************!*\
!*** ./src/extractors/mfcc.js ***!
\********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _powerSpectrum__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./powerSpectrum */ "./src/extractors/powerSpectrum.js");
/* harmony import */ var _utilities__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./../utilities */ "./src/utilities.js");
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
var dct = __webpack_require__(/*! dct */ "./node_modules/dct/index.js");
/* harmony default export */ __webpack_exports__["default"] = (function (args) {
if (_typeof(args.ampSpectrum) !== 'object') {
throw new TypeError('Valid ampSpectrum is required to generate MFCC');
}
if (_typeof(args.melFilterBank) !== 'object') {
throw new TypeError('Valid melFilterBank is required to generate MFCC');
}
var numberOfMFCCCoefficients = Math.min(40, Math.max(1, args.numberOfMFCCCoefficients || 13)); // Tutorial from:
// http://practicalcryptography.com/miscellaneous/machine-learning
// /guide-mel-frequency-cepstral-coefficients-mfccs/
var powSpec = Object(_powerSpectrum__WEBPACK_IMPORTED_MODULE_0__["default"])(args);
var numFilters = args.melFilterBank.length;
var filtered = Array(numFilters);
if (numFilters < numberOfMFCCCoefficients) {
throw new Error("Insufficient filter bank for requested number of coefficients");
}
var loggedMelBands = new Float32Array(numFilters);
for (var i = 0; i < loggedMelBands.length; i++) {
filtered[i] = new Float32Array(args.bufferSize / 2);
loggedMelBands[i] = 0;
for (var j = 0; j < args.bufferSize / 2; j++) {
//point-wise multiplication between power spectrum and filterbanks.
filtered[i][j] = args.melFilterBank[i][j] * powSpec[j]; //summing up all of the coefficients into one array
loggedMelBands[i] += filtered[i][j];
} //log each coefficient.
loggedMelBands[i] = Math.log(loggedMelBands[i] + 1);
} //dct
var loggedMelBandsArray = Array.prototype.slice.call(loggedMelBands);
var mfccs = dct(loggedMelBandsArray).slice(0, numberOfMFCCCoefficients);
return mfccs;
});
/***/ }),
/***/ "./src/extractors/perceptualSharpness.js":
/*!***********************************************!*\
!*** ./src/extractors/perceptualSharpness.js ***!
\***********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _loudness__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./loudness */ "./src/extractors/loudness.js");
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/* harmony default export */ __webpack_exports__["default"] = (function () {
if (_typeof(arguments[0].signal) !== 'object') {
throw new TypeError();
}
var loudnessValue = Object(_loudness__WEBPACK_IMPORTED_MODULE_0__["default"])(arguments[0]);
var spec = loudnessValue.specific;
var output = 0;
for (var i = 0; i < spec.length; i++) {
if (i < 15) {
output += (i + 1) * spec[i + 1];
} else {
output += 0.066 * Math.exp(0.171 * (i + 1));
}
}
output *= 0.11 / loudnessValue.total;
return output;
});
/***/ }),
/***/ "./src/extractors/perceptualSpread.js":
/*!********************************************!*\
!*** ./src/extractors/perceptualSpread.js ***!
\********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _loudness__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./loudness */ "./src/extractors/loudness.js");
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/* harmony default export */ __webpack_exports__["default"] = (function () {
if (_typeof(arguments[0].signal) !== 'object') {
throw new TypeError();
}
var loudnessValue = Object(_loudness__WEBPACK_IMPORTED_MODULE_0__["default"])(arguments[0]);
var max = 0;
for (var i = 0; i < loudnessValue.specific.length; i++) {
if (loudnessValue.specific[i] > max) {
max = loudnessValue.specific[i];
}
}
var spread = Math.pow((loudnessValue.total - max) / loudnessValue.total, 2);
return spread;
});
/***/ }),
/***/ "./src/extractors/powerSpectrum.js":
/*!*****************************************!*\
!*** ./src/extractors/powerSpectrum.js ***!
\*****************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/* harmony default export */ __webpack_exports__["default"] = (function () {
if (_typeof(arguments[0].ampSpectrum) !== 'object') {
throw new TypeError();
}
var powerSpectrum = new Float32Array(arguments[0].ampSpectrum.length);
for (var i = 0; i < powerSpectrum.length; i++) {
powerSpectrum[i] = Math.pow(arguments[0].ampSpectrum[i], 2);
}
return powerSpectrum;
});
/***/ }),
/***/ "./src/extractors/rms.js":
/*!*******************************!*\
!*** ./src/extractors/rms.js ***!
\*******************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/* harmony default export */ __webpack_exports__["default"] = (function (args) {
if (_typeof(args.signal) !== 'object') {
throw new TypeError();
}
var rms = 0;
for (var i = 0; i < args.signal.length; i++) {
rms += Math.pow(args.signal[i], 2);
}
rms = rms / args.signal.length;
rms = Math.sqrt(rms);
return rms;
});
/***/ }),
/***/ "./src/extractors/spectralCentroid.js":
/*!********************************************!*\
!*** ./src/extractors/spectralCentroid.js ***!
\********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _extractorUtilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./extractorUtilities */ "./src/extractors/extractorUtilities.js");
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/* harmony default export */ __webpack_exports__["default"] = (function () {
if (_typeof(arguments[0].ampSpectrum) !== 'object') {
throw new TypeError();
}
return Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(1, arguments[0].ampSpectrum);
});
/***/ }),
/***/ "./src/extractors/spectralFlatness.js":
/*!********************************************!*\
!*** ./src/extractors/spectralFlatness.js ***!
\********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/* harmony default export */ __webpack_exports__["default"] = (function () {
if (_typeof(arguments[0].ampSpectrum) !== 'object') {
throw new TypeError();
}
var numerator = 0;
var denominator = 0;
for (var i = 0; i < arguments[0].ampSpectrum.length; i++) {
numerator += Math.log(arguments[0].ampSpectrum[i]);
denominator += arguments[0].ampSpectrum[i];
}
return Math.exp(numerator / arguments[0].ampSpectrum.length) * arguments[0].ampSpectrum.length / denominator;
});
/***/ }),
/***/ "./src/extractors/spectralFlux.js":
/*!****************************************!*\
!*** ./src/extractors/spectralFlux.js ***!
\****************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/* harmony default export */ __webpack_exports__["default"] = (function (args) {
if (_typeof(args.signal) !== 'object' || _typeof(args.previousSignal) != 'object') {
throw new TypeError();
}
var sf = 0;
for (var i = -(args.bufferSize / 2); i < signal.length / 2 - 1; i++) {
x = Math.abs(args.signal[i]) - Math.abs(args.previousSignal[i]);
sf += (x + Math.abs(x)) / 2;
}
return sf;
});
/***/ }),
/***/ "./src/extractors/spectralKurtosis.js":
/*!********************************************!*\
!*** ./src/extractors/spectralKurtosis.js ***!
\********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _extractorUtilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./extractorUtilities */ "./src/extractors/extractorUtilities.js");
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/* harmony default export */ __webpack_exports__["default"] = (function () {
if (_typeof(arguments[0].ampSpectrum) !== 'object') {
throw new TypeError();
}
var ampspec = arguments[0].ampSpectrum;
var mu1 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(1, ampspec);
var mu2 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(2, ampspec);
var mu3 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(3, ampspec);
var mu4 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(4, ampspec);
var numerator = -3 * Math.pow(mu1, 4) + 6 * mu1 * mu2 - 4 * mu1 * mu3 + mu4;
var denominator = Math.pow(Math.sqrt(mu2 - Math.pow(mu1, 2)), 4);
return numerator / denominator;
});
/***/ }),
/***/ "./src/extractors/spectralRolloff.js":
/*!*******************************************!*\
!*** ./src/extractors/spectralRolloff.js ***!
\*******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/* harmony default export */ __webpack_exports__["default"] = (function () {
if (_typeof(arguments[0].ampSpectrum) !== 'object') {
throw new TypeError();
}
var ampspec = arguments[0].ampSpectrum; //calculate nyquist bin
var nyqBin = arguments[0].sampleRate / (2 * (ampspec.length - 1));
var ec = 0;
for (var i = 0; i < ampspec.length; i++) {
ec += ampspec[i];
}
var threshold = 0.99 * ec;
var n = ampspec.length - 1;
while (ec > threshold && n >= 0) {
ec -= ampspec[n];
--n;
}
return (n + 1) * nyqBin;
});
/***/ }),
/***/ "./src/extractors/spectralSkewness.js":
/*!********************************************!*\
!*** ./src/extractors/spectralSkewness.js ***!
\********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _extractorUtilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./extractorUtilities */ "./src/extractors/extractorUtilities.js");
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/* harmony default export */ __webpack_exports__["default"] = (function (args) {
if (_typeof(args.ampSpectrum) !== 'object') {
throw new TypeError();
}
var mu1 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(1, args.ampSpectrum);
var mu2 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(2, args.ampSpectrum);
var mu3 = Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(3, args.ampSpectrum);
var numerator = 2 * Math.pow(mu1, 3) - 3 * mu1 * mu2 + mu3;
var denominator = Math.pow(Math.sqrt(mu2 - Math.pow(mu1, 2)), 3);
return numerator / denominator;
});
/***/ }),
/***/ "./src/extractors/spectralSlope.js":
/*!*****************************************!*\
!*** ./src/extractors/spectralSlope.js ***!
\*****************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/* harmony default export */ __webpack_exports__["default"] = (function (args) {
if (_typeof(args.ampSpectrum) !== 'object') {
throw new TypeError();
} //linear regression
var ampSum = 0;
var freqSum = 0;
var freqs = new Float32Array(args.ampSpectrum.length);
var powFreqSum = 0;
var ampFreqSum = 0;
for (var i = 0; i < args.ampSpectrum.length; i++) {
ampSum += args.ampSpectrum[i];
var curFreq = i * args.sampleRate / args.bufferSize;
freqs[i] = curFreq;
powFreqSum += curFreq * curFreq;
freqSum += curFreq;
ampFreqSum += curFreq * args.ampSpectrum[i];
}
return (args.ampSpectrum.length * ampFreqSum - freqSum * ampSum) / (ampSum * (powFreqSum - Math.pow(freqSum, 2)));
});
/***/ }),
/***/ "./src/extractors/spectralSpread.js":
/*!******************************************!*\
!*** ./src/extractors/spectralSpread.js ***!
\******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _extractorUtilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./extractorUtilities */ "./src/extractors/extractorUtilities.js");
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/* harmony default export */ __webpack_exports__["default"] = (function (args) {
if (_typeof(args.ampSpectrum) !== 'object') {
throw new TypeError();
}
return Math.sqrt(Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(2, args.ampSpectrum) - Math.pow(Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(1, args.ampSpectrum), 2));
});
/***/ }),
/***/ "./src/extractors/zcr.js":
/*!*******************************!*\
!*** ./src/extractors/zcr.js ***!
\*******************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/* harmony default export */ __webpack_exports__["default"] = (function () {
if (_typeof(arguments[0].signal) !== 'object') {
throw new TypeError();
}
var zcr = 0;
for (var i = 1; i < arguments[0].signal.length; i++) {
if (arguments[0].signal[i - 1] >= 0 && arguments[0].signal[i] < 0 || arguments[0].signal[i - 1] < 0 && arguments[0].signal[i] >= 0) {
zcr++;
}
}
return zcr;
});
/***/ }),
/***/ "./src/featureExtractors.js":
/*!**********************************!*\
!*** ./src/featureExtractors.js ***!
\**********************************/
/*! exports provided: buffer, rms, energy, complexSpectrum, spectralSlope, spectralCentroid, spectralRolloff, spectralFlatness, spectralSpread, spectralSkewness, spectralKurtosis, amplitudeSpectrum, zcr, loudness, perceptualSpread, perceptualSharpness, powerSpectrum, mfcc, chroma, spectralFlux */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buffer", function() { return buffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "complexSpectrum", function() { return complexSpectrum; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "amplitudeSpectrum", function() { return amplitudeSpectrum; });
/* harmony import */ var _extractors_rms__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./extractors/rms */ "./src/extractors/rms.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "rms", function() { return _extractors_rms__WEBPACK_IMPORTED_MODULE_0__["default"]; });
/* harmony import */ var _extractors_energy__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./extractors/energy */ "./src/extractors/energy.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "energy", function() { return _extractors_energy__WEBPACK_IMPORTED_MODULE_1__["default"]; });
/* harmony import */ var _extractors_spectralSlope__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./extractors/spectralSlope */ "./src/extractors/spectralSlope.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralSlope", function() { return _extractors_spectralSlope__WEBPACK_IMPORTED_MODULE_2__["default"]; });
/* harmony import */ var _extractors_spectralCentroid__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./extractors/spectralCentroid */ "./src/extractors/spectralCentroid.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralCentroid", function() { return _extractors_spectralCentroid__WEBPACK_IMPORTED_MODULE_3__["default"]; });
/* harmony import */ var _extractors_spectralRolloff__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./extractors/spectralRolloff */ "./src/extractors/spectralRolloff.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralRolloff", function() { return _extractors_spectralRolloff__WEBPACK_IMPORTED_MODULE_4__["default"]; });
/* harmony import */ var _extractors_spectralFlatness__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./extractors/spectralFlatness */ "./src/extractors/spectralFlatness.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralFlatness", function() { return _extractors_spectralFlatness__WEBPACK_IMPORTED_MODULE_5__["default"]; });
/* harmony import */ var _extractors_spectralSpread__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./extractors/spectralSpread */ "./src/extractors/spectralSpread.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralSpread", function() { return _extractors_spectralSpread__WEBPACK_IMPORTED_MODULE_6__["default"]; });
/* harmony import */ var _extractors_spectralSkewness__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./extractors/spectralSkewness */ "./src/extractors/spectralSkewness.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralSkewness", function() { return _extractors_spectralSkewness__WEBPACK_IMPORTED_MODULE_7__["default"]; });
/* harmony import */ var _extractors_spectralKurtosis__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./extractors/spectralKurtosis */ "./src/extractors/spectralKurtosis.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralKurtosis", function() { return _extractors_spectralKurtosis__WEBPACK_IMPORTED_MODULE_8__["default"]; });
/* harmony import */ var _extractors_zcr__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./extractors/zcr */ "./src/extractors/zcr.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "zcr", function() { return _extractors_zcr__WEBPACK_IMPORTED_MODULE_9__["default"]; });
/* harmony import */ var _extractors_loudness__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./extractors/loudness */ "./src/extractors/loudness.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "loudness", function() { return _extractors_loudness__WEBPACK_IMPORTED_MODULE_10__["default"]; });
/* harmony import */ var _extractors_perceptualSpread__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./extractors/perceptualSpread */ "./src/extractors/perceptualSpread.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "perceptualSpread", function() { return _extractors_perceptualSpread__WEBPACK_IMPORTED_MODULE_11__["default"]; });
/* harmony import */ var _extractors_perceptualSharpness__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./extractors/perceptualSharpness */ "./src/extractors/perceptualSharpness.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "perceptualSharpness", function() { return _extractors_perceptualSharpness__WEBPACK_IMPORTED_MODULE_12__["default"]; });
/* harmony import */ var _extractors_mfcc__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./extractors/mfcc */ "./src/extractors/mfcc.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mfcc", function() { return _extractors_mfcc__WEBPACK_IMPORTED_MODULE_13__["default"]; });
/* harmony import */ var _extractors_chroma__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./extractors/chroma */ "./src/extractors/chroma.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "chroma", function() { return _extractors_chroma__WEBPACK_IMPORTED_MODULE_14__["default"]; });
/* harmony import */ var _extractors_powerSpectrum__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./extractors/powerSpectrum */ "./src/extractors/powerSpectrum.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "powerSpectrum", function() { return _extractors_powerSpectrum__WEBPACK_IMPORTED_MODULE_15__["default"]; });
/* harmony import */ var _extractors_spectralFlux__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./extractors/spectralFlux */ "./src/extractors/spectralFlux.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "spectralFlux", function() { return _extractors_spectralFlux__WEBPACK_IMPORTED_MODULE_16__["default"]; });
var buffer = function buffer(args) {
return args.signal;
};
var complexSpectrum = function complexSpectrum(args) {
return args.complexSpectrum;
};
var amplitudeSpectrum = function amplitudeSpectrum(args) {
return args.ampSpectrum;
};
/***/ }),
/***/ "./src/index.js":
/*!**********************!*\
!*** ./src/index.js ***!
\**********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(/*! ./main */ "./src/main.js")["default"];
/***/ }),
/***/ "./src/main.js":
/*!*********************!*\
!*** ./src/main.js ***!
\*********************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _utilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utilities */ "./src/utilities.js");
/* harmony import */ var _featureExtractors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./featureExtractors */ "./src/featureExtractors.js");
/* harmony import */ var fftjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! fftjs */ "./node_modules/fftjs/dist/fft.js");
/* harmony import */ var fftjs__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(fftjs__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _meyda_wa__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./meyda-wa */ "./src/meyda-wa.js");
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/**
* Meyda Module
* @module meyda
*/
/**
* Options for constructing a MeydaAnalyzer
* @typedef {Object} MeydaOptions
* @property {AudioContext} audioContext - The Audio Context for the MeydaAnalyzer to operate in.
* @property {AudioNode} source - The Audio Node for Meyda to listen to.
* @property {number} [bufferSize] - The size of the buffer.
* @property {number} [hopSize] - The hop size between buffers.
* @property {number} [sampleRate] - The number of samples per second in the audio context.
* @property {Function} [callback] - A function to receive the frames of audio features
* @property {string} [windowingFunction] - The Windowing Function to apply to the signal before transformation to the frequency domain
* @property {string|Array.<string>} [featureExtractors] - Specify the feature extractors you want to run on the audio.
* @property {boolean} [startImmediately] - Pass `true` to start feature extraction immediately
* @property {number} [numberOfMFCCCoefficients] - The number of MFCC co-efficients that the MFCC feature extractor should return
*/
/**
* Web Audio context
* Either an {@link AudioContext|https://developer.mozilla.org/en-US/docs/Web/API/AudioContext}
* or an {@link OfflineAudioContext|https://developer.mozilla.org/en-US/docs/Web/API/OfflineAudioContext}
* @typedef {Object} AudioContext
*/
/**
* AudioNode
* A Web AudioNode
* @typedef {Object} AudioNode
*/
/**
* ScriptProcessorNode
* A Web Audio ScriptProcessorNode
* @typedef {Object} ScriptProcessorNode
*/
/**
* @class Meyda
* @hideconstructor
* @classdesc
* The schema for the default export of the Meyda library.
* @example
* var Meyda = require('meyda');
*/
var Meyda = {
/**
* Meyda stores a reference to the relevant audio context here for use inside
* the Web Audio API.
* @instance
* @member {AudioContext}
*/
audioContext: null,
/**
* Meyda keeps an internal ScriptProcessorNode in which it runs audio feature
* extraction. The ScriptProcessorNode is stored in this member variable.
* @instance
* @member {ScriptProcessorNode}
*/
spn: null,
/**
* The length of each buffer that Meyda will extract audio on. When recieving
* input via the Web Audio API, the Script Processor Node chunks incoming audio
* into arrays of this length. Longer buffers allow for more precision in the
* frequency domain, but increase the amount of time it takes for Meyda to
* output a set of audio features for the buffer. You can calculate how many
* sets of audio features Meyda will output per second by dividing the
* buffer size by the sample rate. If you're using Meyda for visualisation,
* make sure that you're collecting audio features at a rate that's faster
* than or equal to the video frame rate you expect.
* @instance
* @member {number}
*/
bufferSize: 512,
/**
* The number of samples per second of the incoming audio. This affects
* feature extraction outside of the context of the Web Audio API, and must be
* set accurately - otherwise calculations will be off.
* @instance
* @member {number}
*/
sampleRate: 44100,
/**
* The number of Mel bands to use in the Mel Frequency Cepstral Co-efficients
* feature extractor
* @instance
* @member {number}
*/
melBands: 26,
/**
* The number of bands to divide the spectrum into for the Chroma feature
* extractor. 12 is the standard number of semitones per octave in the western
* music tradition, but Meyda can use an arbitrary number of bands, which
* can be useful for microtonal music.
* @instance
* @member {number}
*/
chromaBands: 12,
/**
* A function you can provide that will be called for each buffer that Meyda
* receives from its source node
* @instance
* @member {Function}
*/
callback: null,
/**
* Specify the windowing function to apply to the buffer before the
* transformation from the time domain to the frequency domain is performed
*
* The default windowing function is the hanning window.
*
* @instance
* @member {string}
*/
windowingFunction: 'hanning',
/**
* @member {object}
*/
featureExtractors: _featureExtractors__WEBPACK_IMPORTED_MODULE_1__,
EXTRACTION_STARTED: false,
/**
* The number of MFCC co-efficients that the MFCC feature extractor should return
* @instance
* @member {number}
*/
numberOfMFCCCoefficients: 13,
_featuresToExtract: [],
windowing: _utilities__WEBPACK_IMPORTED_MODULE_0__["applyWindow"],
_errors: {
notPow2: new Error('Meyda: Buffer size must be a power of 2, e.g. 64 or 512'),
featureUndef: new Error('Meyda: No features defined.'),
invalidFeatureFmt: new Error('Meyda: Invalid feature format'),
invalidInput: new Error('Meyda: Invalid input.'),
noAC: new Error('Meyda: No AudioContext specified.'),
noSource: new Error('Meyda: No source node specified.')
},
/**
* @summary
* Create a MeydaAnalyzer
*
* A factory function for creating a MeydaAnalyzer, the interface for using
* Meyda in the context of Web Audio.
*
* @method
* @param {MeydaOptions} options Options - an object containing configuration
* @returns {MeydaAnalyzer}
* @example
* const analyzer = Meyda.createMeydaAnalyzer({
* "audioContext": audioContext,
* "source": source,
* "bufferSize": 512,
* "featureExtractors": ["rms"],
* "inputs": 2,
* "callback": features => {
* levelRangeElement.value = features.rms;
* }
* });
*/
createMeydaAnalyzer: function createMeydaAnalyzer(options) {
return new _meyda_wa__WEBPACK_IMPORTED_MODULE_3__["MeydaAnalyzer"](options, Object.assign({}, Meyda));
},
/**
* Extract an audio feature from a buffer
*
* Unless `meyda.windowingFunction` is set otherwise, `extract` will
* internally apply a hanning window to the buffer prior to conversion into
* the frequency domain.
*
* @function
* @param {(string|Array.<string>)} feature - the feature you want to extract
* @param {Array.<number>} signal
* An array of numbers that represents the signal. It should be of length
* `meyda.bufferSize`
* @param {Array.<number>} [previousSignal] - the previous buffer
* @returns {object} Features
* @example
* meyda.bufferSize = 2048;
* const features = meyda.extract(['zcr', 'spectralCentroid'], signal);
*/
extract: function extract(feature, signal, previousSignal) {
var _this = this;
if (!signal) throw this._errors.invalidInput;else if (_typeof(signal) != 'object') throw this._errors.invalidInput;else if (!feature) throw this._errors.featureUndef;else if (!_utilities__WEBPACK_IMPORTED_MODULE_0__["isPowerOfTwo"](signal.length)) throw this._errors.notPow2;
if (typeof this.barkScale == 'undefined' || this.barkScale.length != this.bufferSize) {
this.barkScale = _utilities__WEBPACK_IMPORTED_MODULE_0__["createBarkScale"](this.bufferSize, this.sampleRate, this.bufferSize);
} // Recalculate mel bank if buffer length changed
if (typeof this.melFilterBank == 'undefined' || this.barkScale.length != this.bufferSize || this.melFilterBank.length != this.melBands) {
this.melFilterBank = _utilities__WEBPACK_IMPORTED_MODULE_0__["createMelFilterBank"](Math.max(this.melBands, this.numberOfMFCCCoefficients), this.sampleRate, this.bufferSize);
} // Recalculate chroma bank if buffer length changed
if (typeof this.chromaFilterBank == 'undefined' || this.chromaFilterBank.length != this.chromaBands) {
this.chromaFilterBank = _utilities__WEBPACK_IMPORTED_MODULE_0__["createChromaFilterBank"](this.chromaBands, this.sampleRate, this.bufferSize);
}
if (typeof signal.buffer == 'undefined') {
//signal is a normal array, convert to F32A
this.signal = _utilities__WEBPACK_IMPORTED_MODULE_0__["arrayToTyped"](signal);
} else {
this.signal = signal;
}
var preparedSignal = prepareSignalWithSpectrum(signal, this.windowingFunction, this.bufferSize);
this.signal = preparedSignal.windowedSignal;
this.complexSpectrum = preparedSignal.complexSpectrum;
this.ampSpectrum = preparedSignal.ampSpectrum;
if (previousSignal) {
var _preparedSignal = prepareSignalWithSpectrum(previousSignal, this.windowingFunction, this.bufferSize);
this.previousSignal = _preparedSignal.windowedSignal;
this.previousComplexSpectrum = _preparedSignal.complexSpectrum;
this.previousAmpSpectrum = _preparedSignal.ampSpectrum;
}
var extract = function extract(feature) {
return _this.featureExtractors[feature]({
ampSpectrum: _this.ampSpectrum,
chromaFilterBank: _this.chromaFilterBank,
complexSpectrum: _this.complexSpectrum,
signal: _this.signal,
bufferSize: _this.bufferSize,
sampleRate: _this.sampleRate,
barkScale: _this.barkScale,
melFilterBank: _this.melFilterBank,
previousSignal: _this.previousSignal,
previousAmpSpectrum: _this.previousAmpSpectrum,
previousComplexSpectrum: _this.previousComplexSpectrum,
numberOfMFCCCoefficients: _this.numberOfMFCCCoefficients
});
};
if (_typeof(feature) === 'object') {
return feature.reduce(function (acc, el) {
return Object.assign({}, acc, _defineProperty({}, el, extract(el)));
}, {});
} else if (typeof feature === 'string') {
return extract(feature);
} else {
throw this._errors.invalidFeatureFmt;
}
}
};
var prepareSignalWithSpectrum = function prepareSignalWithSpectrum(signal, windowingFunction, bufferSize) {
var preparedSignal = {};
if (typeof signal.buffer == 'undefined') {
//signal is a normal array, convert to F32A
preparedSignal.signal = _utilities__WEBPACK_IMPORTED_MODULE_0__["arrayToTyped"](signal);
} else {
preparedSignal.signal = signal;
}
preparedSignal.windowedSignal = _utilities__WEBPACK_IMPORTED_MODULE_0__["applyWindow"](preparedSignal.signal, windowingFunction);
preparedSignal.complexSpectrum = Object(fftjs__WEBPACK_IMPORTED_MODULE_2__["fft"])(preparedSignal.windowedSignal);
preparedSignal.ampSpectrum = new Float32Array(bufferSize / 2);
for (var i = 0; i < bufferSize / 2; i++) {
preparedSignal.ampSpectrum[i] = Math.sqrt(Math.pow(preparedSignal.complexSpectrum.real[i], 2) + Math.pow(preparedSignal.complexSpectrum.imag[i], 2));
}
return preparedSignal;
};
/**
* The Meyda class
* @type {Meyda}
*/
/* harmony default export */ __webpack_exports__["default"] = (Meyda);
if (typeof window !== 'undefined') window.Meyda = Meyda;
/***/ }),
/***/ "./src/meyda-wa.js":
/*!*************************!*\
!*** ./src/meyda-wa.js ***!
\*************************/
/*! exports provided: MeydaAnalyzer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeydaAnalyzer", function() { return MeydaAnalyzer; });
/* harmony import */ var _utilities__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utilities */ "./src/utilities.js");
/* harmony import */ var _featureExtractors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./featureExtractors */ "./src/featureExtractors.js");
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; }
/**
* MeydaAnalyzer
* @classdesc
* Meyda's interface to the Web Audio API. MeydaAnalyzer abstracts an API on
* top of the Web Audio API's ScriptProcessorNode, running the Meyda audio
* feature extractors inside that context.
*
* MeydaAnalyzer's constructor should not be called directly - MeydaAnalyzer
* objects should be generated using the {@link Meyda.createMeydaAnalyzer}
* factory function in the main Meyda class.
*
* @example
* const analyzer = Meyda.createMeydaAnalyzer({
* "audioContext": audioContext,
* "source": source,
* "bufferSize": 512,
* "featureExtractors": ["rms"],
* "inputs": 2,
* "numberOfMFCCCoefficients": 20
* "callback": features => {
* levelRangeElement.value = features.rms;
* }
* });
* @hideconstructor
*/
var MeydaAnalyzer =
/*#__PURE__*/
function () {
function MeydaAnalyzer(options, _this) {
var _this2 = this;
_classCallCheck(this, MeydaAnalyzer);
this._m = _this;
if (!options.audioContext) {
throw this._m.errors.noAC;
} else if (options.bufferSize && !_utilities__WEBPACK_IMPORTED_MODULE_0__["isPowerOfTwo"](options.bufferSize)) {
throw this._m._errors.notPow2;
} else if (!options.source) {
throw this._m._errors.noSource;
}
this._m.audioContext = options.audioContext; // TODO: validate options
this._m.bufferSize = options.bufferSize || this._m.bufferSize || 256;
this._m.hopSize = options.hopSize || this._m.hopSize || this._m.bufferSize;
this._m.sampleRate = options.sampleRate || this._m.audioContext.sampleRate || 44100;
this._m.callback = options.callback;
this._m.windowingFunction = options.windowingFunction || 'hanning';
this._m.featureExtractors = _featureExtractors__WEBPACK_IMPORTED_MODULE_1__;
this._m.EXTRACTION_STARTED = options.startImmediately || false;
this._m.channel = typeof options.channel === 'number' ? options.channel : 0;
this._m.inputs = options.inputs || 1;
this._m.outputs = options.outputs || 1;
this._m.numberOfMFCCCoefficients = options.numberOfMFCCCoefficients || this._m.numberOfMFCCCoefficients || 13; //create nodes
this._m.spn = this._m.audioContext.createScriptProcessor(this._m.bufferSize, this._m.inputs, this._m.outputs);
this._m.spn.connect(this._m.audioContext.destination);
this._m._featuresToExtract = options.featureExtractors || []; //always recalculate BS and MFB when a new Meyda analyzer is created.
this._m.barkScale = _utilities__WEBPACK_IMPORTED_MODULE_0__["createBarkScale"](this._m.bufferSize, this._m.sampleRate, this._m.bufferSize);
this._m.melFilterBank = _utilities__WEBPACK_IMPORTED_MODULE_0__["createMelFilterBank"](Math.max(this._m.melBands, this._m.numberOfMFCCCoefficients), this._m.sampleRate, this._m.bufferSize);
this._m.inputData = null;
this._m.previousInputData = null;
this._m.frame = null;
this._m.previousFrame = null;
this.setSource(options.source);
this._m.spn.onaudioprocess = function (e) {
if (_this2._m.inputData !== null) {
_this2._m.previousInputData = _this2._m.inputData;
}
_this2._m.inputData = e.inputBuffer.getChannelData(_this2._m.channel);
if (!_this2._m.previousInputData) {
var buffer = _this2._m.inputData;
} else {
var buffer = new Float32Array(_this2._m.previousInputData.length + _this2._m.inputData.length - _this2._m.hopSize);
buffer.set(_this2._m.previousInputData.slice(_this2._m.hopSize));
buffer.set(_this2._m.inputData, _this2._m.previousInputData.length - _this2._m.hopSize);
}
;
var frames = _utilities__WEBPACK_IMPORTED_MODULE_0__["frame"](buffer, _this2._m.bufferSize, _this2._m.hopSize);
frames.forEach(function (f) {
_this2._m.frame = f;
var features = _this2._m.extract(_this2._m._featuresToExtract, _this2._m.frame, _this2._m.previousFrame); // call callback if applicable
if (typeof _this2._m.callback === 'function' && _this2._m.EXTRACTION_STARTED) {
_this2._m.callback(features);
}
_this2._m.previousFrame = _this2._m.frame;
});
};
}
/**
* Start feature extraction
* The audio features will be passed to the callback function that was defined
* in the MeydaOptions that were passed to the factory when constructing the
* MeydaAnalyzer.
* @param {(string|Array.<string>)} [features]
* Change the features that Meyda is extracting. Defaults to the features that
* were set upon construction in the options parameter.
* @example
* analyzer.start('chroma');
*/
_createClass(MeydaAnalyzer, [{
key: "start",
value: function start(features) {
this._m._featuresToExtract = features || this._m._featuresToExtract;
this._m.EXTRACTION_STARTED = true;
}
/**
* Stop feature extraction.
* @example
* analyzer.stop();
*/
}, {
key: "stop",
value: function stop() {
this._m.EXTRACTION_STARTED = false;
}
/**
* Set the Audio Node for Meyda to listen to.
* @param {AudioNode} source - The Audio Node for Meyda to listen to
* @example
* analyzer.setSource(audioSourceNode);
*/
}, {
key: "setSource",
value: function setSource(source) {
this._m.source && this._m.source.disconnect(this._m.spn);
this._m.source = source;
this._m.source.connect(this._m.spn);
}
/**
* Set the channel of the audio node for Meyda to listen to
* @param {number} channel - the index of the channel on the input audio node
* for Meyda to listen to.
* @example
* analyzer.setChannel(0);
*/
}, {
key: "setChannel",
value: function setChannel(channel) {
if (channel <= this._m.inputs) {
this._m.channel = channel;
} else {
console.error("Channel ".concat(channel, " does not exist. Make sure you've provided a value for 'inputs' that is greater than ").concat(channel, " when instantiating the MeydaAnalyzer"));
}
}
/**
* Get a set of features from the current frame.
* @param {(string|Array.<string>)} [features]
* Change the features that Meyda is extracting
* @example
* analyzer.get('spectralFlatness');
*/
}, {
key: "get",
value: function get(features) {
if (this._m.inputData) {
return this._m.extract(features || this._m._featuresToExtract, this._m.inputData, this._m.previousInputData);
} else {
return null;
}
}
}]);
return MeydaAnalyzer;
}();
/***/ }),
/***/ "./src/utilities.js":
/*!**************************!*\
!*** ./src/utilities.js ***!
\**************************/
/*! exports provided: isPowerOfTwo, error, pointwiseBufferMult, applyWindow, createBarkScale, typedToArray, arrayToTyped, _normalize, normalize, normalizeToOne, mean, melToFreq, freqToMel, createMelFilterBank, hzToOctaves, normalizeByColumn, createChromaFilterBank, frame */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPowerOfTwo", function() { return isPowerOfTwo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "error", function() { return error; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pointwiseBufferMult", function() { return pointwiseBufferMult; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyWindow", function() { return applyWindow; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createBarkScale", function() { return createBarkScale; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "typedToArray", function() { return typedToArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "arrayToTyped", function() { return arrayToTyped; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_normalize", function() { return _normalize; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalize", function() { return normalize; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalizeToOne", function() { return normalizeToOne; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mean", function() { return mean; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "melToFreq", function() { return melToFreq; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "freqToMel", function() { return freqToMel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createMelFilterBank", function() { return createMelFilterBank; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hzToOctaves", function() { return hzToOctaves; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalizeByColumn", function() { return normalizeByColumn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createChromaFilterBank", function() { return createChromaFilterBank; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "frame", function() { return frame; });
/* harmony import */ var _windowing__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./windowing */ "./src/windowing.js");
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
var windows = {};
function isPowerOfTwo(num) {
while (num % 2 === 0 && num > 1) {
num /= 2;
}
return num === 1;
}
function error(message) {
throw new Error('Meyda: ' + message);
}
function pointwiseBufferMult(a, b) {
var c = [];
for (var i = 0; i < Math.min(a.length, b.length); i++) {
c[i] = a[i] * b[i];
}
return c;
}
function applyWindow(signal, windowname) {
if (windowname !== 'rect') {
if (windowname === '' || !windowname) windowname = 'hanning';
if (!windows[windowname]) windows[windowname] = {};
if (!windows[windowname][signal.length]) {
try {
windows[windowname][signal.length] = _windowing__WEBPACK_IMPORTED_MODULE_0__[windowname](signal.length);
} catch (e) {
throw new Error('Invalid windowing function');
}
}
signal = pointwiseBufferMult(signal, windows[windowname][signal.length]);
}
return signal;
}
function createBarkScale(length, sampleRate, bufferSize) {
var barkScale = new Float32Array(length);
for (var i = 0; i < barkScale.length; i++) {
barkScale[i] = i * sampleRate / bufferSize;
barkScale[i] = 13 * Math.atan(barkScale[i] / 1315.8) + 3.5 * Math.atan(Math.pow(barkScale[i] / 7518, 2));
}
return barkScale;
}
function typedToArray(t) {
// utility to convert typed arrays to normal arrays
return Array.prototype.slice.call(t);
}
function arrayToTyped(t) {
// utility to convert arrays to typed F32 arrays
return Float32Array.from(t);
}
function _normalize(num, range) {
return num / range;
}
function normalize(a, range) {
return a.map(function (n) {
return _normalize(n, range);
});
}
function normalizeToOne(a) {
var max = Math.max.apply(null, a);
return a.map(function (n) {
return n / max;
});
}
function mean(a) {
return a.reduce(function (prev, cur) {
return prev + cur;
}) / a.length;
}
function _melToFreq(melValue) {
var freqValue = 700 * (Math.exp(melValue / 1125) - 1);
return freqValue;
}
function _freqToMel(freqValue) {
var melValue = 1125 * Math.log(1 + freqValue / 700);
return melValue;
}
function melToFreq(mV) {
return _melToFreq(mV);
}
function freqToMel(fV) {
return _freqToMel(fV);
}
function createMelFilterBank(numFilters, sampleRate, bufferSize) {
//the +2 is the upper and lower limits
var melValues = new Float32Array(numFilters + 2);
var melValuesInFreq = new Float32Array(numFilters + 2); //Generate limits in Hz - from 0 to the nyquist.
var lowerLimitFreq = 0;
var upperLimitFreq = sampleRate / 2; //Convert the limits to Mel
var lowerLimitMel = _freqToMel(lowerLimitFreq);
var upperLimitMel = _freqToMel(upperLimitFreq); //Find the range
var range = upperLimitMel - lowerLimitMel; //Find the range as part of the linear interpolation
var valueToAdd = range / (numFilters + 1);
var fftBinsOfFreq = Array(numFilters + 2);
for (var i = 0; i < melValues.length; i++) {
// Initialising the mel frequencies
// They're a linear interpolation between the lower and upper limits.
melValues[i] = i * valueToAdd; // Convert back to Hz
melValuesInFreq[i] = _melToFreq(melValues[i]); // Find the corresponding bins
fftBinsOfFreq[i] = Math.floor((bufferSize + 1) * melValuesInFreq[i] / sampleRate);
}
var filterBank = Array(numFilters);
for (var j = 0; j < filterBank.length; j++) {
// Create a two dimensional array of size numFilters * (buffersize/2)+1
// pre-populating the arrays with 0s.
filterBank[j] = Array.apply(null, new Array(bufferSize / 2 + 1)).map(Number.prototype.valueOf, 0); //creating the lower and upper slopes for each bin
for (var _i = fftBinsOfFreq[j]; _i < fftBinsOfFreq[j + 1]; _i++) {
filterBank[j][_i] = (_i - fftBinsOfFreq[j]) / (fftBinsOfFreq[j + 1] - fftBinsOfFreq[j]);
}
for (var _i2 = fftBinsOfFreq[j + 1]; _i2 < fftBinsOfFreq[j + 2]; _i2++) {
filterBank[j][_i2] = (fftBinsOfFreq[j + 2] - _i2) / (fftBinsOfFreq[j + 2] - fftBinsOfFreq[j + 1]);
}
}
return filterBank;
}
function hzToOctaves(freq, A440) {
return Math.log2(16 * freq / A440);
}
function normalizeByColumn(a) {
var emptyRow = a[0].map(function () {
return 0;
});
var colDenominators = a.reduce(function (acc, row) {
row.forEach(function (cell, j) {
acc[j] += Math.pow(cell, 2);
});
return acc;
}, emptyRow).map(Math.sqrt);
return a.map(function (row, i) {
return row.map(function (v, j) {
return v / (colDenominators[j] || 1);
});
});
}
;
function createChromaFilterBank(numFilters, sampleRate, bufferSize) {
var centerOctave = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 5;
var octaveWidth = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 2;
var baseC = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
var A440 = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 440;
var numOutputBins = Math.floor(bufferSize / 2) + 1;
var frequencyBins = new Array(bufferSize).fill(0).map(function (_, i) {
return numFilters * hzToOctaves(sampleRate * i / bufferSize, A440);
}); // Set a value for the 0 Hz bin that is 1.5 octaves below bin 1
// (so chroma is 50% rotated from bin 1, and bin width is broad)
frequencyBins[0] = frequencyBins[1] - 1.5 * numFilters;
var binWidthBins = frequencyBins.slice(1).map(function (v, i) {
return Math.max(v - frequencyBins[i]);
}, 1).concat([1]);
var halfNumFilters = Math.round(numFilters / 2);
var filterPeaks = new Array(numFilters).fill(0).map(function (_, i) {
return frequencyBins.map(function (frq) {
return (10 * numFilters + halfNumFilters + frq - i) % numFilters - halfNumFilters;
});
});
var weights = filterPeaks.map(function (row, i) {
return row.map(function (_, j) {
return Math.exp(-0.5 * Math.pow(2 * filterPeaks[i][j] / binWidthBins[j], 2));
});
});
weights = normalizeByColumn(weights);
if (octaveWidth) {
var octaveWeights = frequencyBins.map(function (v) {
return Math.exp(-0.5 * Math.pow((v / numFilters - centerOctave) / octaveWidth, 2));
});
weights = weights.map(function (row) {
return row.map(function (cell, j) {
return cell * octaveWeights[j];
});
});
}
if (baseC) {
weights = [].concat(_toConsumableArray(weights.slice(3)), _toConsumableArray(weights.slice(0, 3)));
}
return weights.map(function (row) {
return row.slice(0, numOutputBins);
});
}
function frame(buffer, frameLength, hopLength) {
if (buffer.length < frameLength) {
throw new Error('Buffer is too short for frame length');
}
if (hopLength < 1) {
throw new Error('Hop length cannot be less that 1');
}
if (frameLength < 1) {
throw new Error('Frame length cannot be less that 1');
}
var numFrames = 1 + Math.floor((buffer.length - frameLength) / hopLength);
return new Array(numFrames).fill(0).map(function (_, i) {
return buffer.slice(i * hopLength, i * hopLength + frameLength);
});
}
/***/ }),
/***/ "./src/windowing.js":
/*!**************************!*\
!*** ./src/windowing.js ***!
\**************************/
/*! exports provided: blackman, sine, hanning, hamming */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "blackman", function() { return blackman; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sine", function() { return sine; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hanning", function() { return hanning; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hamming", function() { return hamming; });
function blackman(size) {
var blackmanBuffer = new Float32Array(size);
var coeff1 = 2 * Math.PI / (size - 1);
var coeff2 = 2 * coeff1; //According to http://uk.mathworks.com/help/signal/ref/blackman.html
//first half of the window
for (var i = 0; i < size / 2; i++) {
blackmanBuffer[i] = 0.42 - 0.5 * Math.cos(i * coeff1) + 0.08 * Math.cos(i * coeff2);
} //second half of the window
for (var _i = size / 2; _i > 0; _i--) {
blackmanBuffer[size - _i] = blackmanBuffer[_i - 1];
}
return blackmanBuffer;
}
function sine(size) {
var coeff = Math.PI / (size - 1);
var sineBuffer = new Float32Array(size);
for (var i = 0; i < size; i++) {
sineBuffer[i] = Math.sin(coeff * i);
}
return sineBuffer;
}
function hanning(size) {
var hanningBuffer = new Float32Array(size);
for (var i = 0; i < size; i++) {
// According to the R documentation
// http://ugrad.stat.ubc.ca/R/library/e1071/html/hanning.window.html
hanningBuffer[i] = 0.5 - 0.5 * Math.cos(2 * Math.PI * i / (size - 1));
}
return hanningBuffer;
}
function hamming(size) {
var hammingBuffer = new Float32Array(size);
for (var i = 0; i < size; i++) {
//According to http://uk.mathworks.com/help/signal/ref/hamming.html
hammingBuffer[i] = 0.54 - 0.46 * Math.cos(2 * Math.PI * (i / size - 1));
}
return hammingBuffer;
}
/***/ })
/******/ });
});
},{}],134:[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;
};
},{}],135:[function(require,module,exports){
(function (process){(function (){
// Generated by CoffeeScript 1.12.2
(function() {
var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime;
if ((typeof performance !== "undefined" && performance !== null) && performance.now) {
module.exports = function() {
return performance.now();
};
} else if ((typeof process !== "undefined" && process !== null) && process.hrtime) {
module.exports = function() {
return (getNanoSeconds() - nodeLoadTime) / 1e6;
};
hrtime = process.hrtime;
getNanoSeconds = function() {
var hr;
hr = hrtime();
return hr[0] * 1e9 + hr[1];
};
moduleLoadTime = getNanoSeconds();
upTime = process.uptime() * 1e9;
nodeLoadTime = moduleLoadTime - upTime;
} else if (Date.now) {
module.exports = function() {
return Date.now() - loadTime;
};
loadTime = Date.now();
} else {
module.exports = function() {
return new Date().getTime() - loadTime;
};
loadTime = new Date().getTime();
}
}).call(this);
}).call(this)}).call(this,require('_process'))
},{"_process":136}],136:[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; };
},{}],137:[function(require,module,exports){
var inherits = require('inherits')
var EventEmitter = require('events').EventEmitter
var now = require('right-now')
var raf = require('raf')
module.exports = Engine
function Engine(fn) {
if (!(this instanceof Engine))
return new Engine(fn)
this.running = false
this.last = now()
this._frame = 0
this._tick = this.tick.bind(this)
if (fn)
this.on('tick', fn)
}
inherits(Engine, EventEmitter)
Engine.prototype.start = function() {
if (this.running)
return
this.running = true
this.last = now()
this._frame = raf(this._tick)
return this
}
Engine.prototype.stop = function() {
this.running = false
if (this._frame !== 0)
raf.cancel(this._frame)
this._frame = 0
return this
}
Engine.prototype.tick = function() {
this._frame = raf(this._tick)
var time = now()
var dt = time - this.last
this.emit('tick', dt)
this.last = time
}
},{"events":130,"inherits":132,"raf":138,"right-now":140}],138:[function(require,module,exports){
(function (global){(function (){
var now = require('performance-now')
, root = typeof window === 'undefined' ? global : window
, vendors = ['moz', 'webkit']
, suffix = 'AnimationFrame'
, raf = root['request' + suffix]
, caf = root['cancel' + suffix] || root['cancelRequest' + suffix]
for(var i = 0; !raf && i < vendors.length; i++) {
raf = root[vendors[i] + 'Request' + suffix]
caf = root[vendors[i] + 'Cancel' + suffix]
|| root[vendors[i] + 'CancelRequest' + suffix]
}
// Some versions of FF have rAF but not cAF
if(!raf || !caf) {
var last = 0
, id = 0
, queue = []
, frameDuration = 1000 / 60
raf = function(callback) {
if(queue.length === 0) {
var _now = now()
, next = Math.max(0, frameDuration - (_now - last))
last = next + _now
setTimeout(function() {
var cp = queue.slice(0)
// Clear queue here to prevent
// callbacks from appending listeners
// to the current frame's queue
queue.length = 0
for(var i = 0; i < cp.length; i++) {
if(!cp[i].cancelled) {
try{
cp[i].callback(last)
} catch(e) {
setTimeout(function() { throw e }, 0)
}
}
}
}, Math.round(next))
}
queue.push({
handle: ++id,
callback: callback,
cancelled: false
})
return id
}
caf = function(handle) {
for(var i = 0; i < queue.length; i++) {
if(queue[i].handle === handle) {
queue[i].cancelled = true
}
}
}
}
module.exports = function(fn) {
// Wrap in a new function to prevent
// `cancel` potentially being assigned
// to the native rAF function
return raf.call(root, fn)
}
module.exports.cancel = function() {
caf.apply(root, arguments)
}
module.exports.polyfill = function(object) {
if (!object) {
object = root;
}
object.requestAnimationFrame = raf
object.cancelAnimationFrame = caf
}
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"performance-now":135}],139:[function(require,module,exports){
(function(U,X){"object"===typeof exports&&"undefined"!==typeof module?module.exports=X():"function"===typeof define&&define.amd?define(X):U.createREGL=X()})(this,function(){function U(a,b){this.id=Eb++;this.type=a;this.data=b}function X(a){if(0===a.length)return[];var b=a.charAt(0),c=a.charAt(a.length-1);if(1<a.length&&b===c&&('"'===b||"'"===b))return['"'+a.substr(1,a.length-2).replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'];if(b=/\[(false|true|null|\d+|'[^']*'|"[^"]*")\]/.exec(a))return X(a.substr(0,
b.index)).concat(X(b[1])).concat(X(a.substr(b.index+b[0].length)));b=a.split(".");if(1===b.length)return['"'+a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'];a=[];for(c=0;c<b.length;++c)a=a.concat(X(b[c]));return a}function cb(a){return"["+X(a).join("][")+"]"}function db(a,b){if("function"===typeof a)return new U(0,a);if("number"===typeof a||"boolean"===typeof a)return new U(5,a);if(Array.isArray(a))return new U(6,a.map(function(a,e){return db(a,b+"["+e+"]")}));if(a instanceof U)return a}function Fb(){var a=
{"":0},b=[""];return{id:function(c){var e=a[c];if(e)return e;e=a[c]=b.length;b.push(c);return e},str:function(a){return b[a]}}}function Gb(a,b,c){function e(){var b=window.innerWidth,e=window.innerHeight;a!==document.body&&(e=a.getBoundingClientRect(),b=e.right-e.left,e=e.bottom-e.top);f.width=c*b;f.height=c*e;A(f.style,{width:b+"px",height:e+"px"})}var f=document.createElement("canvas");A(f.style,{border:0,margin:0,padding:0,top:0,left:0});a.appendChild(f);a===document.body&&(f.style.position="absolute",
A(a.style,{margin:0,padding:0}));var d;a!==document.body&&"function"===typeof ResizeObserver?(d=new ResizeObserver(function(){setTimeout(e)}),d.observe(a)):window.addEventListener("resize",e,!1);e();return{canvas:f,onDestroy:function(){d?d.disconnect():window.removeEventListener("resize",e);a.removeChild(f)}}}function Hb(a,b){function c(c){try{return a.getContext(c,b)}catch(f){return null}}return c("webgl")||c("experimental-webgl")||c("webgl-experimental")}function eb(a){return"string"===typeof a?
a.split():a}function fb(a){return"string"===typeof a?document.querySelector(a):a}function Ib(a){var b=a||{},c,e,f,d;a={};var p=[],n=[],u="undefined"===typeof window?1:window.devicePixelRatio,t=!1,w=function(a){},k=function(){};"string"===typeof b?c=document.querySelector(b):"object"===typeof b&&("string"===typeof b.nodeName&&"function"===typeof b.appendChild&&"function"===typeof b.getBoundingClientRect?c=b:"function"===typeof b.drawArrays||"function"===typeof b.drawElements?(d=b,f=d.canvas):("gl"in
b?d=b.gl:"canvas"in b?f=fb(b.canvas):"container"in b&&(e=fb(b.container)),"attributes"in b&&(a=b.attributes),"extensions"in b&&(p=eb(b.extensions)),"optionalExtensions"in b&&(n=eb(b.optionalExtensions)),"onDone"in b&&(w=b.onDone),"profile"in b&&(t=!!b.profile),"pixelRatio"in b&&(u=+b.pixelRatio)));c&&("canvas"===c.nodeName.toLowerCase()?f=c:e=c);if(!d){if(!f){c=Gb(e||document.body,w,u);if(!c)return null;f=c.canvas;k=c.onDestroy}void 0===a.premultipliedAlpha&&(a.premultipliedAlpha=!0);d=Hb(f,a)}return d?
{gl:d,canvas:f,container:e,extensions:p,optionalExtensions:n,pixelRatio:u,profile:t,onDone:w,onDestroy:k}:(k(),w("webgl not supported, try upgrading your browser or graphics drivers http://get.webgl.org"),null)}function Jb(a,b){function c(b){b=b.toLowerCase();var c;try{c=e[b]=a.getExtension(b)}catch(f){}return!!c}for(var e={},f=0;f<b.extensions.length;++f){var d=b.extensions[f];if(!c(d))return b.onDestroy(),b.onDone('"'+d+'" extension is not supported by the current WebGL context, try upgrading your system or a different browser'),
null}b.optionalExtensions.forEach(c);return{extensions:e,restore:function(){Object.keys(e).forEach(function(a){if(e[a]&&!c(a))throw Error("(regl): error restoring extension "+a);})}}}function J(a,b){for(var c=Array(a),e=0;e<a;++e)c[e]=b(e);return c}function gb(a){var b,c;b=(65535<a)<<4;a>>>=b;c=(255<a)<<3;a>>>=c;b|=c;c=(15<a)<<2;a>>>=c;b|=c;c=(3<a)<<1;return b|c|a>>>c>>1}function hb(){function a(a){a:{for(var b=16;268435456>=b;b*=16)if(a<=b){a=b;break a}a=0}b=c[gb(a)>>2];return 0<b.length?b.pop():
new ArrayBuffer(a)}function b(a){c[gb(a.byteLength)>>2].push(a)}var c=J(8,function(){return[]});return{alloc:a,free:b,allocType:function(b,c){var d=null;switch(b){case 5120:d=new Int8Array(a(c),0,c);break;case 5121:d=new Uint8Array(a(c),0,c);break;case 5122:d=new Int16Array(a(2*c),0,c);break;case 5123:d=new Uint16Array(a(2*c),0,c);break;case 5124:d=new Int32Array(a(4*c),0,c);break;case 5125:d=new Uint32Array(a(4*c),0,c);break;case 5126:d=new Float32Array(a(4*c),0,c);break;default:return null}return d.length!==
c?d.subarray(0,c):d},freeType:function(a){b(a.buffer)}}}function da(a){return!!a&&"object"===typeof a&&Array.isArray(a.shape)&&Array.isArray(a.stride)&&"number"===typeof a.offset&&a.shape.length===a.stride.length&&(Array.isArray(a.data)||M(a.data))}function ib(a,b,c,e,f,d){for(var p=0;p<b;++p)for(var n=a[p],u=0;u<c;++u)for(var t=n[u],w=0;w<e;++w)f[d++]=t[w]}function jb(a,b,c,e,f){for(var d=1,p=c+1;p<b.length;++p)d*=b[p];var n=b[c];if(4===b.length-c){var u=b[c+1],t=b[c+2];b=b[c+3];for(p=0;p<n;++p)ib(a[p],
u,t,b,e,f),f+=d}else for(p=0;p<n;++p)jb(a[p],b,c+1,e,f),f+=d}function Fa(a){return Ga[Object.prototype.toString.call(a)]|0}function kb(a,b){for(var c=0;c<b.length;++c)a[c]=b[c]}function lb(a,b,c,e,f,d,p){for(var n=0,u=0;u<c;++u)for(var t=0;t<e;++t)a[n++]=b[f*u+d*t+p]}function Kb(a,b,c,e){function f(b){this.id=u++;this.buffer=a.createBuffer();this.type=b;this.usage=35044;this.byteLength=0;this.dimension=1;this.dtype=5121;this.persistentData=null;c.profile&&(this.stats={size:0})}function d(b,c,l){b.byteLength=
c.byteLength;a.bufferData(b.type,c,l)}function p(a,b,c,h,g,q){a.usage=c;if(Array.isArray(b)){if(a.dtype=h||5126,0<b.length)if(Array.isArray(b[0])){g=mb(b);for(var r=h=1;r<g.length;++r)h*=g[r];a.dimension=h;b=Sa(b,g,a.dtype);d(a,b,c);q?a.persistentData=b:E.freeType(b)}else"number"===typeof b[0]?(a.dimension=g,g=E.allocType(a.dtype,b.length),kb(g,b),d(a,g,c),q?a.persistentData=g:E.freeType(g)):M(b[0])&&(a.dimension=b[0].length,a.dtype=h||Fa(b[0])||5126,b=Sa(b,[b.length,b[0].length],a.dtype),d(a,b,c),
q?a.persistentData=b:E.freeType(b))}else if(M(b))a.dtype=h||Fa(b),a.dimension=g,d(a,b,c),q&&(a.persistentData=new Uint8Array(new Uint8Array(b.buffer)));else if(da(b)){g=b.shape;var m=b.stride,r=b.offset,e=0,f=0,t=0,n=0;1===g.length?(e=g[0],f=1,t=m[0],n=0):2===g.length&&(e=g[0],f=g[1],t=m[0],n=m[1]);a.dtype=h||Fa(b.data)||5126;a.dimension=f;g=E.allocType(a.dtype,e*f);lb(g,b.data,e,f,t,n,r);d(a,g,c);q?a.persistentData=g:E.freeType(g)}else b instanceof ArrayBuffer&&(a.dtype=5121,a.dimension=g,d(a,b,
c),q&&(a.persistentData=new Uint8Array(new Uint8Array(b))))}function n(c){b.bufferCount--;e(c);a.deleteBuffer(c.buffer);c.buffer=null;delete t[c.id]}var u=0,t={};f.prototype.bind=function(){a.bindBuffer(this.type,this.buffer)};f.prototype.destroy=function(){n(this)};var w=[];c.profile&&(b.getTotalBufferSize=function(){var a=0;Object.keys(t).forEach(function(b){a+=t[b].stats.size});return a});return{create:function(k,e,d,h){function g(b){var m=35044,k=null,e=0,d=0,f=1;Array.isArray(b)||M(b)||da(b)||
b instanceof ArrayBuffer?k=b:"number"===typeof b?e=b|0:b&&("data"in b&&(k=b.data),"usage"in b&&(m=ob[b.usage]),"type"in b&&(d=Ia[b.type]),"dimension"in b&&(f=b.dimension|0),"length"in b&&(e=b.length|0));q.bind();k?p(q,k,m,d,f,h):(e&&a.bufferData(q.type,e,m),q.dtype=d||5121,q.usage=m,q.dimension=f,q.byteLength=e);c.profile&&(q.stats.size=q.byteLength*ha[q.dtype]);return g}b.bufferCount++;var q=new f(e);t[q.id]=q;d||g(k);g._reglType="buffer";g._buffer=q;g.subdata=function(b,c){var k=(c||0)|0,e;q.bind();
if(M(b)||b instanceof ArrayBuffer)a.bufferSubData(q.type,k,b);else if(Array.isArray(b)){if(0<b.length)if("number"===typeof b[0]){var h=E.allocType(q.dtype,b.length);kb(h,b);a.bufferSubData(q.type,k,h);E.freeType(h)}else if(Array.isArray(b[0])||M(b[0]))e=mb(b),h=Sa(b,e,q.dtype),a.bufferSubData(q.type,k,h),E.freeType(h)}else if(da(b)){e=b.shape;var d=b.stride,f=h=0,l=0,O=0;1===e.length?(h=e[0],f=1,l=d[0],O=0):2===e.length&&(h=e[0],f=e[1],l=d[0],O=d[1]);e=Array.isArray(b.data)?q.dtype:Fa(b.data);e=E.allocType(e,
h*f);lb(e,b.data,h,f,l,O,b.offset);a.bufferSubData(q.type,k,e);E.freeType(e)}return g};c.profile&&(g.stats=q.stats);g.destroy=function(){n(q)};return g},createStream:function(a,b){var c=w.pop();c||(c=new f(a));c.bind();p(c,b,35040,0,1,!1);return c},destroyStream:function(a){w.push(a)},clear:function(){S(t).forEach(n);w.forEach(n)},getBuffer:function(a){return a&&a._buffer instanceof f?a._buffer:null},restore:function(){S(t).forEach(function(b){b.buffer=a.createBuffer();a.bindBuffer(b.type,b.buffer);
a.bufferData(b.type,b.persistentData||b.byteLength,b.usage)})},_initBuffer:p}}function Lb(a,b,c,e){function f(a){this.id=u++;n[this.id]=this;this.buffer=a;this.primType=4;this.type=this.vertCount=0}function d(e,d,f,h,g,q,r){e.buffer.bind();var m;d?((m=r)||M(d)&&(!da(d)||M(d.data))||(m=b.oes_element_index_uint?5125:5123),c._initBuffer(e.buffer,d,f,m,3)):(a.bufferData(34963,q,f),e.buffer.dtype=m||5121,e.buffer.usage=f,e.buffer.dimension=3,e.buffer.byteLength=q);m=r;if(!r){switch(e.buffer.dtype){case 5121:case 5120:m=
5121;break;case 5123:case 5122:m=5123;break;case 5125:case 5124:m=5125}e.buffer.dtype=m}e.type=m;d=g;0>d&&(d=e.buffer.byteLength,5123===m?d>>=1:5125===m&&(d>>=2));e.vertCount=d;d=h;0>h&&(d=4,h=e.buffer.dimension,1===h&&(d=0),2===h&&(d=1),3===h&&(d=4));e.primType=d}function p(a){e.elementsCount--;delete n[a.id];a.buffer.destroy();a.buffer=null}var n={},u=0,t={uint8:5121,uint16:5123};b.oes_element_index_uint&&(t.uint32=5125);f.prototype.bind=function(){this.buffer.bind()};var w=[];return{create:function(a,
b){function l(a){if(a)if("number"===typeof a)h(a),g.primType=4,g.vertCount=a|0,g.type=5121;else{var b=null,c=35044,e=-1,f=-1,k=0,n=0;if(Array.isArray(a)||M(a)||da(a))b=a;else if("data"in a&&(b=a.data),"usage"in a&&(c=ob[a.usage]),"primitive"in a&&(e=Ta[a.primitive]),"count"in a&&(f=a.count|0),"type"in a&&(n=t[a.type]),"length"in a)k=a.length|0;else if(k=f,5123===n||5122===n)k*=2;else if(5125===n||5124===n)k*=4;d(g,b,c,e,f,k,n)}else h(),g.primType=4,g.vertCount=0,g.type=5121;return l}var h=c.create(null,
34963,!0),g=new f(h._buffer);e.elementsCount++;l(a);l._reglType="elements";l._elements=g;l.subdata=function(a,b){h.subdata(a,b);return l};l.destroy=function(){p(g)};return l},createStream:function(a){var b=w.pop();b||(b=new f(c.create(null,34963,!0,!1)._buffer));d(b,a,35040,-1,-1,0,0);return b},destroyStream:function(a){w.push(a)},getElements:function(a){return"function"===typeof a&&a._elements instanceof f?a._elements:null},clear:function(){S(n).forEach(p)}}}function pb(a){for(var b=E.allocType(5123,
a.length),c=0;c<a.length;++c)if(isNaN(a[c]))b[c]=65535;else if(Infinity===a[c])b[c]=31744;else if(-Infinity===a[c])b[c]=64512;else{qb[0]=a[c];var e=Mb[0],f=e>>>31<<15,d=(e<<1>>>24)-127,e=e>>13&1023;b[c]=-24>d?f:-14>d?f+(e+1024>>-14-d):15<d?f+31744:f+(d+15<<10)+e}return b}function ma(a){return Array.isArray(a)||M(a)}function na(a){return"[object "+a+"]"}function rb(a){return Array.isArray(a)&&(0===a.length||"number"===typeof a[0])}function sb(a){return Array.isArray(a)&&0!==a.length&&ma(a[0])?!0:!1}
function ea(a){return Object.prototype.toString.call(a)}function Ua(a){if(!a)return!1;var b=ea(a);return 0<=Nb.indexOf(b)?!0:rb(a)||sb(a)||da(a)}function tb(a,b){36193===a.type?(a.data=pb(b),E.freeType(b)):a.data=b}function Ja(a,b,c,e,f,d){a="undefined"!==typeof F[a]?F[a]:Q[a]*wa[b];d&&(a*=6);if(f){for(e=0;1<=c;)e+=a*c*c,c/=2;return e}return a*c*e}function Ob(a,b,c,e,f,d,p){function n(){this.format=this.internalformat=6408;this.type=5121;this.flipY=this.premultiplyAlpha=this.compressed=!1;this.unpackAlignment=
1;this.colorSpace=37444;this.channels=this.height=this.width=0}function u(a,b){a.internalformat=b.internalformat;a.format=b.format;a.type=b.type;a.compressed=b.compressed;a.premultiplyAlpha=b.premultiplyAlpha;a.flipY=b.flipY;a.unpackAlignment=b.unpackAlignment;a.colorSpace=b.colorSpace;a.width=b.width;a.height=b.height;a.channels=b.channels}function t(a,b){if("object"===typeof b&&b){"premultiplyAlpha"in b&&(a.premultiplyAlpha=b.premultiplyAlpha);"flipY"in b&&(a.flipY=b.flipY);"alignment"in b&&(a.unpackAlignment=
b.alignment);"colorSpace"in b&&(a.colorSpace=Pb[b.colorSpace]);"type"in b&&(a.type=N[b.type]);var c=a.width,g=a.height,e=a.channels,d=!1;"shape"in b?(c=b.shape[0],g=b.shape[1],3===b.shape.length&&(e=b.shape[2],d=!0)):("radius"in b&&(c=g=b.radius),"width"in b&&(c=b.width),"height"in b&&(g=b.height),"channels"in b&&(e=b.channels,d=!0));a.width=c|0;a.height=g|0;a.channels=e|0;c=!1;"format"in b&&(c=b.format,g=a.internalformat=C[c],a.format=P[g],c in N&&!("type"in b)&&(a.type=N[c]),c in v&&(a.compressed=
!0),c=!0);!d&&c?a.channels=Q[a.format]:d&&!c&&a.channels!==Ma[a.format]&&(a.format=a.internalformat=Ma[a.channels])}}function w(b){a.pixelStorei(37440,b.flipY);a.pixelStorei(37441,b.premultiplyAlpha);a.pixelStorei(37443,b.colorSpace);a.pixelStorei(3317,b.unpackAlignment)}function k(){n.call(this);this.yOffset=this.xOffset=0;this.data=null;this.needsFree=!1;this.element=null;this.needsCopy=!1}function B(a,b){var c=null;Ua(b)?c=b:b&&(t(a,b),"x"in b&&(a.xOffset=b.x|0),"y"in b&&(a.yOffset=b.y|0),Ua(b.data)&&
(c=b.data));if(b.copy){var g=f.viewportWidth,e=f.viewportHeight;a.width=a.width||g-a.xOffset;a.height=a.height||e-a.yOffset;a.needsCopy=!0}else if(!c)a.width=a.width||1,a.height=a.height||1,a.channels=a.channels||4;else if(M(c))a.channels=a.channels||4,a.data=c,"type"in b||5121!==a.type||(a.type=Ga[Object.prototype.toString.call(c)]|0);else if(rb(c)){a.channels=a.channels||4;g=c;e=g.length;switch(a.type){case 5121:case 5123:case 5125:case 5126:e=E.allocType(a.type,e);e.set(g);a.data=e;break;case 36193:a.data=
pb(g)}a.alignment=1;a.needsFree=!0}else if(da(c)){g=c.data;Array.isArray(g)||5121!==a.type||(a.type=Ga[Object.prototype.toString.call(g)]|0);var e=c.shape,d=c.stride,h,r,m,q;3===e.length?(m=e[2],q=d[2]):q=m=1;h=e[0];r=e[1];e=d[0];d=d[1];a.alignment=1;a.width=h;a.height=r;a.channels=m;a.format=a.internalformat=Ma[m];a.needsFree=!0;h=q;c=c.offset;m=a.width;q=a.height;r=a.channels;for(var x=E.allocType(36193===a.type?5126:a.type,m*q*r),I=0,ja=0;ja<q;++ja)for(var ka=0;ka<m;++ka)for(var Va=0;Va<r;++Va)x[I++]=
g[e*ka+d*ja+h*Va+c];tb(a,x)}else if(ea(c)===Wa||ea(c)===Xa||ea(c)===vb)ea(c)===Wa||ea(c)===Xa?a.element=c:a.element=c.canvas,a.width=a.element.width,a.height=a.element.height,a.channels=4;else if(ea(c)===wb)a.element=c,a.width=c.width,a.height=c.height,a.channels=4;else if(ea(c)===xb)a.element=c,a.width=c.naturalWidth,a.height=c.naturalHeight,a.channels=4;else if(ea(c)===yb)a.element=c,a.width=c.videoWidth,a.height=c.videoHeight,a.channels=4;else if(sb(c)){g=a.width||c[0].length;e=a.height||c.length;
d=a.channels;d=ma(c[0][0])?d||c[0][0].length:d||1;h=Oa.shape(c);m=1;for(q=0;q<h.length;++q)m*=h[q];m=E.allocType(36193===a.type?5126:a.type,m);Oa.flatten(c,h,"",m);tb(a,m);a.alignment=1;a.width=g;a.height=e;a.channels=d;a.format=a.internalformat=Ma[d];a.needsFree=!0}}function l(b,c,g,d,h){var m=b.element,f=b.data,r=b.internalformat,q=b.format,l=b.type,x=b.width,I=b.height;w(b);m?a.texSubImage2D(c,h,g,d,q,l,m):b.compressed?a.compressedTexSubImage2D(c,h,g,d,r,x,I,f):b.needsCopy?(e(),a.copyTexSubImage2D(c,
h,g,d,b.xOffset,b.yOffset,x,I)):a.texSubImage2D(c,h,g,d,x,I,q,l,f)}function h(){return J.pop()||new k}function g(a){a.needsFree&&E.freeType(a.data);k.call(a);J.push(a)}function q(){n.call(this);this.genMipmaps=!1;this.mipmapHint=4352;this.mipmask=0;this.images=Array(16)}function r(a,b,c){var g=a.images[0]=h();a.mipmask=1;g.width=a.width=b;g.height=a.height=c;g.channels=a.channels=4}function m(a,b){var c=null;if(Ua(b))c=a.images[0]=h(),u(c,a),B(c,b),a.mipmask=1;else if(t(a,b),Array.isArray(b.mipmap))for(var g=
b.mipmap,e=0;e<g.length;++e)c=a.images[e]=h(),u(c,a),c.width>>=e,c.height>>=e,B(c,g[e]),a.mipmask|=1<<e;else c=a.images[0]=h(),u(c,a),B(c,b),a.mipmask=1;u(a,a.images[0])}function z(b,c){for(var g=b.images,d=0;d<g.length&&g[d];++d){var h=g[d],m=c,f=d,r=h.element,q=h.data,l=h.internalformat,x=h.format,I=h.type,ja=h.width,ka=h.height;w(h);r?a.texImage2D(m,f,x,x,I,r):h.compressed?a.compressedTexImage2D(m,f,l,ja,ka,0,q):h.needsCopy?(e(),a.copyTexImage2D(m,f,x,h.xOffset,h.yOffset,ja,ka,0)):a.texImage2D(m,
f,x,ja,ka,0,x,I,q||null)}}function Ha(){var a=L.pop()||new q;n.call(a);for(var b=a.mipmask=0;16>b;++b)a.images[b]=null;return a}function nb(a){for(var b=a.images,c=0;c<b.length;++c)b[c]&&g(b[c]),b[c]=null;L.push(a)}function Z(){this.magFilter=this.minFilter=9728;this.wrapT=this.wrapS=33071;this.anisotropic=1;this.genMipmaps=!1;this.mipmapHint=4352}function G(a,b){"min"in b&&(a.minFilter=R[b.min],0<=Qb.indexOf(a.minFilter)&&!("faces"in b)&&(a.genMipmaps=!0));"mag"in b&&(a.magFilter=V[b.mag]);var c=
a.wrapS,g=a.wrapT;if("wrap"in b){var e=b.wrap;"string"===typeof e?c=g=la[e]:Array.isArray(e)&&(c=la[e[0]],g=la[e[1]])}else"wrapS"in b&&(c=la[b.wrapS]),"wrapT"in b&&(g=la[b.wrapT]);a.wrapS=c;a.wrapT=g;"anisotropic"in b&&(a.anisotropic=b.anisotropic);if("mipmap"in b){c=!1;switch(typeof b.mipmap){case "string":a.mipmapHint=y[b.mipmap];c=a.genMipmaps=!0;break;case "boolean":c=a.genMipmaps=b.mipmap;break;case "object":a.genMipmaps=!1,c=!0}!c||"min"in b||(a.minFilter=9984)}}function H(c,g){a.texParameteri(g,
10241,c.minFilter);a.texParameteri(g,10240,c.magFilter);a.texParameteri(g,10242,c.wrapS);a.texParameteri(g,10243,c.wrapT);b.ext_texture_filter_anisotropic&&a.texParameteri(g,34046,c.anisotropic);c.genMipmaps&&(a.hint(33170,c.mipmapHint),a.generateMipmap(g))}function O(b){n.call(this);this.mipmask=0;this.internalformat=6408;this.id=Y++;this.refCount=1;this.target=b;this.texture=a.createTexture();this.unit=-1;this.bindCount=0;this.texInfo=new Z;p.profile&&(this.stats={size:0})}function xa(b){a.activeTexture(33984);
a.bindTexture(b.target,b.texture)}function ya(){var b=W[0];b?a.bindTexture(b.target,b.texture):a.bindTexture(3553,null)}function D(b){var c=b.texture,g=b.unit,e=b.target;0<=g&&(a.activeTexture(33984+g),a.bindTexture(e,null),W[g]=null);a.deleteTexture(c);b.texture=null;b.params=null;b.pixels=null;b.refCount=0;delete ia[b.id];d.textureCount--}var y={"don't care":4352,"dont care":4352,nice:4354,fast:4353},la={repeat:10497,clamp:33071,mirror:33648},V={nearest:9728,linear:9729},R=A({mipmap:9987,"nearest mipmap nearest":9984,
"linear mipmap nearest":9985,"nearest mipmap linear":9986,"linear mipmap linear":9987},V),Pb={none:0,browser:37444},N={uint8:5121,rgba4:32819,rgb565:33635,"rgb5 a1":32820},C={alpha:6406,luminance:6409,"luminance alpha":6410,rgb:6407,rgba:6408,rgba4:32854,"rgb5 a1":32855,rgb565:36194},v={};b.ext_srgb&&(C.srgb=35904,C.srgba=35906);b.oes_texture_float&&(N.float32=N["float"]=5126);b.oes_texture_half_float&&(N.float16=N["half float"]=36193);b.webgl_depth_texture&&(A(C,{depth:6402,"depth stencil":34041}),
A(N,{uint16:5123,uint32:5125,"depth stencil":34042}));b.webgl_compressed_texture_s3tc&&A(v,{"rgb s3tc dxt1":33776,"rgba s3tc dxt1":33777,"rgba s3tc dxt3":33778,"rgba s3tc dxt5":33779});b.webgl_compressed_texture_atc&&A(v,{"rgb atc":35986,"rgba atc explicit alpha":35987,"rgba atc interpolated alpha":34798});b.webgl_compressed_texture_pvrtc&&A(v,{"rgb pvrtc 4bppv1":35840,"rgb pvrtc 2bppv1":35841,"rgba pvrtc 4bppv1":35842,"rgba pvrtc 2bppv1":35843});b.webgl_compressed_texture_etc1&&(v["rgb etc1"]=36196);
var F=Array.prototype.slice.call(a.getParameter(34467));Object.keys(v).forEach(function(a){var b=v[a];0<=F.indexOf(b)&&(C[a]=b)});var ta=Object.keys(C);c.textureFormats=ta;var aa=[];Object.keys(C).forEach(function(a){aa[C[a]]=a});var K=[];Object.keys(N).forEach(function(a){K[N[a]]=a});var fa=[];Object.keys(V).forEach(function(a){fa[V[a]]=a});var Da=[];Object.keys(R).forEach(function(a){Da[R[a]]=a});var ua=[];Object.keys(la).forEach(function(a){ua[la[a]]=a});var P=ta.reduce(function(a,c){var g=C[c];
6409===g||6406===g||6409===g||6410===g||6402===g||34041===g||b.ext_srgb&&(35904===g||35906===g)?a[g]=g:32855===g||0<=c.indexOf("rgba")?a[g]=6408:a[g]=6407;return a},{}),J=[],L=[],Y=0,ia={},ga=c.maxTextureUnits,W=Array(ga).map(function(){return null});A(O.prototype,{bind:function(){this.bindCount+=1;var b=this.unit;if(0>b){for(var c=0;c<ga;++c){var g=W[c];if(g){if(0<g.bindCount)continue;g.unit=-1}W[c]=this;b=c;break}p.profile&&d.maxTextureUnits<b+1&&(d.maxTextureUnits=b+1);this.unit=b;a.activeTexture(33984+
b);a.bindTexture(this.target,this.texture)}return b},unbind:function(){--this.bindCount},decRef:function(){0>=--this.refCount&&D(this)}});p.profile&&(d.getTotalTextureSize=function(){var a=0;Object.keys(ia).forEach(function(b){a+=ia[b].stats.size});return a});return{create2D:function(b,c){function e(a,b){var c=f.texInfo;Z.call(c);var g=Ha();"number"===typeof a?"number"===typeof b?r(g,a|0,b|0):r(g,a|0,a|0):a?(G(c,a),m(g,a)):r(g,1,1);c.genMipmaps&&(g.mipmask=(g.width<<1)-1);f.mipmask=g.mipmask;u(f,
g);f.internalformat=g.internalformat;e.width=g.width;e.height=g.height;xa(f);z(g,3553);H(c,3553);ya();nb(g);p.profile&&(f.stats.size=Ja(f.internalformat,f.type,g.width,g.height,c.genMipmaps,!1));e.format=aa[f.internalformat];e.type=K[f.type];e.mag=fa[c.magFilter];e.min=Da[c.minFilter];e.wrapS=ua[c.wrapS];e.wrapT=ua[c.wrapT];return e}var f=new O(3553);ia[f.id]=f;d.textureCount++;e(b,c);e.subimage=function(a,b,c,d){b|=0;c|=0;d|=0;var m=h();u(m,f);m.width=0;m.height=0;B(m,a);m.width=m.width||(f.width>>
d)-b;m.height=m.height||(f.height>>d)-c;xa(f);l(m,3553,b,c,d);ya();g(m);return e};e.resize=function(b,c){var g=b|0,d=c|0||g;if(g===f.width&&d===f.height)return e;e.width=f.width=g;e.height=f.height=d;xa(f);for(var h=0;f.mipmask>>h;++h){var m=g>>h,x=d>>h;if(!m||!x)break;a.texImage2D(3553,h,f.format,m,x,0,f.format,f.type,null)}ya();p.profile&&(f.stats.size=Ja(f.internalformat,f.type,g,d,!1,!1));return e};e._reglType="texture2d";e._texture=f;p.profile&&(e.stats=f.stats);e.destroy=function(){f.decRef()};
return e},createCube:function(b,c,e,f,q,n){function k(a,b,c,g,e,d){var f,ca=y.texInfo;Z.call(ca);for(f=0;6>f;++f)D[f]=Ha();if("number"===typeof a||!a)for(a=a|0||1,f=0;6>f;++f)r(D[f],a,a);else if("object"===typeof a)if(b)m(D[0],a),m(D[1],b),m(D[2],c),m(D[3],g),m(D[4],e),m(D[5],d);else if(G(ca,a),t(y,a),"faces"in a)for(a=a.faces,f=0;6>f;++f)u(D[f],y),m(D[f],a[f]);else for(f=0;6>f;++f)m(D[f],a);u(y,D[0]);y.mipmask=ca.genMipmaps?(D[0].width<<1)-1:D[0].mipmask;y.internalformat=D[0].internalformat;k.width=
D[0].width;k.height=D[0].height;xa(y);for(f=0;6>f;++f)z(D[f],34069+f);H(ca,34067);ya();p.profile&&(y.stats.size=Ja(y.internalformat,y.type,k.width,k.height,ca.genMipmaps,!0));k.format=aa[y.internalformat];k.type=K[y.type];k.mag=fa[ca.magFilter];k.min=Da[ca.minFilter];k.wrapS=ua[ca.wrapS];k.wrapT=ua[ca.wrapT];for(f=0;6>f;++f)nb(D[f]);return k}var y=new O(34067);ia[y.id]=y;d.cubeCount++;var D=Array(6);k(b,c,e,f,q,n);k.subimage=function(a,b,c,e,f){c|=0;e|=0;f|=0;var d=h();u(d,y);d.width=0;d.height=0;
B(d,b);d.width=d.width||(y.width>>f)-c;d.height=d.height||(y.height>>f)-e;xa(y);l(d,34069+a,c,e,f);ya();g(d);return k};k.resize=function(b){b|=0;if(b!==y.width){k.width=y.width=b;k.height=y.height=b;xa(y);for(var c=0;6>c;++c)for(var g=0;y.mipmask>>g;++g)a.texImage2D(34069+c,g,y.format,b>>g,b>>g,0,y.format,y.type,null);ya();p.profile&&(y.stats.size=Ja(y.internalformat,y.type,k.width,k.height,!1,!0));return k}};k._reglType="textureCube";k._texture=y;p.profile&&(k.stats=y.stats);k.destroy=function(){y.decRef()};
return k},clear:function(){for(var b=0;b<ga;++b)a.activeTexture(33984+b),a.bindTexture(3553,null),W[b]=null;S(ia).forEach(D);d.cubeCount=0;d.textureCount=0},getTexture:function(a){return null},restore:function(){for(var b=0;b<ga;++b){var c=W[b];c&&(c.bindCount=0,c.unit=-1,W[b]=null)}S(ia).forEach(function(b){b.texture=a.createTexture();a.bindTexture(b.target,b.texture);for(var c=0;32>c;++c)if(0!==(b.mipmask&1<<c))if(3553===b.target)a.texImage2D(3553,c,b.internalformat,b.width>>c,b.height>>c,0,b.internalformat,
b.type,null);else for(var g=0;6>g;++g)a.texImage2D(34069+g,c,b.internalformat,b.width>>c,b.height>>c,0,b.internalformat,b.type,null);H(b.texInfo,b.target)})},refresh:function(){for(var b=0;b<ga;++b){var c=W[b];c&&(c.bindCount=0,c.unit=-1,W[b]=null);a.activeTexture(33984+b);a.bindTexture(3553,null);a.bindTexture(34067,null)}}}}function Rb(a,b,c,e,f,d){function p(a,b,c){this.target=a;this.texture=b;this.renderbuffer=c;var g=a=0;b?(a=b.width,g=b.height):c&&(a=c.width,g=c.height);this.width=a;this.height=
g}function n(a){a&&(a.texture&&a.texture._texture.decRef(),a.renderbuffer&&a.renderbuffer._renderbuffer.decRef())}function u(a,b,c){a&&(a.texture?a.texture._texture.refCount+=1:a.renderbuffer._renderbuffer.refCount+=1)}function t(b,c){c&&(c.texture?a.framebufferTexture2D(36160,b,c.target,c.texture._texture.texture,0):a.framebufferRenderbuffer(36160,b,36161,c.renderbuffer._renderbuffer.renderbuffer))}function w(a){var b=3553,c=null,g=null,e=a;"object"===typeof a&&(e=a.data,"target"in a&&(b=a.target|
0));a=e._reglType;"texture2d"===a?c=e:"textureCube"===a?c=e:"renderbuffer"===a&&(g=e,b=36161);return new p(b,c,g)}function k(a,b,c,g,d){if(c)return a=e.create2D({width:a,height:b,format:g,type:d}),a._texture.refCount=0,new p(3553,a,null);a=f.create({width:a,height:b,format:g});a._renderbuffer.refCount=0;return new p(36161,null,a)}function B(a){return a&&(a.texture||a.renderbuffer)}function l(a,b,c){a&&(a.texture?a.texture.resize(b,c):a.renderbuffer&&a.renderbuffer.resize(b,c),a.width=b,a.height=c)}
function h(){this.id=G++;H[this.id]=this;this.framebuffer=a.createFramebuffer();this.height=this.width=0;this.colorAttachments=[];this.depthStencilAttachment=this.stencilAttachment=this.depthAttachment=null}function g(a){a.colorAttachments.forEach(n);n(a.depthAttachment);n(a.stencilAttachment);n(a.depthStencilAttachment)}function q(b){a.deleteFramebuffer(b.framebuffer);b.framebuffer=null;d.framebufferCount--;delete H[b.id]}function r(b){var g;a.bindFramebuffer(36160,b.framebuffer);var e=b.colorAttachments;
for(g=0;g<e.length;++g)t(36064+g,e[g]);for(g=e.length;g<c.maxColorAttachments;++g)a.framebufferTexture2D(36160,36064+g,3553,null,0);a.framebufferTexture2D(36160,33306,3553,null,0);a.framebufferTexture2D(36160,36096,3553,null,0);a.framebufferTexture2D(36160,36128,3553,null,0);t(36096,b.depthAttachment);t(36128,b.stencilAttachment);t(33306,b.depthStencilAttachment);a.checkFramebufferStatus(36160);a.isContextLost();a.bindFramebuffer(36160,z.next?z.next.framebuffer:null);z.cur=z.next;a.getError()}function m(a,
b){function c(a,b){var f,d=0,h=0,m=!0,q=!0;f=null;var l=!0,n="rgba",t="uint8",p=1,G=null,fa=null,z=null,O=!1;if("number"===typeof a)d=a|0,h=b|0||d;else if(a){"shape"in a?(h=a.shape,d=h[0],h=h[1]):("radius"in a&&(d=h=a.radius),"width"in a&&(d=a.width),"height"in a&&(h=a.height));if("color"in a||"colors"in a)f=a.color||a.colors,Array.isArray(f);if(!f){"colorCount"in a&&(p=a.colorCount|0);"colorTexture"in a&&(l=!!a.colorTexture,n="rgba4");if("colorType"in a&&(t=a.colorType,!l))if("half float"===t||"float16"===
t)n="rgba16f";else if("float"===t||"float32"===t)n="rgba32f";"colorFormat"in a&&(n=a.colorFormat,0<=Ha.indexOf(n)?l=!0:0<=v.indexOf(n)&&(l=!1))}if("depthTexture"in a||"depthStencilTexture"in a)O=!(!a.depthTexture&&!a.depthStencilTexture);"depth"in a&&("boolean"===typeof a.depth?m=a.depth:(G=a.depth,q=!1));"stencil"in a&&("boolean"===typeof a.stencil?q=a.stencil:(fa=a.stencil,m=!1));"depthStencil"in a&&("boolean"===typeof a.depthStencil?m=q=a.depthStencil:(z=a.depthStencil,q=m=!1))}else d=h=1;var P=
null,Z=null,H=null,A=null;if(Array.isArray(f))P=f.map(w);else if(f)P=[w(f)];else for(P=Array(p),f=0;f<p;++f)P[f]=k(d,h,l,n,t);d=d||P[0].width;h=h||P[0].height;G?Z=w(G):m&&!q&&(Z=k(d,h,O,"depth","uint32"));fa?H=w(fa):q&&!m&&(H=k(d,h,!1,"stencil","uint8"));z?A=w(z):!G&&!fa&&q&&m&&(A=k(d,h,O,"depth stencil","depth stencil"));m=null;for(f=0;f<P.length;++f)u(P[f],d,h),P[f]&&P[f].texture&&(q=Ya[P[f].texture._texture.format]*Pa[P[f].texture._texture.type],null===m&&(m=q));u(Z,d,h);u(H,d,h);u(A,d,h);g(e);
e.width=d;e.height=h;e.colorAttachments=P;e.depthAttachment=Z;e.stencilAttachment=H;e.depthStencilAttachment=A;c.color=P.map(B);c.depth=B(Z);c.stencil=B(H);c.depthStencil=B(A);c.width=e.width;c.height=e.height;r(e);return c}var e=new h;d.framebufferCount++;c(a,b);return A(c,{resize:function(a,b){var g=Math.max(a|0,1),f=Math.max(b|0||g,1);if(g===e.width&&f===e.height)return c;for(var d=e.colorAttachments,h=0;h<d.length;++h)l(d[h],g,f);l(e.depthAttachment,g,f);l(e.stencilAttachment,g,f);l(e.depthStencilAttachment,
g,f);e.width=c.width=g;e.height=c.height=f;r(e);return c},_reglType:"framebuffer",_framebuffer:e,destroy:function(){q(e);g(e)},use:function(a){z.setFBO({framebuffer:c},a)}})}var z={cur:null,next:null,dirty:!1,setFBO:null},Ha=["rgba"],v=["rgba4","rgb565","rgb5 a1"];b.ext_srgb&&v.push("srgba");b.ext_color_buffer_half_float&&v.push("rgba16f","rgb16f");b.webgl_color_buffer_float&&v.push("rgba32f");var Z=["uint8"];b.oes_texture_half_float&&Z.push("half float","float16");b.oes_texture_float&&Z.push("float",
"float32");var G=0,H={};return A(z,{getFramebuffer:function(a){return"function"===typeof a&&"framebuffer"===a._reglType&&(a=a._framebuffer,a instanceof h)?a:null},create:m,createCube:function(a){function b(a){var g,f={color:null},d=0,h=null;g="rgba";var q="uint8",r=1;if("number"===typeof a)d=a|0;else if(a){"shape"in a?d=a.shape[0]:("radius"in a&&(d=a.radius|0),"width"in a?d=a.width|0:"height"in a&&(d=a.height|0));if("color"in a||"colors"in a)h=a.color||a.colors,Array.isArray(h);h||("colorCount"in
a&&(r=a.colorCount|0),"colorType"in a&&(q=a.colorType),"colorFormat"in a&&(g=a.colorFormat));"depth"in a&&(f.depth=a.depth);"stencil"in a&&(f.stencil=a.stencil);"depthStencil"in a&&(f.depthStencil=a.depthStencil)}else d=1;if(h)if(Array.isArray(h))for(a=[],g=0;g<h.length;++g)a[g]=h[g];else a=[h];else for(a=Array(r),h={radius:d,format:g,type:q},g=0;g<r;++g)a[g]=e.createCube(h);f.color=Array(a.length);for(g=0;g<a.length;++g)r=a[g],d=d||r.width,f.color[g]={target:34069,data:a[g]};for(g=0;6>g;++g){for(r=
0;r<a.length;++r)f.color[r].target=34069+g;0<g&&(f.depth=c[0].depth,f.stencil=c[0].stencil,f.depthStencil=c[0].depthStencil);if(c[g])c[g](f);else c[g]=m(f)}return A(b,{width:d,height:d,color:a})}var c=Array(6);b(a);return A(b,{faces:c,resize:function(a){var g=a|0;if(g===b.width)return b;var e=b.color;for(a=0;a<e.length;++a)e[a].resize(g);for(a=0;6>a;++a)c[a].resize(g);b.width=b.height=g;return b},_reglType:"framebufferCube",destroy:function(){c.forEach(function(a){a.destroy()})}})},clear:function(){S(H).forEach(q)},
restore:function(){z.cur=null;z.next=null;z.dirty=!0;S(H).forEach(function(b){b.framebuffer=a.createFramebuffer();r(b)})}})}function Za(){this.w=this.z=this.y=this.x=this.state=0;this.buffer=null;this.size=0;this.normalized=!1;this.type=5126;this.divisor=this.stride=this.offset=0}function Sb(a,b,c,e,f){function d(a){if(a!==h.currentVAO){var c=b.oes_vertex_array_object;a?c.bindVertexArrayOES(a.vao):c.bindVertexArrayOES(null);h.currentVAO=a}}function p(c){if(c!==h.currentVAO){if(c)c.bindAttrs();else for(var e=
b.angle_instanced_arrays,f=0;f<k.length;++f){var d=k[f];d.buffer?(a.enableVertexAttribArray(f),a.vertexAttribPointer(f,d.size,d.type,d.normalized,d.stride,d.offfset),e&&d.divisor&&e.vertexAttribDivisorANGLE(f,d.divisor)):(a.disableVertexAttribArray(f),a.vertexAttrib4f(f,d.x,d.y,d.z,d.w))}h.currentVAO=c}}function n(){S(l).forEach(function(a){a.destroy()})}function u(){this.id=++B;this.attributes=[];var a=b.oes_vertex_array_object;this.vao=a?a.createVertexArrayOES():null;l[this.id]=this;this.buffers=
[]}function t(){b.oes_vertex_array_object&&S(l).forEach(function(a){a.refresh()})}var w=c.maxAttributes,k=Array(w);for(c=0;c<w;++c)k[c]=new Za;var B=0,l={},h={Record:Za,scope:{},state:k,currentVAO:null,targetVAO:null,restore:b.oes_vertex_array_object?t:function(){},createVAO:function(a){function b(a){var g={},e=c.attributes;e.length=a.length;for(var d=0;d<a.length;++d){var h=a[d],k=e[d]=new Za,l=h.data||h;if(Array.isArray(l)||M(l)||da(l)){var n;c.buffers[d]&&(n=c.buffers[d],M(l)&&n._buffer.byteLength>=
l.byteLength?n.subdata(l):(n.destroy(),c.buffers[d]=null));c.buffers[d]||(n=c.buffers[d]=f.create(h,34962,!1,!0));k.buffer=f.getBuffer(n);k.size=k.buffer.dimension|0;k.normalized=!1;k.type=k.buffer.dtype;k.offset=0;k.stride=0;k.divisor=0;k.state=1;g[d]=1}else f.getBuffer(h)?(k.buffer=f.getBuffer(h),k.size=k.buffer.dimension|0,k.normalized=!1,k.type=k.buffer.dtype,k.offset=0,k.stride=0,k.divisor=0,k.state=1):f.getBuffer(h.buffer)?(k.buffer=f.getBuffer(h.buffer),k.size=(+h.size||k.buffer.dimension)|
0,k.normalized=!!h.normalized||!1,k.type="type"in h?Ia[h.type]:k.buffer.dtype,k.offset=(h.offset||0)|0,k.stride=(h.stride||0)|0,k.divisor=(h.divisor||0)|0,k.state=1):"x"in h&&(k.x=+h.x||0,k.y=+h.y||0,k.z=+h.z||0,k.w=+h.w||0,k.state=2)}for(a=0;a<c.buffers.length;++a)!g[a]&&c.buffers[a]&&(c.buffers[a].destroy(),c.buffers[a]=null);c.refresh();return b}var c=new u;e.vaoCount+=1;b.destroy=function(){for(var a=0;a<c.buffers.length;++a)c.buffers[a]&&c.buffers[a].destroy();c.buffers.length=0;c.destroy()};
b._vao=c;b._reglType="vao";return b(a)},getVAO:function(a){return"function"===typeof a&&a._vao?a._vao:null},destroyBuffer:function(b){for(var c=0;c<k.length;++c){var e=k[c];e.buffer===b&&(a.disableVertexAttribArray(c),e.buffer=null)}},setVAO:b.oes_vertex_array_object?d:p,clear:b.oes_vertex_array_object?n:function(){}};u.prototype.bindAttrs=function(){for(var c=b.angle_instanced_arrays,e=this.attributes,f=0;f<e.length;++f){var d=e[f];d.buffer?(a.enableVertexAttribArray(f),a.bindBuffer(34962,d.buffer.buffer),
a.vertexAttribPointer(f,d.size,d.type,d.normalized,d.stride,d.offset),c&&d.divisor&&c.vertexAttribDivisorANGLE(f,d.divisor)):(a.disableVertexAttribArray(f),a.vertexAttrib4f(f,d.x,d.y,d.z,d.w))}for(c=e.length;c<w;++c)a.disableVertexAttribArray(c)};u.prototype.refresh=function(){var a=b.oes_vertex_array_object;a&&(a.bindVertexArrayOES(this.vao),this.bindAttrs(),h.currentVAO=this)};u.prototype.destroy=function(){if(this.vao){var a=b.oes_vertex_array_object;this===h.currentVAO&&(h.currentVAO=null,a.bindVertexArrayOES(null));
a.deleteVertexArrayOES(this.vao);this.vao=null}l[this.id]&&(delete l[this.id],--e.vaoCount)};return h}function Tb(a,b,c,e){function f(a,b,c,e){this.name=a;this.id=b;this.location=c;this.info=e}function d(a,b){for(var c=0;c<a.length;++c)if(a[c].id===b.id){a[c].location=b.location;return}a.push(b)}function p(c,g,e){e=35632===c?t:w;var d=e[g];if(!d){var f=b.str(g),d=a.createShader(c);a.shaderSource(d,f);a.compileShader(d);e[g]=d}return d}function n(a,b){this.id=l++;this.fragId=a;this.vertId=b;this.program=
null;this.uniforms=[];this.attributes=[];this.refCount=1;e.profile&&(this.stats={uniformsCount:0,attributesCount:0})}function u(c,g,k){var l;l=p(35632,c.fragId);var m=p(35633,c.vertId);g=c.program=a.createProgram();a.attachShader(g,l);a.attachShader(g,m);if(k)for(l=0;l<k.length;++l)m=k[l],a.bindAttribLocation(g,m[0],m[1]);a.linkProgram(g);m=a.getProgramParameter(g,35718);e.profile&&(c.stats.uniformsCount=m);var n=c.uniforms;for(l=0;l<m;++l)if(k=a.getActiveUniform(g,l))if(1<k.size)for(var t=0;t<k.size;++t){var u=
k.name.replace("[0]","["+t+"]");d(n,new f(u,b.id(u),a.getUniformLocation(g,u),k))}else d(n,new f(k.name,b.id(k.name),a.getUniformLocation(g,k.name),k));m=a.getProgramParameter(g,35721);e.profile&&(c.stats.attributesCount=m);c=c.attributes;for(l=0;l<m;++l)(k=a.getActiveAttrib(g,l))&&d(c,new f(k.name,b.id(k.name),a.getAttribLocation(g,k.name),k))}var t={},w={},k={},B=[],l=0;e.profile&&(c.getMaxUniformsCount=function(){var a=0;B.forEach(function(b){b.stats.uniformsCount>a&&(a=b.stats.uniformsCount)});
return a},c.getMaxAttributesCount=function(){var a=0;B.forEach(function(b){b.stats.attributesCount>a&&(a=b.stats.attributesCount)});return a});return{clear:function(){var b=a.deleteShader.bind(a);S(t).forEach(b);t={};S(w).forEach(b);w={};B.forEach(function(b){a.deleteProgram(b.program)});B.length=0;k={};c.shaderCount=0},program:function(b,e,d,f){var l=k[e];l||(l=k[e]={});var p=l[b];if(p&&(p.refCount++,!f))return p;var v=new n(e,b);c.shaderCount++;u(v,d,f);p||(l[b]=v);B.push(v);return A(v,{destroy:function(){v.refCount--;
if(0>=v.refCount){a.deleteProgram(v.program);var b=B.indexOf(v);B.splice(b,1);c.shaderCount--}0>=l[v.vertId].refCount&&(a.deleteShader(w[v.vertId]),delete w[v.vertId],delete k[v.fragId][v.vertId]);Object.keys(k[v.fragId]).length||(a.deleteShader(t[v.fragId]),delete t[v.fragId],delete k[v.fragId])}})},restore:function(){t={};w={};for(var a=0;a<B.length;++a)u(B[a],null,B[a].attributes.map(function(a){return[a.location,a.name]}))},shader:p,frag:-1,vert:-1}}function Ub(a,b,c,e,f,d,p){function n(d){var f;
f=null===b.next?5121:b.next.colorAttachments[0].texture._texture.type;var k=0,n=0,l=e.framebufferWidth,h=e.framebufferHeight,g=null;M(d)?g=d:d&&(k=d.x|0,n=d.y|0,l=(d.width||e.framebufferWidth-k)|0,h=(d.height||e.framebufferHeight-n)|0,g=d.data||null);c();d=l*h*4;g||(5121===f?g=new Uint8Array(d):5126===f&&(g=g||new Float32Array(d)));a.pixelStorei(3333,4);a.readPixels(k,n,l,h,6408,f,g);return g}function u(a){var c;b.setFBO({framebuffer:a.framebuffer},function(){c=n(a)});return c}return function(a){return a&&
"framebuffer"in a?u(a):n(a)}}function za(a){return Array.prototype.slice.call(a)}function Aa(a){return za(a).join("")}function Vb(){function a(){var a=[],b=[];return A(function(){a.push.apply(a,za(arguments))},{def:function(){var d="v"+c++;b.push(d);0<arguments.length&&(a.push(d,"="),a.push.apply(a,za(arguments)),a.push(";"));return d},toString:function(){return Aa([0<b.length?"var "+b.join(",")+";":"",Aa(a)])}})}function b(){function b(a,e){d(a,e,"=",c.def(a,e),";")}var c=a(),d=a(),e=c.toString,
f=d.toString;return A(function(){c.apply(c,za(arguments))},{def:c.def,entry:c,exit:d,save:b,set:function(a,d,e){b(a,d);c(a,d,"=",e,";")},toString:function(){return e()+f()}})}var c=0,e=[],f=[],d=a(),p={};return{global:d,link:function(a){for(var b=0;b<f.length;++b)if(f[b]===a)return e[b];b="g"+c++;e.push(b);f.push(a);return b},block:a,proc:function(a,c){function d(){var a="a"+e.length;e.push(a);return a}var e=[];c=c||0;for(var f=0;f<c;++f)d();var f=b(),B=f.toString;return p[a]=A(f,{arg:d,toString:function(){return Aa(["function(",
e.join(),"){",B(),"}"])}})},scope:b,cond:function(){var a=Aa(arguments),c=b(),d=b(),e=c.toString,f=d.toString;return A(c,{then:function(){c.apply(c,za(arguments));return this},"else":function(){d.apply(d,za(arguments));return this},toString:function(){var b=f();b&&(b="else{"+b+"}");return Aa(["if(",a,"){",e(),"}",b])}})},compile:function(){var a=['"use strict";',d,"return {"];Object.keys(p).forEach(function(b){a.push('"',b,'":',p[b].toString(),",")});a.push("}");var b=Aa(a).replace(/;/g,";\n").replace(/}/g,
"}\n").replace(/{/g,"{\n");return Function.apply(null,e.concat(b)).apply(null,f)}}}function Qa(a){return Array.isArray(a)||M(a)||da(a)}function zb(a){return a.sort(function(a,c){return"viewport"===a?-1:"viewport"===c?1:a<c?-1:1})}function K(a,b,c,e){this.thisDep=a;this.contextDep=b;this.propDep=c;this.append=e}function sa(a){return a&&!(a.thisDep||a.contextDep||a.propDep)}function v(a){return new K(!1,!1,!1,a)}function L(a,b){var c=a.type;if(0===c)return c=a.data.length,new K(!0,1<=c,2<=c,b);if(4===
c)return c=a.data,new K(c.thisDep,c.contextDep,c.propDep,b);if(5===c)return new K(!1,!1,!1,b);if(6===c){for(var e=c=!1,f=!1,d=0;d<a.data.length;++d){var p=a.data[d];1===p.type?f=!0:2===p.type?e=!0:3===p.type?c=!0:0===p.type?(c=!0,p=p.data,1<=p&&(e=!0),2<=p&&(f=!0)):4===p.type&&(c=c||p.data.thisDep,e=e||p.data.contextDep,f=f||p.data.propDep)}return new K(c,e,f,b)}return new K(3===c,2===c,1===c,b)}function Wb(a,b,c,e,f,d,p,n,u,t,w,k,B,l,h){function g(a){return a.replace(".","_")}function q(a,b,c){var d=
g(a);La.push(a);Ca[d]=pa[d]=!!c;qa[d]=b}function r(a,b,c){var d=g(a);La.push(a);Array.isArray(c)?(pa[d]=c.slice(),Ca[d]=c.slice()):pa[d]=Ca[d]=c;ra[d]=b}function m(){var a=Vb(),c=a.link,d=a.global;a.id=na++;a.batchId="0";var e=c(ub),f=a.shared={props:"a0"};Object.keys(ub).forEach(function(a){f[a]=d.def(e,".",a)});var g=a.next={},h=a.current={};Object.keys(ra).forEach(function(a){Array.isArray(pa[a])&&(g[a]=d.def(f.next,".",a),h[a]=d.def(f.current,".",a))});var ba=a.constants={};Object.keys(Na).forEach(function(a){ba[a]=
d.def(JSON.stringify(Na[a]))});a.invoke=function(b,d){switch(d.type){case 0:var e=["this",f.context,f.props,a.batchId];return b.def(c(d.data),".call(",e.slice(0,Math.max(d.data.length+1,4)),")");case 1:return b.def(f.props,d.data);case 2:return b.def(f.context,d.data);case 3:return b.def("this",d.data);case 4:return d.data.append(a,b),d.data.ref;case 5:return d.data.toString();case 6:return d.data.map(function(c){return a.invoke(b,c)})}};a.attribCache={};var va={};a.scopeAttrib=function(a){a=b.id(a);
if(a in va)return va[a];var d=t.scope[a];d||(d=t.scope[a]=new ga);return va[a]=c(d)};return a}function z(a){var b=a["static"];a=a.dynamic;var c;if("profile"in b){var d=!!b.profile;c=v(function(a,b){return d});c.enable=d}else if("profile"in a){var e=a.profile;c=L(e,function(a,b){return a.invoke(b,e)})}return c}function E(a,b){var c=a["static"],d=a.dynamic;if("framebuffer"in c){var e=c.framebuffer;return e?(e=n.getFramebuffer(e),v(function(a,b){var c=a.link(e),d=a.shared;b.set(d.framebuffer,".next",
c);d=d.context;b.set(d,".framebufferWidth",c+".width");b.set(d,".framebufferHeight",c+".height");return c})):v(function(a,b){var c=a.shared;b.set(c.framebuffer,".next","null");c=c.context;b.set(c,".framebufferWidth",c+".drawingBufferWidth");b.set(c,".framebufferHeight",c+".drawingBufferHeight");return"null"})}if("framebuffer"in d){var f=d.framebuffer;return L(f,function(a,b){var c=a.invoke(b,f),d=a.shared,e=d.framebuffer,c=b.def(e,".getFramebuffer(",c,")");b.set(e,".next",c);d=d.context;b.set(d,".framebufferWidth",
c+"?"+c+".width:"+d+".drawingBufferWidth");b.set(d,".framebufferHeight",c+"?"+c+".height:"+d+".drawingBufferHeight");return c})}return null}function F(a,b,c){function d(a){if(a in e){var c=e[a];a=!0;var g=c.x|0,x=c.y|0,h,k;"width"in c?h=c.width|0:a=!1;"height"in c?k=c.height|0:a=!1;return new K(!a&&b&&b.thisDep,!a&&b&&b.contextDep,!a&&b&&b.propDep,function(a,b){var d=a.shared.context,e=h;"width"in c||(e=b.def(d,".","framebufferWidth","-",g));var f=k;"height"in c||(f=b.def(d,".","framebufferHeight",
"-",x));return[g,x,e,f]})}if(a in f){var ca=f[a];a=L(ca,function(a,b){var c=a.invoke(b,ca),d=a.shared.context,e=b.def(c,".x|0"),f=b.def(c,".y|0"),g=b.def('"width" in ',c,"?",c,".width|0:","(",d,".","framebufferWidth","-",e,")"),c=b.def('"height" in ',c,"?",c,".height|0:","(",d,".","framebufferHeight","-",f,")");return[e,f,g,c]});b&&(a.thisDep=a.thisDep||b.thisDep,a.contextDep=a.contextDep||b.contextDep,a.propDep=a.propDep||b.propDep);return a}return b?new K(b.thisDep,b.contextDep,b.propDep,function(a,
b){var c=a.shared.context;return[0,0,b.def(c,".","framebufferWidth"),b.def(c,".","framebufferHeight")]}):null}var e=a["static"],f=a.dynamic;if(a=d("viewport")){var g=a;a=new K(a.thisDep,a.contextDep,a.propDep,function(a,b){var c=g.append(a,b),d=a.shared.context;b.set(d,".viewportWidth",c[2]);b.set(d,".viewportHeight",c[3]);return c})}return{viewport:a,scissor_box:d("scissor.box")}}function Z(a,b){var c=a["static"];if("string"===typeof c.frag&&"string"===typeof c.vert){if(0<Object.keys(b.dynamic).length)return null;
var c=b["static"],d=Object.keys(c);if(0<d.length&&"number"===typeof c[d[0]]){for(var e=[],f=0;f<d.length;++f)e.push([c[d[f]]|0,d[f]]);return e}}return null}function G(a,c,d){function e(a){if(a in f){var c=b.id(f[a]);a=v(function(){return c});a.id=c;return a}if(a in g){var d=g[a];return L(d,function(a,b){var c=a.invoke(b,d);return b.def(a.shared.strings,".id(",c,")")})}return null}var f=a["static"],g=a.dynamic,h=e("frag"),ba=e("vert"),va=null;sa(h)&&sa(ba)?(va=w.program(ba.id,h.id,null,d),a=v(function(a,
b){return a.link(va)})):a=new K(h&&h.thisDep||ba&&ba.thisDep,h&&h.contextDep||ba&&ba.contextDep,h&&h.propDep||ba&&ba.propDep,function(a,b){var c=a.shared.shader,d;d=h?h.append(a,b):b.def(c,".","frag");var e;e=ba?ba.append(a,b):b.def(c,".","vert");return b.def(c+".program("+e+","+d+")")});return{frag:h,vert:ba,progVar:a,program:va}}function H(a,b){function c(a,b){if(a in e){var d=e[a]|0;return v(function(a,c){b&&(a.OFFSET=d);return d})}if(a in f){var x=f[a];return L(x,function(a,c){var d=a.invoke(c,
x);b&&(a.OFFSET=d);return d})}return b&&g?v(function(a,b){a.OFFSET="0";return 0}):null}var e=a["static"],f=a.dynamic,g=function(){if("elements"in e){var a=e.elements;Qa(a)?a=d.getElements(d.create(a,!0)):a&&(a=d.getElements(a));var b=v(function(b,c){if(a){var d=b.link(a);return b.ELEMENTS=d}return b.ELEMENTS=null});b.value=a;return b}if("elements"in f){var c=f.elements;return L(c,function(a,b){var d=a.shared,e=d.isBufferArgs,d=d.elements,f=a.invoke(b,c),g=b.def("null"),e=b.def(e,"(",f,")"),f=a.cond(e).then(g,
"=",d,".createStream(",f,");")["else"](g,"=",d,".getElements(",f,");");b.entry(f);b.exit(a.cond(e).then(d,".destroyStream(",g,");"));return a.ELEMENTS=g})}return null}(),h=c("offset",!0);return{elements:g,primitive:function(){if("primitive"in e){var a=e.primitive;return v(function(b,c){return Ta[a]})}if("primitive"in f){var b=f.primitive;return L(b,function(a,c){var d=a.constants.primTypes,e=a.invoke(c,b);return c.def(d,"[",e,"]")})}return g?sa(g)?g.value?v(function(a,b){return b.def(a.ELEMENTS,".primType")}):
v(function(){return 4}):new K(g.thisDep,g.contextDep,g.propDep,function(a,b){var c=a.ELEMENTS;return b.def(c,"?",c,".primType:",4)}):null}(),count:function(){if("count"in e){var a=e.count|0;return v(function(){return a})}if("count"in f){var b=f.count;return L(b,function(a,c){return a.invoke(c,b)})}return g?sa(g)?g?h?new K(h.thisDep,h.contextDep,h.propDep,function(a,b){return b.def(a.ELEMENTS,".vertCount-",a.OFFSET)}):v(function(a,b){return b.def(a.ELEMENTS,".vertCount")}):v(function(){return-1}):
new K(g.thisDep||h.thisDep,g.contextDep||h.contextDep,g.propDep||h.propDep,function(a,b){var c=a.ELEMENTS;return a.OFFSET?b.def(c,"?",c,".vertCount-",a.OFFSET,":-1"):b.def(c,"?",c,".vertCount:-1")}):null}(),instances:c("instances",!1),offset:h}}function O(a,b){var c=a["static"],d=a.dynamic,e={};La.forEach(function(a){function b(g,x){if(a in c){var h=g(c[a]);e[f]=v(function(){return h})}else if(a in d){var I=d[a];e[f]=L(I,function(a,b){return x(a,b,a.invoke(b,I))})}}var f=g(a);switch(a){case "cull.enable":case "blend.enable":case "dither":case "stencil.enable":case "depth.enable":case "scissor.enable":case "polygonOffset.enable":case "sample.alpha":case "sample.enable":case "depth.mask":return b(function(a){return a},
function(a,b,c){return c});case "depth.func":return b(function(a){return ab[a]},function(a,b,c){return b.def(a.constants.compareFuncs,"[",c,"]")});case "depth.range":return b(function(a){return a},function(a,b,c){a=b.def("+",c,"[0]");b=b.def("+",c,"[1]");return[a,b]});case "blend.func":return b(function(a){return[Ea["srcRGB"in a?a.srcRGB:a.src],Ea["dstRGB"in a?a.dstRGB:a.dst],Ea["srcAlpha"in a?a.srcAlpha:a.src],Ea["dstAlpha"in a?a.dstAlpha:a.dst]]},function(a,b,c){function d(a,e){return b.def('"',
a,e,'" in ',c,"?",c,".",a,e,":",c,".",a)}a=a.constants.blendFuncs;var e=d("src","RGB"),f=d("dst","RGB"),e=b.def(a,"[",e,"]"),g=b.def(a,"[",d("src","Alpha"),"]"),f=b.def(a,"[",f,"]");a=b.def(a,"[",d("dst","Alpha"),"]");return[e,f,g,a]});case "blend.equation":return b(function(a){if("string"===typeof a)return[W[a],W[a]];if("object"===typeof a)return[W[a.rgb],W[a.alpha]]},function(a,b,c){var d=a.constants.blendEquations,e=b.def(),f=b.def();a=a.cond("typeof ",c,'==="string"');a.then(e,"=",f,"=",d,"[",
c,"];");a["else"](e,"=",d,"[",c,".rgb];",f,"=",d,"[",c,".alpha];");b(a);return[e,f]});case "blend.color":return b(function(a){return J(4,function(b){return+a[b]})},function(a,b,c){return J(4,function(a){return b.def("+",c,"[",a,"]")})});case "stencil.mask":return b(function(a){return a|0},function(a,b,c){return b.def(c,"|0")});case "stencil.func":return b(function(a){return[ab[a.cmp||"keep"],a.ref||0,"mask"in a?a.mask:-1]},function(a,b,c){a=b.def('"cmp" in ',c,"?",a.constants.compareFuncs,"[",c,".cmp]",
":",7680);var d=b.def(c,".ref|0");b=b.def('"mask" in ',c,"?",c,".mask|0:-1");return[a,d,b]});case "stencil.opFront":case "stencil.opBack":return b(function(b){return["stencil.opBack"===a?1029:1028,Ra[b.fail||"keep"],Ra[b.zfail||"keep"],Ra[b.zpass||"keep"]]},function(b,c,d){function e(a){return c.def('"',a,'" in ',d,"?",f,"[",d,".",a,"]:",7680)}var f=b.constants.stencilOps;return["stencil.opBack"===a?1029:1028,e("fail"),e("zfail"),e("zpass")]});case "polygonOffset.offset":return b(function(a){return[a.factor|
0,a.units|0]},function(a,b,c){a=b.def(c,".factor|0");b=b.def(c,".units|0");return[a,b]});case "cull.face":return b(function(a){var b=0;"front"===a?b=1028:"back"===a&&(b=1029);return b},function(a,b,c){return b.def(c,'==="front"?',1028,":",1029)});case "lineWidth":return b(function(a){return a},function(a,b,c){return c});case "frontFace":return b(function(a){return Ab[a]},function(a,b,c){return b.def(c+'==="cw"?2304:2305')});case "colorMask":return b(function(a){return a.map(function(a){return!!a})},
function(a,b,c){return J(4,function(a){return"!!"+c+"["+a+"]"})});case "sample.coverage":return b(function(a){return["value"in a?a.value:1,!!a.invert]},function(a,b,c){a=b.def('"value" in ',c,"?+",c,".value:1");b=b.def("!!",c,".invert");return[a,b]})}});return e}function M(a,b){var c=a["static"],d=a.dynamic,e={};Object.keys(c).forEach(function(a){var b=c[a],d;if("number"===typeof b||"boolean"===typeof b)d=v(function(){return b});else if("function"===typeof b){var f=b._reglType;if("texture2d"===f||
"textureCube"===f)d=v(function(a){return a.link(b)});else if("framebuffer"===f||"framebufferCube"===f)d=v(function(a){return a.link(b.color[0])})}else ma(b)&&(d=v(function(a){return a.global.def("[",J(b.length,function(a){return b[a]}),"]")}));d.value=b;e[a]=d});Object.keys(d).forEach(function(a){var b=d[a];e[a]=L(b,function(a,c){return a.invoke(c,b)})});return e}function S(a,c){var d=a["static"],e=a.dynamic,g={};Object.keys(d).forEach(function(a){var c=d[a],e=b.id(a),x=new ga;if(Qa(c))x.state=1,
x.buffer=f.getBuffer(f.create(c,34962,!1,!0)),x.type=0;else{var h=f.getBuffer(c);if(h)x.state=1,x.buffer=h,x.type=0;else if("constant"in c){var I=c.constant;x.buffer="null";x.state=2;"number"===typeof I?x.x=I:Ba.forEach(function(a,b){b<I.length&&(x[a]=I[b])})}else{var h=Qa(c.buffer)?f.getBuffer(f.create(c.buffer,34962,!1,!0)):f.getBuffer(c.buffer),k=c.offset|0,l=c.stride|0,m=c.size|0,ka=!!c.normalized,n=0;"type"in c&&(n=Ia[c.type]);c=c.divisor|0;x.buffer=h;x.state=1;x.size=m;x.normalized=ka;x.type=
n||h.dtype;x.offset=k;x.stride=l;x.divisor=c}}g[a]=v(function(a,b){var c=a.attribCache;if(e in c)return c[e];var d={isStream:!1};Object.keys(x).forEach(function(a){d[a]=x[a]});x.buffer&&(d.buffer=a.link(x.buffer),d.type=d.type||d.buffer+".dtype");return c[e]=d})});Object.keys(e).forEach(function(a){var b=e[a];g[a]=L(b,function(a,c){function d(a){c(h[a],"=",e,".",a,"|0;")}var e=a.invoke(c,b),f=a.shared,g=a.constants,x=f.isBufferArgs,f=f.buffer,h={isStream:c.def(!1)},I=new ga;I.state=1;Object.keys(I).forEach(function(a){h[a]=
c.def(""+I[a])});var k=h.buffer,l=h.type;c("if(",x,"(",e,")){",h.isStream,"=true;",k,"=",f,".createStream(",34962,",",e,");",l,"=",k,".dtype;","}else{",k,"=",f,".getBuffer(",e,");","if(",k,"){",l,"=",k,".dtype;",'}else if("constant" in ',e,"){",h.state,"=",2,";","if(typeof "+e+'.constant === "number"){',h[Ba[0]],"=",e,".constant;",Ba.slice(1).map(function(a){return h[a]}).join("="),"=0;","}else{",Ba.map(function(a,b){return h[a]+"="+e+".constant.length>"+b+"?"+e+".constant["+b+"]:0;"}).join(""),"}}else{",
"if(",x,"(",e,".buffer)){",k,"=",f,".createStream(",34962,",",e,".buffer);","}else{",k,"=",f,".getBuffer(",e,".buffer);","}",l,'="type" in ',e,"?",g.glTypes,"[",e,".type]:",k,".dtype;",h.normalized,"=!!",e,".normalized;");d("size");d("offset");d("stride");d("divisor");c("}}");c.exit("if(",h.isStream,"){",f,".destroyStream(",k,");","}");return h})});return g}function D(a,b){var c=a["static"],d=a.dynamic;if("vao"in c){var e=c.vao;null!==e&&null===t.getVAO(e)&&(e=t.createVAO(e));return v(function(a){return a.link(t.getVAO(e))})}if("vao"in
d){var f=d.vao;return L(f,function(a,b){var c=a.invoke(b,f);return b.def(a.shared.vao+".getVAO("+c+")")})}return null}function y(a){var b=a["static"],c=a.dynamic,d={};Object.keys(b).forEach(function(a){var c=b[a];d[a]=v(function(a,b){return"number"===typeof c||"boolean"===typeof c?""+c:a.link(c)})});Object.keys(c).forEach(function(a){var b=c[a];d[a]=L(b,function(a,c){return a.invoke(c,b)})});return d}function la(a,b,d,e,f){function h(a){var b=m[a];b&&($a[a]=b)}var k=Z(a,b),l=E(a,f),m=F(a,l,f),n=H(a,
f),$a=O(a,f),p=G(a,f,k);h("viewport");h(g("scissor.box"));var q=0<Object.keys($a).length,l={framebuffer:l,draw:n,shader:p,state:$a,dirty:q,scopeVAO:null,drawVAO:null,useVAO:!1,attributes:{}};l.profile=z(a,f);l.uniforms=M(d,f);l.drawVAO=l.scopeVAO=D(a,f);if(!l.drawVAO&&p.program&&!k&&c.angle_instanced_arrays){var r=!0;a=p.program.attributes.map(function(a){a=b["static"][a];r=r&&!!a;return a});if(r&&0<a.length){var w=t.getVAO(t.createVAO(a));l.drawVAO=new K(null,null,null,function(a,b){return a.link(w)});
l.useVAO=!0}}k?l.useVAO=!0:l.attributes=S(b,f);l.context=y(e,f);return l}function V(a,b,c){var d=a.shared.context,e=a.scope();Object.keys(c).forEach(function(f){b.save(d,"."+f);var g=c[f].append(a,b);Array.isArray(g)?e(d,".",f,"=[",g.join(),"];"):e(d,".",f,"=",g,";")});b(e)}function R(a,b,c,d){var e=a.shared,f=e.gl,g=e.framebuffer,h;Ka&&(h=b.def(e.extensions,".webgl_draw_buffers"));var k=a.constants,e=k.drawBuffer,k=k.backBuffer;a=c?c.append(a,b):b.def(g,".next");d||b("if(",a,"!==",g,".cur){");b("if(",
a,"){",f,".bindFramebuffer(",36160,",",a,".framebuffer);");Ka&&b(h,".drawBuffersWEBGL(",e,"[",a,".colorAttachments.length]);");b("}else{",f,".bindFramebuffer(",36160,",null);");Ka&&b(h,".drawBuffersWEBGL(",k,");");b("}",g,".cur=",a,";");d||b("}")}function T(a,b,c){var d=a.shared,e=d.gl,f=a.current,h=a.next,k=d.current,l=d.next,m=a.cond(k,".dirty");La.forEach(function(b){b=g(b);if(!(b in c.state)){var d,I;if(b in h){d=h[b];I=f[b];var n=J(pa[b].length,function(a){return m.def(d,"[",a,"]")});m(a.cond(n.map(function(a,
b){return a+"!=="+I+"["+b+"]"}).join("||")).then(e,".",ra[b],"(",n,");",n.map(function(a,b){return I+"["+b+"]="+a}).join(";"),";"))}else d=m.def(l,".",b),n=a.cond(d,"!==",k,".",b),m(n),b in qa?n(a.cond(d).then(e,".enable(",qa[b],");")["else"](e,".disable(",qa[b],");"),k,".",b,"=",d,";"):n(e,".",ra[b],"(",d,");",k,".",b,"=",d,";")}});0===Object.keys(c.state).length&&m(k,".dirty=false;");b(m)}function N(a,b,c,d){var e=a.shared,f=a.current,g=e.current,h=e.gl;zb(Object.keys(c)).forEach(function(e){var k=
c[e];if(!d||d(k)){var l=k.append(a,b);if(qa[e]){var m=qa[e];sa(k)?l?b(h,".enable(",m,");"):b(h,".disable(",m,");"):b(a.cond(l).then(h,".enable(",m,");")["else"](h,".disable(",m,");"));b(g,".",e,"=",l,";")}else if(ma(l)){var n=f[e];b(h,".",ra[e],"(",l,");",l.map(function(a,b){return n+"["+b+"]="+a}).join(";"),";")}else b(h,".",ra[e],"(",l,");",g,".",e,"=",l,";")}})}function C(a,b){oa&&(a.instancing=b.def(a.shared.extensions,".angle_instanced_arrays"))}function Q(a,b,c,d,e){function f(){return"undefined"===
typeof performance?"Date.now()":"performance.now()"}function g(a){r=b.def();a(r,"=",f(),";");"string"===typeof e?a(n,".count+=",e,";"):a(n,".count++;");l&&(d?(t=b.def(),a(t,"=",q,".getNumPendingQueries();")):a(q,".beginQuery(",n,");"))}function h(a){a(n,".cpuTime+=",f(),"-",r,";");l&&(d?a(q,".pushScopeStats(",t,",",q,".getNumPendingQueries(),",n,");"):a(q,".endQuery();"))}function k(a){var c=b.def(p,".profile");b(p,".profile=",a,";");b.exit(p,".profile=",c,";")}var m=a.shared,n=a.stats,p=m.current,
q=m.timer;c=c.profile;var r,t;if(c){if(sa(c)){c.enable?(g(b),h(b.exit),k("true")):k("false");return}c=c.append(a,b);k(c)}else c=b.def(p,".profile");m=a.block();g(m);b("if(",c,"){",m,"}");a=a.block();h(a);b.exit("if(",c,"){",a,"}")}function U(a,b,c,d,e){function f(a){switch(a){case 35664:case 35667:case 35671:return 2;case 35665:case 35668:case 35672:return 3;case 35666:case 35669:case 35673:return 4;default:return 1}}function g(c,d,e){function f(){b("if(!",n,".buffer){",l,".enableVertexAttribArray(",
m,");}");var c=e.type,g;g=e.size?b.def(e.size,"||",d):d;b("if(",n,".type!==",c,"||",n,".size!==",g,"||",q.map(function(a){return n+"."+a+"!=="+e[a]}).join("||"),"){",l,".bindBuffer(",34962,",",ja,".buffer);",l,".vertexAttribPointer(",[m,g,c,e.normalized,e.stride,e.offset],");",n,".type=",c,";",n,".size=",g,";",q.map(function(a){return n+"."+a+"="+e[a]+";"}).join(""),"}");oa&&(c=e.divisor,b("if(",n,".divisor!==",c,"){",a.instancing,".vertexAttribDivisorANGLE(",[m,c],");",n,".divisor=",c,";}"))}function k(){b("if(",
n,".buffer){",l,".disableVertexAttribArray(",m,");",n,".buffer=null;","}if(",Ba.map(function(a,b){return n+"."+a+"!=="+p[b]}).join("||"),"){",l,".vertexAttrib4f(",m,",",p,");",Ba.map(function(a,b){return n+"."+a+"="+p[b]+";"}).join(""),"}")}var l=h.gl,m=b.def(c,".location"),n=b.def(h.attributes,"[",m,"]");c=e.state;var ja=e.buffer,p=[e.x,e.y,e.z,e.w],q=["buffer","normalized","offset","stride"];1===c?f():2===c?k():(b("if(",c,"===",1,"){"),f(),b("}else{"),k(),b("}"))}var h=a.shared;d.forEach(function(d){var h=
d.name,k=c.attributes[h],l;if(k){if(!e(k))return;l=k.append(a,b)}else{if(!e(Bb))return;var m=a.scopeAttrib(h);l={};Object.keys(new ga).forEach(function(a){l[a]=b.def(m,".",a)})}g(a.link(d),f(d.info.type),l)})}function ta(a,c,d,e,f){for(var g=a.shared,h=g.gl,k,l=0;l<e.length;++l){var m=e[l],n=m.name,p=m.info.type,q=d.uniforms[n],m=a.link(m)+".location",r;if(q){if(!f(q))continue;if(sa(q)){n=q.value;if(35678===p||35680===p)p=a.link(n._texture||n.color[0]._texture),c(h,".uniform1i(",m,",",p+".bind());"),
c.exit(p,".unbind();");else if(35674===p||35675===p||35676===p)n=a.global.def("new Float32Array(["+Array.prototype.slice.call(n)+"])"),q=2,35675===p?q=3:35676===p&&(q=4),c(h,".uniformMatrix",q,"fv(",m,",false,",n,");");else{switch(p){case 5126:k="1f";break;case 35664:k="2f";break;case 35665:k="3f";break;case 35666:k="4f";break;case 35670:k="1i";break;case 5124:k="1i";break;case 35671:k="2i";break;case 35667:k="2i";break;case 35672:k="3i";break;case 35668:k="3i";break;case 35673:k="4i";break;case 35669:k=
"4i"}c(h,".uniform",k,"(",m,",",ma(n)?Array.prototype.slice.call(n):n,");")}continue}else r=q.append(a,c)}else{if(!f(Bb))continue;r=c.def(g.uniforms,"[",b.id(n),"]")}35678===p?c("if(",r,"&&",r,'._reglType==="framebuffer"){',r,"=",r,".color[0];","}"):35680===p&&c("if(",r,"&&",r,'._reglType==="framebufferCube"){',r,"=",r,".color[0];","}");n=1;switch(p){case 35678:case 35680:p=c.def(r,"._texture");c(h,".uniform1i(",m,",",p,".bind());");c.exit(p,".unbind();");continue;case 5124:case 35670:k="1i";break;
case 35667:case 35671:k="2i";n=2;break;case 35668:case 35672:k="3i";n=3;break;case 35669:case 35673:k="4i";n=4;break;case 5126:k="1f";break;case 35664:k="2f";n=2;break;case 35665:k="3f";n=3;break;case 35666:k="4f";n=4;break;case 35674:k="Matrix2fv";break;case 35675:k="Matrix3fv";break;case 35676:k="Matrix4fv"}c(h,".uniform",k,"(",m,",");if("M"===k.charAt(0)){var m=Math.pow(p-35674+2,2),t=a.global.def("new Float32Array(",m,")");Array.isArray(r)?c("false,(",J(m,function(a){return t+"["+a+"]="+r[a]}),
",",t,")"):c("false,(Array.isArray(",r,")||",r," instanceof Float32Array)?",r,":(",J(m,function(a){return t+"["+a+"]="+r+"["+a+"]"}),",",t,")")}else 1<n?c(J(n,function(a){return Array.isArray(r)?r[a]:r+"["+a+"]"})):c(r);c(");")}}function aa(a,b,c,d){function e(f){var g=m[f];return g?g.contextDep&&d.contextDynamic||g.propDep?g.append(a,c):g.append(a,b):b.def(l,".",f)}function f(){function a(){c(w,".drawElementsInstancedANGLE(",[p,q,u,r+"<<(("+u+"-5121)>>1)",t],");")}function b(){c(w,".drawArraysInstancedANGLE(",
[p,r,q,t],");")}n?B?a():(c("if(",n,"){"),a(),c("}else{"),b(),c("}")):b()}function g(){function a(){c(k+".drawElements("+[p,q,u,r+"<<(("+u+"-5121)>>1)"]+");")}function b(){c(k+".drawArrays("+[p,r,q]+");")}n?B?a():(c("if(",n,"){"),a(),c("}else{"),b(),c("}")):b()}var h=a.shared,k=h.gl,l=h.draw,m=d.draw,n=function(){var e=m.elements,f=b;if(e){if(e.contextDep&&d.contextDynamic||e.propDep)f=c;e=e.append(a,f)}else e=f.def(l,".","elements");e&&f("if("+e+")"+k+".bindBuffer(34963,"+e+".buffer.buffer);");return e}(),
p=e("primitive"),r=e("offset"),q=function(){var e=m.count,f=b;if(e){if(e.contextDep&&d.contextDynamic||e.propDep)f=c;e=e.append(a,f)}else e=f.def(l,".","count");return e}();if("number"===typeof q){if(0===q)return}else c("if(",q,"){"),c.exit("}");var t,w;oa&&(t=e("instances"),w=a.instancing);var u=n+".type",B=m.elements&&sa(m.elements);oa&&("number"!==typeof t||0<=t)?"string"===typeof t?(c("if(",t,">0){"),f(),c("}else if(",t,"<0){"),g(),c("}")):f():g()}function X(a,b,c,d,e){b=m();e=b.proc("body",e);
oa&&(b.instancing=e.def(b.shared.extensions,".angle_instanced_arrays"));a(b,e,c,d);return b.compile().body}function fa(a,b,c,d){C(a,b);c.useVAO?c.drawVAO?b(a.shared.vao,".setVAO(",c.drawVAO.append(a,b),");"):b(a.shared.vao,".setVAO(",a.shared.vao,".targetVAO);"):(b(a.shared.vao,".setVAO(null);"),U(a,b,c,d.attributes,function(){return!0}));ta(a,b,c,d.uniforms,function(){return!0});aa(a,b,b,c)}function Da(a,b){var c=a.proc("draw",1);C(a,c);V(a,c,b.context);R(a,c,b.framebuffer);T(a,c,b);N(a,c,b.state);
Q(a,c,b,!1,!0);var d=b.shader.progVar.append(a,c);c(a.shared.gl,".useProgram(",d,".program);");if(b.shader.program)fa(a,c,b,b.shader.program);else{c(a.shared.vao,".setVAO(null);");var e=a.global.def("{}"),f=c.def(d,".id"),g=c.def(e,"[",f,"]");c(a.cond(g).then(g,".call(this,a0);")["else"](g,"=",e,"[",f,"]=",a.link(function(c){return X(fa,a,b,c,1)}),"(",d,");",g,".call(this,a0);"))}0<Object.keys(b.state).length&&c(a.shared.current,".dirty=true;")}function ua(a,b,c,d){function e(){return!0}a.batchId=
"a1";C(a,b);U(a,b,c,d.attributes,e);ta(a,b,c,d.uniforms,e);aa(a,b,b,c)}function P(a,b,c,d){function e(a){return a.contextDep&&g||a.propDep}function f(a){return!e(a)}C(a,b);var g=c.contextDep,h=b.def(),k=b.def();a.shared.props=k;a.batchId=h;var l=a.scope(),m=a.scope();b(l.entry,"for(",h,"=0;",h,"<","a1",";++",h,"){",k,"=","a0","[",h,"];",m,"}",l.exit);c.needsContext&&V(a,m,c.context);c.needsFramebuffer&&R(a,m,c.framebuffer);N(a,m,c.state,e);c.profile&&e(c.profile)&&Q(a,m,c,!1,!0);d?(c.useVAO?c.drawVAO?
e(c.drawVAO)?m(a.shared.vao,".setVAO(",c.drawVAO.append(a,m),");"):l(a.shared.vao,".setVAO(",c.drawVAO.append(a,l),");"):l(a.shared.vao,".setVAO(",a.shared.vao,".targetVAO);"):(l(a.shared.vao,".setVAO(null);"),U(a,l,c,d.attributes,f),U(a,m,c,d.attributes,e)),ta(a,l,c,d.uniforms,f),ta(a,m,c,d.uniforms,e),aa(a,l,m,c)):(b=a.global.def("{}"),d=c.shader.progVar.append(a,m),k=m.def(d,".id"),l=m.def(b,"[",k,"]"),m(a.shared.gl,".useProgram(",d,".program);","if(!",l,"){",l,"=",b,"[",k,"]=",a.link(function(b){return X(ua,
a,c,b,2)}),"(",d,");}",l,".call(this,a0[",h,"],",h,");"))}function da(a,b){function c(a){return a.contextDep&&e||a.propDep}var d=a.proc("batch",2);a.batchId="0";C(a,d);var e=!1,f=!0;Object.keys(b.context).forEach(function(a){e=e||b.context[a].propDep});e||(V(a,d,b.context),f=!1);var g=b.framebuffer,h=!1;g?(g.propDep?e=h=!0:g.contextDep&&e&&(h=!0),h||R(a,d,g)):R(a,d,null);b.state.viewport&&b.state.viewport.propDep&&(e=!0);T(a,d,b);N(a,d,b.state,function(a){return!c(a)});b.profile&&c(b.profile)||Q(a,
d,b,!1,"a1");b.contextDep=e;b.needsContext=f;b.needsFramebuffer=h;f=b.shader.progVar;if(f.contextDep&&e||f.propDep)P(a,d,b,null);else if(f=f.append(a,d),d(a.shared.gl,".useProgram(",f,".program);"),b.shader.program)P(a,d,b,b.shader.program);else{d(a.shared.vao,".setVAO(null);");var g=a.global.def("{}"),h=d.def(f,".id"),k=d.def(g,"[",h,"]");d(a.cond(k).then(k,".call(this,a0,a1);")["else"](k,"=",g,"[",h,"]=",a.link(function(c){return X(P,a,b,c,2)}),"(",f,");",k,".call(this,a0,a1);"))}0<Object.keys(b.state).length&&
d(a.shared.current,".dirty=true;")}function ea(a,c){function d(b){var g=c.shader[b];g&&e.set(f.shader,"."+b,g.append(a,e))}var e=a.proc("scope",3);a.batchId="a2";var f=a.shared,g=f.current;V(a,e,c.context);c.framebuffer&&c.framebuffer.append(a,e);zb(Object.keys(c.state)).forEach(function(b){var d=c.state[b].append(a,e);ma(d)?d.forEach(function(c,d){e.set(a.next[b],"["+d+"]",c)}):e.set(f.next,"."+b,d)});Q(a,e,c,!0,!0);["elements","offset","count","instances","primitive"].forEach(function(b){var d=
c.draw[b];d&&e.set(f.draw,"."+b,""+d.append(a,e))});Object.keys(c.uniforms).forEach(function(d){var g=c.uniforms[d].append(a,e);Array.isArray(g)&&(g="["+g.join()+"]");e.set(f.uniforms,"["+b.id(d)+"]",g)});Object.keys(c.attributes).forEach(function(b){var d=c.attributes[b].append(a,e),f=a.scopeAttrib(b);Object.keys(new ga).forEach(function(a){e.set(f,"."+a,d[a])})});c.scopeVAO&&e.set(f.vao,".targetVAO",c.scopeVAO.append(a,e));d("vert");d("frag");0<Object.keys(c.state).length&&(e(g,".dirty=true;"),
e.exit(g,".dirty=true;"));e("a1(",a.shared.context,",a0,",a.batchId,");")}function ha(a){if("object"===typeof a&&!ma(a)){for(var b=Object.keys(a),c=0;c<b.length;++c)if(Y.isDynamic(a[b[c]]))return!0;return!1}}function ia(a,b,c){function d(a,b){g.forEach(function(c){var d=e[c];Y.isDynamic(d)&&(d=a.invoke(b,d),b(m,".",c,"=",d,";"))})}var e=b["static"][c];if(e&&ha(e)){var f=a.global,g=Object.keys(e),h=!1,k=!1,l=!1,m=a.global.def("{}");g.forEach(function(b){var c=e[b];if(Y.isDynamic(c))"function"===typeof c&&
(c=e[b]=Y.unbox(c)),b=L(c,null),h=h||b.thisDep,l=l||b.propDep,k=k||b.contextDep;else{f(m,".",b,"=");switch(typeof c){case "number":f(c);break;case "string":f('"',c,'"');break;case "object":Array.isArray(c)&&f("[",c.join(),"]");break;default:f(a.link(c))}f(";")}});b.dynamic[c]=new Y.DynamicVariable(4,{thisDep:h,contextDep:k,propDep:l,ref:m,append:d});delete b["static"][c]}}var ga=t.Record,W={add:32774,subtract:32778,"reverse subtract":32779};c.ext_blend_minmax&&(W.min=32775,W.max=32776);var oa=c.angle_instanced_arrays,
Ka=c.webgl_draw_buffers,pa={dirty:!0,profile:h.profile},Ca={},La=[],qa={},ra={};q("dither",3024);q("blend.enable",3042);r("blend.color","blendColor",[0,0,0,0]);r("blend.equation","blendEquationSeparate",[32774,32774]);r("blend.func","blendFuncSeparate",[1,0,1,0]);q("depth.enable",2929,!0);r("depth.func","depthFunc",513);r("depth.range","depthRange",[0,1]);r("depth.mask","depthMask",!0);r("colorMask","colorMask",[!0,!0,!0,!0]);q("cull.enable",2884);r("cull.face","cullFace",1029);r("frontFace","frontFace",
2305);r("lineWidth","lineWidth",1);q("polygonOffset.enable",32823);r("polygonOffset.offset","polygonOffset",[0,0]);q("sample.alpha",32926);q("sample.enable",32928);r("sample.coverage","sampleCoverage",[1,!1]);q("stencil.enable",2960);r("stencil.mask","stencilMask",-1);r("stencil.func","stencilFunc",[519,0,-1]);r("stencil.opFront","stencilOpSeparate",[1028,7680,7680,7680]);r("stencil.opBack","stencilOpSeparate",[1029,7680,7680,7680]);q("scissor.enable",3089);r("scissor.box","scissor",[0,0,a.drawingBufferWidth,
a.drawingBufferHeight]);r("viewport","viewport",[0,0,a.drawingBufferWidth,a.drawingBufferHeight]);var ub={gl:a,context:B,strings:b,next:Ca,current:pa,draw:k,elements:d,buffer:f,shader:w,attributes:t.state,vao:t,uniforms:u,framebuffer:n,extensions:c,timer:l,isBufferArgs:Qa},Na={primTypes:Ta,compareFuncs:ab,blendFuncs:Ea,blendEquations:W,stencilOps:Ra,glTypes:Ia,orientationType:Ab};Ka&&(Na.backBuffer=[1029],Na.drawBuffer=J(e.maxDrawbuffers,function(a){return 0===a?[0]:J(a,function(a){return 36064+a})}));
var na=0;return{next:Ca,current:pa,procs:function(){var a=m(),b=a.proc("poll"),d=a.proc("refresh"),f=a.block();b(f);d(f);var g=a.shared,h=g.gl,k=g.next,l=g.current;f(l,".dirty=false;");R(a,b);R(a,d,null,!0);var n;oa&&(n=a.link(oa));c.oes_vertex_array_object&&d(a.link(c.oes_vertex_array_object),".bindVertexArrayOES(null);");for(var p=0;p<e.maxAttributes;++p){var q=d.def(g.attributes,"[",p,"]"),r=a.cond(q,".buffer");r.then(h,".enableVertexAttribArray(",p,");",h,".bindBuffer(",34962,",",q,".buffer.buffer);",
h,".vertexAttribPointer(",p,",",q,".size,",q,".type,",q,".normalized,",q,".stride,",q,".offset);")["else"](h,".disableVertexAttribArray(",p,");",h,".vertexAttrib4f(",p,",",q,".x,",q,".y,",q,".z,",q,".w);",q,".buffer=null;");d(r);oa&&d(n,".vertexAttribDivisorANGLE(",p,",",q,".divisor);")}d(a.shared.vao,".currentVAO=null;",a.shared.vao,".setVAO(",a.shared.vao,".targetVAO);");Object.keys(qa).forEach(function(c){var e=qa[c],g=f.def(k,".",c),m=a.block();m("if(",g,"){",h,".enable(",e,")}else{",h,".disable(",
e,")}",l,".",c,"=",g,";");d(m);b("if(",g,"!==",l,".",c,"){",m,"}")});Object.keys(ra).forEach(function(c){var e=ra[c],g=pa[c],m,n,p=a.block();p(h,".",e,"(");ma(g)?(e=g.length,m=a.global.def(k,".",c),n=a.global.def(l,".",c),p(J(e,function(a){return m+"["+a+"]"}),");",J(e,function(a){return n+"["+a+"]="+m+"["+a+"];"}).join("")),b("if(",J(e,function(a){return m+"["+a+"]!=="+n+"["+a+"]"}).join("||"),"){",p,"}")):(m=f.def(k,".",c),n=f.def(l,".",c),p(m,");",l,".",c,"=",m,";"),b("if(",m,"!==",n,"){",p,"}"));
d(p)});return a.compile()}(),compile:function(a,b,c,d,e){var f=m();f.stats=f.link(e);Object.keys(b["static"]).forEach(function(a){ia(f,b,a)});Xb.forEach(function(b){ia(f,a,b)});var g=la(a,b,c,d,f);Da(f,g);ea(f,g);da(f,g);return A(f.compile(),{destroy:function(){g.shader.program.destroy()}})}}}function Cb(a,b){for(var c=0;c<a.length;++c)if(a[c]===b)return c;return-1}var A=function(a,b){for(var c=Object.keys(b),e=0;e<c.length;++e)a[c[e]]=b[c[e]];return a},Eb=0,Y={DynamicVariable:U,define:function(a,
b){return new U(a,cb(b+""))},isDynamic:function(a){return"function"===typeof a&&!a._reglType||a instanceof U},unbox:db,accessor:cb},bb={next:"function"===typeof requestAnimationFrame?function(a){return requestAnimationFrame(a)}:function(a){return setTimeout(a,16)},cancel:"function"===typeof cancelAnimationFrame?function(a){return cancelAnimationFrame(a)}:clearTimeout},Db="undefined"!==typeof performance&&performance.now?function(){return performance.now()}:function(){return+new Date},E=hb();E.zero=
hb();var Yb=function(a,b){var c=1;b.ext_texture_filter_anisotropic&&(c=a.getParameter(34047));var e=1,f=1;b.webgl_draw_buffers&&(e=a.getParameter(34852),f=a.getParameter(36063));var d=!!b.oes_texture_float;if(d){d=a.createTexture();a.bindTexture(3553,d);a.texImage2D(3553,0,6408,1,1,0,6408,5126,null);var p=a.createFramebuffer();a.bindFramebuffer(36160,p);a.framebufferTexture2D(36160,36064,3553,d,0);a.bindTexture(3553,null);if(36053!==a.checkFramebufferStatus(36160))d=!1;else{a.viewport(0,0,1,1);a.clearColor(1,
0,0,1);a.clear(16384);var n=E.allocType(5126,4);a.readPixels(0,0,1,1,6408,5126,n);a.getError()?d=!1:(a.deleteFramebuffer(p),a.deleteTexture(d),d=1===n[0]);E.freeType(n)}}n=!0;"undefined"!==typeof navigator&&(/MSIE/.test(navigator.userAgent)||/Trident\//.test(navigator.appVersion)||/Edge/.test(navigator.userAgent))||(n=a.createTexture(),p=E.allocType(5121,36),a.activeTexture(33984),a.bindTexture(34067,n),a.texImage2D(34069,0,6408,3,3,0,6408,5121,p),E.freeType(p),a.bindTexture(34067,null),a.deleteTexture(n),
n=!a.getError());return{colorBits:[a.getParameter(3410),a.getParameter(3411),a.getParameter(3412),a.getParameter(3413)],depthBits:a.getParameter(3414),stencilBits:a.getParameter(3415),subpixelBits:a.getParameter(3408),extensions:Object.keys(b).filter(function(a){return!!b[a]}),maxAnisotropic:c,maxDrawbuffers:e,maxColorAttachments:f,pointSizeDims:a.getParameter(33901),lineWidthDims:a.getParameter(33902),maxViewportDims:a.getParameter(3386),maxCombinedTextureUnits:a.getParameter(35661),maxCubeMapSize:a.getParameter(34076),
maxRenderbufferSize:a.getParameter(34024),maxTextureUnits:a.getParameter(34930),maxTextureSize:a.getParameter(3379),maxAttributes:a.getParameter(34921),maxVertexUniforms:a.getParameter(36347),maxVertexTextureUnits:a.getParameter(35660),maxVaryingVectors:a.getParameter(36348),maxFragmentUniforms:a.getParameter(36349),glsl:a.getParameter(35724),renderer:a.getParameter(7937),vendor:a.getParameter(7936),version:a.getParameter(7938),readFloat:d,npotTextureCube:n}},M=function(a){return a instanceof Uint8Array||
a instanceof Uint16Array||a instanceof Uint32Array||a instanceof Int8Array||a instanceof Int16Array||a instanceof Int32Array||a instanceof Float32Array||a instanceof Float64Array||a instanceof Uint8ClampedArray},S=function(a){return Object.keys(a).map(function(b){return a[b]})},Oa={shape:function(a){for(var b=[];a.length;a=a[0])b.push(a.length);return b},flatten:function(a,b,c,e){var f=1;if(b.length)for(var d=0;d<b.length;++d)f*=b[d];else f=0;c=e||E.allocType(c,f);switch(b.length){case 0:break;case 1:e=
b[0];for(b=0;b<e;++b)c[b]=a[b];break;case 2:e=b[0];b=b[1];for(d=f=0;d<e;++d)for(var p=a[d],n=0;n<b;++n)c[f++]=p[n];break;case 3:ib(a,b[0],b[1],b[2],c,0);break;default:jb(a,b,0,c,0)}return c}},Ga={"[object Int8Array]":5120,"[object Int16Array]":5122,"[object Int32Array]":5124,"[object Uint8Array]":5121,"[object Uint8ClampedArray]":5121,"[object Uint16Array]":5123,"[object Uint32Array]":5125,"[object Float32Array]":5126,"[object Float64Array]":5121,"[object ArrayBuffer]":5121},Ia={int8:5120,int16:5122,
int32:5124,uint8:5121,uint16:5123,uint32:5125,"float":5126,float32:5126},ob={dynamic:35048,stream:35040,"static":35044},Sa=Oa.flatten,mb=Oa.shape,ha=[];ha[5120]=1;ha[5122]=2;ha[5124]=4;ha[5121]=1;ha[5123]=2;ha[5125]=4;ha[5126]=4;var Ta={points:0,point:0,lines:1,line:1,triangles:4,triangle:4,"line loop":2,"line strip":3,"triangle strip":5,"triangle fan":6},qb=new Float32Array(1),Mb=new Uint32Array(qb.buffer),Qb=[9984,9986,9985,9987],Ma=[0,6409,6410,6407,6408],Q={};Q[6409]=Q[6406]=Q[6402]=1;Q[34041]=
Q[6410]=2;Q[6407]=Q[35904]=3;Q[6408]=Q[35906]=4;var Wa=na("HTMLCanvasElement"),Xa=na("OffscreenCanvas"),vb=na("CanvasRenderingContext2D"),wb=na("ImageBitmap"),xb=na("HTMLImageElement"),yb=na("HTMLVideoElement"),Nb=Object.keys(Ga).concat([Wa,Xa,vb,wb,xb,yb]),wa=[];wa[5121]=1;wa[5126]=4;wa[36193]=2;wa[5123]=2;wa[5125]=4;var F=[];F[32854]=2;F[32855]=2;F[36194]=2;F[34041]=4;F[33776]=.5;F[33777]=.5;F[33778]=1;F[33779]=1;F[35986]=.5;F[35987]=1;F[34798]=1;F[35840]=.5;F[35841]=.25;F[35842]=.5;F[35843]=.25;
F[36196]=.5;var T=[];T[32854]=2;T[32855]=2;T[36194]=2;T[33189]=2;T[36168]=1;T[34041]=4;T[35907]=4;T[34836]=16;T[34842]=8;T[34843]=6;var Zb=function(a,b,c,e,f){function d(a){this.id=t++;this.refCount=1;this.renderbuffer=a;this.format=32854;this.height=this.width=0;f.profile&&(this.stats={size:0})}function p(b){var c=b.renderbuffer;a.bindRenderbuffer(36161,null);a.deleteRenderbuffer(c);b.renderbuffer=null;b.refCount=0;delete w[b.id];e.renderbufferCount--}var n={rgba4:32854,rgb565:36194,"rgb5 a1":32855,
depth:33189,stencil:36168,"depth stencil":34041};b.ext_srgb&&(n.srgba=35907);b.ext_color_buffer_half_float&&(n.rgba16f=34842,n.rgb16f=34843);b.webgl_color_buffer_float&&(n.rgba32f=34836);var u=[];Object.keys(n).forEach(function(a){u[n[a]]=a});var t=0,w={};d.prototype.decRef=function(){0>=--this.refCount&&p(this)};f.profile&&(e.getTotalRenderbufferSize=function(){var a=0;Object.keys(w).forEach(function(b){a+=w[b].stats.size});return a});return{create:function(b,c){function l(b,c){var d=0,e=0,k=32854;
"object"===typeof b&&b?("shape"in b?(e=b.shape,d=e[0]|0,e=e[1]|0):("radius"in b&&(d=e=b.radius|0),"width"in b&&(d=b.width|0),"height"in b&&(e=b.height|0)),"format"in b&&(k=n[b.format])):"number"===typeof b?(d=b|0,e="number"===typeof c?c|0:d):b||(d=e=1);if(d!==h.width||e!==h.height||k!==h.format)return l.width=h.width=d,l.height=h.height=e,h.format=k,a.bindRenderbuffer(36161,h.renderbuffer),a.renderbufferStorage(36161,k,d,e),f.profile&&(h.stats.size=T[h.format]*h.width*h.height),l.format=u[h.format],
l}var h=new d(a.createRenderbuffer());w[h.id]=h;e.renderbufferCount++;l(b,c);l.resize=function(b,c){var d=b|0,e=c|0||d;if(d===h.width&&e===h.height)return l;l.width=h.width=d;l.height=h.height=e;a.bindRenderbuffer(36161,h.renderbuffer);a.renderbufferStorage(36161,h.format,d,e);f.profile&&(h.stats.size=T[h.format]*h.width*h.height);return l};l._reglType="renderbuffer";l._renderbuffer=h;f.profile&&(l.stats=h.stats);l.destroy=function(){h.decRef()};return l},clear:function(){S(w).forEach(p)},restore:function(){S(w).forEach(function(b){b.renderbuffer=
a.createRenderbuffer();a.bindRenderbuffer(36161,b.renderbuffer);a.renderbufferStorage(36161,b.format,b.width,b.height)});a.bindRenderbuffer(36161,null)}}},Ya=[];Ya[6408]=4;Ya[6407]=3;var Pa=[];Pa[5121]=1;Pa[5126]=4;Pa[36193]=2;var Ba=["x","y","z","w"],Xb="blend.func blend.equation stencil.func stencil.opFront stencil.opBack sample.coverage viewport scissor.box polygonOffset.offset".split(" "),Ea={0:0,1:1,zero:0,one:1,"src color":768,"one minus src color":769,"src alpha":770,"one minus src alpha":771,
"dst color":774,"one minus dst color":775,"dst alpha":772,"one minus dst alpha":773,"constant color":32769,"one minus constant color":32770,"constant alpha":32771,"one minus constant alpha":32772,"src alpha saturate":776},ab={never:512,less:513,"<":513,equal:514,"=":514,"==":514,"===":514,lequal:515,"<=":515,greater:516,">":516,notequal:517,"!=":517,"!==":517,gequal:518,">=":518,always:519},Ra={0:0,zero:0,keep:7680,replace:7681,increment:7682,decrement:7683,"increment wrap":34055,"decrement wrap":34056,
invert:5386},Ab={cw:2304,ccw:2305},Bb=new K(!1,!1,!1,function(){}),$b=function(a,b){function c(){this.endQueryIndex=this.startQueryIndex=-1;this.sum=0;this.stats=null}function e(a,b,d){var e=p.pop()||new c;e.startQueryIndex=a;e.endQueryIndex=b;e.sum=0;e.stats=d;n.push(e)}if(!b.ext_disjoint_timer_query)return null;var f=[],d=[],p=[],n=[],u=[],t=[];return{beginQuery:function(a){var c=f.pop()||b.ext_disjoint_timer_query.createQueryEXT();b.ext_disjoint_timer_query.beginQueryEXT(35007,c);d.push(c);e(d.length-
1,d.length,a)},endQuery:function(){b.ext_disjoint_timer_query.endQueryEXT(35007)},pushScopeStats:e,update:function(){var a,c;a=d.length;if(0!==a){t.length=Math.max(t.length,a+1);u.length=Math.max(u.length,a+1);u[0]=0;var e=t[0]=0;for(c=a=0;c<d.length;++c){var l=d[c];b.ext_disjoint_timer_query.getQueryObjectEXT(l,34919)?(e+=b.ext_disjoint_timer_query.getQueryObjectEXT(l,34918),f.push(l)):d[a++]=l;u[c+1]=e;t[c+1]=a}d.length=a;for(c=a=0;c<n.length;++c){var e=n[c],h=e.startQueryIndex,l=e.endQueryIndex;
e.sum+=u[l]-u[h];h=t[h];l=t[l];l===h?(e.stats.gpuTime+=e.sum/1E6,p.push(e)):(e.startQueryIndex=h,e.endQueryIndex=l,n[a++]=e)}n.length=a}},getNumPendingQueries:function(){return d.length},clear:function(){f.push.apply(f,d);for(var a=0;a<f.length;a++)b.ext_disjoint_timer_query.deleteQueryEXT(f[a]);d.length=0;f.length=0},restore:function(){d.length=0;f.length=0}}};return function(a){function b(){if(0===C.length)z&&z.update(),aa=null;else{aa=bb.next(b);w();for(var a=C.length-1;0<=a;--a){var c=C[a];c&&
c(G,null,0)}l.flush();z&&z.update()}}function c(){!aa&&0<C.length&&(aa=bb.next(b))}function e(){aa&&(bb.cancel(b),aa=null)}function f(a){a.preventDefault();e();S.forEach(function(a){a()})}function d(a){l.getError();g.restore();D.restore();O.restore();y.restore();L.restore();V.restore();J.restore();z&&z.restore();R.procs.refresh();c();T.forEach(function(a){a()})}function p(a){function b(a,c){var d={},e={};Object.keys(a).forEach(function(b){var f=a[b];if(Y.isDynamic(f))e[b]=Y.unbox(f,b);else{if(c&&
Array.isArray(f))for(var g=0;g<f.length;++g)if(Y.isDynamic(f[g])){e[b]=Y.unbox(f,b);return}d[b]=f}});return{dynamic:e,"static":d}}function c(a){for(;n.length<a;)n.push(null);return n}var d=b(a.context||{},!0),e=b(a.uniforms||{},!0),f=b(a.attributes||{},!1);a=b(function(a){function b(a){if(a in c){var d=c[a];delete c[a];Object.keys(d).forEach(function(b){c[a+"."+b]=d[b]})}}var c=A({},a);delete c.uniforms;delete c.attributes;delete c.context;delete c.vao;"stencil"in c&&c.stencil.op&&(c.stencil.opBack=
c.stencil.opFront=c.stencil.op,delete c.stencil.op);b("blend");b("depth");b("cull");b("stencil");b("polygonOffset");b("scissor");b("sample");"vao"in a&&(c.vao=a.vao);return c}(a),!1);var g={gpuTime:0,cpuTime:0,count:0},h=R.compile(a,f,e,d,g),k=h.draw,l=h.batch,m=h.scope,n=[];return A(function(a,b){var d;if("function"===typeof a)return m.call(this,null,a,0);if("function"===typeof b)if("number"===typeof a)for(d=0;d<a;++d)m.call(this,null,b,d);else if(Array.isArray(a))for(d=0;d<a.length;++d)m.call(this,
a[d],b,d);else return m.call(this,a,b,0);else if("number"===typeof a){if(0<a)return l.call(this,c(a|0),a|0)}else if(Array.isArray(a)){if(a.length)return l.call(this,a,a.length)}else return k.call(this,a)},{stats:g,destroy:function(){h.destroy()}})}function n(a,b){var c=0;R.procs.poll();var d=b.color;d&&(l.clearColor(+d[0]||0,+d[1]||0,+d[2]||0,+d[3]||0),c|=16384);"depth"in b&&(l.clearDepth(+b.depth),c|=256);"stencil"in b&&(l.clearStencil(b.stencil|0),c|=1024);l.clear(c)}function u(a){C.push(a);c();
return{cancel:function(){function b(){var a=Cb(C,b);C[a]=C[C.length-1];--C.length;0>=C.length&&e()}var c=Cb(C,a);C[c]=b}}}function t(){var a=Q.viewport,b=Q.scissor_box;a[0]=a[1]=b[0]=b[1]=0;G.viewportWidth=G.framebufferWidth=G.drawingBufferWidth=a[2]=b[2]=l.drawingBufferWidth;G.viewportHeight=G.framebufferHeight=G.drawingBufferHeight=a[3]=b[3]=l.drawingBufferHeight}function w(){G.tick+=1;G.time=v();t();R.procs.poll()}function k(){y.refresh();t();R.procs.refresh();z&&z.update()}function v(){return(Db()-
E)/1E3}a=Ib(a);if(!a)return null;var l=a.gl,h=l.getContextAttributes();l.isContextLost();var g=Jb(l,a);if(!g)return null;var q=Fb(),r={vaoCount:0,bufferCount:0,elementsCount:0,framebufferCount:0,shaderCount:0,textureCount:0,cubeCount:0,renderbufferCount:0,maxTextureUnits:0},m=g.extensions,z=$b(l,m),E=Db(),F=l.drawingBufferWidth,K=l.drawingBufferHeight,G={tick:0,time:0,viewportWidth:F,viewportHeight:K,framebufferWidth:F,framebufferHeight:K,drawingBufferWidth:F,drawingBufferHeight:K,pixelRatio:a.pixelRatio},
H=Yb(l,m),O=Kb(l,r,a,function(a){return J.destroyBuffer(a)}),J=Sb(l,m,H,r,O),M=Lb(l,m,O,r),D=Tb(l,q,r,a),y=Ob(l,m,H,function(){R.procs.poll()},G,r,a),L=Zb(l,m,H,r,a),V=Rb(l,m,H,y,L,r),R=Wb(l,q,m,H,O,M,y,V,{},J,D,{elements:null,primitive:4,count:-1,offset:0,instances:-1},G,z,a),q=Ub(l,V,R.procs.poll,G,h,m,H),Q=R.next,N=l.canvas,C=[],S=[],T=[],U=[a.onDestroy],aa=null;N&&(N.addEventListener("webglcontextlost",f,!1),N.addEventListener("webglcontextrestored",d,!1));var X=V.setFBO=p({framebuffer:Y.define.call(null,
1,"framebuffer")});k();h=A(p,{clear:function(a){if("framebuffer"in a)if(a.framebuffer&&"framebufferCube"===a.framebuffer_reglType)for(var b=0;6>b;++b)X(A({framebuffer:a.framebuffer.faces[b]},a),n);else X(a,n);else n(null,a)},prop:Y.define.bind(null,1),context:Y.define.bind(null,2),"this":Y.define.bind(null,3),draw:p({}),buffer:function(a){return O.create(a,34962,!1,!1)},elements:function(a){return M.create(a,!1)},texture:y.create2D,cube:y.createCube,renderbuffer:L.create,framebuffer:V.create,framebufferCube:V.createCube,
vao:J.createVAO,attributes:h,frame:u,on:function(a,b){var c;switch(a){case "frame":return u(b);case "lost":c=S;break;case "restore":c=T;break;case "destroy":c=U}c.push(b);return{cancel:function(){for(var a=0;a<c.length;++a)if(c[a]===b){c[a]=c[c.length-1];c.pop();break}}}},limits:H,hasExtension:function(a){return 0<=H.extensions.indexOf(a.toLowerCase())},read:q,destroy:function(){C.length=0;e();N&&(N.removeEventListener("webglcontextlost",f),N.removeEventListener("webglcontextrestored",d));D.clear();
V.clear();L.clear();y.clear();M.clear();O.clear();J.clear();z&&z.clear();U.forEach(function(a){a()})},_gl:l,_refresh:k,poll:function(){w();z&&z.update()},now:v,stats:r});a.onDone(null,h);return h}});
},{}],140:[function(require,module,exports){
(function (global){(function (){
module.exports =
global.performance &&
global.performance.now ? function now() {
return performance.now()
} : Date.now || function now() {
return +new Date
}
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[1]);