mindoc/static/cherry/cherry-markdown.js

94835 lines
4.5 MiB
Raw Permalink Blame History

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.Cherry = {}));
}(this, (function (exports) { 'use strict';
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
function getCjsExportFromNamespace (n) {
return n && n['default'] || n;
}
var check = function (it) {
return it && it.Math == Math && it;
};
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global_1 =
// eslint-disable-next-line es-x/no-global-this -- safe
check(typeof globalThis == 'object' && globalThis) ||
check(typeof window == 'object' && window) ||
// eslint-disable-next-line no-restricted-globals -- safe
check(typeof self == 'object' && self) ||
check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||
// eslint-disable-next-line no-new-func -- fallback
(function () { return this; })() || Function('return this')();
var fails = function (exec) {
try {
return !!exec();
} catch (error) {
return true;
}
};
var functionBindNative = !fails(function () {
// eslint-disable-next-line es-x/no-function-prototype-bind -- safe
var test = (function () { /* empty */ }).bind();
// eslint-disable-next-line no-prototype-builtins -- safe
return typeof test != 'function' || test.hasOwnProperty('prototype');
});
var FunctionPrototype = Function.prototype;
var apply = FunctionPrototype.apply;
var call = FunctionPrototype.call;
// eslint-disable-next-line es-x/no-reflect -- safe
var functionApply = typeof Reflect == 'object' && Reflect.apply || (functionBindNative ? call.bind(apply) : function () {
return call.apply(apply, arguments);
});
var FunctionPrototype$1 = Function.prototype;
var bind = FunctionPrototype$1.bind;
var call$1 = FunctionPrototype$1.call;
var uncurryThis = functionBindNative && bind.bind(call$1, call$1);
var functionUncurryThis = functionBindNative ? function (fn) {
return fn && uncurryThis(fn);
} : function (fn) {
return fn && function () {
return call$1.apply(fn, arguments);
};
};
// `IsCallable` abstract operation
// https://tc39.es/ecma262/#sec-iscallable
var isCallable = function (argument) {
return typeof argument == 'function';
};
// Detect IE8's incomplete defineProperty implementation
var descriptors = !fails(function () {
// eslint-disable-next-line es-x/no-object-defineproperty -- required for testing
return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7;
});
var call$2 = Function.prototype.call;
var functionCall = functionBindNative ? call$2.bind(call$2) : function () {
return call$2.apply(call$2, arguments);
};
var $propertyIsEnumerable = {}.propertyIsEnumerable;
// eslint-disable-next-line es-x/no-object-getownpropertydescriptor -- safe
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// Nashorn ~ JDK8 bug
var NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ 1: 2 }, 1);
// `Object.prototype.propertyIsEnumerable` method implementation
// https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
var f = NASHORN_BUG ? function propertyIsEnumerable(V) {
var descriptor = getOwnPropertyDescriptor(this, V);
return !!descriptor && descriptor.enumerable;
} : $propertyIsEnumerable;
var objectPropertyIsEnumerable = {
f: f
};
var createPropertyDescriptor = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
var toString = functionUncurryThis({}.toString);
var stringSlice = functionUncurryThis(''.slice);
var classofRaw = function (it) {
return stringSlice(toString(it), 8, -1);
};
var Object$1 = global_1.Object;
var split = functionUncurryThis(''.split);
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var indexedObject = fails(function () {
// throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
// eslint-disable-next-line no-prototype-builtins -- safe
return !Object$1('z').propertyIsEnumerable(0);
}) ? function (it) {
return classofRaw(it) == 'String' ? split(it, '') : Object$1(it);
} : Object$1;
var TypeError$1 = global_1.TypeError;
// `RequireObjectCoercible` abstract operation
// https://tc39.es/ecma262/#sec-requireobjectcoercible
var requireObjectCoercible = function (it) {
if (it == undefined) throw TypeError$1("Can't call method on " + it);
return it;
};
// toObject with fallback for non-array-like ES3 strings
var toIndexedObject = function (it) {
return indexedObject(requireObjectCoercible(it));
};
var isObject = function (it) {
return typeof it == 'object' ? it !== null : isCallable(it);
};
var path = {};
var aFunction = function (variable) {
return isCallable(variable) ? variable : undefined;
};
var getBuiltIn = function (namespace, method) {
return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global_1[namespace])
: path[namespace] && path[namespace][method] || global_1[namespace] && global_1[namespace][method];
};
var objectIsPrototypeOf = functionUncurryThis({}.isPrototypeOf);
var engineUserAgent = getBuiltIn('navigator', 'userAgent') || '';
var process$1 = global_1.process;
var Deno$1 = global_1.Deno;
var versions = process$1 && process$1.versions || Deno$1 && Deno$1.version;
var v8 = versions && versions.v8;
var match, version;
if (v8) {
match = v8.split('.');
// in old Chrome, versions of V8 isn't V8 = Chrome / 10
// but their correct versions are not interesting for us
version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]);
}
// BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`
// so check `userAgent` even if `.v8` exists, but 0
if (!version && engineUserAgent) {
match = engineUserAgent.match(/Edge\/(\d+)/);
if (!match || match[1] >= 74) {
match = engineUserAgent.match(/Chrome\/(\d+)/);
if (match) version = +match[1];
}
}
var engineV8Version = version;
/* eslint-disable es-x/no-symbol -- required for testing */
// eslint-disable-next-line es-x/no-object-getownpropertysymbols -- required for testing
var nativeSymbol = !!Object.getOwnPropertySymbols && !fails(function () {
var symbol = Symbol();
// Chrome 38 Symbol has incorrect toString conversion
// `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances
return !String(symbol) || !(Object(symbol) instanceof Symbol) ||
// Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
!Symbol.sham && engineV8Version && engineV8Version < 41;
});
/* eslint-disable es-x/no-symbol -- required for testing */
var useSymbolAsUid = nativeSymbol
&& !Symbol.sham
&& typeof Symbol.iterator == 'symbol';
var Object$2 = global_1.Object;
var isSymbol = useSymbolAsUid ? function (it) {
return typeof it == 'symbol';
} : function (it) {
var $Symbol = getBuiltIn('Symbol');
return isCallable($Symbol) && objectIsPrototypeOf($Symbol.prototype, Object$2(it));
};
var String$1 = global_1.String;
var tryToString = function (argument) {
try {
return String$1(argument);
} catch (error) {
return 'Object';
}
};
var TypeError$2 = global_1.TypeError;
// `Assert: IsCallable(argument) is true`
var aCallable = function (argument) {
if (isCallable(argument)) return argument;
throw TypeError$2(tryToString(argument) + ' is not a function');
};
// `GetMethod` abstract operation
// https://tc39.es/ecma262/#sec-getmethod
var getMethod = function (V, P) {
var func = V[P];
return func == null ? undefined : aCallable(func);
};
var TypeError$3 = global_1.TypeError;
// `OrdinaryToPrimitive` abstract operation
// https://tc39.es/ecma262/#sec-ordinarytoprimitive
var ordinaryToPrimitive = function (input, pref) {
var fn, val;
if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = functionCall(fn, input))) return val;
if (isCallable(fn = input.valueOf) && !isObject(val = functionCall(fn, input))) return val;
if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = functionCall(fn, input))) return val;
throw TypeError$3("Can't convert object to primitive value");
};
var isPure = true;
// eslint-disable-next-line es-x/no-object-defineproperty -- safe
var defineProperty = Object.defineProperty;
var defineGlobalProperty = function (key, value) {
try {
defineProperty(global_1, key, { value: value, configurable: true, writable: true });
} catch (error) {
global_1[key] = value;
} return value;
};
var SHARED = '__core-js_shared__';
var store = global_1[SHARED] || defineGlobalProperty(SHARED, {});
var sharedStore = store;
var shared = createCommonjsModule(function (module) {
(module.exports = function (key, value) {
return sharedStore[key] || (sharedStore[key] = value !== undefined ? value : {});
})('versions', []).push({
version: '3.22.6',
mode: 'pure' ,
copyright: '© 2014-2022 Denis Pushkarev (zloirock.ru)',
license: 'https://github.com/zloirock/core-js/blob/v3.22.6/LICENSE',
source: 'https://github.com/zloirock/core-js'
});
});
var Object$3 = global_1.Object;
// `ToObject` abstract operation
// https://tc39.es/ecma262/#sec-toobject
var toObject = function (argument) {
return Object$3(requireObjectCoercible(argument));
};
var hasOwnProperty = functionUncurryThis({}.hasOwnProperty);
// `HasOwnProperty` abstract operation
// https://tc39.es/ecma262/#sec-hasownproperty
// eslint-disable-next-line es-x/no-object-hasown -- safe
var hasOwnProperty_1 = Object.hasOwn || function hasOwn(it, key) {
return hasOwnProperty(toObject(it), key);
};
var id = 0;
var postfix = Math.random();
var toString$1 = functionUncurryThis(1.0.toString);
var uid = function (key) {
return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString$1(++id + postfix, 36);
};
var WellKnownSymbolsStore = shared('wks');
var Symbol$1 = global_1.Symbol;
var symbolFor = Symbol$1 && Symbol$1['for'];
var createWellKnownSymbol = useSymbolAsUid ? Symbol$1 : Symbol$1 && Symbol$1.withoutSetter || uid;
var wellKnownSymbol = function (name) {
if (!hasOwnProperty_1(WellKnownSymbolsStore, name) || !(nativeSymbol || typeof WellKnownSymbolsStore[name] == 'string')) {
var description = 'Symbol.' + name;
if (nativeSymbol && hasOwnProperty_1(Symbol$1, name)) {
WellKnownSymbolsStore[name] = Symbol$1[name];
} else if (useSymbolAsUid && symbolFor) {
WellKnownSymbolsStore[name] = symbolFor(description);
} else {
WellKnownSymbolsStore[name] = createWellKnownSymbol(description);
}
} return WellKnownSymbolsStore[name];
};
var TypeError$4 = global_1.TypeError;
var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
// `ToPrimitive` abstract operation
// https://tc39.es/ecma262/#sec-toprimitive
var toPrimitive = function (input, pref) {
if (!isObject(input) || isSymbol(input)) return input;
var exoticToPrim = getMethod(input, TO_PRIMITIVE);
var result;
if (exoticToPrim) {
if (pref === undefined) pref = 'default';
result = functionCall(exoticToPrim, input, pref);
if (!isObject(result) || isSymbol(result)) return result;
throw TypeError$4("Can't convert object to primitive value");
}
if (pref === undefined) pref = 'number';
return ordinaryToPrimitive(input, pref);
};
// `ToPropertyKey` abstract operation
// https://tc39.es/ecma262/#sec-topropertykey
var toPropertyKey = function (argument) {
var key = toPrimitive(argument, 'string');
return isSymbol(key) ? key : key + '';
};
var document$1 = global_1.document;
// typeof document.createElement is 'object' in old IE
var EXISTS = isObject(document$1) && isObject(document$1.createElement);
var documentCreateElement = function (it) {
return EXISTS ? document$1.createElement(it) : {};
};
// Thanks to IE8 for its funny defineProperty
var ie8DomDefine = !descriptors && !fails(function () {
// eslint-disable-next-line es-x/no-object-defineproperty -- required for testing
return Object.defineProperty(documentCreateElement('div'), 'a', {
get: function () { return 7; }
}).a != 7;
});
// eslint-disable-next-line es-x/no-object-getownpropertydescriptor -- safe
var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// `Object.getOwnPropertyDescriptor` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
var f$1 = descriptors ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
O = toIndexedObject(O);
P = toPropertyKey(P);
if (ie8DomDefine) try {
return $getOwnPropertyDescriptor(O, P);
} catch (error) { /* empty */ }
if (hasOwnProperty_1(O, P)) return createPropertyDescriptor(!functionCall(objectPropertyIsEnumerable.f, O, P), O[P]);
};
var objectGetOwnPropertyDescriptor = {
f: f$1
};
var replacement = /#|\.prototype\./;
var isForced = function (feature, detection) {
var value = data[normalize(feature)];
return value == POLYFILL ? true
: value == NATIVE ? false
: isCallable(detection) ? fails(detection)
: !!detection;
};
var normalize = isForced.normalize = function (string) {
return String(string).replace(replacement, '.').toLowerCase();
};
var data = isForced.data = {};
var NATIVE = isForced.NATIVE = 'N';
var POLYFILL = isForced.POLYFILL = 'P';
var isForced_1 = isForced;
var bind$1 = functionUncurryThis(functionUncurryThis.bind);
// optional / simple context binding
var functionBindContext = function (fn, that) {
aCallable(fn);
return that === undefined ? fn : functionBindNative ? bind$1(fn, that) : function (/* ...args */) {
return fn.apply(that, arguments);
};
};
// V8 ~ Chrome 36-
// https://bugs.chromium.org/p/v8/issues/detail?id=3334
var v8PrototypeDefineBug = descriptors && fails(function () {
// eslint-disable-next-line es-x/no-object-defineproperty -- required for testing
return Object.defineProperty(function () { /* empty */ }, 'prototype', {
value: 42,
writable: false
}).prototype != 42;
});
var String$2 = global_1.String;
var TypeError$5 = global_1.TypeError;
// `Assert: Type(argument) is Object`
var anObject = function (argument) {
if (isObject(argument)) return argument;
throw TypeError$5(String$2(argument) + ' is not an object');
};
var TypeError$6 = global_1.TypeError;
// eslint-disable-next-line es-x/no-object-defineproperty -- safe
var $defineProperty = Object.defineProperty;
// eslint-disable-next-line es-x/no-object-getownpropertydescriptor -- safe
var $getOwnPropertyDescriptor$1 = Object.getOwnPropertyDescriptor;
var ENUMERABLE = 'enumerable';
var CONFIGURABLE = 'configurable';
var WRITABLE = 'writable';
// `Object.defineProperty` method
// https://tc39.es/ecma262/#sec-object.defineproperty
var f$2 = descriptors ? v8PrototypeDefineBug ? function defineProperty(O, P, Attributes) {
anObject(O);
P = toPropertyKey(P);
anObject(Attributes);
if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) {
var current = $getOwnPropertyDescriptor$1(O, P);
if (current && current[WRITABLE]) {
O[P] = Attributes.value;
Attributes = {
configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE],
enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE],
writable: false
};
}
} return $defineProperty(O, P, Attributes);
} : $defineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPropertyKey(P);
anObject(Attributes);
if (ie8DomDefine) try {
return $defineProperty(O, P, Attributes);
} catch (error) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError$6('Accessors not supported');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
var objectDefineProperty = {
f: f$2
};
var createNonEnumerableProperty = descriptors ? function (object, key, value) {
return objectDefineProperty.f(object, key, createPropertyDescriptor(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
var getOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;
var wrapConstructor = function (NativeConstructor) {
var Wrapper = function (a, b, c) {
if (this instanceof Wrapper) {
switch (arguments.length) {
case 0: return new NativeConstructor();
case 1: return new NativeConstructor(a);
case 2: return new NativeConstructor(a, b);
} return new NativeConstructor(a, b, c);
} return functionApply(NativeConstructor, this, arguments);
};
Wrapper.prototype = NativeConstructor.prototype;
return Wrapper;
};
/*
options.target - name of the target object
options.global - target is the global object
options.stat - export as static methods of target
options.proto - export as prototype methods of target
options.real - real prototype method for the `pure` version
options.forced - export even if the native feature is available
options.bind - bind methods to the target, required for the `pure` version
options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
options.unsafe - use the simple assignment of property instead of delete + defineProperty
options.sham - add a flag to not completely full polyfills
options.enumerable - export as enumerable property
options.dontCallGetSet - prevent calling a getter on target
options.name - the .name of the function if it does not match the key
*/
var _export = function (options, source) {
var TARGET = options.target;
var GLOBAL = options.global;
var STATIC = options.stat;
var PROTO = options.proto;
var nativeSource = GLOBAL ? global_1 : STATIC ? global_1[TARGET] : (global_1[TARGET] || {}).prototype;
var target = GLOBAL ? path : path[TARGET] || createNonEnumerableProperty(path, TARGET, {})[TARGET];
var targetPrototype = target.prototype;
var FORCED, USE_NATIVE, VIRTUAL_PROTOTYPE;
var key, sourceProperty, targetProperty, nativeProperty, resultProperty, descriptor;
for (key in source) {
FORCED = isForced_1(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
// contains in native
USE_NATIVE = !FORCED && nativeSource && hasOwnProperty_1(nativeSource, key);
targetProperty = target[key];
if (USE_NATIVE) if (options.dontCallGetSet) {
descriptor = getOwnPropertyDescriptor$1(nativeSource, key);
nativeProperty = descriptor && descriptor.value;
} else nativeProperty = nativeSource[key];
// export native or implementation
sourceProperty = (USE_NATIVE && nativeProperty) ? nativeProperty : source[key];
if (USE_NATIVE && typeof targetProperty == typeof sourceProperty) continue;
// bind timers to global for call from export context
if (options.bind && USE_NATIVE) resultProperty = functionBindContext(sourceProperty, global_1);
// wrap global constructors for prevent changs in this version
else if (options.wrap && USE_NATIVE) resultProperty = wrapConstructor(sourceProperty);
// make static versions for prototype methods
else if (PROTO && isCallable(sourceProperty)) resultProperty = functionUncurryThis(sourceProperty);
// default case
else resultProperty = sourceProperty;
// add a flag to not completely full polyfills
if (options.sham || (sourceProperty && sourceProperty.sham) || (targetProperty && targetProperty.sham)) {
createNonEnumerableProperty(resultProperty, 'sham', true);
}
createNonEnumerableProperty(target, key, resultProperty);
if (PROTO) {
VIRTUAL_PROTOTYPE = TARGET + 'Prototype';
if (!hasOwnProperty_1(path, VIRTUAL_PROTOTYPE)) {
createNonEnumerableProperty(path, VIRTUAL_PROTOTYPE, {});
}
// export virtual prototype methods
createNonEnumerableProperty(path[VIRTUAL_PROTOTYPE], key, sourceProperty);
// export real prototype methods
if (options.real && targetPrototype && !targetPrototype[key]) {
createNonEnumerableProperty(targetPrototype, key, sourceProperty);
}
}
}
};
var arraySlice = functionUncurryThis([].slice);
var Function$1 = global_1.Function;
var concat = functionUncurryThis([].concat);
var join = functionUncurryThis([].join);
var factories = {};
var construct = function (C, argsLength, args) {
if (!hasOwnProperty_1(factories, argsLength)) {
for (var list = [], i = 0; i < argsLength; i++) list[i] = 'a[' + i + ']';
factories[argsLength] = Function$1('C,a', 'return new C(' + join(list, ',') + ')');
} return factories[argsLength](C, args);
};
// `Function.prototype.bind` method implementation
// https://tc39.es/ecma262/#sec-function.prototype.bind
var functionBind = functionBindNative ? Function$1.bind : function bind(that /* , ...args */) {
var F = aCallable(this);
var Prototype = F.prototype;
var partArgs = arraySlice(arguments, 1);
var boundFunction = function bound(/* args... */) {
var args = concat(partArgs, arraySlice(arguments));
return this instanceof boundFunction ? construct(F, args.length, args) : F.apply(that, args);
};
if (isObject(Prototype)) boundFunction.prototype = Prototype;
return boundFunction;
};
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
var test = {};
test[TO_STRING_TAG] = 'z';
var toStringTagSupport = String(test) === '[object z]';
var TO_STRING_TAG$1 = wellKnownSymbol('toStringTag');
var Object$4 = global_1.Object;
// ES3 wrong here
var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
try {
return it[key];
} catch (error) { /* empty */ }
};
// getting tag from ES6+ `Object.prototype.toString`
var classof = toStringTagSupport ? classofRaw : function (it) {
var O, tag, result;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (tag = tryGet(O = Object$4(it), TO_STRING_TAG$1)) == 'string' ? tag
// builtinTag case
: CORRECT_ARGUMENTS ? classofRaw(O)
// ES3 arguments fallback
: (result = classofRaw(O)) == 'Object' && isCallable(O.callee) ? 'Arguments' : result;
};
var functionToString = functionUncurryThis(Function.toString);
// this helper broken in `core-js@3.4.1-3.4.4`, so we can't use `shared` helper
if (!isCallable(sharedStore.inspectSource)) {
sharedStore.inspectSource = function (it) {
return functionToString(it);
};
}
var inspectSource = sharedStore.inspectSource;
var noop = function () { /* empty */ };
var empty = [];
var construct$1 = getBuiltIn('Reflect', 'construct');
var constructorRegExp = /^\s*(?:class|function)\b/;
var exec = functionUncurryThis(constructorRegExp.exec);
var INCORRECT_TO_STRING = !constructorRegExp.exec(noop);
var isConstructorModern = function isConstructor(argument) {
if (!isCallable(argument)) return false;
try {
construct$1(noop, empty, argument);
return true;
} catch (error) {
return false;
}
};
var isConstructorLegacy = function isConstructor(argument) {
if (!isCallable(argument)) return false;
switch (classof(argument)) {
case 'AsyncFunction':
case 'GeneratorFunction':
case 'AsyncGeneratorFunction': return false;
}
try {
// we can't check .prototype since constructors produced by .bind haven't it
// `Function#toString` throws on some built-it function in some legacy engines
// (for example, `DOMQuad` and similar in FF41-)
return INCORRECT_TO_STRING || !!exec(constructorRegExp, inspectSource(argument));
} catch (error) {
return true;
}
};
isConstructorLegacy.sham = true;
// `IsConstructor` abstract operation
// https://tc39.es/ecma262/#sec-isconstructor
var isConstructor = !construct$1 || fails(function () {
var called;
return isConstructorModern(isConstructorModern.call)
|| !isConstructorModern(Object)
|| !isConstructorModern(function () { called = true; })
|| called;
}) ? isConstructorLegacy : isConstructorModern;
var TypeError$7 = global_1.TypeError;
// `Assert: IsConstructor(argument) is true`
var aConstructor = function (argument) {
if (isConstructor(argument)) return argument;
throw TypeError$7(tryToString(argument) + ' is not a constructor');
};
var ceil = Math.ceil;
var floor = Math.floor;
// `Math.trunc` method
// https://tc39.es/ecma262/#sec-math.trunc
// eslint-disable-next-line es-x/no-math-trunc -- safe
var mathTrunc = Math.trunc || function trunc(x) {
var n = +x;
return (n > 0 ? floor : ceil)(n);
};
// `ToIntegerOrInfinity` abstract operation
// https://tc39.es/ecma262/#sec-tointegerorinfinity
var toIntegerOrInfinity = function (argument) {
var number = +argument;
// eslint-disable-next-line no-self-compare -- NaN check
return number !== number || number === 0 ? 0 : mathTrunc(number);
};
var max = Math.max;
var min = Math.min;
// Helper for a popular repeating case of the spec:
// Let integer be ? ToInteger(index).
// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
var toAbsoluteIndex = function (index, length) {
var integer = toIntegerOrInfinity(index);
return integer < 0 ? max(integer + length, 0) : min(integer, length);
};
var min$1 = Math.min;
// `ToLength` abstract operation
// https://tc39.es/ecma262/#sec-tolength
var toLength = function (argument) {
return argument > 0 ? min$1(toIntegerOrInfinity(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
};
// `LengthOfArrayLike` abstract operation
// https://tc39.es/ecma262/#sec-lengthofarraylike
var lengthOfArrayLike = function (obj) {
return toLength(obj.length);
};
// `Array.prototype.{ indexOf, includes }` methods implementation
var createMethod = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIndexedObject($this);
var length = lengthOfArrayLike(O);
var index = toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare -- NaN check
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare -- NaN check
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) {
if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
var arrayIncludes = {
// `Array.prototype.includes` method
// https://tc39.es/ecma262/#sec-array.prototype.includes
includes: createMethod(true),
// `Array.prototype.indexOf` method
// https://tc39.es/ecma262/#sec-array.prototype.indexof
indexOf: createMethod(false)
};
var hiddenKeys = {};
var indexOf = arrayIncludes.indexOf;
var push = functionUncurryThis([].push);
var objectKeysInternal = function (object, names) {
var O = toIndexedObject(object);
var i = 0;
var result = [];
var key;
for (key in O) !hasOwnProperty_1(hiddenKeys, key) && hasOwnProperty_1(O, key) && push(result, key);
// Don't enum bug & hidden keys
while (names.length > i) if (hasOwnProperty_1(O, key = names[i++])) {
~indexOf(result, key) || push(result, key);
}
return result;
};
// IE8- don't enum bug keys
var enumBugKeys = [
'constructor',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toLocaleString',
'toString',
'valueOf'
];
// `Object.keys` method
// https://tc39.es/ecma262/#sec-object.keys
// eslint-disable-next-line es-x/no-object-keys -- safe
var objectKeys = Object.keys || function keys(O) {
return objectKeysInternal(O, enumBugKeys);
};
// `Object.defineProperties` method
// https://tc39.es/ecma262/#sec-object.defineproperties
// eslint-disable-next-line es-x/no-object-defineproperties -- safe
var f$3 = descriptors && !v8PrototypeDefineBug ? Object.defineProperties : function defineProperties(O, Properties) {
anObject(O);
var props = toIndexedObject(Properties);
var keys = objectKeys(Properties);
var length = keys.length;
var index = 0;
var key;
while (length > index) objectDefineProperty.f(O, key = keys[index++], props[key]);
return O;
};
var objectDefineProperties = {
f: f$3
};
var html = getBuiltIn('document', 'documentElement');
var keys = shared('keys');
var sharedKey = function (key) {
return keys[key] || (keys[key] = uid(key));
};
/* global ActiveXObject -- old IE, WSH */
var GT = '>';
var LT = '<';
var PROTOTYPE = 'prototype';
var SCRIPT = 'script';
var IE_PROTO = sharedKey('IE_PROTO');
var EmptyConstructor = function () { /* empty */ };
var scriptTag = function (content) {
return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
};
// Create object with fake `null` prototype: use ActiveX Object with cleared prototype
var NullProtoObjectViaActiveX = function (activeXDocument) {
activeXDocument.write(scriptTag(''));
activeXDocument.close();
var temp = activeXDocument.parentWindow.Object;
activeXDocument = null; // avoid memory leak
return temp;
};
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var NullProtoObjectViaIFrame = function () {
// Thrash, waste and sodomy: IE GC bug
var iframe = documentCreateElement('iframe');
var JS = 'java' + SCRIPT + ':';
var iframeDocument;
iframe.style.display = 'none';
html.appendChild(iframe);
// https://github.com/zloirock/core-js/issues/475
iframe.src = String(JS);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(scriptTag('document.F=Object'));
iframeDocument.close();
return iframeDocument.F;
};
// Check for document.domain and active x support
// No need to use active x approach when document.domain is not set
// see https://github.com/es-shims/es5-shim/issues/150
// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
// avoid IE GC bug
var activeXDocument;
var NullProtoObject = function () {
try {
activeXDocument = new ActiveXObject('htmlfile');
} catch (error) { /* ignore */ }
NullProtoObject = typeof document != 'undefined'
? document.domain && activeXDocument
? NullProtoObjectViaActiveX(activeXDocument) // old IE
: NullProtoObjectViaIFrame()
: NullProtoObjectViaActiveX(activeXDocument); // WSH
var length = enumBugKeys.length;
while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];
return NullProtoObject();
};
hiddenKeys[IE_PROTO] = true;
// `Object.create` method
// https://tc39.es/ecma262/#sec-object.create
// eslint-disable-next-line es-x/no-object-create -- safe
var objectCreate = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
EmptyConstructor[PROTOTYPE] = anObject(O);
result = new EmptyConstructor();
EmptyConstructor[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = NullProtoObject();
return Properties === undefined ? result : objectDefineProperties.f(result, Properties);
};
var nativeConstruct = getBuiltIn('Reflect', 'construct');
var ObjectPrototype = Object.prototype;
var push$1 = [].push;
// `Reflect.construct` method
// https://tc39.es/ecma262/#sec-reflect.construct
// MS Edge supports only 2 arguments and argumentsList argument is optional
// FF Nightly sets third argument as `new.target`, but does not create `this` from it
var NEW_TARGET_BUG = fails(function () {
function F() { /* empty */ }
return !(nativeConstruct(function () { /* empty */ }, [], F) instanceof F);
});
var ARGS_BUG = !fails(function () {
nativeConstruct(function () { /* empty */ });
});
var FORCED = NEW_TARGET_BUG || ARGS_BUG;
_export({ target: 'Reflect', stat: true, forced: FORCED, sham: FORCED }, {
construct: function construct(Target, args /* , newTarget */) {
aConstructor(Target);
anObject(args);
var newTarget = arguments.length < 3 ? Target : aConstructor(arguments[2]);
if (ARGS_BUG && !NEW_TARGET_BUG) return nativeConstruct(Target, args, newTarget);
if (Target == newTarget) {
// w/o altered newTarget, optimization for 0-4 arguments
switch (args.length) {
case 0: return new Target();
case 1: return new Target(args[0]);
case 2: return new Target(args[0], args[1]);
case 3: return new Target(args[0], args[1], args[2]);
case 4: return new Target(args[0], args[1], args[2], args[3]);
}
// w/o altered newTarget, lot of arguments case
var $args = [null];
functionApply(push$1, $args, args);
return new (functionApply(functionBind, Target, $args))();
}
// with altered newTarget, not support built-in constructors
var proto = newTarget.prototype;
var instance = objectCreate(isObject(proto) ? proto : ObjectPrototype);
var result = functionApply(Target, instance, args);
return isObject(result) ? result : instance;
}
});
var construct$2 = path.Reflect.construct;
var construct$3 = construct$2;
var construct$4 = construct$3;
var FAILS_ON_PRIMITIVES = fails(function () { objectKeys(1); });
// `Object.keys` method
// https://tc39.es/ecma262/#sec-object.keys
_export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, {
keys: function keys(it) {
return objectKeys(toObject(it));
}
});
var keys$1 = path.Object.keys;
var keys$2 = keys$1;
var keys$3 = keys$2;
var String$3 = global_1.String;
var toString_1 = function (argument) {
if (classof(argument) === 'Symbol') throw TypeError('Cannot convert a Symbol value to a string');
return String$3(argument);
};
var hiddenKeys$1 = enumBugKeys.concat('length', 'prototype');
// `Object.getOwnPropertyNames` method
// https://tc39.es/ecma262/#sec-object.getownpropertynames
// eslint-disable-next-line es-x/no-object-getownpropertynames -- safe
var f$4 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return objectKeysInternal(O, hiddenKeys$1);
};
var objectGetOwnPropertyNames = {
f: f$4
};
var createProperty = function (object, key, value) {
var propertyKey = toPropertyKey(key);
if (propertyKey in object) objectDefineProperty.f(object, propertyKey, createPropertyDescriptor(0, value));
else object[propertyKey] = value;
};
var Array$1 = global_1.Array;
var max$1 = Math.max;
var arraySliceSimple = function (O, start, end) {
var length = lengthOfArrayLike(O);
var k = toAbsoluteIndex(start, length);
var fin = toAbsoluteIndex(end === undefined ? length : end, length);
var result = Array$1(max$1(fin - k, 0));
for (var n = 0; k < fin; k++, n++) createProperty(result, n, O[k]);
result.length = n;
return result;
};
/* eslint-disable es-x/no-object-getownpropertynames -- safe */
var $getOwnPropertyNames = objectGetOwnPropertyNames.f;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function (it) {
try {
return $getOwnPropertyNames(it);
} catch (error) {
return arraySliceSimple(windowNames);
}
};
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var f$5 = function getOwnPropertyNames(it) {
return windowNames && classofRaw(it) == 'Window'
? getWindowNames(it)
: $getOwnPropertyNames(toIndexedObject(it));
};
var objectGetOwnPropertyNamesExternal = {
f: f$5
};
// eslint-disable-next-line es-x/no-object-getownpropertysymbols -- safe
var f$6 = Object.getOwnPropertySymbols;
var objectGetOwnPropertySymbols = {
f: f$6
};
var defineBuiltIn = function (target, key, value, options) {
if (options && options.enumerable) target[key] = value;
else createNonEnumerableProperty(target, key, value);
return target;
};
var f$7 = wellKnownSymbol;
var wellKnownSymbolWrapped = {
f: f$7
};
var defineProperty$1 = objectDefineProperty.f;
var defineWellKnownSymbol = function (NAME) {
var Symbol = path.Symbol || (path.Symbol = {});
if (!hasOwnProperty_1(Symbol, NAME)) defineProperty$1(Symbol, NAME, {
value: wellKnownSymbolWrapped.f(NAME)
});
};
var symbolDefineToPrimitive = function () {
var Symbol = getBuiltIn('Symbol');
var SymbolPrototype = Symbol && Symbol.prototype;
var valueOf = SymbolPrototype && SymbolPrototype.valueOf;
var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
if (SymbolPrototype && !SymbolPrototype[TO_PRIMITIVE]) {
// `Symbol.prototype[@@toPrimitive]` method
// https://tc39.es/ecma262/#sec-symbol.prototype-@@toprimitive
// eslint-disable-next-line no-unused-vars -- required for .length
defineBuiltIn(SymbolPrototype, TO_PRIMITIVE, function (hint) {
return functionCall(valueOf, this);
}, { arity: 1 });
}
};
// `Object.prototype.toString` method implementation
// https://tc39.es/ecma262/#sec-object.prototype.tostring
var objectToString = toStringTagSupport ? {}.toString : function toString() {
return '[object ' + classof(this) + ']';
};
var defineProperty$2 = objectDefineProperty.f;
var TO_STRING_TAG$2 = wellKnownSymbol('toStringTag');
var setToStringTag = function (it, TAG, STATIC, SET_METHOD) {
if (it) {
var target = STATIC ? it : it.prototype;
if (!hasOwnProperty_1(target, TO_STRING_TAG$2)) {
defineProperty$2(target, TO_STRING_TAG$2, { configurable: true, value: TAG });
}
if (SET_METHOD && !toStringTagSupport) {
createNonEnumerableProperty(target, 'toString', objectToString);
}
}
};
var WeakMap = global_1.WeakMap;
var nativeWeakMap = isCallable(WeakMap) && /native code/.test(inspectSource(WeakMap));
var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
var TypeError$8 = global_1.TypeError;
var WeakMap$1 = global_1.WeakMap;
var set, get, has;
var enforce = function (it) {
return has(it) ? get(it) : set(it, {});
};
var getterFor = function (TYPE) {
return function (it) {
var state;
if (!isObject(it) || (state = get(it)).type !== TYPE) {
throw TypeError$8('Incompatible receiver, ' + TYPE + ' required');
} return state;
};
};
if (nativeWeakMap || sharedStore.state) {
var store$1 = sharedStore.state || (sharedStore.state = new WeakMap$1());
var wmget = functionUncurryThis(store$1.get);
var wmhas = functionUncurryThis(store$1.has);
var wmset = functionUncurryThis(store$1.set);
set = function (it, metadata) {
if (wmhas(store$1, it)) throw new TypeError$8(OBJECT_ALREADY_INITIALIZED);
metadata.facade = it;
wmset(store$1, it, metadata);
return metadata;
};
get = function (it) {
return wmget(store$1, it) || {};
};
has = function (it) {
return wmhas(store$1, it);
};
} else {
var STATE = sharedKey('state');
hiddenKeys[STATE] = true;
set = function (it, metadata) {
if (hasOwnProperty_1(it, STATE)) throw new TypeError$8(OBJECT_ALREADY_INITIALIZED);
metadata.facade = it;
createNonEnumerableProperty(it, STATE, metadata);
return metadata;
};
get = function (it) {
return hasOwnProperty_1(it, STATE) ? it[STATE] : {};
};
has = function (it) {
return hasOwnProperty_1(it, STATE);
};
}
var internalState = {
set: set,
get: get,
has: has,
enforce: enforce,
getterFor: getterFor
};
// `IsArray` abstract operation
// https://tc39.es/ecma262/#sec-isarray
// eslint-disable-next-line es-x/no-array-isarray -- safe
var isArray = Array.isArray || function isArray(argument) {
return classofRaw(argument) == 'Array';
};
var SPECIES = wellKnownSymbol('species');
var Array$2 = global_1.Array;
// a part of `ArraySpeciesCreate` abstract operation
// https://tc39.es/ecma262/#sec-arrayspeciescreate
var arraySpeciesConstructor = function (originalArray) {
var C;
if (isArray(originalArray)) {
C = originalArray.constructor;
// cross-realm fallback
if (isConstructor(C) && (C === Array$2 || isArray(C.prototype))) C = undefined;
else if (isObject(C)) {
C = C[SPECIES];
if (C === null) C = undefined;
}
} return C === undefined ? Array$2 : C;
};
// `ArraySpeciesCreate` abstract operation
// https://tc39.es/ecma262/#sec-arrayspeciescreate
var arraySpeciesCreate = function (originalArray, length) {
return new (arraySpeciesConstructor(originalArray))(length === 0 ? 0 : length);
};
var push$2 = functionUncurryThis([].push);
// `Array.prototype.{ forEach, map, filter, some, every, find, findIndex, filterReject }` methods implementation
var createMethod$1 = function (TYPE) {
var IS_MAP = TYPE == 1;
var IS_FILTER = TYPE == 2;
var IS_SOME = TYPE == 3;
var IS_EVERY = TYPE == 4;
var IS_FIND_INDEX = TYPE == 6;
var IS_FILTER_REJECT = TYPE == 7;
var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
return function ($this, callbackfn, that, specificCreate) {
var O = toObject($this);
var self = indexedObject(O);
var boundFunction = functionBindContext(callbackfn, that);
var length = lengthOfArrayLike(self);
var index = 0;
var create = specificCreate || arraySpeciesCreate;
var target = IS_MAP ? create($this, length) : IS_FILTER || IS_FILTER_REJECT ? create($this, 0) : undefined;
var value, result;
for (;length > index; index++) if (NO_HOLES || index in self) {
value = self[index];
result = boundFunction(value, index, O);
if (TYPE) {
if (IS_MAP) target[index] = result; // map
else if (result) switch (TYPE) {
case 3: return true; // some
case 5: return value; // find
case 6: return index; // findIndex
case 2: push$2(target, value); // filter
} else switch (TYPE) {
case 4: return false; // every
case 7: push$2(target, value); // filterReject
}
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target;
};
};
var arrayIteration = {
// `Array.prototype.forEach` method
// https://tc39.es/ecma262/#sec-array.prototype.foreach
forEach: createMethod$1(0),
// `Array.prototype.map` method
// https://tc39.es/ecma262/#sec-array.prototype.map
map: createMethod$1(1),
// `Array.prototype.filter` method
// https://tc39.es/ecma262/#sec-array.prototype.filter
filter: createMethod$1(2),
// `Array.prototype.some` method
// https://tc39.es/ecma262/#sec-array.prototype.some
some: createMethod$1(3),
// `Array.prototype.every` method
// https://tc39.es/ecma262/#sec-array.prototype.every
every: createMethod$1(4),
// `Array.prototype.find` method
// https://tc39.es/ecma262/#sec-array.prototype.find
find: createMethod$1(5),
// `Array.prototype.findIndex` method
// https://tc39.es/ecma262/#sec-array.prototype.findIndex
findIndex: createMethod$1(6),
// `Array.prototype.filterReject` method
// https://github.com/tc39/proposal-array-filtering
filterReject: createMethod$1(7)
};
var $forEach = arrayIteration.forEach;
var HIDDEN = sharedKey('hidden');
var SYMBOL = 'Symbol';
var PROTOTYPE$1 = 'prototype';
var setInternalState = internalState.set;
var getInternalState = internalState.getterFor(SYMBOL);
var ObjectPrototype$1 = Object[PROTOTYPE$1];
var $Symbol = global_1.Symbol;
var SymbolPrototype = $Symbol && $Symbol[PROTOTYPE$1];
var TypeError$9 = global_1.TypeError;
var QObject = global_1.QObject;
var nativeGetOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;
var nativeDefineProperty = objectDefineProperty.f;
var nativeGetOwnPropertyNames = objectGetOwnPropertyNamesExternal.f;
var nativePropertyIsEnumerable = objectPropertyIsEnumerable.f;
var push$3 = functionUncurryThis([].push);
var AllSymbols = shared('symbols');
var ObjectPrototypeSymbols = shared('op-symbols');
var WellKnownSymbolsStore$1 = shared('wks');
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var USE_SETTER = !QObject || !QObject[PROTOTYPE$1] || !QObject[PROTOTYPE$1].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDescriptor = descriptors && fails(function () {
return objectCreate(nativeDefineProperty({}, 'a', {
get: function () { return nativeDefineProperty(this, 'a', { value: 7 }).a; }
})).a != 7;
}) ? function (O, P, Attributes) {
var ObjectPrototypeDescriptor = nativeGetOwnPropertyDescriptor(ObjectPrototype$1, P);
if (ObjectPrototypeDescriptor) delete ObjectPrototype$1[P];
nativeDefineProperty(O, P, Attributes);
if (ObjectPrototypeDescriptor && O !== ObjectPrototype$1) {
nativeDefineProperty(ObjectPrototype$1, P, ObjectPrototypeDescriptor);
}
} : nativeDefineProperty;
var wrap = function (tag, description) {
var symbol = AllSymbols[tag] = objectCreate(SymbolPrototype);
setInternalState(symbol, {
type: SYMBOL,
tag: tag,
description: description
});
if (!descriptors) symbol.description = description;
return symbol;
};
var $defineProperty$1 = function defineProperty(O, P, Attributes) {
if (O === ObjectPrototype$1) $defineProperty$1(ObjectPrototypeSymbols, P, Attributes);
anObject(O);
var key = toPropertyKey(P);
anObject(Attributes);
if (hasOwnProperty_1(AllSymbols, key)) {
if (!Attributes.enumerable) {
if (!hasOwnProperty_1(O, HIDDEN)) nativeDefineProperty(O, HIDDEN, createPropertyDescriptor(1, {}));
O[HIDDEN][key] = true;
} else {
if (hasOwnProperty_1(O, HIDDEN) && O[HIDDEN][key]) O[HIDDEN][key] = false;
Attributes = objectCreate(Attributes, { enumerable: createPropertyDescriptor(0, false) });
} return setSymbolDescriptor(O, key, Attributes);
} return nativeDefineProperty(O, key, Attributes);
};
var $defineProperties = function defineProperties(O, Properties) {
anObject(O);
var properties = toIndexedObject(Properties);
var keys = objectKeys(properties).concat($getOwnPropertySymbols(properties));
$forEach(keys, function (key) {
if (!descriptors || functionCall($propertyIsEnumerable$1, properties, key)) $defineProperty$1(O, key, properties[key]);
});
return O;
};
var $create = function create(O, Properties) {
return Properties === undefined ? objectCreate(O) : $defineProperties(objectCreate(O), Properties);
};
var $propertyIsEnumerable$1 = function propertyIsEnumerable(V) {
var P = toPropertyKey(V);
var enumerable = functionCall(nativePropertyIsEnumerable, this, P);
if (this === ObjectPrototype$1 && hasOwnProperty_1(AllSymbols, P) && !hasOwnProperty_1(ObjectPrototypeSymbols, P)) return false;
return enumerable || !hasOwnProperty_1(this, P) || !hasOwnProperty_1(AllSymbols, P) || hasOwnProperty_1(this, HIDDEN) && this[HIDDEN][P]
? enumerable : true;
};
var $getOwnPropertyDescriptor$2 = function getOwnPropertyDescriptor(O, P) {
var it = toIndexedObject(O);
var key = toPropertyKey(P);
if (it === ObjectPrototype$1 && hasOwnProperty_1(AllSymbols, key) && !hasOwnProperty_1(ObjectPrototypeSymbols, key)) return;
var descriptor = nativeGetOwnPropertyDescriptor(it, key);
if (descriptor && hasOwnProperty_1(AllSymbols, key) && !(hasOwnProperty_1(it, HIDDEN) && it[HIDDEN][key])) {
descriptor.enumerable = true;
}
return descriptor;
};
var $getOwnPropertyNames$1 = function getOwnPropertyNames(O) {
var names = nativeGetOwnPropertyNames(toIndexedObject(O));
var result = [];
$forEach(names, function (key) {
if (!hasOwnProperty_1(AllSymbols, key) && !hasOwnProperty_1(hiddenKeys, key)) push$3(result, key);
});
return result;
};
var $getOwnPropertySymbols = function (O) {
var IS_OBJECT_PROTOTYPE = O === ObjectPrototype$1;
var names = nativeGetOwnPropertyNames(IS_OBJECT_PROTOTYPE ? ObjectPrototypeSymbols : toIndexedObject(O));
var result = [];
$forEach(names, function (key) {
if (hasOwnProperty_1(AllSymbols, key) && (!IS_OBJECT_PROTOTYPE || hasOwnProperty_1(ObjectPrototype$1, key))) {
push$3(result, AllSymbols[key]);
}
});
return result;
};
// `Symbol` constructor
// https://tc39.es/ecma262/#sec-symbol-constructor
if (!nativeSymbol) {
$Symbol = function Symbol() {
if (objectIsPrototypeOf(SymbolPrototype, this)) throw TypeError$9('Symbol is not a constructor');
var description = !arguments.length || arguments[0] === undefined ? undefined : toString_1(arguments[0]);
var tag = uid(description);
var setter = function (value) {
if (this === ObjectPrototype$1) functionCall(setter, ObjectPrototypeSymbols, value);
if (hasOwnProperty_1(this, HIDDEN) && hasOwnProperty_1(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
setSymbolDescriptor(this, tag, createPropertyDescriptor(1, value));
};
if (descriptors && USE_SETTER) setSymbolDescriptor(ObjectPrototype$1, tag, { configurable: true, set: setter });
return wrap(tag, description);
};
SymbolPrototype = $Symbol[PROTOTYPE$1];
defineBuiltIn(SymbolPrototype, 'toString', function toString() {
return getInternalState(this).tag;
});
defineBuiltIn($Symbol, 'withoutSetter', function (description) {
return wrap(uid(description), description);
});
objectPropertyIsEnumerable.f = $propertyIsEnumerable$1;
objectDefineProperty.f = $defineProperty$1;
objectDefineProperties.f = $defineProperties;
objectGetOwnPropertyDescriptor.f = $getOwnPropertyDescriptor$2;
objectGetOwnPropertyNames.f = objectGetOwnPropertyNamesExternal.f = $getOwnPropertyNames$1;
objectGetOwnPropertySymbols.f = $getOwnPropertySymbols;
wellKnownSymbolWrapped.f = function (name) {
return wrap(wellKnownSymbol(name), name);
};
if (descriptors) {
// https://github.com/tc39/proposal-Symbol-description
nativeDefineProperty(SymbolPrototype, 'description', {
configurable: true,
get: function description() {
return getInternalState(this).description;
}
});
}
}
_export({ global: true, constructor: true, wrap: true, forced: !nativeSymbol, sham: !nativeSymbol }, {
Symbol: $Symbol
});
$forEach(objectKeys(WellKnownSymbolsStore$1), function (name) {
defineWellKnownSymbol(name);
});
_export({ target: SYMBOL, stat: true, forced: !nativeSymbol }, {
useSetter: function () { USE_SETTER = true; },
useSimple: function () { USE_SETTER = false; }
});
_export({ target: 'Object', stat: true, forced: !nativeSymbol, sham: !descriptors }, {
// `Object.create` method
// https://tc39.es/ecma262/#sec-object.create
create: $create,
// `Object.defineProperty` method
// https://tc39.es/ecma262/#sec-object.defineproperty
defineProperty: $defineProperty$1,
// `Object.defineProperties` method
// https://tc39.es/ecma262/#sec-object.defineproperties
defineProperties: $defineProperties,
// `Object.getOwnPropertyDescriptor` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptors
getOwnPropertyDescriptor: $getOwnPropertyDescriptor$2
});
_export({ target: 'Object', stat: true, forced: !nativeSymbol }, {
// `Object.getOwnPropertyNames` method
// https://tc39.es/ecma262/#sec-object.getownpropertynames
getOwnPropertyNames: $getOwnPropertyNames$1
});
// `Symbol.prototype[@@toPrimitive]` method
// https://tc39.es/ecma262/#sec-symbol.prototype-@@toprimitive
symbolDefineToPrimitive();
// `Symbol.prototype[@@toStringTag]` property
// https://tc39.es/ecma262/#sec-symbol.prototype-@@tostringtag
setToStringTag($Symbol, SYMBOL);
hiddenKeys[HIDDEN] = true;
/* eslint-disable es-x/no-symbol -- safe */
var nativeSymbolRegistry = nativeSymbol && !!Symbol['for'] && !!Symbol.keyFor;
var StringToSymbolRegistry = shared('string-to-symbol-registry');
var SymbolToStringRegistry = shared('symbol-to-string-registry');
// `Symbol.for` method
// https://tc39.es/ecma262/#sec-symbol.for
_export({ target: 'Symbol', stat: true, forced: !nativeSymbolRegistry }, {
'for': function (key) {
var string = toString_1(key);
if (hasOwnProperty_1(StringToSymbolRegistry, string)) return StringToSymbolRegistry[string];
var symbol = getBuiltIn('Symbol')(string);
StringToSymbolRegistry[string] = symbol;
SymbolToStringRegistry[symbol] = string;
return symbol;
}
});
var SymbolToStringRegistry$1 = shared('symbol-to-string-registry');
// `Symbol.keyFor` method
// https://tc39.es/ecma262/#sec-symbol.keyfor
_export({ target: 'Symbol', stat: true, forced: !nativeSymbolRegistry }, {
keyFor: function keyFor(sym) {
if (!isSymbol(sym)) throw TypeError(tryToString(sym) + ' is not a symbol');
if (hasOwnProperty_1(SymbolToStringRegistry$1, sym)) return SymbolToStringRegistry$1[sym];
}
});
var $stringify = getBuiltIn('JSON', 'stringify');
var exec$1 = functionUncurryThis(/./.exec);
var charAt = functionUncurryThis(''.charAt);
var charCodeAt = functionUncurryThis(''.charCodeAt);
var replace = functionUncurryThis(''.replace);
var numberToString = functionUncurryThis(1.0.toString);
var tester = /[\uD800-\uDFFF]/g;
var low = /^[\uD800-\uDBFF]$/;
var hi = /^[\uDC00-\uDFFF]$/;
var WRONG_SYMBOLS_CONVERSION = !nativeSymbol || fails(function () {
var symbol = getBuiltIn('Symbol')();
// MS Edge converts symbol values to JSON as {}
return $stringify([symbol]) != '[null]'
// WebKit converts symbol values to JSON as null
|| $stringify({ a: symbol }) != '{}'
// V8 throws on boxed symbols
|| $stringify(Object(symbol)) != '{}';
});
// https://github.com/tc39/proposal-well-formed-stringify
var ILL_FORMED_UNICODE = fails(function () {
return $stringify('\uDF06\uD834') !== '"\\udf06\\ud834"'
|| $stringify('\uDEAD') !== '"\\udead"';
});
var stringifyWithSymbolsFix = function (it, replacer) {
var args = arraySlice(arguments);
var $replacer = replacer;
if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
if (!isArray(replacer)) replacer = function (key, value) {
if (isCallable($replacer)) value = functionCall($replacer, this, key, value);
if (!isSymbol(value)) return value;
};
args[1] = replacer;
return functionApply($stringify, null, args);
};
var fixIllFormed = function (match, offset, string) {
var prev = charAt(string, offset - 1);
var next = charAt(string, offset + 1);
if ((exec$1(low, match) && !exec$1(hi, next)) || (exec$1(hi, match) && !exec$1(low, prev))) {
return '\\u' + numberToString(charCodeAt(match, 0), 16);
} return match;
};
if ($stringify) {
// `JSON.stringify` method
// https://tc39.es/ecma262/#sec-json.stringify
_export({ target: 'JSON', stat: true, arity: 3, forced: WRONG_SYMBOLS_CONVERSION || ILL_FORMED_UNICODE }, {
// eslint-disable-next-line no-unused-vars -- required for `.length`
stringify: function stringify(it, replacer, space) {
var args = arraySlice(arguments);
var result = functionApply(WRONG_SYMBOLS_CONVERSION ? stringifyWithSymbolsFix : $stringify, null, args);
return ILL_FORMED_UNICODE && typeof result == 'string' ? replace(result, tester, fixIllFormed) : result;
}
});
}
// V8 ~ Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives
// https://bugs.chromium.org/p/v8/issues/detail?id=3443
var FORCED$1 = !nativeSymbol || fails(function () { objectGetOwnPropertySymbols.f(1); });
// `Object.getOwnPropertySymbols` method
// https://tc39.es/ecma262/#sec-object.getownpropertysymbols
_export({ target: 'Object', stat: true, forced: FORCED$1 }, {
getOwnPropertySymbols: function getOwnPropertySymbols(it) {
var $getOwnPropertySymbols = objectGetOwnPropertySymbols.f;
return $getOwnPropertySymbols ? $getOwnPropertySymbols(toObject(it)) : [];
}
});
var getOwnPropertySymbols = path.Object.getOwnPropertySymbols;
var getOwnPropertySymbols$1 = getOwnPropertySymbols;
var getOwnPropertySymbols$2 = getOwnPropertySymbols$1;
var SPECIES$1 = wellKnownSymbol('species');
var arrayMethodHasSpeciesSupport = function (METHOD_NAME) {
// We can't use this feature detection in V8 since it causes
// deoptimization and serious performance degradation
// https://github.com/zloirock/core-js/issues/677
return engineV8Version >= 51 || !fails(function () {
var array = [];
var constructor = array.constructor = {};
constructor[SPECIES$1] = function () {
return { foo: 1 };
};
return array[METHOD_NAME](Boolean).foo !== 1;
});
};
var $filter = arrayIteration.filter;
var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('filter');
// `Array.prototype.filter` method
// https://tc39.es/ecma262/#sec-array.prototype.filter
// with adding support of @@species
_export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT }, {
filter: function filter(callbackfn /* , thisArg */) {
return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
var entryVirtual = function (CONSTRUCTOR) {
return path[CONSTRUCTOR + 'Prototype'];
};
var filter = entryVirtual('Array').filter;
var ArrayPrototype = Array.prototype;
var filter$1 = function (it) {
var own = it.filter;
return it === ArrayPrototype || (objectIsPrototypeOf(ArrayPrototype, it) && own === ArrayPrototype.filter) ? filter : own;
};
var filter$2 = filter$1;
var filter$3 = filter$2;
var nativeGetOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;
var FAILS_ON_PRIMITIVES$1 = fails(function () { nativeGetOwnPropertyDescriptor$1(1); });
var FORCED$2 = !descriptors || FAILS_ON_PRIMITIVES$1;
// `Object.getOwnPropertyDescriptor` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
_export({ target: 'Object', stat: true, forced: FORCED$2, sham: !descriptors }, {
getOwnPropertyDescriptor: function getOwnPropertyDescriptor(it, key) {
return nativeGetOwnPropertyDescriptor$1(toIndexedObject(it), key);
}
});
var getOwnPropertyDescriptor_1 = createCommonjsModule(function (module) {
var Object = path.Object;
var getOwnPropertyDescriptor = module.exports = function getOwnPropertyDescriptor(it, key) {
return Object.getOwnPropertyDescriptor(it, key);
};
if (Object.getOwnPropertyDescriptor.sham) getOwnPropertyDescriptor.sham = true;
});
var getOwnPropertyDescriptor$2 = getOwnPropertyDescriptor_1;
var getOwnPropertyDescriptor$3 = getOwnPropertyDescriptor$2;
var iterators = {};
var FunctionPrototype$2 = Function.prototype;
// eslint-disable-next-line es-x/no-object-getownpropertydescriptor -- safe
var getDescriptor = descriptors && Object.getOwnPropertyDescriptor;
var EXISTS$1 = hasOwnProperty_1(FunctionPrototype$2, 'name');
// additional protection from minified / mangled / dropped function names
var PROPER = EXISTS$1 && (function something() { /* empty */ }).name === 'something';
var CONFIGURABLE$1 = EXISTS$1 && (!descriptors || (descriptors && getDescriptor(FunctionPrototype$2, 'name').configurable));
var functionName = {
EXISTS: EXISTS$1,
PROPER: PROPER,
CONFIGURABLE: CONFIGURABLE$1
};
var correctPrototypeGetter = !fails(function () {
function F() { /* empty */ }
F.prototype.constructor = null;
// eslint-disable-next-line es-x/no-object-getprototypeof -- required for testing
return Object.getPrototypeOf(new F()) !== F.prototype;
});
var IE_PROTO$1 = sharedKey('IE_PROTO');
var Object$5 = global_1.Object;
var ObjectPrototype$2 = Object$5.prototype;
// `Object.getPrototypeOf` method
// https://tc39.es/ecma262/#sec-object.getprototypeof
var objectGetPrototypeOf = correctPrototypeGetter ? Object$5.getPrototypeOf : function (O) {
var object = toObject(O);
if (hasOwnProperty_1(object, IE_PROTO$1)) return object[IE_PROTO$1];
var constructor = object.constructor;
if (isCallable(constructor) && object instanceof constructor) {
return constructor.prototype;
} return object instanceof Object$5 ? ObjectPrototype$2 : null;
};
var ITERATOR = wellKnownSymbol('iterator');
var BUGGY_SAFARI_ITERATORS = false;
// `%IteratorPrototype%` object
// https://tc39.es/ecma262/#sec-%iteratorprototype%-object
var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;
/* eslint-disable es-x/no-array-prototype-keys -- safe */
if ([].keys) {
arrayIterator = [].keys();
// Safari 8 has buggy iterators w/o `next`
if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;
else {
PrototypeOfArrayIteratorPrototype = objectGetPrototypeOf(objectGetPrototypeOf(arrayIterator));
if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
}
}
var NEW_ITERATOR_PROTOTYPE = IteratorPrototype == undefined || fails(function () {
var test = {};
// FF44- legacy iterators case
return IteratorPrototype[ITERATOR].call(test) !== test;
});
if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype = {};
else IteratorPrototype = objectCreate(IteratorPrototype);
// `%IteratorPrototype%[@@iterator]()` method
// https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator
if (!isCallable(IteratorPrototype[ITERATOR])) {
defineBuiltIn(IteratorPrototype, ITERATOR, function () {
return this;
});
}
var iteratorsCore = {
IteratorPrototype: IteratorPrototype,
BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
};
var IteratorPrototype$1 = iteratorsCore.IteratorPrototype;
var returnThis = function () { return this; };
var createIteratorConstructor = function (IteratorConstructor, NAME, next, ENUMERABLE_NEXT) {
var TO_STRING_TAG = NAME + ' Iterator';
IteratorConstructor.prototype = objectCreate(IteratorPrototype$1, { next: createPropertyDescriptor(+!ENUMERABLE_NEXT, next) });
setToStringTag(IteratorConstructor, TO_STRING_TAG, false, true);
iterators[TO_STRING_TAG] = returnThis;
return IteratorConstructor;
};
var String$4 = global_1.String;
var TypeError$a = global_1.TypeError;
var aPossiblePrototype = function (argument) {
if (typeof argument == 'object' || isCallable(argument)) return argument;
throw TypeError$a("Can't set " + String$4(argument) + ' as a prototype');
};
/* eslint-disable no-proto -- safe */
// `Object.setPrototypeOf` method
// https://tc39.es/ecma262/#sec-object.setprototypeof
// Works with __proto__ only. Old v8 can't work with null proto objects.
// eslint-disable-next-line es-x/no-object-setprototypeof -- safe
var objectSetPrototypeOf = Object.setPrototypeOf || ('__proto__' in {} ? function () {
var CORRECT_SETTER = false;
var test = {};
var setter;
try {
// eslint-disable-next-line es-x/no-object-getownpropertydescriptor -- safe
setter = functionUncurryThis(Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set);
setter(test, []);
CORRECT_SETTER = test instanceof Array;
} catch (error) { /* empty */ }
return function setPrototypeOf(O, proto) {
anObject(O);
aPossiblePrototype(proto);
if (CORRECT_SETTER) setter(O, proto);
else O.__proto__ = proto;
return O;
};
}() : undefined);
var PROPER_FUNCTION_NAME = functionName.PROPER;
var BUGGY_SAFARI_ITERATORS$1 = iteratorsCore.BUGGY_SAFARI_ITERATORS;
var ITERATOR$1 = wellKnownSymbol('iterator');
var KEYS = 'keys';
var VALUES = 'values';
var ENTRIES = 'entries';
var returnThis$1 = function () { return this; };
var defineIterator = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {
createIteratorConstructor(IteratorConstructor, NAME, next);
var getIterationMethod = function (KIND) {
if (KIND === DEFAULT && defaultIterator) return defaultIterator;
if (!BUGGY_SAFARI_ITERATORS$1 && KIND in IterablePrototype) return IterablePrototype[KIND];
switch (KIND) {
case KEYS: return function keys() { return new IteratorConstructor(this, KIND); };
case VALUES: return function values() { return new IteratorConstructor(this, KIND); };
case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); };
} return function () { return new IteratorConstructor(this); };
};
var TO_STRING_TAG = NAME + ' Iterator';
var INCORRECT_VALUES_NAME = false;
var IterablePrototype = Iterable.prototype;
var nativeIterator = IterablePrototype[ITERATOR$1]
|| IterablePrototype['@@iterator']
|| DEFAULT && IterablePrototype[DEFAULT];
var defaultIterator = !BUGGY_SAFARI_ITERATORS$1 && nativeIterator || getIterationMethod(DEFAULT);
var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator;
var CurrentIteratorPrototype, methods, KEY;
// fix native
if (anyNativeIterator) {
CurrentIteratorPrototype = objectGetPrototypeOf(anyNativeIterator.call(new Iterable()));
if (CurrentIteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) {
// Set @@toStringTag to native iterators
setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true);
iterators[TO_STRING_TAG] = returnThis$1;
}
}
// fix Array.prototype.{ values, @@iterator }.name in V8 / FF
if (PROPER_FUNCTION_NAME && DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {
{
INCORRECT_VALUES_NAME = true;
defaultIterator = function values() { return functionCall(nativeIterator, this); };
}
}
// export additional methods
if (DEFAULT) {
methods = {
values: getIterationMethod(VALUES),
keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),
entries: getIterationMethod(ENTRIES)
};
if (FORCED) for (KEY in methods) {
if (BUGGY_SAFARI_ITERATORS$1 || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) {
defineBuiltIn(IterablePrototype, KEY, methods[KEY]);
}
} else _export({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS$1 || INCORRECT_VALUES_NAME }, methods);
}
// define iterator
if (( FORCED) && IterablePrototype[ITERATOR$1] !== defaultIterator) {
defineBuiltIn(IterablePrototype, ITERATOR$1, defaultIterator, { name: DEFAULT });
}
iterators[NAME] = defaultIterator;
return methods;
};
var ARRAY_ITERATOR = 'Array Iterator';
var setInternalState$1 = internalState.set;
var getInternalState$1 = internalState.getterFor(ARRAY_ITERATOR);
// `Array.prototype.entries` method
// https://tc39.es/ecma262/#sec-array.prototype.entries
// `Array.prototype.keys` method
// https://tc39.es/ecma262/#sec-array.prototype.keys
// `Array.prototype.values` method
// https://tc39.es/ecma262/#sec-array.prototype.values
// `Array.prototype[@@iterator]` method
// https://tc39.es/ecma262/#sec-array.prototype-@@iterator
// `CreateArrayIterator` internal method
// https://tc39.es/ecma262/#sec-createarrayiterator
var es_array_iterator = defineIterator(Array, 'Array', function (iterated, kind) {
setInternalState$1(this, {
type: ARRAY_ITERATOR,
target: toIndexedObject(iterated), // target
index: 0, // next index
kind: kind // kind
});
// `%ArrayIteratorPrototype%.next` method
// https://tc39.es/ecma262/#sec-%arrayiteratorprototype%.next
}, function () {
var state = getInternalState$1(this);
var target = state.target;
var kind = state.kind;
var index = state.index++;
if (!target || index >= target.length) {
state.target = undefined;
return { value: undefined, done: true };
}
if (kind == 'keys') return { value: index, done: false };
if (kind == 'values') return { value: target[index], done: false };
return { value: [index, target[index]], done: false };
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values%
// https://tc39.es/ecma262/#sec-createunmappedargumentsobject
// https://tc39.es/ecma262/#sec-createmappedargumentsobject
var values = iterators.Arguments = iterators.Array;
// iterable DOM collections
// flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods
var domIterables = {
CSSRuleList: 0,
CSSStyleDeclaration: 0,
CSSValueList: 0,
ClientRectList: 0,
DOMRectList: 0,
DOMStringList: 0,
DOMTokenList: 1,
DataTransferItemList: 0,
FileList: 0,
HTMLAllCollection: 0,
HTMLCollection: 0,
HTMLFormElement: 0,
HTMLSelectElement: 0,
MediaList: 0,
MimeTypeArray: 0,
NamedNodeMap: 0,
NodeList: 1,
PaintRequestList: 0,
Plugin: 0,
PluginArray: 0,
SVGLengthList: 0,
SVGNumberList: 0,
SVGPathSegList: 0,
SVGPointList: 0,
SVGStringList: 0,
SVGTransformList: 0,
SourceBufferList: 0,
StyleSheetList: 0,
TextTrackCueList: 0,
TextTrackList: 0,
TouchList: 0
};
var TO_STRING_TAG$3 = wellKnownSymbol('toStringTag');
for (var COLLECTION_NAME in domIterables) {
var Collection = global_1[COLLECTION_NAME];
var CollectionPrototype = Collection && Collection.prototype;
if (CollectionPrototype && classof(CollectionPrototype) !== TO_STRING_TAG$3) {
createNonEnumerableProperty(CollectionPrototype, TO_STRING_TAG$3, COLLECTION_NAME);
}
iterators[COLLECTION_NAME] = iterators.Array;
}
var arrayMethodIsStrict = function (METHOD_NAME, argument) {
var method = [][METHOD_NAME];
return !!method && fails(function () {
// eslint-disable-next-line no-useless-call -- required for testing
method.call(null, argument || function () { return 1; }, 1);
});
};
var $forEach$1 = arrayIteration.forEach;
var STRICT_METHOD = arrayMethodIsStrict('forEach');
// `Array.prototype.forEach` method implementation
// https://tc39.es/ecma262/#sec-array.prototype.foreach
var arrayForEach = !STRICT_METHOD ? function forEach(callbackfn /* , thisArg */) {
return $forEach$1(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
// eslint-disable-next-line es-x/no-array-prototype-foreach -- safe
} : [].forEach;
// `Array.prototype.forEach` method
// https://tc39.es/ecma262/#sec-array.prototype.foreach
// eslint-disable-next-line es-x/no-array-prototype-foreach -- safe
_export({ target: 'Array', proto: true, forced: [].forEach != arrayForEach }, {
forEach: arrayForEach
});
var forEach = entryVirtual('Array').forEach;
var forEach$1 = forEach;
var ArrayPrototype$1 = Array.prototype;
var DOMIterables = {
DOMTokenList: true,
NodeList: true
};
var forEach$2 = function (it) {
var own = it.forEach;
return it === ArrayPrototype$1 || (objectIsPrototypeOf(ArrayPrototype$1, it) && own === ArrayPrototype$1.forEach)
|| hasOwnProperty_1(DOMIterables, classof(it)) ? forEach$1 : own;
};
var forEach$3 = forEach$2;
var concat$1 = functionUncurryThis([].concat);
// all object keys, includes non-enumerable and symbols
var ownKeys = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
var keys = objectGetOwnPropertyNames.f(anObject(it));
var getOwnPropertySymbols = objectGetOwnPropertySymbols.f;
return getOwnPropertySymbols ? concat$1(keys, getOwnPropertySymbols(it)) : keys;
};
// `Object.getOwnPropertyDescriptors` method
// https://tc39.es/ecma262/#sec-object.getownpropertydescriptors
_export({ target: 'Object', stat: true, sham: !descriptors }, {
getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) {
var O = toIndexedObject(object);
var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;
var keys = ownKeys(O);
var result = {};
var index = 0;
var key, descriptor;
while (keys.length > index) {
descriptor = getOwnPropertyDescriptor(O, key = keys[index++]);
if (descriptor !== undefined) createProperty(result, key, descriptor);
}
return result;
}
});
var getOwnPropertyDescriptors = path.Object.getOwnPropertyDescriptors;
var getOwnPropertyDescriptors$1 = getOwnPropertyDescriptors;
var getOwnPropertyDescriptors$2 = getOwnPropertyDescriptors$1;
var defineProperties = objectDefineProperties.f;
// `Object.defineProperties` method
// https://tc39.es/ecma262/#sec-object.defineproperties
// eslint-disable-next-line es-x/no-object-defineproperties -- safe
_export({ target: 'Object', stat: true, forced: Object.defineProperties !== defineProperties, sham: !descriptors }, {
defineProperties: defineProperties
});
var defineProperties_1 = createCommonjsModule(function (module) {
var Object = path.Object;
var defineProperties = module.exports = function defineProperties(T, D) {
return Object.defineProperties(T, D);
};
if (Object.defineProperties.sham) defineProperties.sham = true;
});
var defineProperties$1 = defineProperties_1;
var defineProperties$2 = defineProperties$1;
var defineProperty$3 = objectDefineProperty.f;
// `Object.defineProperty` method
// https://tc39.es/ecma262/#sec-object.defineproperty
// eslint-disable-next-line es-x/no-object-defineproperty -- safe
_export({ target: 'Object', stat: true, forced: Object.defineProperty !== defineProperty$3, sham: !descriptors }, {
defineProperty: defineProperty$3
});
var defineProperty_1 = createCommonjsModule(function (module) {
var Object = path.Object;
var defineProperty = module.exports = function defineProperty(it, key, desc) {
return Object.defineProperty(it, key, desc);
};
if (Object.defineProperty.sham) defineProperty.sham = true;
});
var defineProperty$4 = defineProperty_1;
var defineProperty$5 = defineProperty$4;
var classCallCheck = createCommonjsModule(function (module) {
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
module.exports = _classCallCheck, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
var _classCallCheck = unwrapExports(classCallCheck);
var defineProperty$6 = defineProperty$4;
var defineProperty$7 = defineProperty$6;
var defineProperty$8 = defineProperty$7;
var defineProperty$9 = defineProperty$8;
var createClass = createCommonjsModule(function (module) {
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;
defineProperty$9(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
defineProperty$9(Constructor, "prototype", {
writable: false
});
return Constructor;
}
module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
var _createClass = unwrapExports(createClass);
var assertThisInitialized = createCommonjsModule(function (module) {
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
module.exports = _assertThisInitialized, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
var _assertThisInitialized = unwrapExports(assertThisInitialized);
// TODO: Remove from `core-js@4`
// `Object.create` method
// https://tc39.es/ecma262/#sec-object.create
_export({ target: 'Object', stat: true, sham: !descriptors }, {
create: objectCreate
});
var Object$6 = path.Object;
var create = function create(P, D) {
return Object$6.create(P, D);
};
var create$1 = create;
var create$2 = create$1;
var create$3 = create$2;
var create$4 = create$3;
var create$5 = create$4;
// `Object.setPrototypeOf` method
// https://tc39.es/ecma262/#sec-object.setprototypeof
_export({ target: 'Object', stat: true }, {
setPrototypeOf: objectSetPrototypeOf
});
var setPrototypeOf = path.Object.setPrototypeOf;
var setPrototypeOf$1 = setPrototypeOf;
var setPrototypeOf$2 = setPrototypeOf$1;
var setPrototypeOf$3 = setPrototypeOf$2;
var setPrototypeOf$4 = setPrototypeOf$3;
var setPrototypeOf$5 = setPrototypeOf$4;
var setPrototypeOf$6 = createCommonjsModule(function (module) {
function _setPrototypeOf(o, p) {
module.exports = _setPrototypeOf = setPrototypeOf$5 || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
}, module.exports.__esModule = true, module.exports["default"] = module.exports;
return _setPrototypeOf(o, p);
}
module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(setPrototypeOf$6);
var inherits = createCommonjsModule(function (module) {
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = create$5(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
defineProperty$9(subClass, "prototype", {
writable: false
});
if (superClass) setPrototypeOf$6(subClass, superClass);
}
module.exports = _inherits, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
var _inherits = unwrapExports(inherits);
var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable');
var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;
var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded';
var TypeError$b = global_1.TypeError;
// We can't use this feature detection in V8 since it causes
// deoptimization and serious performance degradation
// https://github.com/zloirock/core-js/issues/679
var IS_CONCAT_SPREADABLE_SUPPORT = engineV8Version >= 51 || !fails(function () {
var array = [];
array[IS_CONCAT_SPREADABLE] = false;
return array.concat()[0] !== array;
});
var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat');
var isConcatSpreadable = function (O) {
if (!isObject(O)) return false;
var spreadable = O[IS_CONCAT_SPREADABLE];
return spreadable !== undefined ? !!spreadable : isArray(O);
};
var FORCED$3 = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT;
// `Array.prototype.concat` method
// https://tc39.es/ecma262/#sec-array.prototype.concat
// with adding support of @@isConcatSpreadable and @@species
_export({ target: 'Array', proto: true, arity: 1, forced: FORCED$3 }, {
// eslint-disable-next-line no-unused-vars -- required for `.length`
concat: function concat(arg) {
var O = toObject(this);
var A = arraySpeciesCreate(O, 0);
var n = 0;
var i, k, length, len, E;
for (i = -1, length = arguments.length; i < length; i++) {
E = i === -1 ? O : arguments[i];
if (isConcatSpreadable(E)) {
len = lengthOfArrayLike(E);
if (n + len > MAX_SAFE_INTEGER) throw TypeError$b(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]);
} else {
if (n >= MAX_SAFE_INTEGER) throw TypeError$b(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
createProperty(A, n++, E);
}
}
A.length = n;
return A;
}
});
// `Symbol.asyncIterator` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.asynciterator
defineWellKnownSymbol('asyncIterator');
// `Symbol.hasInstance` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.hasinstance
defineWellKnownSymbol('hasInstance');
// `Symbol.isConcatSpreadable` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.isconcatspreadable
defineWellKnownSymbol('isConcatSpreadable');
// `Symbol.iterator` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.iterator
defineWellKnownSymbol('iterator');
// `Symbol.match` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.match
defineWellKnownSymbol('match');
// `Symbol.matchAll` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.matchall
defineWellKnownSymbol('matchAll');
// `Symbol.replace` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.replace
defineWellKnownSymbol('replace');
// `Symbol.search` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.search
defineWellKnownSymbol('search');
// `Symbol.species` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.species
defineWellKnownSymbol('species');
// `Symbol.split` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.split
defineWellKnownSymbol('split');
// `Symbol.toPrimitive` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.toprimitive
defineWellKnownSymbol('toPrimitive');
// `Symbol.prototype[@@toPrimitive]` method
// https://tc39.es/ecma262/#sec-symbol.prototype-@@toprimitive
symbolDefineToPrimitive();
// `Symbol.toStringTag` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.tostringtag
defineWellKnownSymbol('toStringTag');
// `Symbol.prototype[@@toStringTag]` property
// https://tc39.es/ecma262/#sec-symbol.prototype-@@tostringtag
setToStringTag(getBuiltIn('Symbol'), 'Symbol');
// `Symbol.unscopables` well-known symbol
// https://tc39.es/ecma262/#sec-symbol.unscopables
defineWellKnownSymbol('unscopables');
// JSON[@@toStringTag] property
// https://tc39.es/ecma262/#sec-json-@@tostringtag
setToStringTag(global_1.JSON, 'JSON', true);
var symbol = path.Symbol;
var symbol$1 = symbol;
var symbol$2 = symbol$1;
// `Symbol.asyncDispose` well-known symbol
// https://github.com/tc39/proposal-using-statement
defineWellKnownSymbol('asyncDispose');
// `Symbol.dispose` well-known symbol
// https://github.com/tc39/proposal-using-statement
defineWellKnownSymbol('dispose');
// `Symbol.matcher` well-known symbol
// https://github.com/tc39/proposal-pattern-matching
defineWellKnownSymbol('matcher');
// `Symbol.metadata` well-known symbol
// https://github.com/tc39/proposal-decorators
defineWellKnownSymbol('metadata');
// `Symbol.observable` well-known symbol
// https://github.com/tc39/proposal-observable
defineWellKnownSymbol('observable');
// TODO: remove from `core-js@4`
// `Symbol.patternMatch` well-known symbol
// https://github.com/tc39/proposal-pattern-matching
defineWellKnownSymbol('patternMatch');
// TODO: remove from `core-js@4`
defineWellKnownSymbol('replaceAll');
// TODO: Remove from `core-js@4`
// TODO: Remove from `core-js@4`
var symbol$3 = symbol$2;
var symbol$4 = symbol$3;
var symbol$5 = symbol$4;
var charAt$1 = functionUncurryThis(''.charAt);
var charCodeAt$1 = functionUncurryThis(''.charCodeAt);
var stringSlice$1 = functionUncurryThis(''.slice);
var createMethod$2 = function (CONVERT_TO_STRING) {
return function ($this, pos) {
var S = toString_1(requireObjectCoercible($this));
var position = toIntegerOrInfinity(pos);
var size = S.length;
var first, second;
if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;
first = charCodeAt$1(S, position);
return first < 0xD800 || first > 0xDBFF || position + 1 === size
|| (second = charCodeAt$1(S, position + 1)) < 0xDC00 || second > 0xDFFF
? CONVERT_TO_STRING
? charAt$1(S, position)
: first
: CONVERT_TO_STRING
? stringSlice$1(S, position, position + 2)
: (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;
};
};
var stringMultibyte = {
// `String.prototype.codePointAt` method
// https://tc39.es/ecma262/#sec-string.prototype.codepointat
codeAt: createMethod$2(false),
// `String.prototype.at` method
// https://github.com/mathiasbynens/String.prototype.at
charAt: createMethod$2(true)
};
var charAt$2 = stringMultibyte.charAt;
var STRING_ITERATOR = 'String Iterator';
var setInternalState$2 = internalState.set;
var getInternalState$2 = internalState.getterFor(STRING_ITERATOR);
// `String.prototype[@@iterator]` method
// https://tc39.es/ecma262/#sec-string.prototype-@@iterator
defineIterator(String, 'String', function (iterated) {
setInternalState$2(this, {
type: STRING_ITERATOR,
string: toString_1(iterated),
index: 0
});
// `%StringIteratorPrototype%.next` method
// https://tc39.es/ecma262/#sec-%stringiteratorprototype%.next
}, function next() {
var state = getInternalState$2(this);
var string = state.string;
var index = state.index;
var point;
if (index >= string.length) return { value: undefined, done: true };
point = charAt$2(string, index);
state.index += point.length;
return { value: point, done: false };
});
var iterator = wellKnownSymbolWrapped.f('iterator');
var iterator$1 = iterator;
var iterator$2 = iterator$1;
var iterator$3 = iterator$2;
var iterator$4 = iterator$3;
var iterator$5 = iterator$4;
var _typeof_1 = createCommonjsModule(function (module) {
function _typeof(obj) {
"@babel/helpers - typeof";
return (module.exports = _typeof = "function" == typeof symbol$5 && "symbol" == typeof iterator$5 ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof symbol$5 && obj.constructor === symbol$5 && obj !== symbol$5.prototype ? "symbol" : typeof obj;
}, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(obj);
}
module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
var _typeof = unwrapExports(_typeof_1);
var possibleConstructorReturn = createCommonjsModule(function (module) {
var _typeof = _typeof_1["default"];
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return assertThisInitialized(self);
}
module.exports = _possibleConstructorReturn, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
var _possibleConstructorReturn = unwrapExports(possibleConstructorReturn);
var FAILS_ON_PRIMITIVES$2 = fails(function () { objectGetPrototypeOf(1); });
// `Object.getPrototypeOf` method
// https://tc39.es/ecma262/#sec-object.getprototypeof
_export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES$2, sham: !correctPrototypeGetter }, {
getPrototypeOf: function getPrototypeOf(it) {
return objectGetPrototypeOf(toObject(it));
}
});
var getPrototypeOf = path.Object.getPrototypeOf;
var getPrototypeOf$1 = getPrototypeOf;
var getPrototypeOf$2 = getPrototypeOf$1;
var getPrototypeOf$3 = getPrototypeOf$2;
var getPrototypeOf$4 = getPrototypeOf$3;
var getPrototypeOf$5 = getPrototypeOf$4;
var getPrototypeOf$6 = createCommonjsModule(function (module) {
function _getPrototypeOf(o) {
module.exports = _getPrototypeOf = setPrototypeOf$5 ? getPrototypeOf$5 : function _getPrototypeOf(o) {
return o.__proto__ || getPrototypeOf$5(o);
}, module.exports.__esModule = true, module.exports["default"] = module.exports;
return _getPrototypeOf(o);
}
module.exports = _getPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
var _getPrototypeOf = unwrapExports(getPrototypeOf$6);
var defineProperty$a = createCommonjsModule(function (module) {
function _defineProperty(obj, key, value) {
if (key in obj) {
defineProperty$9(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
var _defineProperty = unwrapExports(defineProperty$a);
var concat$2 = entryVirtual('Array').concat;
var ArrayPrototype$2 = Array.prototype;
var concat$3 = function (it) {
var own = it.concat;
return it === ArrayPrototype$2 || (objectIsPrototypeOf(ArrayPrototype$2, it) && own === ArrayPrototype$2.concat) ? concat$2 : own;
};
var concat$4 = concat$3;
var concat$5 = concat$4;
// TODO: Remove from `core-js@4`
// `Function.prototype.bind` method
// https://tc39.es/ecma262/#sec-function.prototype.bind
_export({ target: 'Function', proto: true, forced: Function.bind !== functionBind }, {
bind: functionBind
});
var bind$2 = entryVirtual('Function').bind;
var FunctionPrototype$3 = Function.prototype;
var bind$3 = function (it) {
var own = it.bind;
return it === FunctionPrototype$3 || (objectIsPrototypeOf(FunctionPrototype$3, it) && own === FunctionPrototype$3.bind) ? bind$2 : own;
};
var bind$4 = bind$3;
var bind$5 = bind$4;
var TypeError$c = global_1.TypeError;
var validateArgumentsLength = function (passed, required) {
if (passed < required) throw TypeError$c('Not enough arguments');
return passed;
};
var MSIE = /MSIE .\./.test(engineUserAgent); // <- dirty ie9- check
var Function$2 = global_1.Function;
var wrap$1 = function (scheduler) {
return MSIE ? function (handler, timeout /* , ...arguments */) {
var boundArgs = validateArgumentsLength(arguments.length, 1) > 2;
var fn = isCallable(handler) ? handler : Function$2(handler);
var args = boundArgs ? arraySlice(arguments, 2) : undefined;
return scheduler(boundArgs ? function () {
functionApply(fn, this, args);
} : fn, timeout);
} : scheduler;
};
// ie9- setTimeout & setInterval additional parameters fix
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers
var schedulersFix = {
// `setTimeout` method
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
setTimeout: wrap$1(global_1.setTimeout),
// `setInterval` method
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
setInterval: wrap$1(global_1.setInterval)
};
var setInterval$1 = schedulersFix.setInterval;
// ie9- setInterval additional parameters fix
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
_export({ global: true, bind: true, forced: global_1.setInterval !== setInterval$1 }, {
setInterval: setInterval$1
});
var setTimeout$1 = schedulersFix.setTimeout;
// ie9- setTimeout additional parameters fix
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
_export({ global: true, bind: true, forced: global_1.setTimeout !== setTimeout$1 }, {
setTimeout: setTimeout$1
});
var setTimeout$2 = path.setTimeout;
var setTimeout$3 = setTimeout$2;
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
var _listCacheClear = listCacheClear;
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
var eq_1 = eq;
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq_1(array[length][0], key)) {
return length;
}
}
return -1;
}
var _assocIndexOf = assocIndexOf;
/** Used for built-in method references. */
var arrayProto = Array.prototype;
/** Built-in value references. */
var splice = arrayProto.splice;
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = _assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
var _listCacheDelete = listCacheDelete;
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = _assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
var _listCacheGet = listCacheGet;
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return _assocIndexOf(this.__data__, key) > -1;
}
var _listCacheHas = listCacheHas;
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = _assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
var _listCacheSet = listCacheSet;
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `ListCache`.
ListCache.prototype.clear = _listCacheClear;
ListCache.prototype['delete'] = _listCacheDelete;
ListCache.prototype.get = _listCacheGet;
ListCache.prototype.has = _listCacheHas;
ListCache.prototype.set = _listCacheSet;
var _ListCache = ListCache;
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new _ListCache;
this.size = 0;
}
var _stackClear = stackClear;
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
var _stackDelete = stackDelete;
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
var _stackGet = stackGet;
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
var _stackHas = stackHas;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
var _freeGlobal = freeGlobal;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = _freeGlobal || freeSelf || Function('return this')();
var _root = root;
/** Built-in value references. */
var Symbol$2 = _root.Symbol;
var _Symbol = Symbol$2;
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$1 = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Built-in value references. */
var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty$1.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
var _getRawTag = getRawTag;
/** Used for built-in method references. */
var objectProto$1 = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString$1 = objectProto$1.toString;
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString$1(value) {
return nativeObjectToString$1.call(value);
}
var _objectToString = objectToString$1;
/** `Object#toString` result references. */
var nullTag = '[object Null]',
undefinedTag = '[object Undefined]';
/** Built-in value references. */
var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (symToStringTag$1 && symToStringTag$1 in Object(value))
? _getRawTag(value)
: _objectToString(value);
}
var _baseGetTag = baseGetTag;
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject$1(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
var isObject_1 = isObject$1;
/** `Object#toString` result references. */
var asyncTag = '[object AsyncFunction]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
proxyTag = '[object Proxy]';
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!isObject_1(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = _baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
var isFunction_1 = isFunction;
/** Used to detect overreaching core-js shims. */
var coreJsData = _root['__core-js_shared__'];
var _coreJsData = coreJsData;
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
var _isMasked = isMasked;
/** Used for built-in method references. */
var funcProto = Function.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
var _toSource = toSource;
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */
var funcProto$1 = Function.prototype,
objectProto$2 = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString$1 = funcProto$1.toString;
/** Used to check objects for own properties. */
var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString$1.call(hasOwnProperty$2).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject_1(value) || _isMasked(value)) {
return false;
}
var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
return pattern.test(_toSource(value));
}
var _baseIsNative = baseIsNative;
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
var _getValue = getValue;
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = _getValue(object, key);
return _baseIsNative(value) ? value : undefined;
}
var _getNative = getNative;
/* Built-in method references that are verified to be native. */
var Map$1 = _getNative(_root, 'Map');
var _Map = Map$1;
/* Built-in method references that are verified to be native. */
var nativeCreate = _getNative(Object, 'create');
var _nativeCreate = nativeCreate;
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
this.size = 0;
}
var _hashClear = hashClear;
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
var _hashDelete = hashDelete;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used for built-in method references. */
var objectProto$3 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$3 = objectProto$3.hasOwnProperty;
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (_nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty$3.call(data, key) ? data[key] : undefined;
}
var _hashGet = hashGet;
/** Used for built-in method references. */
var objectProto$4 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$4 = objectProto$4.hasOwnProperty;
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$4.call(data, key);
}
var _hashHas = hashHas;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value;
return this;
}
var _hashSet = hashSet;
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `Hash`.
Hash.prototype.clear = _hashClear;
Hash.prototype['delete'] = _hashDelete;
Hash.prototype.get = _hashGet;
Hash.prototype.has = _hashHas;
Hash.prototype.set = _hashSet;
var _Hash = Hash;
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new _Hash,
'map': new (_Map || _ListCache),
'string': new _Hash
};
}
var _mapCacheClear = mapCacheClear;
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
var _isKeyable = isKeyable;
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return _isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
var _getMapData = getMapData;
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
var result = _getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
var _mapCacheDelete = mapCacheDelete;
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return _getMapData(this, key).get(key);
}
var _mapCacheGet = mapCacheGet;
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return _getMapData(this, key).has(key);
}
var _mapCacheHas = mapCacheHas;
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = _getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
var _mapCacheSet = mapCacheSet;
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `MapCache`.
MapCache.prototype.clear = _mapCacheClear;
MapCache.prototype['delete'] = _mapCacheDelete;
MapCache.prototype.get = _mapCacheGet;
MapCache.prototype.has = _mapCacheHas;
MapCache.prototype.set = _mapCacheSet;
var _MapCache = MapCache;
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof _ListCache) {
var pairs = data.__data__;
if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new _MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
var _stackSet = stackSet;
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new _ListCache(entries);
this.size = data.size;
}
// Add methods to `Stack`.
Stack.prototype.clear = _stackClear;
Stack.prototype['delete'] = _stackDelete;
Stack.prototype.get = _stackGet;
Stack.prototype.has = _stackHas;
Stack.prototype.set = _stackSet;
var _Stack = Stack;
var defineProperty$b = (function() {
try {
var func = _getNative(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
var _defineProperty$1 = defineProperty$b;
/**
* The base implementation of `assignValue` and `assignMergeValue` without
* value checks.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function baseAssignValue(object, key, value) {
if (key == '__proto__' && _defineProperty$1) {
_defineProperty$1(object, key, {
'configurable': true,
'enumerable': true,
'value': value,
'writable': true
});
} else {
object[key] = value;
}
}
var _baseAssignValue = baseAssignValue;
/**
* This function is like `assignValue` except that it doesn't assign
* `undefined` values.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignMergeValue(object, key, value) {
if ((value !== undefined && !eq_1(object[key], value)) ||
(value === undefined && !(key in object))) {
_baseAssignValue(object, key, value);
}
}
var _assignMergeValue = assignMergeValue;
/**
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1,
iterable = Object(object),
props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
var _createBaseFor = createBaseFor;
/**
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` and invokes `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = _createBaseFor();
var _baseFor = baseFor;
var _cloneBuffer = createCommonjsModule(function (module, exports) {
/** Detect free variable `exports`. */
var freeExports = exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? _root.Buffer : undefined,
allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var length = buffer.length,
result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
buffer.copy(result);
return result;
}
module.exports = cloneBuffer;
});
/** Built-in value references. */
var Uint8Array$1 = _root.Uint8Array;
var _Uint8Array = Uint8Array$1;
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new _Uint8Array(result).set(new _Uint8Array(arrayBuffer));
return result;
}
var _cloneArrayBuffer = cloneArrayBuffer;
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
var _cloneTypedArray = cloneTypedArray;
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
var _copyArray = copyArray;
/** Built-in value references. */
var objectCreate$1 = Object.create;
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function object() {}
return function(proto) {
if (!isObject_1(proto)) {
return {};
}
if (objectCreate$1) {
return objectCreate$1(proto);
}
object.prototype = proto;
var result = new object;
object.prototype = undefined;
return result;
};
}());
var _baseCreate = baseCreate;
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
var _overArg = overArg;
/** Built-in value references. */
var getPrototype = _overArg(Object.getPrototypeOf, Object);
var _getPrototype = getPrototype;
/** Used for built-in method references. */
var objectProto$5 = Object.prototype;
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5;
return value === proto;
}
var _isPrototype = isPrototype;
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
return (typeof object.constructor == 'function' && !_isPrototype(object))
? _baseCreate(_getPrototype(object))
: {};
}
var _initCloneObject = initCloneObject;
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
var isObjectLike_1 = isObjectLike;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]';
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike_1(value) && _baseGetTag(value) == argsTag;
}
var _baseIsArguments = baseIsArguments;
/** Used for built-in method references. */
var objectProto$6 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$5 = objectProto$6.hasOwnProperty;
/** Built-in value references. */
var propertyIsEnumerable = objectProto$6.propertyIsEnumerable;
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) {
return isObjectLike_1(value) && hasOwnProperty$5.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
var isArguments_1 = isArguments;
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray$1 = Array.isArray;
var isArray_1 = isArray$1;
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER$1 = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1;
}
var isLength_1 = isLength;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength_1(value.length) && !isFunction_1(value);
}
var isArrayLike_1 = isArrayLike;
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike_1(value) && isArrayLike_1(value);
}
var isArrayLikeObject_1 = isArrayLikeObject;
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
var stubFalse_1 = stubFalse;
var isBuffer_1 = createCommonjsModule(function (module, exports) {
/** Detect free variable `exports`. */
var freeExports = exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? _root.Buffer : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse_1;
module.exports = isBuffer;
});
/** `Object#toString` result references. */
var objectTag = '[object Object]';
/** Used for built-in method references. */
var funcProto$2 = Function.prototype,
objectProto$7 = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString$2 = funcProto$2.toString;
/** Used to check objects for own properties. */
var hasOwnProperty$6 = objectProto$7.hasOwnProperty;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString$2.call(Object);
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag) {
return false;
}
var proto = _getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty$6.call(proto, 'constructor') && proto.constructor;
return typeof Ctor == 'function' && Ctor instanceof Ctor &&
funcToString$2.call(Ctor) == objectCtorString;
}
var isPlainObject_1 = isPlainObject;
/** `Object#toString` result references. */
var argsTag$1 = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag$1 = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag$1 = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag$1] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag$1] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike_1(value) &&
isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
}
var _baseIsTypedArray = baseIsTypedArray;
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
var _baseUnary = baseUnary;
var _nodeUtil = createCommonjsModule(function (module, exports) {
/** Detect free variable `exports`. */
var freeExports = exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && _freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
// Use `util.types` for Node.js 10+.
var types = freeModule && freeModule.require && freeModule.require('util').types;
if (types) {
return types;
}
// Legacy `process.binding('util')` for Node.js < 10.
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
module.exports = nodeUtil;
});
/* Node.js helper references. */
var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
var isTypedArray_1 = isTypedArray;
/**
* Gets the value at `key`, unless `key` is "__proto__" or "constructor".
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function safeGet(object, key) {
if (key === 'constructor' && typeof object[key] === 'function') {
return;
}
if (key == '__proto__') {
return;
}
return object[key];
}
var _safeGet = safeGet;
/** Used for built-in method references. */
var objectProto$8 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$7 = objectProto$8.hasOwnProperty;
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty$7.call(object, key) && eq_1(objValue, value)) ||
(value === undefined && !(key in object))) {
_baseAssignValue(object, key, value);
}
}
var _assignValue = assignValue;
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined;
if (newValue === undefined) {
newValue = source[key];
}
if (isNew) {
_baseAssignValue(object, key, newValue);
} else {
_assignValue(object, key, newValue);
}
}
return object;
}
var _copyObject = copyObject;
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
var _baseTimes = baseTimes;
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER$2 = 9007199254740991;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
var type = typeof value;
length = length == null ? MAX_SAFE_INTEGER$2 : length;
return !!length &&
(type == 'number' ||
(type != 'symbol' && reIsUint.test(value))) &&
(value > -1 && value % 1 == 0 && value < length);
}
var _isIndex = isIndex;
/** Used for built-in method references. */
var objectProto$9 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$8 = objectProto$9.hasOwnProperty;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray_1(value),
isArg = !isArr && isArguments_1(value),
isBuff = !isArr && !isArg && isBuffer_1(value),
isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? _baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty$8.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
_isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
var _arrayLikeKeys = arrayLikeKeys;
/**
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function nativeKeysIn(object) {
var result = [];
if (object != null) {
for (var key in Object(object)) {
result.push(key);
}
}
return result;
}
var _nativeKeysIn = nativeKeysIn;
/** Used for built-in method references. */
var objectProto$a = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$9 = objectProto$a.hasOwnProperty;
/**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeysIn(object) {
if (!isObject_1(object)) {
return _nativeKeysIn(object);
}
var isProto = _isPrototype(object),
result = [];
for (var key in object) {
if (!(key == 'constructor' && (isProto || !hasOwnProperty$9.call(object, key)))) {
result.push(key);
}
}
return result;
}
var _baseKeysIn = baseKeysIn;
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object);
}
var keysIn_1 = keysIn;
/**
* Converts `value` to a plain object flattening inherited enumerable string
* keyed properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return _copyObject(value, keysIn_1(value));
}
var toPlainObject_1 = toPlainObject;
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {number} srcIndex The index of `source`.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize assigned values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
var objValue = _safeGet(object, key),
srcValue = _safeGet(source, key),
stacked = stack.get(srcValue);
if (stacked) {
_assignMergeValue(object, key, stacked);
return;
}
var newValue = customizer
? customizer(objValue, srcValue, (key + ''), object, source, stack)
: undefined;
var isCommon = newValue === undefined;
if (isCommon) {
var isArr = isArray_1(srcValue),
isBuff = !isArr && isBuffer_1(srcValue),
isTyped = !isArr && !isBuff && isTypedArray_1(srcValue);
newValue = srcValue;
if (isArr || isBuff || isTyped) {
if (isArray_1(objValue)) {
newValue = objValue;
}
else if (isArrayLikeObject_1(objValue)) {
newValue = _copyArray(objValue);
}
else if (isBuff) {
isCommon = false;
newValue = _cloneBuffer(srcValue, true);
}
else if (isTyped) {
isCommon = false;
newValue = _cloneTypedArray(srcValue, true);
}
else {
newValue = [];
}
}
else if (isPlainObject_1(srcValue) || isArguments_1(srcValue)) {
newValue = objValue;
if (isArguments_1(objValue)) {
newValue = toPlainObject_1(objValue);
}
else if (!isObject_1(objValue) || isFunction_1(objValue)) {
newValue = _initCloneObject(srcValue);
}
}
else {
isCommon = false;
}
}
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, newValue);
mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
stack['delete'](srcValue);
}
_assignMergeValue(object, key, newValue);
}
var _baseMergeDeep = baseMergeDeep;
/**
* The base implementation of `_.merge` without support for multiple sources.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {number} srcIndex The index of `source`.
* @param {Function} [customizer] The function to customize merged values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMerge(object, source, srcIndex, customizer, stack) {
if (object === source) {
return;
}
_baseFor(source, function(srcValue, key) {
stack || (stack = new _Stack);
if (isObject_1(srcValue)) {
_baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
}
else {
var newValue = customizer
? customizer(_safeGet(object, key), srcValue, (key + ''), object, source, stack)
: undefined;
if (newValue === undefined) {
newValue = srcValue;
}
_assignMergeValue(object, key, newValue);
}
}, keysIn_1);
}
var _baseMerge = baseMerge;
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/
function identity(value) {
return value;
}
var identity_1 = identity;
/**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/
function apply$1(func, thisArg, args) {
switch (args.length) {
case 0: return func.call(thisArg);
case 1: return func.call(thisArg, args[0]);
case 2: return func.call(thisArg, args[0], args[1]);
case 3: return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
var _apply = apply$1;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* A specialized version of `baseRest` which transforms the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @param {Function} transform The rest array transform.
* @returns {Function} Returns the new function.
*/
function overRest(func, start, transform) {
start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
index = -1;
var otherArgs = Array(start + 1);
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = transform(array);
return _apply(func, this, otherArgs);
};
}
var _overRest = overRest;
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
var constant_1 = constant;
/**
* The base implementation of `setToString` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var baseSetToString = !_defineProperty$1 ? identity_1 : function(func, string) {
return _defineProperty$1(func, 'toString', {
'configurable': true,
'enumerable': false,
'value': constant_1(string),
'writable': true
});
};
var _baseSetToString = baseSetToString;
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
HOT_SPAN = 16;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;
/**
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
*/
function shortOut(func) {
var count = 0,
lastCalled = 0;
return function() {
var stamp = nativeNow(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return arguments[0];
}
} else {
count = 0;
}
return func.apply(undefined, arguments);
};
}
var _shortOut = shortOut;
/**
* Sets the `toString` method of `func` to return `string`.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var setToString = _shortOut(_baseSetToString);
var _setToString = setToString;
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/
function baseRest(func, start) {
return _setToString(_overRest(func, start, identity_1), func + '');
}
var _baseRest = baseRest;
/**
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject_1(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike_1(object) && _isIndex(index, object.length))
: (type == 'string' && index in object)
) {
return eq_1(object[index], value);
}
return false;
}
var _isIterateeCall = isIterateeCall;
/**
* Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return _baseRest(function(object, sources) {
var index = -1,
length = sources.length,
customizer = length > 1 ? sources[length - 1] : undefined,
guard = length > 2 ? sources[2] : undefined;
customizer = (assigner.length > 3 && typeof customizer == 'function')
? (length--, customizer)
: undefined;
if (guard && _isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
object = Object(object);
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, index, customizer);
}
}
return object;
});
}
var _createAssigner = createAssigner;
/**
* This method is like `_.merge` except that it accepts `customizer` which
* is invoked to produce the merged values of the destination and source
* properties. If `customizer` returns `undefined`, merging is handled by the
* method instead. The `customizer` is invoked with six arguments:
* (objValue, srcValue, key, object, source, stack).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} customizer The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* function customizer(objValue, srcValue) {
* if (_.isArray(objValue)) {
* return objValue.concat(srcValue);
* }
* }
*
* var object = { 'a': [1], 'b': [2] };
* var other = { 'a': [3], 'b': [4] };
*
* _.mergeWith(object, other, customizer);
* // => { 'a': [1, 3], 'b': [2, 4] }
*/
var mergeWith = _createAssigner(function(object, source, srcIndex, customizer) {
_baseMerge(object, source, srcIndex, customizer);
});
var mergeWith_1 = mergeWith;
var getOwnPropertySymbols$3 = getOwnPropertySymbols$1;
var getOwnPropertySymbols$4 = getOwnPropertySymbols$3;
var getOwnPropertySymbols$5 = getOwnPropertySymbols$4;
var getOwnPropertySymbols$6 = getOwnPropertySymbols$5;
/* eslint-disable es-x/no-array-prototype-indexof -- required for testing */
var $IndexOf = arrayIncludes.indexOf;
var un$IndexOf = functionUncurryThis([].indexOf);
var NEGATIVE_ZERO = !!un$IndexOf && 1 / un$IndexOf([1], 1, -0) < 0;
var STRICT_METHOD$1 = arrayMethodIsStrict('indexOf');
// `Array.prototype.indexOf` method
// https://tc39.es/ecma262/#sec-array.prototype.indexof
_export({ target: 'Array', proto: true, forced: NEGATIVE_ZERO || !STRICT_METHOD$1 }, {
indexOf: function indexOf(searchElement /* , fromIndex = 0 */) {
var fromIndex = arguments.length > 1 ? arguments[1] : undefined;
return NEGATIVE_ZERO
// convert -0 to +0
? un$IndexOf(this, searchElement, fromIndex) || 0
: $IndexOf(this, searchElement, fromIndex);
}
});
var indexOf$1 = entryVirtual('Array').indexOf;
var ArrayPrototype$3 = Array.prototype;
var indexOf$2 = function (it) {
var own = it.indexOf;
return it === ArrayPrototype$3 || (objectIsPrototypeOf(ArrayPrototype$3, it) && own === ArrayPrototype$3.indexOf) ? indexOf$1 : own;
};
var indexOf$3 = indexOf$2;
var indexOf$4 = indexOf$3;
var indexOf$5 = indexOf$4;
var indexOf$6 = indexOf$5;
var indexOf$7 = indexOf$6;
var keys$4 = keys$2;
var keys$5 = keys$4;
var keys$6 = keys$5;
var keys$7 = keys$6;
var objectWithoutPropertiesLoose = createCommonjsModule(function (module) {
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = keys$7(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (indexOf$7(excluded).call(excluded, key) >= 0) continue;
target[key] = source[key];
}
return target;
}
module.exports = _objectWithoutPropertiesLoose, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(objectWithoutPropertiesLoose);
var objectWithoutProperties = createCommonjsModule(function (module) {
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (getOwnPropertySymbols$6) {
var sourceSymbolKeys = getOwnPropertySymbols$6(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (indexOf$7(excluded).call(excluded, key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
module.exports = _objectWithoutProperties, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
var _objectWithoutProperties = unwrapExports(objectWithoutProperties);
// eslint-disable-next-line es-x/no-object-assign -- safe
var $assign = Object.assign;
// eslint-disable-next-line es-x/no-object-defineproperty -- required for testing
var defineProperty$c = Object.defineProperty;
var concat$6 = functionUncurryThis([].concat);
// `Object.assign` method
// https://tc39.es/ecma262/#sec-object.assign
var objectAssign = !$assign || fails(function () {
// should have correct order of operations (Edge bug)
if (descriptors && $assign({ b: 1 }, $assign(defineProperty$c({}, 'a', {
enumerable: true,
get: function () {
defineProperty$c(this, 'b', {
value: 3,
enumerable: false
});
}
}), { b: 2 })).b !== 1) return true;
// should work with symbols and should have deterministic property order (V8 bug)
var A = {};
var B = {};
// eslint-disable-next-line es-x/no-symbol -- safe
var symbol = Symbol();
var alphabet = 'abcdefghijklmnopqrst';
A[symbol] = 7;
alphabet.split('').forEach(function (chr) { B[chr] = chr; });
return $assign({}, A)[symbol] != 7 || objectKeys($assign({}, B)).join('') != alphabet;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars -- required for `.length`
var T = toObject(target);
var argumentsLength = arguments.length;
var index = 1;
var getOwnPropertySymbols = objectGetOwnPropertySymbols.f;
var propertyIsEnumerable = objectPropertyIsEnumerable.f;
while (argumentsLength > index) {
var S = indexedObject(arguments[index++]);
var keys = getOwnPropertySymbols ? concat$6(objectKeys(S), getOwnPropertySymbols(S)) : objectKeys(S);
var length = keys.length;
var j = 0;
var key;
while (length > j) {
key = keys[j++];
if (!descriptors || functionCall(propertyIsEnumerable, S, key)) T[key] = S[key];
}
} return T;
} : $assign;
// `Object.assign` method
// https://tc39.es/ecma262/#sec-object.assign
// eslint-disable-next-line es-x/no-object-assign -- required for testing
_export({ target: 'Object', stat: true, arity: 2, forced: Object.assign !== objectAssign }, {
assign: objectAssign
});
var assign = path.Object.assign;
var assign$1 = assign;
var assign$2 = assign$1;
// a string of all valid unicode whitespaces
var whitespaces = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002' +
'\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
var replace$1 = functionUncurryThis(''.replace);
var whitespace = '[' + whitespaces + ']';
var ltrim = RegExp('^' + whitespace + whitespace + '*');
var rtrim = RegExp(whitespace + whitespace + '*$');
// `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation
var createMethod$3 = function (TYPE) {
return function ($this) {
var string = toString_1(requireObjectCoercible($this));
if (TYPE & 1) string = replace$1(string, ltrim, '');
if (TYPE & 2) string = replace$1(string, rtrim, '');
return string;
};
};
var stringTrim = {
// `String.prototype.{ trimLeft, trimStart }` methods
// https://tc39.es/ecma262/#sec-string.prototype.trimstart
start: createMethod$3(1),
// `String.prototype.{ trimRight, trimEnd }` methods
// https://tc39.es/ecma262/#sec-string.prototype.trimend
end: createMethod$3(2),
// `String.prototype.trim` method
// https://tc39.es/ecma262/#sec-string.prototype.trim
trim: createMethod$3(3)
};
var PROPER_FUNCTION_NAME$1 = functionName.PROPER;
var non = '\u200B\u0085\u180E';
// check that a method works with the correct list
// of whitespaces and has a correct name
var stringTrimForced = function (METHOD_NAME) {
return fails(function () {
return !!whitespaces[METHOD_NAME]()
|| non[METHOD_NAME]() !== non
|| (PROPER_FUNCTION_NAME$1 && whitespaces[METHOD_NAME].name !== METHOD_NAME);
});
};
var $trim = stringTrim.trim;
// `String.prototype.trim` method
// https://tc39.es/ecma262/#sec-string.prototype.trim
_export({ target: 'String', proto: true, forced: stringTrimForced('trim') }, {
trim: function trim() {
return $trim(this);
}
});
var trim = entryVirtual('String').trim;
var StringPrototype = String.prototype;
var trim$1 = function (it) {
var own = it.trim;
return typeof it == 'string' || it === StringPrototype
|| (objectIsPrototypeOf(StringPrototype, it) && own === StringPrototype.trim) ? trim : own;
};
var trim$2 = trim$1;
var trim$3 = trim$2;
var iteratorClose = function (iterator, kind, value) {
var innerResult, innerError;
anObject(iterator);
try {
innerResult = getMethod(iterator, 'return');
if (!innerResult) {
if (kind === 'throw') throw value;
return value;
}
innerResult = functionCall(innerResult, iterator);
} catch (error) {
innerError = true;
innerResult = error;
}
if (kind === 'throw') throw value;
if (innerError) throw innerResult;
anObject(innerResult);
return value;
};
// call something on iterator step with safe closing on error
var callWithSafeIterationClosing = function (iterator, fn, value, ENTRIES) {
try {
return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);
} catch (error) {
iteratorClose(iterator, 'throw', error);
}
};
var ITERATOR$2 = wellKnownSymbol('iterator');
var ArrayPrototype$4 = Array.prototype;
// check on default Array iterator
var isArrayIteratorMethod = function (it) {
return it !== undefined && (iterators.Array === it || ArrayPrototype$4[ITERATOR$2] === it);
};
var ITERATOR$3 = wellKnownSymbol('iterator');
var getIteratorMethod = function (it) {
if (it != undefined) return getMethod(it, ITERATOR$3)
|| getMethod(it, '@@iterator')
|| iterators[classof(it)];
};
var TypeError$d = global_1.TypeError;
var getIterator = function (argument, usingIterator) {
var iteratorMethod = arguments.length < 2 ? getIteratorMethod(argument) : usingIterator;
if (aCallable(iteratorMethod)) return anObject(functionCall(iteratorMethod, argument));
throw TypeError$d(tryToString(argument) + ' is not iterable');
};
var Array$3 = global_1.Array;
// `Array.from` method implementation
// https://tc39.es/ecma262/#sec-array.from
var arrayFrom = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
var O = toObject(arrayLike);
var IS_CONSTRUCTOR = isConstructor(this);
var argumentsLength = arguments.length;
var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
var mapping = mapfn !== undefined;
if (mapping) mapfn = functionBindContext(mapfn, argumentsLength > 2 ? arguments[2] : undefined);
var iteratorMethod = getIteratorMethod(O);
var index = 0;
var length, result, step, iterator, next, value;
// if the target is not iterable or it's an array with the default iterator - use a simple case
if (iteratorMethod && !(this == Array$3 && isArrayIteratorMethod(iteratorMethod))) {
iterator = getIterator(O, iteratorMethod);
next = iterator.next;
result = IS_CONSTRUCTOR ? new this() : [];
for (;!(step = functionCall(next, iterator)).done; index++) {
value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value;
createProperty(result, index, value);
}
} else {
length = lengthOfArrayLike(O);
result = IS_CONSTRUCTOR ? new this(length) : Array$3(length);
for (;length > index; index++) {
value = mapping ? mapfn(O[index], index) : O[index];
createProperty(result, index, value);
}
}
result.length = index;
return result;
};
var ITERATOR$4 = wellKnownSymbol('iterator');
var SAFE_CLOSING = false;
try {
var called = 0;
var iteratorWithReturn = {
next: function () {
return { done: !!called++ };
},
'return': function () {
SAFE_CLOSING = true;
}
};
iteratorWithReturn[ITERATOR$4] = function () {
return this;
};
// eslint-disable-next-line es-x/no-array-from, no-throw-literal -- required for testing
Array.from(iteratorWithReturn, function () { throw 2; });
} catch (error) { /* empty */ }
var checkCorrectnessOfIteration = function (exec, SKIP_CLOSING) {
if (!SKIP_CLOSING && !SAFE_CLOSING) return false;
var ITERATION_SUPPORT = false;
try {
var object = {};
object[ITERATOR$4] = function () {
return {
next: function () {
return { done: ITERATION_SUPPORT = true };
}
};
};
exec(object);
} catch (error) { /* empty */ }
return ITERATION_SUPPORT;
};
var INCORRECT_ITERATION = !checkCorrectnessOfIteration(function (iterable) {
// eslint-disable-next-line es-x/no-array-from -- required for testing
Array.from(iterable);
});
// `Array.from` method
// https://tc39.es/ecma262/#sec-array.from
_export({ target: 'Array', stat: true, forced: INCORRECT_ITERATION }, {
from: arrayFrom
});
var from_1 = path.Array.from;
var from_1$1 = from_1;
var from_1$2 = from_1$1;
var MATCH = wellKnownSymbol('match');
// `IsRegExp` abstract operation
// https://tc39.es/ecma262/#sec-isregexp
var isRegexp = function (it) {
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : classofRaw(it) == 'RegExp');
};
var TypeError$e = global_1.TypeError;
var notARegexp = function (it) {
if (isRegexp(it)) {
throw TypeError$e("The method doesn't accept regular expressions");
} return it;
};
var MATCH$1 = wellKnownSymbol('match');
var correctIsRegexpLogic = function (METHOD_NAME) {
var regexp = /./;
try {
'/./'[METHOD_NAME](regexp);
} catch (error1) {
try {
regexp[MATCH$1] = false;
return '/./'[METHOD_NAME](regexp);
} catch (error2) { /* empty */ }
} return false;
};
// eslint-disable-next-line es-x/no-string-prototype-startswith -- safe
var un$StartsWith = functionUncurryThis(''.startsWith);
var stringSlice$2 = functionUncurryThis(''.slice);
var min$2 = Math.min;
var CORRECT_IS_REGEXP_LOGIC = correctIsRegexpLogic('startsWith');
// `String.prototype.startsWith` method
// https://tc39.es/ecma262/#sec-string.prototype.startswith
_export({ target: 'String', proto: true, forced: !CORRECT_IS_REGEXP_LOGIC }, {
startsWith: function startsWith(searchString /* , position = 0 */) {
var that = toString_1(requireObjectCoercible(this));
notARegexp(searchString);
var index = toLength(min$2(arguments.length > 1 ? arguments[1] : undefined, that.length));
var search = toString_1(searchString);
return un$StartsWith
? un$StartsWith(that, search, index)
: stringSlice$2(that, index, index + search.length) === search;
}
});
var startsWith = entryVirtual('String').startsWith;
var StringPrototype$1 = String.prototype;
var startsWith$1 = function (it) {
var own = it.startsWith;
return typeof it == 'string' || it === StringPrototype$1
|| (objectIsPrototypeOf(StringPrototype$1, it) && own === StringPrototype$1.startsWith) ? startsWith : own;
};
var startsWith$2 = startsWith$1;
var startsWith$3 = startsWith$2;
var $find = arrayIteration.find;
var FIND = 'find';
var SKIPS_HOLES = true;
// Shouldn't skip holes
if (FIND in []) Array(1)[FIND](function () { SKIPS_HOLES = false; });
// `Array.prototype.find` method
// https://tc39.es/ecma262/#sec-array.prototype.find
_export({ target: 'Array', proto: true, forced: SKIPS_HOLES }, {
find: function find(callbackfn /* , that = undefined */) {
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
var find = entryVirtual('Array').find;
var ArrayPrototype$5 = Array.prototype;
var find$1 = function (it) {
var own = it.find;
return it === ArrayPrototype$5 || (objectIsPrototypeOf(ArrayPrototype$5, it) && own === ArrayPrototype$5.find) ? find : own;
};
var find$2 = find$1;
var find$3 = find$2;
var codemirror = createCommonjsModule(function (module, exports) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
// This is CodeMirror (https://codemirror.net), a code editor
// implemented in JavaScript on top of the browser's DOM.
//
// You can find some technical background for some of the code below
// at http://marijnhaverbeke.nl/blog/#cm-internals .
(function (global, factory) {
module.exports = factory() ;
}(commonjsGlobal, (function () {
// Kludges for bugs and behavior differences that can't be feature
// detected are enabled based on userAgent etc sniffing.
var userAgent = navigator.userAgent;
var platform = navigator.platform;
var gecko = /gecko\/\d/i.test(userAgent);
var ie_upto10 = /MSIE \d/.test(userAgent);
var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
var edge = /Edge\/(\d+)/.exec(userAgent);
var ie = ie_upto10 || ie_11up || edge;
var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
var webkit = !edge && /WebKit\//.test(userAgent);
var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
var chrome = !edge && /Chrome\//.test(userAgent);
var presto = /Opera\//.test(userAgent);
var safari = /Apple Computer/.test(navigator.vendor);
var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
var phantom = /PhantomJS/.test(userAgent);
var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
var android = /Android/.test(userAgent);
// This is woefully incomplete. Suggestions for alternative methods welcome.
var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
var mac = ios || /Mac/.test(platform);
var chromeOS = /\bCrOS\b/.test(userAgent);
var windows = /win/i.test(platform);
var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
if (presto_version) { presto_version = Number(presto_version[1]); }
if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
// Some browsers use the wrong event properties to signal cmd/ctrl on OS X
var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
var captureRightClick = gecko || (ie && ie_version >= 9);
function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
var rmClass = function(node, cls) {
var current = node.className;
var match = classTest(cls).exec(current);
if (match) {
var after = current.slice(match.index + match[0].length);
node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
}
};
function removeChildren(e) {
for (var count = e.childNodes.length; count > 0; --count)
{ e.removeChild(e.firstChild); }
return e
}
function removeChildrenAndAdd(parent, e) {
return removeChildren(parent).appendChild(e)
}
function elt(tag, content, className, style) {
var e = document.createElement(tag);
if (className) { e.className = className; }
if (style) { e.style.cssText = style; }
if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
return e
}
// wrapper for elt, which removes the elt from the accessibility tree
function eltP(tag, content, className, style) {
var e = elt(tag, content, className, style);
e.setAttribute("role", "presentation");
return e
}
var range;
if (document.createRange) { range = function(node, start, end, endNode) {
var r = document.createRange();
r.setEnd(endNode || node, end);
r.setStart(node, start);
return r
}; }
else { range = function(node, start, end) {
var r = document.body.createTextRange();
try { r.moveToElementText(node.parentNode); }
catch(e) { return r }
r.collapse(true);
r.moveEnd("character", end);
r.moveStart("character", start);
return r
}; }
function contains(parent, child) {
if (child.nodeType == 3) // Android browser always returns false when child is a textnode
{ child = child.parentNode; }
if (parent.contains)
{ return parent.contains(child) }
do {
if (child.nodeType == 11) { child = child.host; }
if (child == parent) { return true }
} while (child = child.parentNode)
}
function activeElt() {
// IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
// IE < 10 will throw when accessed while the page is loading or in an iframe.
// IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
var activeElement;
try {
activeElement = document.activeElement;
} catch(e) {
activeElement = document.body || null;
}
while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
{ activeElement = activeElement.shadowRoot.activeElement; }
return activeElement
}
function addClass(node, cls) {
var current = node.className;
if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
}
function joinClasses(a, b) {
var as = a.split(" ");
for (var i = 0; i < as.length; i++)
{ if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
return b
}
var selectInput = function(node) { node.select(); };
if (ios) // Mobile Safari apparently has a bug where select() is broken.
{ selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
else if (ie) // Suppress mysterious IE10 errors
{ selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
function bind(f) {
var args = Array.prototype.slice.call(arguments, 1);
return function(){return f.apply(null, args)}
}
function copyObj(obj, target, overwrite) {
if (!target) { target = {}; }
for (var prop in obj)
{ if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
{ target[prop] = obj[prop]; } }
return target
}
// Counts the column offset in a string, taking tabs into account.
// Used mostly to find indentation.
function countColumn(string, end, tabSize, startIndex, startValue) {
if (end == null) {
end = string.search(/[^\s\u00a0]/);
if (end == -1) { end = string.length; }
}
for (var i = startIndex || 0, n = startValue || 0;;) {
var nextTab = string.indexOf("\t", i);
if (nextTab < 0 || nextTab >= end)
{ return n + (end - i) }
n += nextTab - i;
n += tabSize - (n % tabSize);
i = nextTab + 1;
}
}
var Delayed = function() {
this.id = null;
this.f = null;
this.time = 0;
this.handler = bind(this.onTimeout, this);
};
Delayed.prototype.onTimeout = function (self) {
self.id = 0;
if (self.time <= +new Date) {
self.f();
} else {
setTimeout(self.handler, self.time - +new Date);
}
};
Delayed.prototype.set = function (ms, f) {
this.f = f;
var time = +new Date + ms;
if (!this.id || time < this.time) {
clearTimeout(this.id);
this.id = setTimeout(this.handler, ms);
this.time = time;
}
};
function indexOf(array, elt) {
for (var i = 0; i < array.length; ++i)
{ if (array[i] == elt) { return i } }
return -1
}
// Number of pixels added to scroller and sizer to hide scrollbar
var scrollerGap = 50;
// Returned or thrown by various protocols to signal 'I'm not
// handling this'.
var Pass = {toString: function(){return "CodeMirror.Pass"}};
// Reused option objects for setSelection & friends
var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
// The inverse of countColumn -- find the offset that corresponds to
// a particular column.
function findColumn(string, goal, tabSize) {
for (var pos = 0, col = 0;;) {
var nextTab = string.indexOf("\t", pos);
if (nextTab == -1) { nextTab = string.length; }
var skipped = nextTab - pos;
if (nextTab == string.length || col + skipped >= goal)
{ return pos + Math.min(skipped, goal - col) }
col += nextTab - pos;
col += tabSize - (col % tabSize);
pos = nextTab + 1;
if (col >= goal) { return pos }
}
}
var spaceStrs = [""];
function spaceStr(n) {
while (spaceStrs.length <= n)
{ spaceStrs.push(lst(spaceStrs) + " "); }
return spaceStrs[n]
}
function lst(arr) { return arr[arr.length-1] }
function map(array, f) {
var out = [];
for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
return out
}
function insertSorted(array, value, score) {
var pos = 0, priority = score(value);
while (pos < array.length && score(array[pos]) <= priority) { pos++; }
array.splice(pos, 0, value);
}
function nothing() {}
function createObj(base, props) {
var inst;
if (Object.create) {
inst = Object.create(base);
} else {
nothing.prototype = base;
inst = new nothing();
}
if (props) { copyObj(props, inst); }
return inst
}
var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
function isWordCharBasic(ch) {
return /\w/.test(ch) || ch > "\x80" &&
(ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
}
function isWordChar(ch, helper) {
if (!helper) { return isWordCharBasic(ch) }
if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
return helper.test(ch)
}
function isEmpty(obj) {
for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
return true
}
// Extending unicode characters. A series of a non-extending char +
// any number of extending chars is treated as a single unit as far
// as editing and measuring is concerned. This is not fully correct,
// since some scripts/fonts/browsers also treat other configurations
// of code points as a group.
var extendingChars = /[\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]/;
function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
// Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
function skipExtendingChars(str, pos, dir) {
while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
return pos
}
// Returns the value from the range [`from`; `to`] that satisfies
// `pred` and is closest to `from`. Assumes that at least `to`
// satisfies `pred`. Supports `from` being greater than `to`.
function findFirst(pred, from, to) {
// At any point we are certain `to` satisfies `pred`, don't know
// whether `from` does.
var dir = from > to ? -1 : 1;
for (;;) {
if (from == to) { return from }
var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
if (mid == from) { return pred(mid) ? from : to }
if (pred(mid)) { to = mid; }
else { from = mid + dir; }
}
}
// BIDI HELPERS
function iterateBidiSections(order, from, to, f) {
if (!order) { return f(from, to, "ltr", 0) }
var found = false;
for (var i = 0; i < order.length; ++i) {
var part = order[i];
if (part.from < to && part.to > from || from == to && part.to == from) {
f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
found = true;
}
}
if (!found) { f(from, to, "ltr"); }
}
var bidiOther = null;
function getBidiPartAt(order, ch, sticky) {
var found;
bidiOther = null;
for (var i = 0; i < order.length; ++i) {
var cur = order[i];
if (cur.from < ch && cur.to > ch) { return i }
if (cur.to == ch) {
if (cur.from != cur.to && sticky == "before") { found = i; }
else { bidiOther = i; }
}
if (cur.from == ch) {
if (cur.from != cur.to && sticky != "before") { found = i; }
else { bidiOther = i; }
}
}
return found != null ? found : bidiOther
}
// Bidirectional ordering algorithm
// See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
// that this (partially) implements.
// One-char codes used for character types:
// L (L): Left-to-Right
// R (R): Right-to-Left
// r (AL): Right-to-Left Arabic
// 1 (EN): European Number
// + (ES): European Number Separator
// % (ET): European Number Terminator
// n (AN): Arabic Number
// , (CS): Common Number Separator
// m (NSM): Non-Spacing Mark
// b (BN): Boundary Neutral
// s (B): Paragraph Separator
// t (S): Segment Separator
// w (WS): Whitespace
// N (ON): Other Neutrals
// Returns null if characters are ordered as they appear
// (left-to-right), or an array of sections ({from, to, level}
// objects) in the order in which they occur visually.
var bidiOrdering = (function() {
// Character types for codepoints 0 to 0xff
var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
// Character types for codepoints 0x600 to 0x6f9
var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
function charType(code) {
if (code <= 0xf7) { return lowTypes.charAt(code) }
else if (0x590 <= code && code <= 0x5f4) { return "R" }
else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
else if (0x6ee <= code && code <= 0x8ac) { return "r" }
else if (0x2000 <= code && code <= 0x200b) { return "w" }
else if (code == 0x200c) { return "b" }
else { return "L" }
}
var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
function BidiSpan(level, from, to) {
this.level = level;
this.from = from; this.to = to;
}
return function(str, direction) {
var outerType = direction == "ltr" ? "L" : "R";
if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
var len = str.length, types = [];
for (var i = 0; i < len; ++i)
{ types.push(charType(str.charCodeAt(i))); }
// W1. Examine each non-spacing mark (NSM) in the level run, and
// change the type of the NSM to the type of the previous
// character. If the NSM is at the start of the level run, it will
// get the type of sor.
for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
var type = types[i$1];
if (type == "m") { types[i$1] = prev; }
else { prev = type; }
}
// W2. Search backwards from each instance of a European number
// until the first strong type (R, L, AL, or sor) is found. If an
// AL is found, change the type of the European number to Arabic
// number.
// W3. Change all ALs to R.
for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
var type$1 = types[i$2];
if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
}
// W4. A single European separator between two European numbers
// changes to a European number. A single common separator between
// two numbers of the same type changes to that type.
for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
var type$2 = types[i$3];
if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
else if (type$2 == "," && prev$1 == types[i$3+1] &&
(prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
prev$1 = type$2;
}
// W5. A sequence of European terminators adjacent to European
// numbers changes to all European numbers.
// W6. Otherwise, separators and terminators change to Other
// Neutral.
for (var i$4 = 0; i$4 < len; ++i$4) {
var type$3 = types[i$4];
if (type$3 == ",") { types[i$4] = "N"; }
else if (type$3 == "%") {
var end = (void 0);
for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
for (var j = i$4; j < end; ++j) { types[j] = replace; }
i$4 = end - 1;
}
}
// W7. Search backwards from each instance of a European number
// until the first strong type (R, L, or sor) is found. If an L is
// found, then change the type of the European number to L.
for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
var type$4 = types[i$5];
if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
else if (isStrong.test(type$4)) { cur$1 = type$4; }
}
// N1. A sequence of neutrals takes the direction of the
// surrounding strong text if the text on both sides has the same
// direction. European and Arabic numbers act as if they were R in
// terms of their influence on neutrals. Start-of-level-run (sor)
// and end-of-level-run (eor) are used at level run boundaries.
// N2. Any remaining neutrals take the embedding direction.
for (var i$6 = 0; i$6 < len; ++i$6) {
if (isNeutral.test(types[i$6])) {
var end$1 = (void 0);
for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
var before = (i$6 ? types[i$6-1] : outerType) == "L";
var after = (end$1 < len ? types[end$1] : outerType) == "L";
var replace$1 = before == after ? (before ? "L" : "R") : outerType;
for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
i$6 = end$1 - 1;
}
}
// Here we depart from the documented algorithm, in order to avoid
// building up an actual levels array. Since there are only three
// levels (0, 1, 2) in an implementation that doesn't take
// explicit embedding into account, we can build up the order on
// the fly, without following the level-based algorithm.
var order = [], m;
for (var i$7 = 0; i$7 < len;) {
if (countsAsLeft.test(types[i$7])) {
var start = i$7;
for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
order.push(new BidiSpan(0, start, i$7));
} else {
var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
for (var j$2 = pos; j$2 < i$7;) {
if (countsAsNum.test(types[j$2])) {
if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; }
var nstart = j$2;
for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
order.splice(at, 0, new BidiSpan(2, nstart, j$2));
at += isRTL;
pos = j$2;
} else { ++j$2; }
}
if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
}
}
if (direction == "ltr") {
if (order[0].level == 1 && (m = str.match(/^\s+/))) {
order[0].from = m[0].length;
order.unshift(new BidiSpan(0, 0, m[0].length));
}
if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
lst(order).to -= m[0].length;
order.push(new BidiSpan(0, len - m[0].length, len));
}
}
return direction == "rtl" ? order.reverse() : order
}
})();
// Get the bidi ordering for the given line (and cache it). Returns
// false for lines that are fully left-to-right, and an array of
// BidiSpan objects otherwise.
function getOrder(line, direction) {
var order = line.order;
if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
return order
}
// EVENT HANDLING
// Lightweight event framework. on/off also work on DOM nodes,
// registering native DOM handlers.
var noHandlers = [];
var on = function(emitter, type, f) {
if (emitter.addEventListener) {
emitter.addEventListener(type, f, false);
} else if (emitter.attachEvent) {
emitter.attachEvent("on" + type, f);
} else {
var map = emitter._handlers || (emitter._handlers = {});
map[type] = (map[type] || noHandlers).concat(f);
}
};
function getHandlers(emitter, type) {
return emitter._handlers && emitter._handlers[type] || noHandlers
}
function off(emitter, type, f) {
if (emitter.removeEventListener) {
emitter.removeEventListener(type, f, false);
} else if (emitter.detachEvent) {
emitter.detachEvent("on" + type, f);
} else {
var map = emitter._handlers, arr = map && map[type];
if (arr) {
var index = indexOf(arr, f);
if (index > -1)
{ map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
}
}
}
function signal(emitter, type /*, values...*/) {
var handlers = getHandlers(emitter, type);
if (!handlers.length) { return }
var args = Array.prototype.slice.call(arguments, 2);
for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
}
// The DOM events that CodeMirror handles can be overridden by
// registering a (non-DOM) handler on the editor for the event name,
// and preventDefault-ing the event in that handler.
function signalDOMEvent(cm, e, override) {
if (typeof e == "string")
{ e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
signal(cm, override || e.type, cm, e);
return e_defaultPrevented(e) || e.codemirrorIgnore
}
function signalCursorActivity(cm) {
var arr = cm._handlers && cm._handlers.cursorActivity;
if (!arr) { return }
var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
{ set.push(arr[i]); } }
}
function hasHandler(emitter, type) {
return getHandlers(emitter, type).length > 0
}
// Add on and off methods to a constructor's prototype, to make
// registering events on such objects more convenient.
function eventMixin(ctor) {
ctor.prototype.on = function(type, f) {on(this, type, f);};
ctor.prototype.off = function(type, f) {off(this, type, f);};
}
// Due to the fact that we still support jurassic IE versions, some
// compatibility wrappers are needed.
function e_preventDefault(e) {
if (e.preventDefault) { e.preventDefault(); }
else { e.returnValue = false; }
}
function e_stopPropagation(e) {
if (e.stopPropagation) { e.stopPropagation(); }
else { e.cancelBubble = true; }
}
function e_defaultPrevented(e) {
return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
}
function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
function e_target(e) {return e.target || e.srcElement}
function e_button(e) {
var b = e.which;
if (b == null) {
if (e.button & 1) { b = 1; }
else if (e.button & 2) { b = 3; }
else if (e.button & 4) { b = 2; }
}
if (mac && e.ctrlKey && b == 1) { b = 3; }
return b
}
// Detect drag-and-drop
var dragAndDrop = function() {
// There is *some* kind of drag-and-drop support in IE6-8, but I
// couldn't get it to work yet.
if (ie && ie_version < 9) { return false }
var div = elt('div');
return "draggable" in div || "dragDrop" in div
}();
var zwspSupported;
function zeroWidthElement(measure) {
if (zwspSupported == null) {
var test = elt("span", "\u200b");
removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
if (measure.firstChild.offsetHeight != 0)
{ zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
}
var node = zwspSupported ? elt("span", "\u200b") :
elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
node.setAttribute("cm-text", "");
return node
}
// Feature-detect IE's crummy client rect reporting for bidi text
var badBidiRects;
function hasBadBidiRects(measure) {
if (badBidiRects != null) { return badBidiRects }
var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
var r0 = range(txt, 0, 1).getBoundingClientRect();
var r1 = range(txt, 1, 2).getBoundingClientRect();
removeChildren(measure);
if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
return badBidiRects = (r1.right - r0.right < 3)
}
// See if "".split is the broken IE version, if so, provide an
// alternative way to split lines.
var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
var pos = 0, result = [], l = string.length;
while (pos <= l) {
var nl = string.indexOf("\n", pos);
if (nl == -1) { nl = string.length; }
var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
var rt = line.indexOf("\r");
if (rt != -1) {
result.push(line.slice(0, rt));
pos += rt + 1;
} else {
result.push(line);
pos = nl + 1;
}
}
return result
} : function (string) { return string.split(/\r\n?|\n/); };
var hasSelection = window.getSelection ? function (te) {
try { return te.selectionStart != te.selectionEnd }
catch(e) { return false }
} : function (te) {
var range;
try {range = te.ownerDocument.selection.createRange();}
catch(e) {}
if (!range || range.parentElement() != te) { return false }
return range.compareEndPoints("StartToEnd", range) != 0
};
var hasCopyEvent = (function () {
var e = elt("div");
if ("oncopy" in e) { return true }
e.setAttribute("oncopy", "return;");
return typeof e.oncopy == "function"
})();
var badZoomedRects = null;
function hasBadZoomedRects(measure) {
if (badZoomedRects != null) { return badZoomedRects }
var node = removeChildrenAndAdd(measure, elt("span", "x"));
var normal = node.getBoundingClientRect();
var fromRange = range(node, 0, 1).getBoundingClientRect();
return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
}
// Known modes, by name and by MIME
var modes = {}, mimeModes = {};
// Extra arguments are stored as the mode's dependencies, which is
// used by (legacy) mechanisms like loadmode.js to automatically
// load a mode. (Preferred mechanism is the require/define calls.)
function defineMode(name, mode) {
if (arguments.length > 2)
{ mode.dependencies = Array.prototype.slice.call(arguments, 2); }
modes[name] = mode;
}
function defineMIME(mime, spec) {
mimeModes[mime] = spec;
}
// Given a MIME type, a {name, ...options} config object, or a name
// string, return a mode config object.
function resolveMode(spec) {
if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
spec = mimeModes[spec];
} else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
var found = mimeModes[spec.name];
if (typeof found == "string") { found = {name: found}; }
spec = createObj(found, spec);
spec.name = found.name;
} else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
return resolveMode("application/xml")
} else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
return resolveMode("application/json")
}
if (typeof spec == "string") { return {name: spec} }
else { return spec || {name: "null"} }
}
// Given a mode spec (anything that resolveMode accepts), find and
// initialize an actual mode object.
function getMode(options, spec) {
spec = resolveMode(spec);
var mfactory = modes[spec.name];
if (!mfactory) { return getMode(options, "text/plain") }
var modeObj = mfactory(options, spec);
if (modeExtensions.hasOwnProperty(spec.name)) {
var exts = modeExtensions[spec.name];
for (var prop in exts) {
if (!exts.hasOwnProperty(prop)) { continue }
if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
modeObj[prop] = exts[prop];
}
}
modeObj.name = spec.name;
if (spec.helperType) { modeObj.helperType = spec.helperType; }
if (spec.modeProps) { for (var prop$1 in spec.modeProps)
{ modeObj[prop$1] = spec.modeProps[prop$1]; } }
return modeObj
}
// This can be used to attach properties to mode objects from
// outside the actual mode definition.
var modeExtensions = {};
function extendMode(mode, properties) {
var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
copyObj(properties, exts);
}
function copyState(mode, state) {
if (state === true) { return state }
if (mode.copyState) { return mode.copyState(state) }
var nstate = {};
for (var n in state) {
var val = state[n];
if (val instanceof Array) { val = val.concat([]); }
nstate[n] = val;
}
return nstate
}
// Given a mode and a state (for that mode), find the inner mode and
// state at the position that the state refers to.
function innerMode(mode, state) {
var info;
while (mode.innerMode) {
info = mode.innerMode(state);
if (!info || info.mode == mode) { break }
state = info.state;
mode = info.mode;
}
return info || {mode: mode, state: state}
}
function startState(mode, a1, a2) {
return mode.startState ? mode.startState(a1, a2) : true
}
// STRING STREAM
// Fed to the mode parsers, provides helper functions to make
// parsers more succinct.
var StringStream = function(string, tabSize, lineOracle) {
this.pos = this.start = 0;
this.string = string;
this.tabSize = tabSize || 8;
this.lastColumnPos = this.lastColumnValue = 0;
this.lineStart = 0;
this.lineOracle = lineOracle;
};
StringStream.prototype.eol = function () {return this.pos >= this.string.length};
StringStream.prototype.sol = function () {return this.pos == this.lineStart};
StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
StringStream.prototype.next = function () {
if (this.pos < this.string.length)
{ return this.string.charAt(this.pos++) }
};
StringStream.prototype.eat = function (match) {
var ch = this.string.charAt(this.pos);
var ok;
if (typeof match == "string") { ok = ch == match; }
else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
if (ok) {++this.pos; return ch}
};
StringStream.prototype.eatWhile = function (match) {
var start = this.pos;
while (this.eat(match)){}
return this.pos > start
};
StringStream.prototype.eatSpace = function () {
var start = this.pos;
while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; }
return this.pos > start
};
StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
StringStream.prototype.skipTo = function (ch) {
var found = this.string.indexOf(ch, this.pos);
if (found > -1) {this.pos = found; return true}
};
StringStream.prototype.backUp = function (n) {this.pos -= n;};
StringStream.prototype.column = function () {
if (this.lastColumnPos < this.start) {
this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
this.lastColumnPos = this.start;
}
return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
};
StringStream.prototype.indentation = function () {
return countColumn(this.string, null, this.tabSize) -
(this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
};
StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
if (typeof pattern == "string") {
var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
var substr = this.string.substr(this.pos, pattern.length);
if (cased(substr) == cased(pattern)) {
if (consume !== false) { this.pos += pattern.length; }
return true
}
} else {
var match = this.string.slice(this.pos).match(pattern);
if (match && match.index > 0) { return null }
if (match && consume !== false) { this.pos += match[0].length; }
return match
}
};
StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
StringStream.prototype.hideFirstChars = function (n, inner) {
this.lineStart += n;
try { return inner() }
finally { this.lineStart -= n; }
};
StringStream.prototype.lookAhead = function (n) {
var oracle = this.lineOracle;
return oracle && oracle.lookAhead(n)
};
StringStream.prototype.baseToken = function () {
var oracle = this.lineOracle;
return oracle && oracle.baseToken(this.pos)
};
// Find the line object corresponding to the given line number.
function getLine(doc, n) {
n -= doc.first;
if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
var chunk = doc;
while (!chunk.lines) {
for (var i = 0;; ++i) {
var child = chunk.children[i], sz = child.chunkSize();
if (n < sz) { chunk = child; break }
n -= sz;
}
}
return chunk.lines[n]
}
// Get the part of a document between two positions, as an array of
// strings.
function getBetween(doc, start, end) {
var out = [], n = start.line;
doc.iter(start.line, end.line + 1, function (line) {
var text = line.text;
if (n == end.line) { text = text.slice(0, end.ch); }
if (n == start.line) { text = text.slice(start.ch); }
out.push(text);
++n;
});
return out
}
// Get the lines between from and to, as array of strings.
function getLines(doc, from, to) {
var out = [];
doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
return out
}
// Update the height of a line, propagating the height change
// upwards to parent nodes.
function updateLineHeight(line, height) {
var diff = height - line.height;
if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
}
// Given a line object, find its line number by walking up through
// its parent links.
function lineNo(line) {
if (line.parent == null) { return null }
var cur = line.parent, no = indexOf(cur.lines, line);
for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
for (var i = 0;; ++i) {
if (chunk.children[i] == cur) { break }
no += chunk.children[i].chunkSize();
}
}
return no + cur.first
}
// Find the line at the given vertical position, using the height
// information in the document tree.
function lineAtHeight(chunk, h) {
var n = chunk.first;
outer: do {
for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
var child = chunk.children[i$1], ch = child.height;
if (h < ch) { chunk = child; continue outer }
h -= ch;
n += child.chunkSize();
}
return n
} while (!chunk.lines)
var i = 0;
for (; i < chunk.lines.length; ++i) {
var line = chunk.lines[i], lh = line.height;
if (h < lh) { break }
h -= lh;
}
return n + i
}
function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
function lineNumberFor(options, i) {
return String(options.lineNumberFormatter(i + options.firstLineNumber))
}
// A Pos instance represents a position within the text.
function Pos(line, ch, sticky) {
if ( sticky === void 0 ) sticky = null;
if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
this.line = line;
this.ch = ch;
this.sticky = sticky;
}
// Compare two positions, return 0 if they are the same, a negative
// number when a is less, and a positive number otherwise.
function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
function copyPos(x) {return Pos(x.line, x.ch)}
function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
// Most of the external API clips given positions to make sure they
// actually exist within the document.
function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
function clipPos(doc, pos) {
if (pos.line < doc.first) { return Pos(doc.first, 0) }
var last = doc.first + doc.size - 1;
if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
return clipToLen(pos, getLine(doc, pos.line).text.length)
}
function clipToLen(pos, linelen) {
var ch = pos.ch;
if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
else if (ch < 0) { return Pos(pos.line, 0) }
else { return pos }
}
function clipPosArray(doc, array) {
var out = [];
for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
return out
}
var SavedContext = function(state, lookAhead) {
this.state = state;
this.lookAhead = lookAhead;
};
var Context = function(doc, state, line, lookAhead) {
this.state = state;
this.doc = doc;
this.line = line;
this.maxLookAhead = lookAhead || 0;
this.baseTokens = null;
this.baseTokenPos = 1;
};
Context.prototype.lookAhead = function (n) {
var line = this.doc.getLine(this.line + n);
if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
return line
};
Context.prototype.baseToken = function (n) {
if (!this.baseTokens) { return null }
while (this.baseTokens[this.baseTokenPos] <= n)
{ this.baseTokenPos += 2; }
var type = this.baseTokens[this.baseTokenPos + 1];
return {type: type && type.replace(/( |^)overlay .*/, ""),
size: this.baseTokens[this.baseTokenPos] - n}
};
Context.prototype.nextLine = function () {
this.line++;
if (this.maxLookAhead > 0) { this.maxLookAhead--; }
};
Context.fromSaved = function (doc, saved, line) {
if (saved instanceof SavedContext)
{ return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
else
{ return new Context(doc, copyState(doc.mode, saved), line) }
};
Context.prototype.save = function (copy) {
var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
};
// Compute a style array (an array starting with a mode generation
// -- for invalidation -- followed by pairs of end positions and
// style strings), which is used to highlight the tokens on the
// line.
function highlightLine(cm, line, context, forceToEnd) {
// A styles array always starts with a number identifying the
// mode/overlays that it is based on (for easy invalidation).
var st = [cm.state.modeGen], lineClasses = {};
// Compute the base array of styles
runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
lineClasses, forceToEnd);
var state = context.state;
// Run overlays, adjust style array.
var loop = function ( o ) {
context.baseTokens = st;
var overlay = cm.state.overlays[o], i = 1, at = 0;
context.state = true;
runMode(cm, line.text, overlay.mode, context, function (end, style) {
var start = i;
// Ensure there's a token end at the current position, and that i points at it
while (at < end) {
var i_end = st[i];
if (i_end > end)
{ st.splice(i, 1, end, st[i+1], i_end); }
i += 2;
at = Math.min(end, i_end);
}
if (!style) { return }
if (overlay.opaque) {
st.splice(start, i - start, end, "overlay " + style);
i = start + 2;
} else {
for (; start < i; start += 2) {
var cur = st[start+1];
st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
}
}
}, lineClasses);
context.state = state;
context.baseTokens = null;
context.baseTokenPos = 1;
};
for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
}
function getLineStyles(cm, line, updateFrontier) {
if (!line.styles || line.styles[0] != cm.state.modeGen) {
var context = getContextBefore(cm, lineNo(line));
var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
var result = highlightLine(cm, line, context);
if (resetState) { context.state = resetState; }
line.stateAfter = context.save(!resetState);
line.styles = result.styles;
if (result.classes) { line.styleClasses = result.classes; }
else if (line.styleClasses) { line.styleClasses = null; }
if (updateFrontier === cm.doc.highlightFrontier)
{ cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
}
return line.styles
}
function getContextBefore(cm, n, precise) {
var doc = cm.doc, display = cm.display;
if (!doc.mode.startState) { return new Context(doc, true, n) }
var start = findStartLine(cm, n, precise);
var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
doc.iter(start, n, function (line) {
processLine(cm, line.text, context);
var pos = context.line;
line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
context.nextLine();
});
if (precise) { doc.modeFrontier = context.line; }
return context
}
// Lightweight form of highlight -- proceed over this line and
// update state, but don't save a style array. Used for lines that
// aren't currently visible.
function processLine(cm, text, context, startAt) {
var mode = cm.doc.mode;
var stream = new StringStream(text, cm.options.tabSize, context);
stream.start = stream.pos = startAt || 0;
if (text == "") { callBlankLine(mode, context.state); }
while (!stream.eol()) {
readToken(mode, stream, context.state);
stream.start = stream.pos;
}
}
function callBlankLine(mode, state) {
if (mode.blankLine) { return mode.blankLine(state) }
if (!mode.innerMode) { return }
var inner = innerMode(mode, state);
if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
}
function readToken(mode, stream, state, inner) {
for (var i = 0; i < 10; i++) {
if (inner) { inner[0] = innerMode(mode, state).mode; }
var style = mode.token(stream, state);
if (stream.pos > stream.start) { return style }
}
throw new Error("Mode " + mode.name + " failed to advance stream.")
}
var Token = function(stream, type, state) {
this.start = stream.start; this.end = stream.pos;
this.string = stream.current();
this.type = type || null;
this.state = state;
};
// Utility for getTokenAt and getLineTokens
function takeToken(cm, pos, precise, asArray) {
var doc = cm.doc, mode = doc.mode, style;
pos = clipPos(doc, pos);
var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
if (asArray) { tokens = []; }
while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
stream.start = stream.pos;
style = readToken(mode, stream, context.state);
if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
}
return asArray ? tokens : new Token(stream, style, context.state)
}
function extractLineClasses(type, output) {
if (type) { for (;;) {
var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
if (!lineClass) { break }
type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
var prop = lineClass[1] ? "bgClass" : "textClass";
if (output[prop] == null)
{ output[prop] = lineClass[2]; }
else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop]))
{ output[prop] += " " + lineClass[2]; }
} }
return type
}
// Run the given mode's parser over a line, calling f for each token.
function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
var flattenSpans = mode.flattenSpans;
if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
var curStart = 0, curStyle = null;
var stream = new StringStream(text, cm.options.tabSize, context), style;
var inner = cm.options.addModeClass && [null];
if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
while (!stream.eol()) {
if (stream.pos > cm.options.maxHighlightLength) {
flattenSpans = false;
if (forceToEnd) { processLine(cm, text, context, stream.pos); }
stream.pos = text.length;
style = null;
} else {
style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
}
if (inner) {
var mName = inner[0].name;
if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
}
if (!flattenSpans || curStyle != style) {
while (curStart < stream.start) {
curStart = Math.min(stream.start, curStart + 5000);
f(curStart, curStyle);
}
curStyle = style;
}
stream.start = stream.pos;
}
while (curStart < stream.pos) {
// Webkit seems to refuse to render text nodes longer than 57444
// characters, and returns inaccurate measurements in nodes
// starting around 5000 chars.
var pos = Math.min(stream.pos, curStart + 5000);
f(pos, curStyle);
curStart = pos;
}
}
// Finds the line to start with when starting a parse. Tries to
// find a line with a stateAfter, so that it can start with a
// valid state. If that fails, it returns the line with the
// smallest indentation, which tends to need the least context to
// parse correctly.
function findStartLine(cm, n, precise) {
var minindent, minline, doc = cm.doc;
var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
for (var search = n; search > lim; --search) {
if (search <= doc.first) { return doc.first }
var line = getLine(doc, search - 1), after = line.stateAfter;
if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
{ return search }
var indented = countColumn(line.text, null, cm.options.tabSize);
if (minline == null || minindent > indented) {
minline = search - 1;
minindent = indented;
}
}
return minline
}
function retreatFrontier(doc, n) {
doc.modeFrontier = Math.min(doc.modeFrontier, n);
if (doc.highlightFrontier < n - 10) { return }
var start = doc.first;
for (var line = n - 1; line > start; line--) {
var saved = getLine(doc, line).stateAfter;
// change is on 3
// state on line 1 looked ahead 2 -- so saw 3
// test 1 + 2 < 3 should cover this
if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
start = line + 1;
break
}
}
doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
}
// Optimize some code when these features are not used.
var sawReadOnlySpans = false, sawCollapsedSpans = false;
function seeReadOnlySpans() {
sawReadOnlySpans = true;
}
function seeCollapsedSpans() {
sawCollapsedSpans = true;
}
// TEXTMARKER SPANS
function MarkedSpan(marker, from, to) {
this.marker = marker;
this.from = from; this.to = to;
}
// Search an array of spans for a span matching the given marker.
function getMarkedSpanFor(spans, marker) {
if (spans) { for (var i = 0; i < spans.length; ++i) {
var span = spans[i];
if (span.marker == marker) { return span }
} }
}
// Remove a span from an array, returning undefined if no spans are
// left (we don't store arrays for lines without spans).
function removeMarkedSpan(spans, span) {
var r;
for (var i = 0; i < spans.length; ++i)
{ if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
return r
}
// Add a span to a line.
function addMarkedSpan(line, span) {
line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
span.marker.attachLine(line);
}
// Used for the algorithm that adjusts markers for a change in the
// document. These functions cut an array of spans at a given
// character position, returning an array of remaining chunks (or
// undefined if nothing remains).
function markedSpansBefore(old, startCh, isInsert) {
var nw;
if (old) { for (var i = 0; i < old.length; ++i) {
var span = old[i], marker = span.marker;
var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
}
} }
return nw
}
function markedSpansAfter(old, endCh, isInsert) {
var nw;
if (old) { for (var i = 0; i < old.length; ++i) {
var span = old[i], marker = span.marker;
var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
span.to == null ? null : span.to - endCh));
}
} }
return nw
}
// Given a change object, compute the new set of marker spans that
// cover the line in which the change took place. Removes spans
// entirely within the change, reconnects spans belonging to the
// same marker that appear on both sides of the change, and cuts off
// spans partially within the change. Returns an array of span
// arrays with one element for each line in (after) the change.
function stretchSpansOverChange(doc, change) {
if (change.full) { return null }
var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
if (!oldFirst && !oldLast) { return null }
var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
// Get the spans that 'stick out' on both sides
var first = markedSpansBefore(oldFirst, startCh, isInsert);
var last = markedSpansAfter(oldLast, endCh, isInsert);
// Next, merge those two ends
var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
if (first) {
// Fix up .to properties of first
for (var i = 0; i < first.length; ++i) {
var span = first[i];
if (span.to == null) {
var found = getMarkedSpanFor(last, span.marker);
if (!found) { span.to = startCh; }
else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
}
}
}
if (last) {
// Fix up .from in last (or move them into first in case of sameLine)
for (var i$1 = 0; i$1 < last.length; ++i$1) {
var span$1 = last[i$1];
if (span$1.to != null) { span$1.to += offset; }
if (span$1.from == null) {
var found$1 = getMarkedSpanFor(first, span$1.marker);
if (!found$1) {
span$1.from = offset;
if (sameLine) { (first || (first = [])).push(span$1); }
}
} else {
span$1.from += offset;
if (sameLine) { (first || (first = [])).push(span$1); }
}
}
}
// Make sure we didn't create any zero-length spans
if (first) { first = clearEmptySpans(first); }
if (last && last != first) { last = clearEmptySpans(last); }
var newMarkers = [first];
if (!sameLine) {
// Fill gap with whole-line-spans
var gap = change.text.length - 2, gapMarkers;
if (gap > 0 && first)
{ for (var i$2 = 0; i$2 < first.length; ++i$2)
{ if (first[i$2].to == null)
{ (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
for (var i$3 = 0; i$3 < gap; ++i$3)
{ newMarkers.push(gapMarkers); }
newMarkers.push(last);
}
return newMarkers
}
// Remove spans that are empty and don't have a clearWhenEmpty
// option of false.
function clearEmptySpans(spans) {
for (var i = 0; i < spans.length; ++i) {
var span = spans[i];
if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
{ spans.splice(i--, 1); }
}
if (!spans.length) { return null }
return spans
}
// Used to 'clip' out readOnly ranges when making a change.
function removeReadOnlyRanges(doc, from, to) {
var markers = null;
doc.iter(from.line, to.line + 1, function (line) {
if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
var mark = line.markedSpans[i].marker;
if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
{ (markers || (markers = [])).push(mark); }
} }
});
if (!markers) { return null }
var parts = [{from: from, to: to}];
for (var i = 0; i < markers.length; ++i) {
var mk = markers[i], m = mk.find(0);
for (var j = 0; j < parts.length; ++j) {
var p = parts[j];
if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
{ newParts.push({from: p.from, to: m.from}); }
if (dto > 0 || !mk.inclusiveRight && !dto)
{ newParts.push({from: m.to, to: p.to}); }
parts.splice.apply(parts, newParts);
j += newParts.length - 3;
}
}
return parts
}
// Connect or disconnect spans from a line.
function detachMarkedSpans(line) {
var spans = line.markedSpans;
if (!spans) { return }
for (var i = 0; i < spans.length; ++i)
{ spans[i].marker.detachLine(line); }
line.markedSpans = null;
}
function attachMarkedSpans(line, spans) {
if (!spans) { return }
for (var i = 0; i < spans.length; ++i)
{ spans[i].marker.attachLine(line); }
line.markedSpans = spans;
}
// Helpers used when computing which overlapping collapsed span
// counts as the larger one.
function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
// Returns a number indicating which of two overlapping collapsed
// spans is larger (and thus includes the other). Falls back to
// comparing ids when the spans cover exactly the same range.
function compareCollapsedMarkers(a, b) {
var lenDiff = a.lines.length - b.lines.length;
if (lenDiff != 0) { return lenDiff }
var aPos = a.find(), bPos = b.find();
var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
if (fromCmp) { return -fromCmp }
var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
if (toCmp) { return toCmp }
return b.id - a.id
}
// Find out whether a line ends or starts in a collapsed span. If
// so, return the marker for that span.
function collapsedSpanAtSide(line, start) {
var sps = sawCollapsedSpans && line.markedSpans, found;
if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
sp = sps[i];
if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
(!found || compareCollapsedMarkers(found, sp.marker) < 0))
{ found = sp.marker; }
} }
return found
}
function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
function collapsedSpanAround(line, ch) {
var sps = sawCollapsedSpans && line.markedSpans, found;
if (sps) { for (var i = 0; i < sps.length; ++i) {
var sp = sps[i];
if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
(!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
} }
return found
}
// Test whether there exists a collapsed span that partially
// overlaps (covers the start or end, but not both) of a new span.
// Such overlap is not allowed.
function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
var line = getLine(doc, lineNo);
var sps = sawCollapsedSpans && line.markedSpans;
if (sps) { for (var i = 0; i < sps.length; ++i) {
var sp = sps[i];
if (!sp.marker.collapsed) { continue }
var found = sp.marker.find(0);
var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
{ return true }
} }
}
// A visual line is a line as drawn on the screen. Folding, for
// example, can cause multiple logical lines to appear on the same
// visual line. This finds the start of the visual line that the
// given line is part of (usually that is the line itself).
function visualLine(line) {
var merged;
while (merged = collapsedSpanAtStart(line))
{ line = merged.find(-1, true).line; }
return line
}
function visualLineEnd(line) {
var merged;
while (merged = collapsedSpanAtEnd(line))
{ line = merged.find(1, true).line; }
return line
}
// Returns an array of logical lines that continue the visual line
// started by the argument, or undefined if there are no such lines.
function visualLineContinued(line) {
var merged, lines;
while (merged = collapsedSpanAtEnd(line)) {
line = merged.find(1, true).line
;(lines || (lines = [])).push(line);
}
return lines
}
// Get the line number of the start of the visual line that the
// given line number is part of.
function visualLineNo(doc, lineN) {
var line = getLine(doc, lineN), vis = visualLine(line);
if (line == vis) { return lineN }
return lineNo(vis)
}
// Get the line number of the start of the next visual line after
// the given line.
function visualLineEndNo(doc, lineN) {
if (lineN > doc.lastLine()) { return lineN }
var line = getLine(doc, lineN), merged;
if (!lineIsHidden(doc, line)) { return lineN }
while (merged = collapsedSpanAtEnd(line))
{ line = merged.find(1, true).line; }
return lineNo(line) + 1
}
// Compute whether a line is hidden. Lines count as hidden when they
// are part of a visual line that starts with another line, or when
// they are entirely covered by collapsed, non-widget span.
function lineIsHidden(doc, line) {
var sps = sawCollapsedSpans && line.markedSpans;
if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
sp = sps[i];
if (!sp.marker.collapsed) { continue }
if (sp.from == null) { return true }
if (sp.marker.widgetNode) { continue }
if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
{ return true }
} }
}
function lineIsHiddenInner(doc, line, span) {
if (span.to == null) {
var end = span.marker.find(1, true);
return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
}
if (span.marker.inclusiveRight && span.to == line.text.length)
{ return true }
for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
sp = line.markedSpans[i];
if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
(sp.to == null || sp.to != span.from) &&
(sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
lineIsHiddenInner(doc, line, sp)) { return true }
}
}
// Find the height above the given line.
function heightAtLine(lineObj) {
lineObj = visualLine(lineObj);
var h = 0, chunk = lineObj.parent;
for (var i = 0; i < chunk.lines.length; ++i) {
var line = chunk.lines[i];
if (line == lineObj) { break }
else { h += line.height; }
}
for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
var cur = p.children[i$1];
if (cur == chunk) { break }
else { h += cur.height; }
}
}
return h
}
// Compute the character length of a line, taking into account
// collapsed ranges (see markText) that might hide parts, and join
// other lines onto it.
function lineLength(line) {
if (line.height == 0) { return 0 }
var len = line.text.length, merged, cur = line;
while (merged = collapsedSpanAtStart(cur)) {
var found = merged.find(0, true);
cur = found.from.line;
len += found.from.ch - found.to.ch;
}
cur = line;
while (merged = collapsedSpanAtEnd(cur)) {
var found$1 = merged.find(0, true);
len -= cur.text.length - found$1.from.ch;
cur = found$1.to.line;
len += cur.text.length - found$1.to.ch;
}
return len
}
// Find the longest line in the document.
function findMaxLine(cm) {
var d = cm.display, doc = cm.doc;
d.maxLine = getLine(doc, doc.first);
d.maxLineLength = lineLength(d.maxLine);
d.maxLineChanged = true;
doc.iter(function (line) {
var len = lineLength(line);
if (len > d.maxLineLength) {
d.maxLineLength = len;
d.maxLine = line;
}
});
}
// LINE DATA STRUCTURE
// Line objects. These hold state related to a line, including
// highlighting info (the styles array).
var Line = function(text, markedSpans, estimateHeight) {
this.text = text;
attachMarkedSpans(this, markedSpans);
this.height = estimateHeight ? estimateHeight(this) : 1;
};
Line.prototype.lineNo = function () { return lineNo(this) };
eventMixin(Line);
// Change the content (text, markers) of a line. Automatically
// invalidates cached information and tries to re-estimate the
// line's height.
function updateLine(line, text, markedSpans, estimateHeight) {
line.text = text;
if (line.stateAfter) { line.stateAfter = null; }
if (line.styles) { line.styles = null; }
if (line.order != null) { line.order = null; }
detachMarkedSpans(line);
attachMarkedSpans(line, markedSpans);
var estHeight = estimateHeight ? estimateHeight(line) : 1;
if (estHeight != line.height) { updateLineHeight(line, estHeight); }
}
// Detach a line from the document tree and its markers.
function cleanUpLine(line) {
line.parent = null;
detachMarkedSpans(line);
}
// Convert a style as returned by a mode (either null, or a string
// containing one or more styles) to a CSS style. This is cached,
// and also looks for line-wide styles.
var styleToClassCache = {}, styleToClassCacheWithMode = {};
function interpretTokenStyle(style, options) {
if (!style || /^\s*$/.test(style)) { return null }
var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
return cache[style] ||
(cache[style] = style.replace(/\S+/g, "cm-$&"))
}
// Render the DOM representation of the text of a line. Also builds
// up a 'line map', which points at the DOM nodes that represent
// specific stretches of text, and is used by the measuring code.
// The returned object contains the DOM node, this map, and
// information about line-wide styles that were set by the mode.
function buildLineContent(cm, lineView) {
// The padding-right forces the element to have a 'border', which
// is needed on Webkit to be able to get line-level bounding
// rectangles for it (in measureChar).
var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
col: 0, pos: 0, cm: cm,
trailingSpace: false,
splitSpaces: cm.getOption("lineWrapping")};
lineView.measure = {};
// Iterate over the logical lines that make up this visual line.
for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
builder.pos = 0;
builder.addToken = buildToken;
// Optionally wire in some hacks into the token-rendering
// algorithm, to deal with browser quirks.
if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
{ builder.addToken = buildTokenBadBidi(builder.addToken, order); }
builder.map = [];
var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
if (line.styleClasses) {
if (line.styleClasses.bgClass)
{ builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
if (line.styleClasses.textClass)
{ builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
}
// Ensure at least a single node is present, for measuring.
if (builder.map.length == 0)
{ builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
// Store the map and a cache object for the current logical line
if (i == 0) {
lineView.measure.map = builder.map;
lineView.measure.cache = {};
} else {
(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
}
}
// See issue #2901
if (webkit) {
var last = builder.content.lastChild;
if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
{ builder.content.className = "cm-tab-wrap-hack"; }
}
signal(cm, "renderLine", cm, lineView.line, builder.pre);
if (builder.pre.className)
{ builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
return builder
}
function defaultSpecialCharPlaceholder(ch) {
var token = elt("span", "\u2022", "cm-invalidchar");
token.title = "\\u" + ch.charCodeAt(0).toString(16);
token.setAttribute("aria-label", token.title);
return token
}
// Build up the DOM representation for a single token, and add it to
// the line map. Takes care to render special characters separately.
function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
if (!text) { return }
var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
var special = builder.cm.state.specialChars, mustWrap = false;
var content;
if (!special.test(text)) {
builder.col += text.length;
content = document.createTextNode(displayText);
builder.map.push(builder.pos, builder.pos + text.length, content);
if (ie && ie_version < 9) { mustWrap = true; }
builder.pos += text.length;
} else {
content = document.createDocumentFragment();
var pos = 0;
while (true) {
special.lastIndex = pos;
var m = special.exec(text);
var skipped = m ? m.index - pos : text.length - pos;
if (skipped) {
var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
else { content.appendChild(txt); }
builder.map.push(builder.pos, builder.pos + skipped, txt);
builder.col += skipped;
builder.pos += skipped;
}
if (!m) { break }
pos += skipped + 1;
var txt$1 = (void 0);
if (m[0] == "\t") {
var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
txt$1.setAttribute("role", "presentation");
txt$1.setAttribute("cm-text", "\t");
builder.col += tabWidth;
} else if (m[0] == "\r" || m[0] == "\n") {
txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
txt$1.setAttribute("cm-text", m[0]);
builder.col += 1;
} else {
txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
txt$1.setAttribute("cm-text", m[0]);
if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
else { content.appendChild(txt$1); }
builder.col += 1;
}
builder.map.push(builder.pos, builder.pos + 1, txt$1);
builder.pos++;
}
}
builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
if (style || startStyle || endStyle || mustWrap || css || attributes) {
var fullStyle = style || "";
if (startStyle) { fullStyle += startStyle; }
if (endStyle) { fullStyle += endStyle; }
var token = elt("span", [content], fullStyle, css);
if (attributes) {
for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
{ token.setAttribute(attr, attributes[attr]); } }
}
return builder.content.appendChild(token)
}
builder.content.appendChild(content);
}
// Change some spaces to NBSP to prevent the browser from collapsing
// trailing spaces at the end of a line when rendering text (issue #1362).
function splitSpaces(text, trailingBefore) {
if (text.length > 1 && !/ /.test(text)) { return text }
var spaceBefore = trailingBefore, result = "";
for (var i = 0; i < text.length; i++) {
var ch = text.charAt(i);
if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
{ ch = "\u00a0"; }
result += ch;
spaceBefore = ch == " ";
}
return result
}
// Work around nonsense dimensions being reported for stretches of
// right-to-left text.
function buildTokenBadBidi(inner, order) {
return function (builder, text, style, startStyle, endStyle, css, attributes) {
style = style ? style + " cm-force-border" : "cm-force-border";
var start = builder.pos, end = start + text.length;
for (;;) {
// Find the part that overlaps with the start of this text
var part = (void 0);
for (var i = 0; i < order.length; i++) {
part = order[i];
if (part.to > start && part.from <= start) { break }
}
if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
startStyle = null;
text = text.slice(part.to - start);
start = part.to;
}
}
}
function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
var widget = !ignoreWidget && marker.widgetNode;
if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
if (!widget)
{ widget = builder.content.appendChild(document.createElement("span")); }
widget.setAttribute("cm-marker", marker.id);
}
if (widget) {
builder.cm.display.input.setUneditable(widget);
builder.content.appendChild(widget);
}
builder.pos += size;
builder.trailingSpace = false;
}
// Outputs a number of spans to make up a line, taking highlighting
// and marked text into account.
function insertLineContent(line, builder, styles) {
var spans = line.markedSpans, allText = line.text, at = 0;
if (!spans) {
for (var i$1 = 1; i$1 < styles.length; i$1+=2)
{ builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
return
}
var len = allText.length, pos = 0, i = 1, text = "", style, css;
var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
for (;;) {
if (nextChange == pos) { // Update current marker set
spanStyle = spanEndStyle = spanStartStyle = css = "";
attributes = null;
collapsed = null; nextChange = Infinity;
var foundBookmarks = [], endStyles = (void 0);
for (var j = 0; j < spans.length; ++j) {
var sp = spans[j], m = sp.marker;
if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
foundBookmarks.push(m);
} else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
if (sp.to != null && sp.to != pos && nextChange > sp.to) {
nextChange = sp.to;
spanEndStyle = "";
}
if (m.className) { spanStyle += " " + m.className; }
if (m.css) { css = (css ? css + ";" : "") + m.css; }
if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
// support for the old title property
// https://github.com/codemirror/CodeMirror/pull/5673
if (m.title) { (attributes || (attributes = {})).title = m.title; }
if (m.attributes) {
for (var attr in m.attributes)
{ (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
}
if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
{ collapsed = sp; }
} else if (sp.from > pos && nextChange > sp.from) {
nextChange = sp.from;
}
}
if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
{ if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
{ buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
if (collapsed && (collapsed.from || 0) == pos) {
buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
collapsed.marker, collapsed.from == null);
if (collapsed.to == null) { return }
if (collapsed.to == pos) { collapsed = false; }
}
}
if (pos >= len) { break }
var upto = Math.min(len, nextChange);
while (true) {
if (text) {
var end = pos + text.length;
if (!collapsed) {
var tokenText = end > upto ? text.slice(0, upto - pos) : text;
builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
}
if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
pos = end;
spanStartStyle = "";
}
text = allText.slice(at, at = styles[i++]);
style = interpretTokenStyle(styles[i++], builder.cm.options);
}
}
}
// These objects are used to represent the visible (currently drawn)
// part of the document. A LineView may correspond to multiple
// logical lines, if those are connected by collapsed ranges.
function LineView(doc, line, lineN) {
// The starting line
this.line = line;
// Continuing lines, if any
this.rest = visualLineContinued(line);
// Number of logical lines in this visual line
this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
this.node = this.text = null;
this.hidden = lineIsHidden(doc, line);
}
// Create a range of LineView objects for the given lines.
function buildViewArray(cm, from, to) {
var array = [], nextPos;
for (var pos = from; pos < to; pos = nextPos) {
var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
nextPos = pos + view.size;
array.push(view);
}
return array
}
var operationGroup = null;
function pushOperation(op) {
if (operationGroup) {
operationGroup.ops.push(op);
} else {
op.ownsGroup = operationGroup = {
ops: [op],
delayedCallbacks: []
};
}
}
function fireCallbacksForOps(group) {
// Calls delayed callbacks and cursorActivity handlers until no
// new ones appear
var callbacks = group.delayedCallbacks, i = 0;
do {
for (; i < callbacks.length; i++)
{ callbacks[i].call(null); }
for (var j = 0; j < group.ops.length; j++) {
var op = group.ops[j];
if (op.cursorActivityHandlers)
{ while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
{ op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
}
} while (i < callbacks.length)
}
function finishOperation(op, endCb) {
var group = op.ownsGroup;
if (!group) { return }
try { fireCallbacksForOps(group); }
finally {
operationGroup = null;
endCb(group);
}
}
var orphanDelayedCallbacks = null;
// Often, we want to signal events at a point where we are in the
// middle of some work, but don't want the handler to start calling
// other methods on the editor, which might be in an inconsistent
// state or simply not expect any other events to happen.
// signalLater looks whether there are any handlers, and schedules
// them to be executed when the last operation ends, or, if no
// operation is active, when a timeout fires.
function signalLater(emitter, type /*, values...*/) {
var arr = getHandlers(emitter, type);
if (!arr.length) { return }
var args = Array.prototype.slice.call(arguments, 2), list;
if (operationGroup) {
list = operationGroup.delayedCallbacks;
} else if (orphanDelayedCallbacks) {
list = orphanDelayedCallbacks;
} else {
list = orphanDelayedCallbacks = [];
setTimeout(fireOrphanDelayed, 0);
}
var loop = function ( i ) {
list.push(function () { return arr[i].apply(null, args); });
};
for (var i = 0; i < arr.length; ++i)
loop( i );
}
function fireOrphanDelayed() {
var delayed = orphanDelayedCallbacks;
orphanDelayedCallbacks = null;
for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
}
// When an aspect of a line changes, a string is added to
// lineView.changes. This updates the relevant part of the line's
// DOM structure.
function updateLineForChanges(cm, lineView, lineN, dims) {
for (var j = 0; j < lineView.changes.length; j++) {
var type = lineView.changes[j];
if (type == "text") { updateLineText(cm, lineView); }
else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
else if (type == "class") { updateLineClasses(cm, lineView); }
else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
}
lineView.changes = null;
}
// Lines with gutter elements, widgets or a background class need to
// be wrapped, and have the extra elements added to the wrapper div
function ensureLineWrapped(lineView) {
if (lineView.node == lineView.text) {
lineView.node = elt("div", null, null, "position: relative");
if (lineView.text.parentNode)
{ lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
lineView.node.appendChild(lineView.text);
if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
}
return lineView.node
}
function updateLineBackground(cm, lineView) {
var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
if (cls) { cls += " CodeMirror-linebackground"; }
if (lineView.background) {
if (cls) { lineView.background.className = cls; }
else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
} else if (cls) {
var wrap = ensureLineWrapped(lineView);
lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
cm.display.input.setUneditable(lineView.background);
}
}
// Wrapper around buildLineContent which will reuse the structure
// in display.externalMeasured when possible.
function getLineContent(cm, lineView) {
var ext = cm.display.externalMeasured;
if (ext && ext.line == lineView.line) {
cm.display.externalMeasured = null;
lineView.measure = ext.measure;
return ext.built
}
return buildLineContent(cm, lineView)
}
// Redraw the line's text. Interacts with the background and text
// classes because the mode may output tokens that influence these
// classes.
function updateLineText(cm, lineView) {
var cls = lineView.text.className;
var built = getLineContent(cm, lineView);
if (lineView.text == lineView.node) { lineView.node = built.pre; }
lineView.text.parentNode.replaceChild(built.pre, lineView.text);
lineView.text = built.pre;
if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
lineView.bgClass = built.bgClass;
lineView.textClass = built.textClass;
updateLineClasses(cm, lineView);
} else if (cls) {
lineView.text.className = cls;
}
}
function updateLineClasses(cm, lineView) {
updateLineBackground(cm, lineView);
if (lineView.line.wrapClass)
{ ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
else if (lineView.node != lineView.text)
{ lineView.node.className = ""; }
var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
lineView.text.className = textClass || "";
}
function updateLineGutter(cm, lineView, lineN, dims) {
if (lineView.gutter) {
lineView.node.removeChild(lineView.gutter);
lineView.gutter = null;
}
if (lineView.gutterBackground) {
lineView.node.removeChild(lineView.gutterBackground);
lineView.gutterBackground = null;
}
if (lineView.line.gutterClass) {
var wrap = ensureLineWrapped(lineView);
lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
cm.display.input.setUneditable(lineView.gutterBackground);
wrap.insertBefore(lineView.gutterBackground, lineView.text);
}
var markers = lineView.line.gutterMarkers;
if (cm.options.lineNumbers || markers) {
var wrap$1 = ensureLineWrapped(lineView);
var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
cm.display.input.setUneditable(gutterWrap);
wrap$1.insertBefore(gutterWrap, lineView.text);
if (lineView.line.gutterClass)
{ gutterWrap.className += " " + lineView.line.gutterClass; }
if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
{ lineView.lineNumber = gutterWrap.appendChild(
elt("div", lineNumberFor(cm.options, lineN),
"CodeMirror-linenumber CodeMirror-gutter-elt",
("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
if (found)
{ gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
} }
}
}
function updateLineWidgets(cm, lineView, dims) {
if (lineView.alignable) { lineView.alignable = null; }
var isWidget = classTest("CodeMirror-linewidget");
for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
next = node.nextSibling;
if (isWidget.test(node.className)) { lineView.node.removeChild(node); }
}
insertLineWidgets(cm, lineView, dims);
}
// Build a line's DOM representation from scratch
function buildLineElement(cm, lineView, lineN, dims) {
var built = getLineContent(cm, lineView);
lineView.text = lineView.node = built.pre;
if (built.bgClass) { lineView.bgClass = built.bgClass; }
if (built.textClass) { lineView.textClass = built.textClass; }
updateLineClasses(cm, lineView);
updateLineGutter(cm, lineView, lineN, dims);
insertLineWidgets(cm, lineView, dims);
return lineView.node
}
// A lineView may contain multiple logical lines (when merged by
// collapsed spans). The widgets for all of them need to be drawn.
function insertLineWidgets(cm, lineView, dims) {
insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
{ insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
}
function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
if (!line.widgets) { return }
var wrap = ensureLineWrapped(lineView);
for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
positionLineWidget(widget, node, lineView, dims);
cm.display.input.setUneditable(node);
if (allowAbove && widget.above)
{ wrap.insertBefore(node, lineView.gutter || lineView.text); }
else
{ wrap.appendChild(node); }
signalLater(widget, "redraw");
}
}
function positionLineWidget(widget, node, lineView, dims) {
if (widget.noHScroll) {
(lineView.alignable || (lineView.alignable = [])).push(node);
var width = dims.wrapperWidth;
node.style.left = dims.fixedPos + "px";
if (!widget.coverGutter) {
width -= dims.gutterTotalWidth;
node.style.paddingLeft = dims.gutterTotalWidth + "px";
}
node.style.width = width + "px";
}
if (widget.coverGutter) {
node.style.zIndex = 5;
node.style.position = "relative";
if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
}
}
function widgetHeight(widget) {
if (widget.height != null) { return widget.height }
var cm = widget.doc.cm;
if (!cm) { return 0 }
if (!contains(document.body, widget.node)) {
var parentStyle = "position: relative;";
if (widget.coverGutter)
{ parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
if (widget.noHScroll)
{ parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
}
return widget.height = widget.node.parentNode.offsetHeight
}
// Return true when the given mouse event happened in a widget
function eventInWidget(display, e) {
for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
(n.parentNode == display.sizer && n != display.mover))
{ return true }
}
}
// POSITION MEASUREMENT
function paddingTop(display) {return display.lineSpace.offsetTop}
function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
function paddingH(display) {
if (display.cachedPaddingH) { return display.cachedPaddingH }
var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
return data
}
function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
function displayWidth(cm) {
return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
}
function displayHeight(cm) {
return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
}
// Ensure the lineView.wrapping.heights array is populated. This is
// an array of bottom offsets for the lines that make up a drawn
// line. When lineWrapping is on, there might be more than one
// height.
function ensureLineHeights(cm, lineView, rect) {
var wrapping = cm.options.lineWrapping;
var curWidth = wrapping && displayWidth(cm);
if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
var heights = lineView.measure.heights = [];
if (wrapping) {
lineView.measure.width = curWidth;
var rects = lineView.text.firstChild.getClientRects();
for (var i = 0; i < rects.length - 1; i++) {
var cur = rects[i], next = rects[i + 1];
if (Math.abs(cur.bottom - next.bottom) > 2)
{ heights.push((cur.bottom + next.top) / 2 - rect.top); }
}
}
heights.push(rect.bottom - rect.top);
}
}
// Find a line map (mapping character offsets to text nodes) and a
// measurement cache for the given line number. (A line view might
// contain multiple lines when collapsed ranges are present.)
function mapFromLineView(lineView, line, lineN) {
if (lineView.line == line)
{ return {map: lineView.measure.map, cache: lineView.measure.cache} }
for (var i = 0; i < lineView.rest.length; i++)
{ if (lineView.rest[i] == line)
{ return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
{ if (lineNo(lineView.rest[i$1]) > lineN)
{ return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
}
// Render a line into the hidden node display.externalMeasured. Used
// when measurement is needed for a line that's not in the viewport.
function updateExternalMeasurement(cm, line) {
line = visualLine(line);
var lineN = lineNo(line);
var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
view.lineN = lineN;
var built = view.built = buildLineContent(cm, view);
view.text = built.pre;
removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
return view
}
// Get a {top, bottom, left, right} box (in line-local coordinates)
// for a given character.
function measureChar(cm, line, ch, bias) {
return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
}
// Find a line view that corresponds to the given line number.
function findViewForLine(cm, lineN) {
if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
{ return cm.display.view[findViewIndex(cm, lineN)] }
var ext = cm.display.externalMeasured;
if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
{ return ext }
}
// Measurement can be split in two steps, the set-up work that
// applies to the whole line, and the measurement of the actual
// character. Functions like coordsChar, that need to do a lot of
// measurements in a row, can thus ensure that the set-up work is
// only done once.
function prepareMeasureForLine(cm, line) {
var lineN = lineNo(line);
var view = findViewForLine(cm, lineN);
if (view && !view.text) {
view = null;
} else if (view && view.changes) {
updateLineForChanges(cm, view, lineN, getDimensions(cm));
cm.curOp.forceUpdate = true;
}
if (!view)
{ view = updateExternalMeasurement(cm, line); }
var info = mapFromLineView(view, line, lineN);
return {
line: line, view: view, rect: null,
map: info.map, cache: info.cache, before: info.before,
hasHeights: false
}
}
// Given a prepared measurement object, measures the position of an
// actual character (or fetches it from the cache).
function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
if (prepared.before) { ch = -1; }
var key = ch + (bias || ""), found;
if (prepared.cache.hasOwnProperty(key)) {
found = prepared.cache[key];
} else {
if (!prepared.rect)
{ prepared.rect = prepared.view.text.getBoundingClientRect(); }
if (!prepared.hasHeights) {
ensureLineHeights(cm, prepared.view, prepared.rect);
prepared.hasHeights = true;
}
found = measureCharInner(cm, prepared, ch, bias);
if (!found.bogus) { prepared.cache[key] = found; }
}
return {left: found.left, right: found.right,
top: varHeight ? found.rtop : found.top,
bottom: varHeight ? found.rbottom : found.bottom}
}
var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
function nodeAndOffsetInLineMap(map, ch, bias) {
var node, start, end, collapse, mStart, mEnd;
// First, search the line map for the text node corresponding to,
// or closest to, the target character.
for (var i = 0; i < map.length; i += 3) {
mStart = map[i];
mEnd = map[i + 1];
if (ch < mStart) {
start = 0; end = 1;
collapse = "left";
} else if (ch < mEnd) {
start = ch - mStart;
end = start + 1;
} else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
end = mEnd - mStart;
start = end - 1;
if (ch >= mEnd) { collapse = "right"; }
}
if (start != null) {
node = map[i + 2];
if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
{ collapse = bias; }
if (bias == "left" && start == 0)
{ while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
node = map[(i -= 3) + 2];
collapse = "left";
} }
if (bias == "right" && start == mEnd - mStart)
{ while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
node = map[(i += 3) + 2];
collapse = "right";
} }
break
}
}
return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
}
function getUsefulRect(rects, bias) {
var rect = nullRect;
if (bias == "left") { for (var i = 0; i < rects.length; i++) {
if ((rect = rects[i]).left != rect.right) { break }
} } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
if ((rect = rects[i$1]).left != rect.right) { break }
} }
return rect
}
function measureCharInner(cm, prepared, ch, bias) {
var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
var rect;
if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
{ rect = node.parentNode.getBoundingClientRect(); }
else
{ rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
if (rect.left || rect.right || start == 0) { break }
end = start;
start = start - 1;
collapse = "right";
}
if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
} else { // If it is a widget, simply get the box for the whole widget.
if (start > 0) { collapse = bias = "right"; }
var rects;
if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
{ rect = rects[bias == "right" ? rects.length - 1 : 0]; }
else
{ rect = node.getBoundingClientRect(); }
}
if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
var rSpan = node.parentNode.getClientRects()[0];
if (rSpan)
{ rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
else
{ rect = nullRect; }
}
var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
var mid = (rtop + rbot) / 2;
var heights = prepared.view.measure.heights;
var i = 0;
for (; i < heights.length - 1; i++)
{ if (mid < heights[i]) { break } }
var top = i ? heights[i - 1] : 0, bot = heights[i];
var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
top: top, bottom: bot};
if (!rect.left && !rect.right) { result.bogus = true; }
if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
return result
}
// Work around problem with bounding client rects on ranges being
// returned incorrectly when zoomed on IE10 and below.
function maybeUpdateRectForZooming(measure, rect) {
if (!window.screen || screen.logicalXDPI == null ||
screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
{ return rect }
var scaleX = screen.logicalXDPI / screen.deviceXDPI;
var scaleY = screen.logicalYDPI / screen.deviceYDPI;
return {left: rect.left * scaleX, right: rect.right * scaleX,
top: rect.top * scaleY, bottom: rect.bottom * scaleY}
}
function clearLineMeasurementCacheFor(lineView) {
if (lineView.measure) {
lineView.measure.cache = {};
lineView.measure.heights = null;
if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
{ lineView.measure.caches[i] = {}; } }
}
}
function clearLineMeasurementCache(cm) {
cm.display.externalMeasure = null;
removeChildren(cm.display.lineMeasure);
for (var i = 0; i < cm.display.view.length; i++)
{ clearLineMeasurementCacheFor(cm.display.view[i]); }
}
function clearCaches(cm) {
clearLineMeasurementCache(cm);
cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
cm.display.lineNumChars = null;
}
function pageScrollX() {
// Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
// which causes page_Offset and bounding client rects to use
// different reference viewports and invalidate our calculations.
if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
return window.pageXOffset || (document.documentElement || document.body).scrollLeft
}
function pageScrollY() {
if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
return window.pageYOffset || (document.documentElement || document.body).scrollTop
}
function widgetTopHeight(lineObj) {
var height = 0;
if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
{ height += widgetHeight(lineObj.widgets[i]); } } }
return height
}
// Converts a {top, bottom, left, right} box from line-local
// coordinates into another coordinate system. Context may be one of
// "line", "div" (display.lineDiv), "local"./null (editor), "window",
// or "page".
function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
if (!includeWidgets) {
var height = widgetTopHeight(lineObj);
rect.top += height; rect.bottom += height;
}
if (context == "line") { return rect }
if (!context) { context = "local"; }
var yOff = heightAtLine(lineObj);
if (context == "local") { yOff += paddingTop(cm.display); }
else { yOff -= cm.display.viewOffset; }
if (context == "page" || context == "window") {
var lOff = cm.display.lineSpace.getBoundingClientRect();
yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
rect.left += xOff; rect.right += xOff;
}
rect.top += yOff; rect.bottom += yOff;
return rect
}
// Coverts a box from "div" coords to another coordinate system.
// Context may be "window", "page", "div", or "local"./null.
function fromCoordSystem(cm, coords, context) {
if (context == "div") { return coords }
var left = coords.left, top = coords.top;
// First move into "page" coordinate system
if (context == "page") {
left -= pageScrollX();
top -= pageScrollY();
} else if (context == "local" || !context) {
var localBox = cm.display.sizer.getBoundingClientRect();
left += localBox.left;
top += localBox.top;
}
var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
}
function charCoords(cm, pos, context, lineObj, bias) {
if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
}
// Returns a box for a given cursor position, which may have an
// 'other' property containing the position of the secondary cursor
// on a bidi boundary.
// A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
// and after `char - 1` in writing order of `char - 1`
// A cursor Pos(line, char, "after") is on the same visual line as `char`
// and before `char` in writing order of `char`
// Examples (upper-case letters are RTL, lower-case are LTR):
// Pos(0, 1, ...)
// before after
// ab a|b a|b
// aB a|B aB|
// Ab |Ab A|b
// AB B|A B|A
// Every position after the last character on a line is considered to stick
// to the last character on the line.
function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
lineObj = lineObj || getLine(cm.doc, pos.line);
if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
function get(ch, right) {
var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
if (right) { m.left = m.right; } else { m.right = m.left; }
return intoCoordSystem(cm, lineObj, m, context)
}
var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
if (ch >= lineObj.text.length) {
ch = lineObj.text.length;
sticky = "before";
} else if (ch <= 0) {
ch = 0;
sticky = "after";
}
if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
function getBidi(ch, partPos, invert) {
var part = order[partPos], right = part.level == 1;
return get(invert ? ch - 1 : ch, right != invert)
}
var partPos = getBidiPartAt(order, ch, sticky);
var other = bidiOther;
var val = getBidi(ch, partPos, sticky == "before");
if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
return val
}
// Used to cheaply estimate the coordinates for a position. Used for
// intermediate scroll updates.
function estimateCoords(cm, pos) {
var left = 0;
pos = clipPos(cm.doc, pos);
if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
var lineObj = getLine(cm.doc, pos.line);
var top = heightAtLine(lineObj) + paddingTop(cm.display);
return {left: left, right: left, top: top, bottom: top + lineObj.height}
}
// Positions returned by coordsChar contain some extra information.
// xRel is the relative x position of the input coordinates compared
// to the found position (so xRel > 0 means the coordinates are to
// the right of the character position, for example). When outside
// is true, that means the coordinates lie outside the line's
// vertical range.
function PosWithInfo(line, ch, sticky, outside, xRel) {
var pos = Pos(line, ch, sticky);
pos.xRel = xRel;
if (outside) { pos.outside = outside; }
return pos
}
// Compute the character position closest to the given coordinates.
// Input must be lineSpace-local ("div" coordinate system).
function coordsChar(cm, x, y) {
var doc = cm.doc;
y += cm.display.viewOffset;
if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }
var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
if (lineN > last)
{ return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }
if (x < 0) { x = 0; }
var lineObj = getLine(doc, lineN);
for (;;) {
var found = coordsCharInner(cm, lineObj, lineN, x, y);
var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
if (!collapsed) { return found }
var rangeEnd = collapsed.find(1);
if (rangeEnd.line == lineN) { return rangeEnd }
lineObj = getLine(doc, lineN = rangeEnd.line);
}
}
function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
y -= widgetTopHeight(lineObj);
var end = lineObj.text.length;
var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
return {begin: begin, end: end}
}
function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
}
// Returns true if the given side of a box is after the given
// coordinates, in top-to-bottom, left-to-right order.
function boxIsAfter(box, x, y, left) {
return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
}
function coordsCharInner(cm, lineObj, lineNo, x, y) {
// Move y into line-local coordinate space
y -= heightAtLine(lineObj);
var preparedMeasure = prepareMeasureForLine(cm, lineObj);
// When directly calling `measureCharPrepared`, we have to adjust
// for the widgets at this line.
var widgetHeight = widgetTopHeight(lineObj);
var begin = 0, end = lineObj.text.length, ltr = true;
var order = getOrder(lineObj, cm.doc.direction);
// If the line isn't plain left-to-right text, first figure out
// which bidi section the coordinates fall into.
if (order) {
var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
(cm, lineObj, lineNo, preparedMeasure, order, x, y);
ltr = part.level != 1;
// The awkward -1 offsets are needed because findFirst (called
// on these below) will treat its first bound as inclusive,
// second as exclusive, but we want to actually address the
// characters in the part's range
begin = ltr ? part.from : part.to - 1;
end = ltr ? part.to : part.from - 1;
}
// A binary search to find the first character whose bounding box
// starts after the coordinates. If we run across any whose box wrap
// the coordinates, store that.
var chAround = null, boxAround = null;
var ch = findFirst(function (ch) {
var box = measureCharPrepared(cm, preparedMeasure, ch);
box.top += widgetHeight; box.bottom += widgetHeight;
if (!boxIsAfter(box, x, y, false)) { return false }
if (box.top <= y && box.left <= x) {
chAround = ch;
boxAround = box;
}
return true
}, begin, end);
var baseX, sticky, outside = false;
// If a box around the coordinates was found, use that
if (boxAround) {
// Distinguish coordinates nearer to the left or right side of the box
var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
ch = chAround + (atStart ? 0 : 1);
sticky = atStart ? "after" : "before";
baseX = atLeft ? boxAround.left : boxAround.right;
} else {
// (Adjust for extended bound, if necessary.)
if (!ltr && (ch == end || ch == begin)) { ch++; }
// To determine which side to associate with, get the box to the
// left of the character and compare it's vertical position to the
// coordinates
sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
(measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
"after" : "before";
// Now get accurate coordinates for this place, in order to get a
// base X position
var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure);
baseX = coords.left;
outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
}
ch = skipExtendingChars(lineObj.text, ch, 1);
return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
}
function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
// Bidi parts are sorted left-to-right, and in a non-line-wrapping
// situation, we can take this ordering to correspond to the visual
// ordering. This finds the first part whose end is after the given
// coordinates.
var index = findFirst(function (i) {
var part = order[i], ltr = part.level != 1;
return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
"line", lineObj, preparedMeasure), x, y, true)
}, 0, order.length - 1);
var part = order[index];
// If this isn't the first part, the part's start is also after
// the coordinates, and the coordinates aren't on the same line as
// that start, move one part back.
if (index > 0) {
var ltr = part.level != 1;
var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
"line", lineObj, preparedMeasure);
if (boxIsAfter(start, x, y, true) && start.top > y)
{ part = order[index - 1]; }
}
return part
}
function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
// In a wrapped line, rtl text on wrapping boundaries can do things
// that don't correspond to the ordering in our `order` array at
// all, so a binary search doesn't work, and we want to return a
// part that only spans one line so that the binary search in
// coordsCharInner is safe. As such, we first find the extent of the
// wrapped line, and then do a flat search in which we discard any
// spans that aren't on the line.
var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
var begin = ref.begin;
var end = ref.end;
if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
var part = null, closestDist = null;
for (var i = 0; i < order.length; i++) {
var p = order[i];
if (p.from >= end || p.to <= begin) { continue }
var ltr = p.level != 1;
var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
// Weigh against spans ending before this, so that they are only
// picked if nothing ends after
var dist = endX < x ? x - endX + 1e9 : endX - x;
if (!part || closestDist > dist) {
part = p;
closestDist = dist;
}
}
if (!part) { part = order[order.length - 1]; }
// Clip the part to the wrapped line.
if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
return part
}
var measureText;
// Compute the default text height.
function textHeight(display) {
if (display.cachedTextHeight != null) { return display.cachedTextHeight }
if (measureText == null) {
measureText = elt("pre", null, "CodeMirror-line-like");
// Measure a bunch of lines, for browsers that compute
// fractional heights.
for (var i = 0; i < 49; ++i) {
measureText.appendChild(document.createTextNode("x"));
measureText.appendChild(elt("br"));
}
measureText.appendChild(document.createTextNode("x"));
}
removeChildrenAndAdd(display.measure, measureText);
var height = measureText.offsetHeight / 50;
if (height > 3) { display.cachedTextHeight = height; }
removeChildren(display.measure);
return height || 1
}
// Compute the default character width.
function charWidth(display) {
if (display.cachedCharWidth != null) { return display.cachedCharWidth }
var anchor = elt("span", "xxxxxxxxxx");
var pre = elt("pre", [anchor], "CodeMirror-line-like");
removeChildrenAndAdd(display.measure, pre);
var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
if (width > 2) { display.cachedCharWidth = width; }
return width || 10
}
// Do a bulk-read of the DOM positions and sizes needed to draw the
// view, so that we don't interleave reading and writing to the DOM.
function getDimensions(cm) {
var d = cm.display, left = {}, width = {};
var gutterLeft = d.gutters.clientLeft;
for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
var id = cm.display.gutterSpecs[i].className;
left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
width[id] = n.clientWidth;
}
return {fixedPos: compensateForHScroll(d),
gutterTotalWidth: d.gutters.offsetWidth,
gutterLeft: left,
gutterWidth: width,
wrapperWidth: d.wrapper.clientWidth}
}
// Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
// but using getBoundingClientRect to get a sub-pixel-accurate
// result.
function compensateForHScroll(display) {
return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
}
// Returns a function that estimates the height of a line, to use as
// first approximation until the line becomes visible (and is thus
// properly measurable).
function estimateHeight(cm) {
var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
return function (line) {
if (lineIsHidden(cm.doc, line)) { return 0 }
var widgetsHeight = 0;
if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
} }
if (wrapping)
{ return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
else
{ return widgetsHeight + th }
}
}
function estimateLineHeights(cm) {
var doc = cm.doc, est = estimateHeight(cm);
doc.iter(function (line) {
var estHeight = est(line);
if (estHeight != line.height) { updateLineHeight(line, estHeight); }
});
}
// Given a mouse event, find the corresponding position. If liberal
// is false, it checks whether a gutter or scrollbar was clicked,
// and returns null if it was. forRect is used by rectangular
// selections, and tries to estimate a character position even for
// coordinates beyond the right of the text.
function posFromMouse(cm, e, liberal, forRect) {
var display = cm.display;
if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
var x, y, space = display.lineSpace.getBoundingClientRect();
// Fails unpredictably on IE[67] when mouse is dragged around quickly.
try { x = e.clientX - space.left; y = e.clientY - space.top; }
catch (e$1) { return null }
var coords = coordsChar(cm, x, y), line;
if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
}
return coords
}
// Find the view element corresponding to a given line. Return null
// when the line isn't visible.
function findViewIndex(cm, n) {
if (n >= cm.display.viewTo) { return null }
n -= cm.display.viewFrom;
if (n < 0) { return null }
var view = cm.display.view;
for (var i = 0; i < view.length; i++) {
n -= view[i].size;
if (n < 0) { return i }
}
}
// Updates the display.view data structure for a given change to the
// document. From and to are in pre-change coordinates. Lendiff is
// the amount of lines added or subtracted by the change. This is
// used for changes that span multiple lines, or change the way
// lines are divided into visual lines. regLineChange (below)
// registers single-line changes.
function regChange(cm, from, to, lendiff) {
if (from == null) { from = cm.doc.first; }
if (to == null) { to = cm.doc.first + cm.doc.size; }
if (!lendiff) { lendiff = 0; }
var display = cm.display;
if (lendiff && to < display.viewTo &&
(display.updateLineNumbers == null || display.updateLineNumbers > from))
{ display.updateLineNumbers = from; }
cm.curOp.viewChanged = true;
if (from >= display.viewTo) { // Change after
if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
{ resetView(cm); }
} else if (to <= display.viewFrom) { // Change before
if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
resetView(cm);
} else {
display.viewFrom += lendiff;
display.viewTo += lendiff;
}
} else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
resetView(cm);
} else if (from <= display.viewFrom) { // Top overlap
var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
if (cut) {
display.view = display.view.slice(cut.index);
display.viewFrom = cut.lineN;
display.viewTo += lendiff;
} else {
resetView(cm);
}
} else if (to >= display.viewTo) { // Bottom overlap
var cut$1 = viewCuttingPoint(cm, from, from, -1);
if (cut$1) {
display.view = display.view.slice(0, cut$1.index);
display.viewTo = cut$1.lineN;
} else {
resetView(cm);
}
} else { // Gap in the middle
var cutTop = viewCuttingPoint(cm, from, from, -1);
var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
if (cutTop && cutBot) {
display.view = display.view.slice(0, cutTop.index)
.concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
.concat(display.view.slice(cutBot.index));
display.viewTo += lendiff;
} else {
resetView(cm);
}
}
var ext = display.externalMeasured;
if (ext) {
if (to < ext.lineN)
{ ext.lineN += lendiff; }
else if (from < ext.lineN + ext.size)
{ display.externalMeasured = null; }
}
}
// Register a change to a single line. Type must be one of "text",
// "gutter", "class", "widget"
function regLineChange(cm, line, type) {
cm.curOp.viewChanged = true;
var display = cm.display, ext = cm.display.externalMeasured;
if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
{ display.externalMeasured = null; }
if (line < display.viewFrom || line >= display.viewTo) { return }
var lineView = display.view[findViewIndex(cm, line)];
if (lineView.node == null) { return }
var arr = lineView.changes || (lineView.changes = []);
if (indexOf(arr, type) == -1) { arr.push(type); }
}
// Clear the view.
function resetView(cm) {
cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
cm.display.view = [];
cm.display.viewOffset = 0;
}
function viewCuttingPoint(cm, oldN, newN, dir) {
var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
{ return {index: index, lineN: newN} }
var n = cm.display.viewFrom;
for (var i = 0; i < index; i++)
{ n += view[i].size; }
if (n != oldN) {
if (dir > 0) {
if (index == view.length - 1) { return null }
diff = (n + view[index].size) - oldN;
index++;
} else {
diff = n - oldN;
}
oldN += diff; newN += diff;
}
while (visualLineNo(cm.doc, newN) != newN) {
if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
index += dir;
}
return {index: index, lineN: newN}
}
// Force the view to cover a given range, adding empty view element
// or clipping off existing ones as needed.
function adjustView(cm, from, to) {
var display = cm.display, view = display.view;
if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
display.view = buildViewArray(cm, from, to);
display.viewFrom = from;
} else {
if (display.viewFrom > from)
{ display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
else if (display.viewFrom < from)
{ display.view = display.view.slice(findViewIndex(cm, from)); }
display.viewFrom = from;
if (display.viewTo < to)
{ display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
else if (display.viewTo > to)
{ display.view = display.view.slice(0, findViewIndex(cm, to)); }
}
display.viewTo = to;
}
// Count the number of lines in the view whose DOM representation is
// out of date (or nonexistent).
function countDirtyView(cm) {
var view = cm.display.view, dirty = 0;
for (var i = 0; i < view.length; i++) {
var lineView = view[i];
if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
}
return dirty
}
function updateSelection(cm) {
cm.display.input.showSelection(cm.display.input.prepareSelection());
}
function prepareSelection(cm, primary) {
if ( primary === void 0 ) primary = true;
var doc = cm.doc, result = {};
var curFragment = result.cursors = document.createDocumentFragment();
var selFragment = result.selection = document.createDocumentFragment();
for (var i = 0; i < doc.sel.ranges.length; i++) {
if (!primary && i == doc.sel.primIndex) { continue }
var range = doc.sel.ranges[i];
if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
var collapsed = range.empty();
if (collapsed || cm.options.showCursorWhenSelecting)
{ drawSelectionCursor(cm, range.head, curFragment); }
if (!collapsed)
{ drawSelectionRange(cm, range, selFragment); }
}
return result
}
// Draws a cursor for the given range
function drawSelectionCursor(cm, head, output) {
var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
cursor.style.left = pos.left + "px";
cursor.style.top = pos.top + "px";
cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
if (pos.other) {
// Secondary cursor, shown when on a 'jump' in bi-directional text
var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
otherCursor.style.display = "";
otherCursor.style.left = pos.other.left + "px";
otherCursor.style.top = pos.other.top + "px";
otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
}
}
function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
// Draws the given range as a highlighted selection
function drawSelectionRange(cm, range, output) {
var display = cm.display, doc = cm.doc;
var fragment = document.createDocumentFragment();
var padding = paddingH(cm.display), leftSide = padding.left;
var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
var docLTR = doc.direction == "ltr";
function add(left, top, width, bottom) {
if (top < 0) { top = 0; }
top = Math.round(top);
bottom = Math.round(bottom);
fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px")));
}
function drawForLine(line, fromArg, toArg) {
var lineObj = getLine(doc, line);
var lineLen = lineObj.text.length;
var start, end;
function coords(ch, bias) {
return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
}
function wrapX(pos, dir, side) {
var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
return coords(ch, prop)[prop]
}
var order = getOrder(lineObj, doc.direction);
iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
var ltr = dir == "ltr";
var fromPos = coords(from, ltr ? "left" : "right");
var toPos = coords(to - 1, ltr ? "right" : "left");
var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
var first = i == 0, last = !order || i == order.length - 1;
if (toPos.top - fromPos.top <= 3) { // Single line
var openLeft = (docLTR ? openStart : openEnd) && first;
var openRight = (docLTR ? openEnd : openStart) && last;
var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
add(left, fromPos.top, right - left, fromPos.bottom);
} else { // Multiple lines
var topLeft, topRight, botLeft, botRight;
if (ltr) {
topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
topRight = docLTR ? rightSide : wrapX(from, dir, "before");
botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
botRight = docLTR && openEnd && last ? rightSide : toPos.right;
} else {
topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
}
add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
}
if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
if (cmpCoords(toPos, start) < 0) { start = toPos; }
if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
if (cmpCoords(toPos, end) < 0) { end = toPos; }
});
return {start: start, end: end}
}
var sFrom = range.from(), sTo = range.to();
if (sFrom.line == sTo.line) {
drawForLine(sFrom.line, sFrom.ch, sTo.ch);
} else {
var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
var singleVLine = visualLine(fromLine) == visualLine(toLine);
var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
if (singleVLine) {
if (leftEnd.top < rightStart.top - 2) {
add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
} else {
add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
}
}
if (leftEnd.bottom < rightStart.top)
{ add(leftSide, leftEnd.bottom, null, rightStart.top); }
}
output.appendChild(fragment);
}
// Cursor-blinking
function restartBlink(cm) {
if (!cm.state.focused) { return }
var display = cm.display;
clearInterval(display.blinker);
var on = true;
display.cursorDiv.style.visibility = "";
if (cm.options.cursorBlinkRate > 0)
{ display.blinker = setInterval(function () {
if (!cm.hasFocus()) { onBlur(cm); }
display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
}, cm.options.cursorBlinkRate); }
else if (cm.options.cursorBlinkRate < 0)
{ display.cursorDiv.style.visibility = "hidden"; }
}
function ensureFocus(cm) {
if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
}
function delayBlurEvent(cm) {
cm.state.delayingBlurEvent = true;
setTimeout(function () { if (cm.state.delayingBlurEvent) {
cm.state.delayingBlurEvent = false;
onBlur(cm);
} }, 100);
}
function onFocus(cm, e) {
if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }
if (cm.options.readOnly == "nocursor") { return }
if (!cm.state.focused) {
signal(cm, "focus", cm, e);
cm.state.focused = true;
addClass(cm.display.wrapper, "CodeMirror-focused");
// This test prevents this from firing when a context
// menu is closed (since the input reset would kill the
// select-all detection hack)
if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
cm.display.input.reset();
if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
}
cm.display.input.receivedFocus();
}
restartBlink(cm);
}
function onBlur(cm, e) {
if (cm.state.delayingBlurEvent) { return }
if (cm.state.focused) {
signal(cm, "blur", cm, e);
cm.state.focused = false;
rmClass(cm.display.wrapper, "CodeMirror-focused");
}
clearInterval(cm.display.blinker);
setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
}
// Read the actual heights of the rendered lines, and update their
// stored heights to match.
function updateHeightsInViewport(cm) {
var display = cm.display;
var prevBottom = display.lineDiv.offsetTop;
for (var i = 0; i < display.view.length; i++) {
var cur = display.view[i], wrapping = cm.options.lineWrapping;
var height = (void 0), width = 0;
if (cur.hidden) { continue }
if (ie && ie_version < 8) {
var bot = cur.node.offsetTop + cur.node.offsetHeight;
height = bot - prevBottom;
prevBottom = bot;
} else {
var box = cur.node.getBoundingClientRect();
height = box.bottom - box.top;
// Check that lines don't extend past the right of the current
// editor width
if (!wrapping && cur.text.firstChild)
{ width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
}
var diff = cur.line.height - height;
if (diff > .005 || diff < -.005) {
updateLineHeight(cur.line, height);
updateWidgetHeight(cur.line);
if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
{ updateWidgetHeight(cur.rest[j]); } }
}
if (width > cm.display.sizerWidth) {
var chWidth = Math.ceil(width / charWidth(cm.display));
if (chWidth > cm.display.maxLineLength) {
cm.display.maxLineLength = chWidth;
cm.display.maxLine = cur.line;
cm.display.maxLineChanged = true;
}
}
}
}
// Read and store the height of line widgets associated with the
// given line.
function updateWidgetHeight(line) {
if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
var w = line.widgets[i], parent = w.node.parentNode;
if (parent) { w.height = parent.offsetHeight; }
} }
}
// Compute the lines that are visible in a given viewport (defaults
// the the current scroll position). viewport may contain top,
// height, and ensure (see op.scrollToPos) properties.
function visibleLines(display, doc, viewport) {
var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
top = Math.floor(top - paddingTop(display));
var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
// Ensure is a {from: {line, ch}, to: {line, ch}} object, and
// forces those lines into the viewport (if possible).
if (viewport && viewport.ensure) {
var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
if (ensureFrom < from) {
from = ensureFrom;
to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
} else if (Math.min(ensureTo, doc.lastLine()) >= to) {
from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
to = ensureTo;
}
}
return {from: from, to: Math.max(to, from + 1)}
}
// SCROLLING THINGS INTO VIEW
// If an editor sits on the top or bottom of the window, partially
// scrolled out of view, this ensures that the cursor is visible.
function maybeScrollWindow(cm, rect) {
if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
if (rect.top + box.top < 0) { doScroll = true; }
else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
if (doScroll != null && !phantom) {
var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;"));
cm.display.lineSpace.appendChild(scrollNode);
scrollNode.scrollIntoView(doScroll);
cm.display.lineSpace.removeChild(scrollNode);
}
}
// Scroll a given position into view (immediately), verifying that
// it actually became visible (as line heights are accurately
// measured, the position of something may 'drift' during drawing).
function scrollPosIntoView(cm, pos, end, margin) {
if (margin == null) { margin = 0; }
var rect;
if (!cm.options.lineWrapping && pos == end) {
// Set pos and end to the cursor positions around the character pos sticks to
// If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
// If pos == Pos(_, 0, "before"), pos and end are unchanged
pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
}
for (var limit = 0; limit < 5; limit++) {
var changed = false;
var coords = cursorCoords(cm, pos);
var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
rect = {left: Math.min(coords.left, endCoords.left),
top: Math.min(coords.top, endCoords.top) - margin,
right: Math.max(coords.left, endCoords.left),
bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
var scrollPos = calculateScrollPos(cm, rect);
var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
if (scrollPos.scrollTop != null) {
updateScrollTop(cm, scrollPos.scrollTop);
if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
}
if (scrollPos.scrollLeft != null) {
setScrollLeft(cm, scrollPos.scrollLeft);
if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
}
if (!changed) { break }
}
return rect
}
// Scroll a given set of coordinates into view (immediately).
function scrollIntoView(cm, rect) {
var scrollPos = calculateScrollPos(cm, rect);
if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
}
// Calculate a new scroll position needed to scroll the given
// rectangle into view. Returns an object with scrollTop and
// scrollLeft properties. When these are undefined, the
// vertical/horizontal position does not need to be adjusted.
function calculateScrollPos(cm, rect) {
var display = cm.display, snapMargin = textHeight(cm.display);
if (rect.top < 0) { rect.top = 0; }
var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
var screen = displayHeight(cm), result = {};
if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
var docBottom = cm.doc.height + paddingVert(display);
var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
if (rect.top < screentop) {
result.scrollTop = atTop ? 0 : rect.top;
} else if (rect.bottom > screentop + screen) {
var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
if (newTop != screentop) { result.scrollTop = newTop; }
}
var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;
var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;
var screenw = displayWidth(cm) - display.gutters.offsetWidth;
var tooWide = rect.right - rect.left > screenw;
if (tooWide) { rect.right = rect.left + screenw; }
if (rect.left < 10)
{ result.scrollLeft = 0; }
else if (rect.left < screenleft)
{ result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); }
else if (rect.right > screenw + screenleft - 3)
{ result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
return result
}
// Store a relative adjustment to the scroll position in the current
// operation (to be applied when the operation finishes).
function addToScrollTop(cm, top) {
if (top == null) { return }
resolveScrollToPos(cm);
cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
}
// Make sure that at the end of the operation the current cursor is
// shown.
function ensureCursorVisible(cm) {
resolveScrollToPos(cm);
var cur = cm.getCursor();
cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
}
function scrollToCoords(cm, x, y) {
if (x != null || y != null) { resolveScrollToPos(cm); }
if (x != null) { cm.curOp.scrollLeft = x; }
if (y != null) { cm.curOp.scrollTop = y; }
}
function scrollToRange(cm, range) {
resolveScrollToPos(cm);
cm.curOp.scrollToPos = range;
}
// When an operation has its scrollToPos property set, and another
// scroll action is applied before the end of the operation, this
// 'simulates' scrolling that position into view in a cheap way, so
// that the effect of intermediate scroll commands is not ignored.
function resolveScrollToPos(cm) {
var range = cm.curOp.scrollToPos;
if (range) {
cm.curOp.scrollToPos = null;
var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
scrollToCoordsRange(cm, from, to, range.margin);
}
}
function scrollToCoordsRange(cm, from, to, margin) {
var sPos = calculateScrollPos(cm, {
left: Math.min(from.left, to.left),
top: Math.min(from.top, to.top) - margin,
right: Math.max(from.right, to.right),
bottom: Math.max(from.bottom, to.bottom) + margin
});
scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
}
// Sync the scrollable area and scrollbars, ensure the viewport
// covers the visible area.
function updateScrollTop(cm, val) {
if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
if (!gecko) { updateDisplaySimple(cm, {top: val}); }
setScrollTop(cm, val, true);
if (gecko) { updateDisplaySimple(cm); }
startWorker(cm, 100);
}
function setScrollTop(cm, val, forceScroll) {
val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
cm.doc.scrollTop = val;
cm.display.scrollbars.setScrollTop(val);
if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
}
// Sync scroller and scrollbar, ensure the gutter elements are
// aligned.
function setScrollLeft(cm, val, isScroller, forceScroll) {
val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
cm.doc.scrollLeft = val;
alignHorizontally(cm);
if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
cm.display.scrollbars.setScrollLeft(val);
}
// SCROLLBARS
// Prepare DOM reads needed to update the scrollbars. Done in one
// shot to minimize update/measure roundtrips.
function measureForScrollbars(cm) {
var d = cm.display, gutterW = d.gutters.offsetWidth;
var docH = Math.round(cm.doc.height + paddingVert(cm.display));
return {
clientHeight: d.scroller.clientHeight,
viewHeight: d.wrapper.clientHeight,
scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
viewWidth: d.wrapper.clientWidth,
barLeft: cm.options.fixedGutter ? gutterW : 0,
docHeight: docH,
scrollHeight: docH + scrollGap(cm) + d.barHeight,
nativeBarWidth: d.nativeBarWidth,
gutterWidth: gutterW
}
}
var NativeScrollbars = function(place, scroll, cm) {
this.cm = cm;
var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
vert.tabIndex = horiz.tabIndex = -1;
place(vert); place(horiz);
on(vert, "scroll", function () {
if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
});
on(horiz, "scroll", function () {
if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
});
this.checkedZeroWidth = false;
// Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
};
NativeScrollbars.prototype.update = function (measure) {
var needsH = measure.scrollWidth > measure.clientWidth + 1;
var needsV = measure.scrollHeight > measure.clientHeight + 1;
var sWidth = measure.nativeBarWidth;
if (needsV) {
this.vert.style.display = "block";
this.vert.style.bottom = needsH ? sWidth + "px" : "0";
var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
// A bug in IE8 can cause this value to be negative, so guard it.
this.vert.firstChild.style.height =
Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
} else {
this.vert.style.display = "";
this.vert.firstChild.style.height = "0";
}
if (needsH) {
this.horiz.style.display = "block";
this.horiz.style.right = needsV ? sWidth + "px" : "0";
this.horiz.style.left = measure.barLeft + "px";
var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
this.horiz.firstChild.style.width =
Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
} else {
this.horiz.style.display = "";
this.horiz.firstChild.style.width = "0";
}
if (!this.checkedZeroWidth && measure.clientHeight > 0) {
if (sWidth == 0) { this.zeroWidthHack(); }
this.checkedZeroWidth = true;
}
return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
};
NativeScrollbars.prototype.setScrollLeft = function (pos) {
if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
};
NativeScrollbars.prototype.setScrollTop = function (pos) {
if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
};
NativeScrollbars.prototype.zeroWidthHack = function () {
var w = mac && !mac_geMountainLion ? "12px" : "18px";
this.horiz.style.height = this.vert.style.width = w;
this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
this.disableHoriz = new Delayed;
this.disableVert = new Delayed;
};
NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
bar.style.pointerEvents = "auto";
function maybeDisable() {
// To find out whether the scrollbar is still visible, we
// check whether the element under the pixel in the bottom
// right corner of the scrollbar box is the scrollbar box
// itself (when the bar is still visible) or its filler child
// (when the bar is hidden). If it is still visible, we keep
// it enabled, if it's hidden, we disable pointer events.
var box = bar.getBoundingClientRect();
var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
: document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
if (elt != bar) { bar.style.pointerEvents = "none"; }
else { delay.set(1000, maybeDisable); }
}
delay.set(1000, maybeDisable);
};
NativeScrollbars.prototype.clear = function () {
var parent = this.horiz.parentNode;
parent.removeChild(this.horiz);
parent.removeChild(this.vert);
};
var NullScrollbars = function () {};
NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
NullScrollbars.prototype.setScrollLeft = function () {};
NullScrollbars.prototype.setScrollTop = function () {};
NullScrollbars.prototype.clear = function () {};
function updateScrollbars(cm, measure) {
if (!measure) { measure = measureForScrollbars(cm); }
var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
updateScrollbarsInner(cm, measure);
for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
{ updateHeightsInViewport(cm); }
updateScrollbarsInner(cm, measureForScrollbars(cm));
startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
}
}
// Re-synchronize the fake scrollbars with the actual size of the
// content.
function updateScrollbarsInner(cm, measure) {
var d = cm.display;
var sizes = d.scrollbars.update(measure);
d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
if (sizes.right && sizes.bottom) {
d.scrollbarFiller.style.display = "block";
d.scrollbarFiller.style.height = sizes.bottom + "px";
d.scrollbarFiller.style.width = sizes.right + "px";
} else { d.scrollbarFiller.style.display = ""; }
if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
d.gutterFiller.style.display = "block";
d.gutterFiller.style.height = sizes.bottom + "px";
d.gutterFiller.style.width = measure.gutterWidth + "px";
} else { d.gutterFiller.style.display = ""; }
}
var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
function initScrollbars(cm) {
if (cm.display.scrollbars) {
cm.display.scrollbars.clear();
if (cm.display.scrollbars.addClass)
{ rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
}
cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
// Prevent clicks in the scrollbars from killing focus
on(node, "mousedown", function () {
if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
});
node.setAttribute("cm-not-content", "true");
}, function (pos, axis) {
if (axis == "horizontal") { setScrollLeft(cm, pos); }
else { updateScrollTop(cm, pos); }
}, cm);
if (cm.display.scrollbars.addClass)
{ addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
}
// Operations are used to wrap a series of changes to the editor
// state in such a way that each change won't have to update the
// cursor and display (which would be awkward, slow, and
// error-prone). Instead, display updates are batched and then all
// combined and executed at once.
var nextOpId = 0;
// Start a new operation.
function startOperation(cm) {
cm.curOp = {
cm: cm,
viewChanged: false, // Flag that indicates that lines might need to be redrawn
startHeight: cm.doc.height, // Used to detect need to update scrollbar
forceUpdate: false, // Used to force a redraw
updateInput: 0, // Whether to reset the input textarea
typing: false, // Whether this reset should be careful to leave existing text (for compositing)
changeObjs: null, // Accumulated changes, for firing change events
cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
selectionChanged: false, // Whether the selection needs to be redrawn
updateMaxLine: false, // Set when the widest line needs to be determined anew
scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
scrollToPos: null, // Used to scroll to a specific position
focus: false,
id: ++nextOpId // Unique ID
};
pushOperation(cm.curOp);
}
// Finish an operation, updating the display and signalling delayed events
function endOperation(cm) {
var op = cm.curOp;
if (op) { finishOperation(op, function (group) {
for (var i = 0; i < group.ops.length; i++)
{ group.ops[i].cm.curOp = null; }
endOperations(group);
}); }
}
// The DOM updates done when an operation finishes are batched so
// that the minimum number of relayouts are required.
function endOperations(group) {
var ops = group.ops;
for (var i = 0; i < ops.length; i++) // Read DOM
{ endOperation_R1(ops[i]); }
for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
{ endOperation_W1(ops[i$1]); }
for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
{ endOperation_R2(ops[i$2]); }
for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
{ endOperation_W2(ops[i$3]); }
for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
{ endOperation_finish(ops[i$4]); }
}
function endOperation_R1(op) {
var cm = op.cm, display = cm.display;
maybeClipScrollbars(cm);
if (op.updateMaxLine) { findMaxLine(cm); }
op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
op.scrollToPos.to.line >= display.viewTo) ||
display.maxLineChanged && cm.options.lineWrapping;
op.update = op.mustUpdate &&
new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
}
function endOperation_W1(op) {
op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
}
function endOperation_R2(op) {
var cm = op.cm, display = cm.display;
if (op.updatedDisplay) { updateHeightsInViewport(cm); }
op.barMeasure = measureForScrollbars(cm);
// If the max line changed since it was last measured, measure it,
// and ensure the document's width matches it.
// updateDisplay_W2 will use these properties to do the actual resizing
if (display.maxLineChanged && !cm.options.lineWrapping) {
op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
cm.display.sizerWidth = op.adjustWidthTo;
op.barMeasure.scrollWidth =
Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
}
if (op.updatedDisplay || op.selectionChanged)
{ op.preparedSelection = display.input.prepareSelection(); }
}
function endOperation_W2(op) {
var cm = op.cm;
if (op.adjustWidthTo != null) {
cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
if (op.maxScrollLeft < cm.doc.scrollLeft)
{ setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
cm.display.maxLineChanged = false;
}
var takeFocus = op.focus && op.focus == activeElt();
if (op.preparedSelection)
{ cm.display.input.showSelection(op.preparedSelection, takeFocus); }
if (op.updatedDisplay || op.startHeight != cm.doc.height)
{ updateScrollbars(cm, op.barMeasure); }
if (op.updatedDisplay)
{ setDocumentHeight(cm, op.barMeasure); }
if (op.selectionChanged) { restartBlink(cm); }
if (cm.state.focused && op.updateInput)
{ cm.display.input.reset(op.typing); }
if (takeFocus) { ensureFocus(op.cm); }
}
function endOperation_finish(op) {
var cm = op.cm, display = cm.display, doc = cm.doc;
if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
// Abort mouse wheel delta measurement, when scrolling explicitly
if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
{ display.wheelStartX = display.wheelStartY = null; }
// Propagate the scroll position to the actual DOM scroller
if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
// If we need to scroll a specific position into view, do so.
if (op.scrollToPos) {
var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
maybeScrollWindow(cm, rect);
}
// Fire events for markers that are hidden/unidden by editing or
// undoing
var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
if (hidden) { for (var i = 0; i < hidden.length; ++i)
{ if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
{ if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
if (display.wrapper.offsetHeight)
{ doc.scrollTop = cm.display.scroller.scrollTop; }
// Fire change events, and delayed event handlers
if (op.changeObjs)
{ signal(cm, "changes", cm, op.changeObjs); }
if (op.update)
{ op.update.finish(); }
}
// Run the given function in an operation
function runInOp(cm, f) {
if (cm.curOp) { return f() }
startOperation(cm);
try { return f() }
finally { endOperation(cm); }
}
// Wraps a function in an operation. Returns the wrapped function.
function operation(cm, f) {
return function() {
if (cm.curOp) { return f.apply(cm, arguments) }
startOperation(cm);
try { return f.apply(cm, arguments) }
finally { endOperation(cm); }
}
}
// Used to add methods to editor and doc instances, wrapping them in
// operations.
function methodOp(f) {
return function() {
if (this.curOp) { return f.apply(this, arguments) }
startOperation(this);
try { return f.apply(this, arguments) }
finally { endOperation(this); }
}
}
function docMethodOp(f) {
return function() {
var cm = this.cm;
if (!cm || cm.curOp) { return f.apply(this, arguments) }
startOperation(cm);
try { return f.apply(this, arguments) }
finally { endOperation(cm); }
}
}
// HIGHLIGHT WORKER
function startWorker(cm, time) {
if (cm.doc.highlightFrontier < cm.display.viewTo)
{ cm.state.highlight.set(time, bind(highlightWorker, cm)); }
}
function highlightWorker(cm) {
var doc = cm.doc;
if (doc.highlightFrontier >= cm.display.viewTo) { return }
var end = +new Date + cm.options.workTime;
var context = getContextBefore(cm, doc.highlightFrontier);
var changedLines = [];
doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
if (context.line >= cm.display.viewFrom) { // Visible
var oldStyles = line.styles;
var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
var highlighted = highlightLine(cm, line, context, true);
if (resetState) { context.state = resetState; }
line.styles = highlighted.styles;
var oldCls = line.styleClasses, newCls = highlighted.classes;
if (newCls) { line.styleClasses = newCls; }
else if (oldCls) { line.styleClasses = null; }
var ischange = !oldStyles || oldStyles.length != line.styles.length ||
oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
if (ischange) { changedLines.push(context.line); }
line.stateAfter = context.save();
context.nextLine();
} else {
if (line.text.length <= cm.options.maxHighlightLength)
{ processLine(cm, line.text, context); }
line.stateAfter = context.line % 5 == 0 ? context.save() : null;
context.nextLine();
}
if (+new Date > end) {
startWorker(cm, cm.options.workDelay);
return true
}
});
doc.highlightFrontier = context.line;
doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
if (changedLines.length) { runInOp(cm, function () {
for (var i = 0; i < changedLines.length; i++)
{ regLineChange(cm, changedLines[i], "text"); }
}); }
}
// DISPLAY DRAWING
var DisplayUpdate = function(cm, viewport, force) {
var display = cm.display;
this.viewport = viewport;
// Store some values that we'll need later (but don't want to force a relayout for)
this.visible = visibleLines(display, cm.doc, viewport);
this.editorIsHidden = !display.wrapper.offsetWidth;
this.wrapperHeight = display.wrapper.clientHeight;
this.wrapperWidth = display.wrapper.clientWidth;
this.oldDisplayWidth = displayWidth(cm);
this.force = force;
this.dims = getDimensions(cm);
this.events = [];
};
DisplayUpdate.prototype.signal = function (emitter, type) {
if (hasHandler(emitter, type))
{ this.events.push(arguments); }
};
DisplayUpdate.prototype.finish = function () {
for (var i = 0; i < this.events.length; i++)
{ signal.apply(null, this.events[i]); }
};
function maybeClipScrollbars(cm) {
var display = cm.display;
if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
display.heightForcer.style.height = scrollGap(cm) + "px";
display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
display.scrollbarsClipped = true;
}
}
function selectionSnapshot(cm) {
if (cm.hasFocus()) { return null }
var active = activeElt();
if (!active || !contains(cm.display.lineDiv, active)) { return null }
var result = {activeElt: active};
if (window.getSelection) {
var sel = window.getSelection();
if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
result.anchorNode = sel.anchorNode;
result.anchorOffset = sel.anchorOffset;
result.focusNode = sel.focusNode;
result.focusOffset = sel.focusOffset;
}
}
return result
}
function restoreSelection(snapshot) {
if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
snapshot.activeElt.focus();
if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&
snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
var sel = window.getSelection(), range = document.createRange();
range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
sel.extend(snapshot.focusNode, snapshot.focusOffset);
}
}
// Does the actual updating of the line display. Bails out
// (returning false) when there is nothing to be done and forced is
// false.
function updateDisplayIfNeeded(cm, update) {
var display = cm.display, doc = cm.doc;
if (update.editorIsHidden) {
resetView(cm);
return false
}
// Bail out if the visible area is already rendered and nothing changed.
if (!update.force &&
update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
(display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
display.renderedView == display.view && countDirtyView(cm) == 0)
{ return false }
if (maybeUpdateLineNumberWidth(cm)) {
resetView(cm);
update.dims = getDimensions(cm);
}
// Compute a suitable new viewport (from & to)
var end = doc.first + doc.size;
var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
if (sawCollapsedSpans) {
from = visualLineNo(cm.doc, from);
to = visualLineEndNo(cm.doc, to);
}
var different = from != display.viewFrom || to != display.viewTo ||
display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
adjustView(cm, from, to);
display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
// Position the mover div to align with the current scroll position
cm.display.mover.style.top = display.viewOffset + "px";
var toUpdate = countDirtyView(cm);
if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
(display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
{ return false }
// For big changes, we hide the enclosing element during the
// update, since that speeds up the operations on most browsers.
var selSnapshot = selectionSnapshot(cm);
if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
patchDisplay(cm, display.updateLineNumbers, update.dims);
if (toUpdate > 4) { display.lineDiv.style.display = ""; }
display.renderedView = display.view;
// There might have been a widget with a focused element that got
// hidden or updated, if so re-focus it.
restoreSelection(selSnapshot);
// Prevent selection and cursors from interfering with the scroll
// width and height.
removeChildren(display.cursorDiv);
removeChildren(display.selectionDiv);
display.gutters.style.height = display.sizer.style.minHeight = 0;
if (different) {
display.lastWrapHeight = update.wrapperHeight;
display.lastWrapWidth = update.wrapperWidth;
startWorker(cm, 400);
}
display.updateLineNumbers = null;
return true
}
function postUpdateDisplay(cm, update) {
var viewport = update.viewport;
for (var first = true;; first = false) {
if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
// Clip forced viewport to actual scrollable area.
if (viewport && viewport.top != null)
{ viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
// Updated line heights might result in the drawn area not
// actually covering the viewport. Keep looping until it does.
update.visible = visibleLines(cm.display, cm.doc, viewport);
if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
{ break }
} else if (first) {
update.visible = visibleLines(cm.display, cm.doc, viewport);
}
if (!updateDisplayIfNeeded(cm, update)) { break }
updateHeightsInViewport(cm);
var barMeasure = measureForScrollbars(cm);
updateSelection(cm);
updateScrollbars(cm, barMeasure);
setDocumentHeight(cm, barMeasure);
update.force = false;
}
update.signal(cm, "update", cm);
if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
}
}
function updateDisplaySimple(cm, viewport) {
var update = new DisplayUpdate(cm, viewport);
if (updateDisplayIfNeeded(cm, update)) {
updateHeightsInViewport(cm);
postUpdateDisplay(cm, update);
var barMeasure = measureForScrollbars(cm);
updateSelection(cm);
updateScrollbars(cm, barMeasure);
setDocumentHeight(cm, barMeasure);
update.finish();
}
}
// Sync the actual display DOM structure with display.view, removing
// nodes for lines that are no longer in view, and creating the ones
// that are not there yet, and updating the ones that are out of
// date.
function patchDisplay(cm, updateNumbersFrom, dims) {
var display = cm.display, lineNumbers = cm.options.lineNumbers;
var container = display.lineDiv, cur = container.firstChild;
function rm(node) {
var next = node.nextSibling;
// Works around a throw-scroll bug in OS X Webkit
if (webkit && mac && cm.display.currentWheelTarget == node)
{ node.style.display = "none"; }
else
{ node.parentNode.removeChild(node); }
return next
}
var view = display.view, lineN = display.viewFrom;
// Loop over the elements in the view, syncing cur (the DOM nodes
// in display.lineDiv) with the view as we go.
for (var i = 0; i < view.length; i++) {
var lineView = view[i];
if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
var node = buildLineElement(cm, lineView, lineN, dims);
container.insertBefore(node, cur);
} else { // Already drawn
while (cur != lineView.node) { cur = rm(cur); }
var updateNumber = lineNumbers && updateNumbersFrom != null &&
updateNumbersFrom <= lineN && lineView.lineNumber;
if (lineView.changes) {
if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
updateLineForChanges(cm, lineView, lineN, dims);
}
if (updateNumber) {
removeChildren(lineView.lineNumber);
lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
}
cur = lineView.node.nextSibling;
}
lineN += lineView.size;
}
while (cur) { cur = rm(cur); }
}
function updateGutterSpace(display) {
var width = display.gutters.offsetWidth;
display.sizer.style.marginLeft = width + "px";
}
function setDocumentHeight(cm, measure) {
cm.display.sizer.style.minHeight = measure.docHeight + "px";
cm.display.heightForcer.style.top = measure.docHeight + "px";
cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
}
// Re-align line numbers and gutter marks to compensate for
// horizontal scrolling.
function alignHorizontally(cm) {
var display = cm.display, view = display.view;
if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
var gutterW = display.gutters.offsetWidth, left = comp + "px";
for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
if (cm.options.fixedGutter) {
if (view[i].gutter)
{ view[i].gutter.style.left = left; }
if (view[i].gutterBackground)
{ view[i].gutterBackground.style.left = left; }
}
var align = view[i].alignable;
if (align) { for (var j = 0; j < align.length; j++)
{ align[j].style.left = left; } }
} }
if (cm.options.fixedGutter)
{ display.gutters.style.left = (comp + gutterW) + "px"; }
}
// Used to ensure that the line number gutter is still the right
// size for the current document size. Returns true when an update
// is needed.
function maybeUpdateLineNumberWidth(cm) {
if (!cm.options.lineNumbers) { return false }
var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
if (last.length != display.lineNumChars) {
var test = display.measure.appendChild(elt("div", [elt("div", last)],
"CodeMirror-linenumber CodeMirror-gutter-elt"));
var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
display.lineGutter.style.width = "";
display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
display.lineNumWidth = display.lineNumInnerWidth + padding;
display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
display.lineGutter.style.width = display.lineNumWidth + "px";
updateGutterSpace(cm.display);
return true
}
return false
}
function getGutters(gutters, lineNumbers) {
var result = [], sawLineNumbers = false;
for (var i = 0; i < gutters.length; i++) {
var name = gutters[i], style = null;
if (typeof name != "string") { style = name.style; name = name.className; }
if (name == "CodeMirror-linenumbers") {
if (!lineNumbers) { continue }
else { sawLineNumbers = true; }
}
result.push({className: name, style: style});
}
if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
return result
}
// Rebuild the gutter elements, ensure the margin to the left of the
// code matches their width.
function renderGutters(display) {
var gutters = display.gutters, specs = display.gutterSpecs;
removeChildren(gutters);
display.lineGutter = null;
for (var i = 0; i < specs.length; ++i) {
var ref = specs[i];
var className = ref.className;
var style = ref.style;
var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
if (style) { gElt.style.cssText = style; }
if (className == "CodeMirror-linenumbers") {
display.lineGutter = gElt;
gElt.style.width = (display.lineNumWidth || 1) + "px";
}
}
gutters.style.display = specs.length ? "" : "none";
updateGutterSpace(display);
}
function updateGutters(cm) {
renderGutters(cm.display);
regChange(cm);
alignHorizontally(cm);
}
// The display handles the DOM integration, both for input reading
// and content drawing. It holds references to DOM nodes and
// display-related state.
function Display(place, doc, input, options) {
var d = this;
this.input = input;
// Covers bottom-right square when both scrollbars are present.
d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
d.scrollbarFiller.setAttribute("cm-not-content", "true");
// Covers bottom of gutter when coverGutterNextToScrollbar is on
// and h scrollbar is present.
d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
d.gutterFiller.setAttribute("cm-not-content", "true");
// Will contain the actual code, positioned to cover the viewport.
d.lineDiv = eltP("div", null, "CodeMirror-code");
// Elements are added to these to represent selection and cursors.
d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
d.cursorDiv = elt("div", null, "CodeMirror-cursors");
// A visibility: hidden element used to find the size of things.
d.measure = elt("div", null, "CodeMirror-measure");
// When lines outside of the viewport are measured, they are drawn in this.
d.lineMeasure = elt("div", null, "CodeMirror-measure");
// Wraps everything that needs to exist inside the vertically-padded coordinate system
d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
null, "position: relative; outline: none");
var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
// Moved around its parent to cover visible view.
d.mover = elt("div", [lines], null, "position: relative");
// Set to the height of the document, allowing scrolling.
d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
d.sizerWidth = null;
// Behavior of elts with overflow: auto and padding is
// inconsistent across browsers. This is used to ensure the
// scrollable area is big enough.
d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
// Will contain the gutters, if any.
d.gutters = elt("div", null, "CodeMirror-gutters");
d.lineGutter = null;
// Actual scrollable element.
d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
d.scroller.setAttribute("tabIndex", "-1");
// The element in which the editor lives.
d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
// Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
if (place) {
if (place.appendChild) { place.appendChild(d.wrapper); }
else { place(d.wrapper); }
}
// Current rendered range (may be bigger than the view window).
d.viewFrom = d.viewTo = doc.first;
d.reportedViewFrom = d.reportedViewTo = doc.first;
// Information about the rendered lines.
d.view = [];
d.renderedView = null;
// Holds info about a single rendered line when it was rendered
// for measurement, while not in view.
d.externalMeasured = null;
// Empty space (in pixels) above the view
d.viewOffset = 0;
d.lastWrapHeight = d.lastWrapWidth = 0;
d.updateLineNumbers = null;
d.nativeBarWidth = d.barHeight = d.barWidth = 0;
d.scrollbarsClipped = false;
// Used to only resize the line number gutter when necessary (when
// the amount of lines crosses a boundary that makes its width change)
d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
// Set to true when a non-horizontal-scrolling line widget is
// added. As an optimization, line widget aligning is skipped when
// this is false.
d.alignWidgets = false;
d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
// Tracks the maximum line length so that the horizontal scrollbar
// can be kept static when scrolling.
d.maxLine = null;
d.maxLineLength = 0;
d.maxLineChanged = false;
// Used for measuring wheel scrolling granularity
d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
// True when shift is held down.
d.shift = false;
// Used to track whether anything happened since the context menu
// was opened.
d.selForContextMenu = null;
d.activeTouch = null;
d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
renderGutters(d);
input.init(d);
}
// Since the delta values reported on mouse wheel events are
// unstandardized between browsers and even browser versions, and
// generally horribly unpredictable, this code starts by measuring
// the scroll effect that the first few mouse wheel events have,
// and, from that, detects the way it can convert deltas to pixel
// offsets afterwards.
//
// The reason we want to know the amount a wheel event will scroll
// is that it gives us a chance to update the display before the
// actual scrolling happens, reducing flickering.
var wheelSamples = 0, wheelPixelsPerUnit = null;
// Fill in a browser-detected starting value on browsers where we
// know one. These don't have to be accurate -- the result of them
// being wrong would just be a slight flicker on the first wheel
// scroll (if it is large enough).
if (ie) { wheelPixelsPerUnit = -.53; }
else if (gecko) { wheelPixelsPerUnit = 15; }
else if (chrome) { wheelPixelsPerUnit = -.7; }
else if (safari) { wheelPixelsPerUnit = -1/3; }
function wheelEventDelta(e) {
var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
else if (dy == null) { dy = e.wheelDelta; }
return {x: dx, y: dy}
}
function wheelEventPixels(e) {
var delta = wheelEventDelta(e);
delta.x *= wheelPixelsPerUnit;
delta.y *= wheelPixelsPerUnit;
return delta
}
function onScrollWheel(cm, e) {
var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
var display = cm.display, scroll = display.scroller;
// Quit if there's nothing to scroll here
var canScrollX = scroll.scrollWidth > scroll.clientWidth;
var canScrollY = scroll.scrollHeight > scroll.clientHeight;
if (!(dx && canScrollX || dy && canScrollY)) { return }
// Webkit browsers on OS X abort momentum scrolls when the target
// of the scroll event is removed from the scrollable element.
// This hack (see related code in patchDisplay) makes sure the
// element is kept around.
if (dy && mac && webkit) {
outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
for (var i = 0; i < view.length; i++) {
if (view[i].node == cur) {
cm.display.currentWheelTarget = cur;
break outer
}
}
}
}
// On some browsers, horizontal scrolling will cause redraws to
// happen before the gutter has been realigned, causing it to
// wriggle around in a most unseemly way. When we have an
// estimated pixels/delta value, we just handle horizontal
// scrolling entirely here. It'll be slightly off from native, but
// better than glitching out.
if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
if (dy && canScrollY)
{ updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
// Only prevent default scrolling if vertical scrolling is
// actually possible. Otherwise, it causes vertical scroll
// jitter on OSX trackpads when deltaX is small and deltaY
// is large (issue #3579)
if (!dy || (dy && canScrollY))
{ e_preventDefault(e); }
display.wheelStartX = null; // Abort measurement, if in progress
return
}
// 'Project' the visible viewport to cover the area that is being
// scrolled into view (if we know enough to estimate it).
if (dy && wheelPixelsPerUnit != null) {
var pixels = dy * wheelPixelsPerUnit;
var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
updateDisplaySimple(cm, {top: top, bottom: bot});
}
if (wheelSamples < 20) {
if (display.wheelStartX == null) {
display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
display.wheelDX = dx; display.wheelDY = dy;
setTimeout(function () {
if (display.wheelStartX == null) { return }
var movedX = scroll.scrollLeft - display.wheelStartX;
var movedY = scroll.scrollTop - display.wheelStartY;
var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
(movedX && display.wheelDX && movedX / display.wheelDX);
display.wheelStartX = display.wheelStartY = null;
if (!sample) { return }
wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
++wheelSamples;
}, 200);
} else {
display.wheelDX += dx; display.wheelDY += dy;
}
}
}
// Selection objects are immutable. A new one is created every time
// the selection changes. A selection is one or more non-overlapping
// (and non-touching) ranges, sorted, and an integer that indicates
// which one is the primary selection (the one that's scrolled into
// view, that getCursor returns, etc).
var Selection = function(ranges, primIndex) {
this.ranges = ranges;
this.primIndex = primIndex;
};
Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
Selection.prototype.equals = function (other) {
if (other == this) { return true }
if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
for (var i = 0; i < this.ranges.length; i++) {
var here = this.ranges[i], there = other.ranges[i];
if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
}
return true
};
Selection.prototype.deepCopy = function () {
var out = [];
for (var i = 0; i < this.ranges.length; i++)
{ out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); }
return new Selection(out, this.primIndex)
};
Selection.prototype.somethingSelected = function () {
for (var i = 0; i < this.ranges.length; i++)
{ if (!this.ranges[i].empty()) { return true } }
return false
};
Selection.prototype.contains = function (pos, end) {
if (!end) { end = pos; }
for (var i = 0; i < this.ranges.length; i++) {
var range = this.ranges[i];
if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
{ return i }
}
return -1
};
var Range = function(anchor, head) {
this.anchor = anchor; this.head = head;
};
Range.prototype.from = function () { return minPos(this.anchor, this.head) };
Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
// Take an unsorted, potentially overlapping set of ranges, and
// build a selection out of it. 'Consumes' ranges array (modifying
// it).
function normalizeSelection(cm, ranges, primIndex) {
var mayTouch = cm && cm.options.selectionsMayTouch;
var prim = ranges[primIndex];
ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
primIndex = indexOf(ranges, prim);
for (var i = 1; i < ranges.length; i++) {
var cur = ranges[i], prev = ranges[i - 1];
var diff = cmp(prev.to(), cur.from());
if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
if (i <= primIndex) { --primIndex; }
ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
}
}
return new Selection(ranges, primIndex)
}
function simpleSelection(anchor, head) {
return new Selection([new Range(anchor, head || anchor)], 0)
}
// Compute the position of the end of a change (its 'to' property
// refers to the pre-change end).
function changeEnd(change) {
if (!change.text) { return change.to }
return Pos(change.from.line + change.text.length - 1,
lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
}
// Adjust a position to refer to the post-change position of the
// same text, or the end of the change if the change covers it.
function adjustForChange(pos, change) {
if (cmp(pos, change.from) < 0) { return pos }
if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
return Pos(line, ch)
}
function computeSelAfterChange(doc, change) {
var out = [];
for (var i = 0; i < doc.sel.ranges.length; i++) {
var range = doc.sel.ranges[i];
out.push(new Range(adjustForChange(range.anchor, change),
adjustForChange(range.head, change)));
}
return normalizeSelection(doc.cm, out, doc.sel.primIndex)
}
function offsetPos(pos, old, nw) {
if (pos.line == old.line)
{ return Pos(nw.line, pos.ch - old.ch + nw.ch) }
else
{ return Pos(nw.line + (pos.line - old.line), pos.ch) }
}
// Used by replaceSelections to allow moving the selection to the
// start or around the replaced test. Hint may be "start" or "around".
function computeReplacedSel(doc, changes, hint) {
var out = [];
var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
for (var i = 0; i < changes.length; i++) {
var change = changes[i];
var from = offsetPos(change.from, oldPrev, newPrev);
var to = offsetPos(changeEnd(change), oldPrev, newPrev);
oldPrev = change.to;
newPrev = to;
if (hint == "around") {
var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
out[i] = new Range(inv ? to : from, inv ? from : to);
} else {
out[i] = new Range(from, from);
}
}
return new Selection(out, doc.sel.primIndex)
}
// Used to get the editor into a consistent state again when options change.
function loadMode(cm) {
cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
resetModeState(cm);
}
function resetModeState(cm) {
cm.doc.iter(function (line) {
if (line.stateAfter) { line.stateAfter = null; }
if (line.styles) { line.styles = null; }
});
cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
startWorker(cm, 100);
cm.state.modeGen++;
if (cm.curOp) { regChange(cm); }
}
// DOCUMENT DATA STRUCTURE
// By default, updates that start and end at the beginning of a line
// are treated specially, in order to make the association of line
// widgets and marker elements with the text behave more intuitive.
function isWholeLineUpdate(doc, change) {
return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
(!doc.cm || doc.cm.options.wholeLineUpdateBefore)
}
// Perform a change on the document data structure.
function updateDoc(doc, change, markedSpans, estimateHeight) {
function spansFor(n) {return markedSpans ? markedSpans[n] : null}
function update(line, text, spans) {
updateLine(line, text, spans, estimateHeight);
signalLater(line, "change", line, change);
}
function linesFor(start, end) {
var result = [];
for (var i = start; i < end; ++i)
{ result.push(new Line(text[i], spansFor(i), estimateHeight)); }
return result
}
var from = change.from, to = change.to, text = change.text;
var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
// Adjust the line structure
if (change.full) {
doc.insert(0, linesFor(0, text.length));
doc.remove(text.length, doc.size - text.length);
} else if (isWholeLineUpdate(doc, change)) {
// This is a whole-line replace. Treated specially to make
// sure line objects move the way they are supposed to.
var added = linesFor(0, text.length - 1);
update(lastLine, lastLine.text, lastSpans);
if (nlines) { doc.remove(from.line, nlines); }
if (added.length) { doc.insert(from.line, added); }
} else if (firstLine == lastLine) {
if (text.length == 1) {
update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
} else {
var added$1 = linesFor(1, text.length - 1);
added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
doc.insert(from.line + 1, added$1);
}
} else if (text.length == 1) {
update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
doc.remove(from.line + 1, nlines);
} else {
update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
var added$2 = linesFor(1, text.length - 1);
if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
doc.insert(from.line + 1, added$2);
}
signalLater(doc, "change", doc, change);
}
// Call f for all linked documents.
function linkedDocs(doc, f, sharedHistOnly) {
function propagate(doc, skip, sharedHist) {
if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
var rel = doc.linked[i];
if (rel.doc == skip) { continue }
var shared = sharedHist && rel.sharedHist;
if (sharedHistOnly && !shared) { continue }
f(rel.doc, shared);
propagate(rel.doc, doc, shared);
} }
}
propagate(doc, null, true);
}
// Attach a document to an editor.
function attachDoc(cm, doc) {
if (doc.cm) { throw new Error("This document is already in use.") }
cm.doc = doc;
doc.cm = cm;
estimateLineHeights(cm);
loadMode(cm);
setDirectionClass(cm);
if (!cm.options.lineWrapping) { findMaxLine(cm); }
cm.options.mode = doc.modeOption;
regChange(cm);
}
function setDirectionClass(cm) {
(cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
}
function directionChanged(cm) {
runInOp(cm, function () {
setDirectionClass(cm);
regChange(cm);
});
}
function History(startGen) {
// Arrays of change events and selections. Doing something adds an
// event to done and clears undo. Undoing moves events from done
// to undone, redoing moves them in the other direction.
this.done = []; this.undone = [];
this.undoDepth = Infinity;
// Used to track when changes can be merged into a single undo
// event
this.lastModTime = this.lastSelTime = 0;
this.lastOp = this.lastSelOp = null;
this.lastOrigin = this.lastSelOrigin = null;
// Used by the isClean() method
this.generation = this.maxGeneration = startGen || 1;
}
// Create a history change event from an updateDoc-style change
// object.
function historyChangeFromChange(doc, change) {
var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
return histChange
}
// Pop all selection events off the end of a history array. Stop at
// a change event.
function clearSelectionEvents(array) {
while (array.length) {
var last = lst(array);
if (last.ranges) { array.pop(); }
else { break }
}
}
// Find the top change event in the history. Pop off selection
// events that are in the way.
function lastChangeEvent(hist, force) {
if (force) {
clearSelectionEvents(hist.done);
return lst(hist.done)
} else if (hist.done.length && !lst(hist.done).ranges) {
return lst(hist.done)
} else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
hist.done.pop();
return lst(hist.done)
}
}
// Register a change in the history. Merges changes that are within
// a single operation, or are close together with an origin that
// allows merging (starting with "+") into a single event.
function addChangeToHistory(doc, change, selAfter, opId) {
var hist = doc.history;
hist.undone.length = 0;
var time = +new Date, cur;
var last;
if ((hist.lastOp == opId ||
hist.lastOrigin == change.origin && change.origin &&
((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
change.origin.charAt(0) == "*")) &&
(cur = lastChangeEvent(hist, hist.lastOp == opId))) {
// Merge this change into the last event
last = lst(cur.changes);
if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
// Optimized case for simple insertion -- don't want to add
// new changesets for every character typed
last.to = changeEnd(change);
} else {
// Add new sub-event
cur.changes.push(historyChangeFromChange(doc, change));
}
} else {
// Can not be merged, start a new event.
var before = lst(hist.done);
if (!before || !before.ranges)
{ pushSelectionToHistory(doc.sel, hist.done); }
cur = {changes: [historyChangeFromChange(doc, change)],
generation: hist.generation};
hist.done.push(cur);
while (hist.done.length > hist.undoDepth) {
hist.done.shift();
if (!hist.done[0].ranges) { hist.done.shift(); }
}
}
hist.done.push(selAfter);
hist.generation = ++hist.maxGeneration;
hist.lastModTime = hist.lastSelTime = time;
hist.lastOp = hist.lastSelOp = opId;
hist.lastOrigin = hist.lastSelOrigin = change.origin;
if (!last) { signal(doc, "historyAdded"); }
}
function selectionEventCanBeMerged(doc, origin, prev, sel) {
var ch = origin.charAt(0);
return ch == "*" ||
ch == "+" &&
prev.ranges.length == sel.ranges.length &&
prev.somethingSelected() == sel.somethingSelected() &&
new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
}
// Called whenever the selection changes, sets the new selection as
// the pending selection in the history, and pushes the old pending
// selection into the 'done' array when it was significantly
// different (in number of selected ranges, emptiness, or time).
function addSelectionToHistory(doc, sel, opId, options) {
var hist = doc.history, origin = options && options.origin;
// A new event is started when the previous origin does not match
// the current, or the origins don't allow matching. Origins
// starting with * are always merged, those starting with + are
// merged when similar and close together in time.
if (opId == hist.lastSelOp ||
(origin && hist.lastSelOrigin == origin &&
(hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
{ hist.done[hist.done.length - 1] = sel; }
else
{ pushSelectionToHistory(sel, hist.done); }
hist.lastSelTime = +new Date;
hist.lastSelOrigin = origin;
hist.lastSelOp = opId;
if (options && options.clearRedo !== false)
{ clearSelectionEvents(hist.undone); }
}
function pushSelectionToHistory(sel, dest) {
var top = lst(dest);
if (!(top && top.ranges && top.equals(sel)))
{ dest.push(sel); }
}
// Used to store marked span information in the history.
function attachLocalSpans(doc, change, from, to) {
var existing = change["spans_" + doc.id], n = 0;
doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
if (line.markedSpans)
{ (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
++n;
});
}
// When un/re-doing restores text containing marked spans, those
// that have been explicitly cleared should not be restored.
function removeClearedSpans(spans) {
if (!spans) { return null }
var out;
for (var i = 0; i < spans.length; ++i) {
if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
else if (out) { out.push(spans[i]); }
}
return !out ? spans : out.length ? out : null
}
// Retrieve and filter the old marked spans stored in a change event.
function getOldSpans(doc, change) {
var found = change["spans_" + doc.id];
if (!found) { return null }
var nw = [];
for (var i = 0; i < change.text.length; ++i)
{ nw.push(removeClearedSpans(found[i])); }
return nw
}
// Used for un/re-doing changes from the history. Combines the
// result of computing the existing spans with the set of spans that
// existed in the history (so that deleting around a span and then
// undoing brings back the span).
function mergeOldSpans(doc, change) {
var old = getOldSpans(doc, change);
var stretched = stretchSpansOverChange(doc, change);
if (!old) { return stretched }
if (!stretched) { return old }
for (var i = 0; i < old.length; ++i) {
var oldCur = old[i], stretchCur = stretched[i];
if (oldCur && stretchCur) {
spans: for (var j = 0; j < stretchCur.length; ++j) {
var span = stretchCur[j];
for (var k = 0; k < oldCur.length; ++k)
{ if (oldCur[k].marker == span.marker) { continue spans } }
oldCur.push(span);
}
} else if (stretchCur) {
old[i] = stretchCur;
}
}
return old
}
// Used both to provide a JSON-safe object in .getHistory, and, when
// detaching a document, to split the history in two
function copyHistoryArray(events, newGroup, instantiateSel) {
var copy = [];
for (var i = 0; i < events.length; ++i) {
var event = events[i];
if (event.ranges) {
copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
continue
}
var changes = event.changes, newChanges = [];
copy.push({changes: newChanges});
for (var j = 0; j < changes.length; ++j) {
var change = changes[j], m = (void 0);
newChanges.push({from: change.from, to: change.to, text: change.text});
if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
if (indexOf(newGroup, Number(m[1])) > -1) {
lst(newChanges)[prop] = change[prop];
delete change[prop];
}
} } }
}
}
return copy
}
// The 'scroll' parameter given to many of these indicated whether
// the new cursor position should be scrolled into view after
// modifying the selection.
// If shift is held or the extend flag is set, extends a range to
// include a given position (and optionally a second position).
// Otherwise, simply returns the range between the given positions.
// Used for cursor motion and such.
function extendRange(range, head, other, extend) {
if (extend) {
var anchor = range.anchor;
if (other) {
var posBefore = cmp(head, anchor) < 0;
if (posBefore != (cmp(other, anchor) < 0)) {
anchor = head;
head = other;
} else if (posBefore != (cmp(head, other) < 0)) {
head = other;
}
}
return new Range(anchor, head)
} else {
return new Range(other || head, head)
}
}
// Extend the primary selection range, discard the rest.
function extendSelection(doc, head, other, options, extend) {
if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
}
// Extend all selections (pos is an array of selections with length
// equal the number of selections)
function extendSelections(doc, heads, options) {
var out = [];
var extend = doc.cm && (doc.cm.display.shift || doc.extend);
for (var i = 0; i < doc.sel.ranges.length; i++)
{ out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
setSelection(doc, newSel, options);
}
// Updates a single range in the selection.
function replaceOneSelection(doc, i, range, options) {
var ranges = doc.sel.ranges.slice(0);
ranges[i] = range;
setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
}
// Reset the selection to a single range.
function setSimpleSelection(doc, anchor, head, options) {
setSelection(doc, simpleSelection(anchor, head), options);
}
// Give beforeSelectionChange handlers a change to influence a
// selection update.
function filterSelectionChange(doc, sel, options) {
var obj = {
ranges: sel.ranges,
update: function(ranges) {
this.ranges = [];
for (var i = 0; i < ranges.length; i++)
{ this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
clipPos(doc, ranges[i].head)); }
},
origin: options && options.origin
};
signal(doc, "beforeSelectionChange", doc, obj);
if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
else { return sel }
}
function setSelectionReplaceHistory(doc, sel, options) {
var done = doc.history.done, last = lst(done);
if (last && last.ranges) {
done[done.length - 1] = sel;
setSelectionNoUndo(doc, sel, options);
} else {
setSelection(doc, sel, options);
}
}
// Set a new selection.
function setSelection(doc, sel, options) {
setSelectionNoUndo(doc, sel, options);
addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
}
function setSelectionNoUndo(doc, sel, options) {
if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
{ sel = filterSelectionChange(doc, sel, options); }
var bias = options && options.bias ||
(cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
if (!(options && options.scroll === false) && doc.cm)
{ ensureCursorVisible(doc.cm); }
}
function setSelectionInner(doc, sel) {
if (sel.equals(doc.sel)) { return }
doc.sel = sel;
if (doc.cm) {
doc.cm.curOp.updateInput = 1;
doc.cm.curOp.selectionChanged = true;
signalCursorActivity(doc.cm);
}
signalLater(doc, "cursorActivity", doc);
}
// Verify that the selection does not partially select any atomic
// marked ranges.
function reCheckSelection(doc) {
setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
}
// Return a selection that does not partially select any atomic
// ranges.
function skipAtomicInSelection(doc, sel, bias, mayClear) {
var out;
for (var i = 0; i < sel.ranges.length; i++) {
var range = sel.ranges[i];
var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
if (out || newAnchor != range.anchor || newHead != range.head) {
if (!out) { out = sel.ranges.slice(0, i); }
out[i] = new Range(newAnchor, newHead);
}
}
return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
}
function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
var line = getLine(doc, pos.line);
if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
var sp = line.markedSpans[i], m = sp.marker;
// Determine if we should prevent the cursor being placed to the left/right of an atomic marker
// Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
// is with selectLeft/Right
var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
(sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
if (mayClear) {
signal(m, "beforeCursorEnter");
if (m.explicitlyCleared) {
if (!line.markedSpans) { break }
else {--i; continue}
}
}
if (!m.atomic) { continue }
if (oldPos) {
var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
if (dir < 0 ? preventCursorRight : preventCursorLeft)
{ near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
{ return skipAtomicInner(doc, near, pos, dir, mayClear) }
}
var far = m.find(dir < 0 ? -1 : 1);
if (dir < 0 ? preventCursorLeft : preventCursorRight)
{ far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
}
} }
return pos
}
// Ensure a given position is not inside an atomic range.
function skipAtomic(doc, pos, oldPos, bias, mayClear) {
var dir = bias || 1;
var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
(!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
(!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
if (!found) {
doc.cantEdit = true;
return Pos(doc.first, 0)
}
return found
}
function movePos(doc, pos, dir, line) {
if (dir < 0 && pos.ch == 0) {
if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
else { return null }
} else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
else { return null }
} else {
return new Pos(pos.line, pos.ch + dir)
}
}
function selectAll(cm) {
cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
}
// UPDATING
// Allow "beforeChange" event handlers to influence a change
function filterChange(doc, change, update) {
var obj = {
canceled: false,
from: change.from,
to: change.to,
text: change.text,
origin: change.origin,
cancel: function () { return obj.canceled = true; }
};
if (update) { obj.update = function (from, to, text, origin) {
if (from) { obj.from = clipPos(doc, from); }
if (to) { obj.to = clipPos(doc, to); }
if (text) { obj.text = text; }
if (origin !== undefined) { obj.origin = origin; }
}; }
signal(doc, "beforeChange", doc, obj);
if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
if (obj.canceled) {
if (doc.cm) { doc.cm.curOp.updateInput = 2; }
return null
}
return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
}
// Apply a change to a document, and add it to the document's
// history, and propagating it to all linked documents.
function makeChange(doc, change, ignoreReadOnly) {
if (doc.cm) {
if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
if (doc.cm.state.suppressEdits) { return }
}
if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
change = filterChange(doc, change, true);
if (!change) { return }
}
// Possibly split or suppress the update based on the presence
// of read-only spans in its range.
var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
if (split) {
for (var i = split.length - 1; i >= 0; --i)
{ makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
} else {
makeChangeInner(doc, change);
}
}
function makeChangeInner(doc, change) {
if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
var selAfter = computeSelAfterChange(doc, change);
addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
var rebased = [];
linkedDocs(doc, function (doc, sharedHist) {
if (!sharedHist && indexOf(rebased, doc.history) == -1) {
rebaseHist(doc.history, change);
rebased.push(doc.history);
}
makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
});
}
// Revert a change stored in a document's history.
function makeChangeFromHistory(doc, type, allowSelectionOnly) {
var suppress = doc.cm && doc.cm.state.suppressEdits;
if (suppress && !allowSelectionOnly) { return }
var hist = doc.history, event, selAfter = doc.sel;
var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
// Verify that there is a useable event (so that ctrl-z won't
// needlessly clear selection events)
var i = 0;
for (; i < source.length; i++) {
event = source[i];
if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
{ break }
}
if (i == source.length) { return }
hist.lastOrigin = hist.lastSelOrigin = null;
for (;;) {
event = source.pop();
if (event.ranges) {
pushSelectionToHistory(event, dest);
if (allowSelectionOnly && !event.equals(doc.sel)) {
setSelection(doc, event, {clearRedo: false});
return
}
selAfter = event;
} else if (suppress) {
source.push(event);
return
} else { break }
}
// Build up a reverse change object to add to the opposite history
// stack (redo when undoing, and vice versa).
var antiChanges = [];
pushSelectionToHistory(selAfter, dest);
dest.push({changes: antiChanges, generation: hist.generation});
hist.generation = event.generation || ++hist.maxGeneration;
var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
var loop = function ( i ) {
var change = event.changes[i];
change.origin = type;
if (filter && !filterChange(doc, change, false)) {
source.length = 0;
return {}
}
antiChanges.push(historyChangeFromChange(doc, change));
var after = i ? computeSelAfterChange(doc, change) : lst(source);
makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
var rebased = [];
// Propagate to the linked documents
linkedDocs(doc, function (doc, sharedHist) {
if (!sharedHist && indexOf(rebased, doc.history) == -1) {
rebaseHist(doc.history, change);
rebased.push(doc.history);
}
makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
});
};
for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
var returned = loop( i$1 );
if ( returned ) return returned.v;
}
}
// Sub-views need their line numbers shifted when text is added
// above or below them in the parent document.
function shiftDoc(doc, distance) {
if (distance == 0) { return }
doc.first += distance;
doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
Pos(range.anchor.line + distance, range.anchor.ch),
Pos(range.head.line + distance, range.head.ch)
); }), doc.sel.primIndex);
if (doc.cm) {
regChange(doc.cm, doc.first, doc.first - distance, distance);
for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
{ regLineChange(doc.cm, l, "gutter"); }
}
}
// More lower-level change function, handling only a single document
// (not linked ones).
function makeChangeSingleDoc(doc, change, selAfter, spans) {
if (doc.cm && !doc.cm.curOp)
{ return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
if (change.to.line < doc.first) {
shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
return
}
if (change.from.line > doc.lastLine()) { return }
// Clip the change to the size of this doc
if (change.from.line < doc.first) {
var shift = change.text.length - 1 - (doc.first - change.from.line);
shiftDoc(doc, shift);
change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
text: [lst(change.text)], origin: change.origin};
}
var last = doc.lastLine();
if (change.to.line > last) {
change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
text: [change.text[0]], origin: change.origin};
}
change.removed = getBetween(doc, change.from, change.to);
if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
else { updateDoc(doc, change, spans); }
setSelectionNoUndo(doc, selAfter, sel_dontScroll);
if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
{ doc.cantEdit = false; }
}
// Handle the interaction of a change to a document with the editor
// that this document is part of.
function makeChangeSingleDocInEditor(cm, change, spans) {
var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
var recomputeMaxLength = false, checkWidthStart = from.line;
if (!cm.options.lineWrapping) {
checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
doc.iter(checkWidthStart, to.line + 1, function (line) {
if (line == display.maxLine) {
recomputeMaxLength = true;
return true
}
});
}
if (doc.sel.contains(change.from, change.to) > -1)
{ signalCursorActivity(cm); }
updateDoc(doc, change, spans, estimateHeight(cm));
if (!cm.options.lineWrapping) {
doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
var len = lineLength(line);
if (len > display.maxLineLength) {
display.maxLine = line;
display.maxLineLength = len;
display.maxLineChanged = true;
recomputeMaxLength = false;
}
});
if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
}
retreatFrontier(doc, from.line);
startWorker(cm, 400);
var lendiff = change.text.length - (to.line - from.line) - 1;
// Remember that these lines changed, for updating the display
if (change.full)
{ regChange(cm); }
else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
{ regLineChange(cm, from.line, "text"); }
else
{ regChange(cm, from.line, to.line + 1, lendiff); }
var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
if (changeHandler || changesHandler) {
var obj = {
from: from, to: to,
text: change.text,
removed: change.removed,
origin: change.origin
};
if (changeHandler) { signalLater(cm, "change", cm, obj); }
if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
}
cm.display.selForContextMenu = null;
}
function replaceRange(doc, code, from, to, origin) {
var assign;
if (!to) { to = from; }
if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
if (typeof code == "string") { code = doc.splitLines(code); }
makeChange(doc, {from: from, to: to, text: code, origin: origin});
}
// Rebasing/resetting history to deal with externally-sourced changes
function rebaseHistSelSingle(pos, from, to, diff) {
if (to < pos.line) {
pos.line += diff;
} else if (from < pos.line) {
pos.line = from;
pos.ch = 0;
}
}
// Tries to rebase an array of history events given a change in the
// document. If the change touches the same lines as the event, the
// event, and everything 'behind' it, is discarded. If the change is
// before the event, the event's positions are updated. Uses a
// copy-on-write scheme for the positions, to avoid having to
// reallocate them all on every rebase, but also avoid problems with
// shared position objects being unsafely updated.
function rebaseHistArray(array, from, to, diff) {
for (var i = 0; i < array.length; ++i) {
var sub = array[i], ok = true;
if (sub.ranges) {
if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
for (var j = 0; j < sub.ranges.length; j++) {
rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
}
continue
}
for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
var cur = sub.changes[j$1];
if (to < cur.from.line) {
cur.from = Pos(cur.from.line + diff, cur.from.ch);
cur.to = Pos(cur.to.line + diff, cur.to.ch);
} else if (from <= cur.to.line) {
ok = false;
break
}
}
if (!ok) {
array.splice(0, i + 1);
i = 0;
}
}
}
function rebaseHist(hist, change) {
var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
rebaseHistArray(hist.done, from, to, diff);
rebaseHistArray(hist.undone, from, to, diff);
}
// Utility for applying a change to a line by handle or number,
// returning the number and optionally registering the line as
// changed.
function changeLine(doc, handle, changeType, op) {
var no = handle, line = handle;
if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
else { no = lineNo(handle); }
if (no == null) { return null }
if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
return line
}
// The document is represented as a BTree consisting of leaves, with
// chunk of lines in them, and branches, with up to ten leaves or
// other branch nodes below them. The top node is always a branch
// node, and is the document object itself (meaning it has
// additional methods and properties).
//
// All nodes have parent links. The tree is used both to go from
// line numbers to line objects, and to go from objects to numbers.
// It also indexes by height, and is used to convert between height
// and line object, and to find the total height of the document.
//
// See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
function LeafChunk(lines) {
this.lines = lines;
this.parent = null;
var height = 0;
for (var i = 0; i < lines.length; ++i) {
lines[i].parent = this;
height += lines[i].height;
}
this.height = height;
}
LeafChunk.prototype = {
chunkSize: function() { return this.lines.length },
// Remove the n lines at offset 'at'.
removeInner: function(at, n) {
for (var i = at, e = at + n; i < e; ++i) {
var line = this.lines[i];
this.height -= line.height;
cleanUpLine(line);
signalLater(line, "delete");
}
this.lines.splice(at, n);
},
// Helper used to collapse a small branch into a single leaf.
collapse: function(lines) {
lines.push.apply(lines, this.lines);
},
// Insert the given array of lines at offset 'at', count them as
// having the given height.
insertInner: function(at, lines, height) {
this.height += height;
this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; }
},
// Used to iterate over a part of the tree.
iterN: function(at, n, op) {
for (var e = at + n; at < e; ++at)
{ if (op(this.lines[at])) { return true } }
}
};
function BranchChunk(children) {
this.children = children;
var size = 0, height = 0;
for (var i = 0; i < children.length; ++i) {
var ch = children[i];
size += ch.chunkSize(); height += ch.height;
ch.parent = this;
}
this.size = size;
this.height = height;
this.parent = null;
}
BranchChunk.prototype = {
chunkSize: function() { return this.size },
removeInner: function(at, n) {
this.size -= n;
for (var i = 0; i < this.children.length; ++i) {
var child = this.children[i], sz = child.chunkSize();
if (at < sz) {
var rm = Math.min(n, sz - at), oldHeight = child.height;
child.removeInner(at, rm);
this.height -= oldHeight - child.height;
if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
if ((n -= rm) == 0) { break }
at = 0;
} else { at -= sz; }
}
// If the result is smaller than 25 lines, ensure that it is a
// single leaf node.
if (this.size - n < 25 &&
(this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
var lines = [];
this.collapse(lines);
this.children = [new LeafChunk(lines)];
this.children[0].parent = this;
}
},
collapse: function(lines) {
for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); }
},
insertInner: function(at, lines, height) {
this.size += lines.length;
this.height += height;
for (var i = 0; i < this.children.length; ++i) {
var child = this.children[i], sz = child.chunkSize();
if (at <= sz) {
child.insertInner(at, lines, height);
if (child.lines && child.lines.length > 50) {
// To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
// Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
var remaining = child.lines.length % 25 + 25;
for (var pos = remaining; pos < child.lines.length;) {
var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
child.height -= leaf.height;
this.children.splice(++i, 0, leaf);
leaf.parent = this;
}
child.lines = child.lines.slice(0, remaining);
this.maybeSpill();
}
break
}
at -= sz;
}
},
// When a node has grown, check whether it should be split.
maybeSpill: function() {
if (this.children.length <= 10) { return }
var me = this;
do {
var spilled = me.children.splice(me.children.length - 5, 5);
var sibling = new BranchChunk(spilled);
if (!me.parent) { // Become the parent node
var copy = new BranchChunk(me.children);
copy.parent = me;
me.children = [copy, sibling];
me = copy;
} else {
me.size -= sibling.size;
me.height -= sibling.height;
var myIndex = indexOf(me.parent.children, me);
me.parent.children.splice(myIndex + 1, 0, sibling);
}
sibling.parent = me.parent;
} while (me.children.length > 10)
me.parent.maybeSpill();
},
iterN: function(at, n, op) {
for (var i = 0; i < this.children.length; ++i) {
var child = this.children[i], sz = child.chunkSize();
if (at < sz) {
var used = Math.min(n, sz - at);
if (child.iterN(at, used, op)) { return true }
if ((n -= used) == 0) { break }
at = 0;
} else { at -= sz; }
}
}
};
// Line widgets are block elements displayed above or below a line.
var LineWidget = function(doc, node, options) {
if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
{ this[opt] = options[opt]; } } }
this.doc = doc;
this.node = node;
};
LineWidget.prototype.clear = function () {
var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
if (no == null || !ws) { return }
for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } }
if (!ws.length) { line.widgets = null; }
var height = widgetHeight(this);
updateLineHeight(line, Math.max(0, line.height - height));
if (cm) {
runInOp(cm, function () {
adjustScrollWhenAboveVisible(cm, line, -height);
regLineChange(cm, no, "widget");
});
signalLater(cm, "lineWidgetCleared", cm, this, no);
}
};
LineWidget.prototype.changed = function () {
var this$1 = this;
var oldH = this.height, cm = this.doc.cm, line = this.line;
this.height = null;
var diff = widgetHeight(this) - oldH;
if (!diff) { return }
if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
if (cm) {
runInOp(cm, function () {
cm.curOp.forceUpdate = true;
adjustScrollWhenAboveVisible(cm, line, diff);
signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
});
}
};
eventMixin(LineWidget);
function adjustScrollWhenAboveVisible(cm, line, diff) {
if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
{ addToScrollTop(cm, diff); }
}
function addLineWidget(doc, handle, node, options) {
var widget = new LineWidget(doc, node, options);
var cm = doc.cm;
if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
changeLine(doc, handle, "widget", function (line) {
var widgets = line.widgets || (line.widgets = []);
if (widget.insertAt == null) { widgets.push(widget); }
else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }
widget.line = line;
if (cm && !lineIsHidden(doc, line)) {
var aboveVisible = heightAtLine(line) < doc.scrollTop;
updateLineHeight(line, line.height + widgetHeight(widget));
if (aboveVisible) { addToScrollTop(cm, widget.height); }
cm.curOp.forceUpdate = true;
}
return true
});
if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
return widget
}
// TEXTMARKERS
// Created with markText and setBookmark methods. A TextMarker is a
// handle that can be used to clear or find a marked position in the
// document. Line objects hold arrays (markedSpans) containing
// {from, to, marker} object pointing to such marker objects, and
// indicating that such a marker is present on that line. Multiple
// lines may point to the same marker when it spans across lines.
// The spans will have null for their from/to properties when the
// marker continues beyond the start/end of the line. Markers have
// links back to the lines they currently touch.
// Collapsed markers have unique ids, in order to be able to order
// them, which is needed for uniquely determining an outer marker
// when they overlap (they may nest, but not partially overlap).
var nextMarkerId = 0;
var TextMarker = function(doc, type) {
this.lines = [];
this.type = type;
this.doc = doc;
this.id = ++nextMarkerId;
};
// Clear the marker.
TextMarker.prototype.clear = function () {
if (this.explicitlyCleared) { return }
var cm = this.doc.cm, withOp = cm && !cm.curOp;
if (withOp) { startOperation(cm); }
if (hasHandler(this, "clear")) {
var found = this.find();
if (found) { signalLater(this, "clear", found.from, found.to); }
}
var min = null, max = null;
for (var i = 0; i < this.lines.length; ++i) {
var line = this.lines[i];
var span = getMarkedSpanFor(line.markedSpans, this);
if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); }
else if (cm) {
if (span.to != null) { max = lineNo(line); }
if (span.from != null) { min = lineNo(line); }
}
line.markedSpans = removeMarkedSpan(line.markedSpans, span);
if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
{ updateLineHeight(line, textHeight(cm.display)); }
}
if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
var visual = visualLine(this.lines[i$1]), len = lineLength(visual);
if (len > cm.display.maxLineLength) {
cm.display.maxLine = visual;
cm.display.maxLineLength = len;
cm.display.maxLineChanged = true;
}
} }
if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
this.lines.length = 0;
this.explicitlyCleared = true;
if (this.atomic && this.doc.cantEdit) {
this.doc.cantEdit = false;
if (cm) { reCheckSelection(cm.doc); }
}
if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
if (withOp) { endOperation(cm); }
if (this.parent) { this.parent.clear(); }
};
// Find the position of the marker in the document. Returns a {from,
// to} object by default. Side can be passed to get a specific side
// -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
// Pos objects returned contain a line object, rather than a line
// number (used to prevent looking up the same line twice).
TextMarker.prototype.find = function (side, lineObj) {
if (side == null && this.type == "bookmark") { side = 1; }
var from, to;
for (var i = 0; i < this.lines.length; ++i) {
var line = this.lines[i];
var span = getMarkedSpanFor(line.markedSpans, this);
if (span.from != null) {
from = Pos(lineObj ? line : lineNo(line), span.from);
if (side == -1) { return from }
}
if (span.to != null) {
to = Pos(lineObj ? line : lineNo(line), span.to);
if (side == 1) { return to }
}
}
return from && {from: from, to: to}
};
// Signals that the marker's widget changed, and surrounding layout
// should be recomputed.
TextMarker.prototype.changed = function () {
var this$1 = this;
var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
if (!pos || !cm) { return }
runInOp(cm, function () {
var line = pos.line, lineN = lineNo(pos.line);
var view = findViewForLine(cm, lineN);
if (view) {
clearLineMeasurementCacheFor(view);
cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
}
cm.curOp.updateMaxLine = true;
if (!lineIsHidden(widget.doc, line) && widget.height != null) {
var oldHeight = widget.height;
widget.height = null;
var dHeight = widgetHeight(widget) - oldHeight;
if (dHeight)
{ updateLineHeight(line, line.height + dHeight); }
}
signalLater(cm, "markerChanged", cm, this$1);
});
};
TextMarker.prototype.attachLine = function (line) {
if (!this.lines.length && this.doc.cm) {
var op = this.doc.cm.curOp;
if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
{ (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
}
this.lines.push(line);
};
TextMarker.prototype.detachLine = function (line) {
this.lines.splice(indexOf(this.lines, line), 1);
if (!this.lines.length && this.doc.cm) {
var op = this.doc.cm.curOp
;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
}
};
eventMixin(TextMarker);
// Create a marker, wire it up to the right lines, and
function markText(doc, from, to, options, type) {
// Shared markers (across linked documents) are handled separately
// (markTextShared will call out to this again, once per
// document).
if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
// Ensure we are in an operation.
if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
var marker = new TextMarker(doc, type), diff = cmp(from, to);
if (options) { copyObj(options, marker, false); }
// Don't connect empty markers unless clearWhenEmpty is false
if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
{ return marker }
if (marker.replacedWith) {
// Showing up as a widget implies collapsed (widget replaces text)
marker.collapsed = true;
marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
}
if (marker.collapsed) {
if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
{ throw new Error("Inserting collapsed marker partially overlapping an existing one") }
seeCollapsedSpans();
}
if (marker.addToHistory)
{ addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
var curLine = from.line, cm = doc.cm, updateMaxLine;
doc.iter(curLine, to.line + 1, function (line) {
if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
{ updateMaxLine = true; }
if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
addMarkedSpan(line, new MarkedSpan(marker,
curLine == from.line ? from.ch : null,
curLine == to.line ? to.ch : null));
++curLine;
});
// lineIsHidden depends on the presence of the spans, so needs a second pass
if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
}); }
if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
if (marker.readOnly) {
seeReadOnlySpans();
if (doc.history.done.length || doc.history.undone.length)
{ doc.clearHistory(); }
}
if (marker.collapsed) {
marker.id = ++nextMarkerId;
marker.atomic = true;
}
if (cm) {
// Sync editor state
if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
if (marker.collapsed)
{ regChange(cm, from.line, to.line + 1); }
else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
marker.attributes || marker.title)
{ for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
if (marker.atomic) { reCheckSelection(cm.doc); }
signalLater(cm, "markerAdded", cm, marker);
}
return marker
}
// SHARED TEXTMARKERS
// A shared marker spans multiple linked documents. It is
// implemented as a meta-marker-object controlling multiple normal
// markers.
var SharedTextMarker = function(markers, primary) {
this.markers = markers;
this.primary = primary;
for (var i = 0; i < markers.length; ++i)
{ markers[i].parent = this; }
};
SharedTextMarker.prototype.clear = function () {
if (this.explicitlyCleared) { return }
this.explicitlyCleared = true;
for (var i = 0; i < this.markers.length; ++i)
{ this.markers[i].clear(); }
signalLater(this, "clear");
};
SharedTextMarker.prototype.find = function (side, lineObj) {
return this.primary.find(side, lineObj)
};
eventMixin(SharedTextMarker);
function markTextShared(doc, from, to, options, type) {
options = copyObj(options);
options.shared = false;
var markers = [markText(doc, from, to, options, type)], primary = markers[0];
var widget = options.widgetNode;
linkedDocs(doc, function (doc) {
if (widget) { options.widgetNode = widget.cloneNode(true); }
markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
for (var i = 0; i < doc.linked.length; ++i)
{ if (doc.linked[i].isParent) { return } }
primary = lst(markers);
});
return new SharedTextMarker(markers, primary)
}
function findSharedMarkers(doc) {
return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
}
function copySharedMarkers(doc, markers) {
for (var i = 0; i < markers.length; i++) {
var marker = markers[i], pos = marker.find();
var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
if (cmp(mFrom, mTo)) {
var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
marker.markers.push(subMark);
subMark.parent = marker;
}
}
}
function detachSharedMarkers(markers) {
var loop = function ( i ) {
var marker = markers[i], linked = [marker.primary.doc];
linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
for (var j = 0; j < marker.markers.length; j++) {
var subMarker = marker.markers[j];
if (indexOf(linked, subMarker.doc) == -1) {
subMarker.parent = null;
marker.markers.splice(j--, 1);
}
}
};
for (var i = 0; i < markers.length; i++) loop( i );
}
var nextDocId = 0;
var Doc = function(text, mode, firstLine, lineSep, direction) {
if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
if (firstLine == null) { firstLine = 0; }
BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
this.first = firstLine;
this.scrollTop = this.scrollLeft = 0;
this.cantEdit = false;
this.cleanGeneration = 1;
this.modeFrontier = this.highlightFrontier = firstLine;
var start = Pos(firstLine, 0);
this.sel = simpleSelection(start);
this.history = new History(null);
this.id = ++nextDocId;
this.modeOption = mode;
this.lineSep = lineSep;
this.direction = (direction == "rtl") ? "rtl" : "ltr";
this.extend = false;
if (typeof text == "string") { text = this.splitLines(text); }
updateDoc(this, {from: start, to: start, text: text});
setSelection(this, simpleSelection(start), sel_dontScroll);
};
Doc.prototype = createObj(BranchChunk.prototype, {
constructor: Doc,
// Iterate over the document. Supports two forms -- with only one
// argument, it calls that for each line in the document. With
// three, it iterates over the range given by the first two (with
// the second being non-inclusive).
iter: function(from, to, op) {
if (op) { this.iterN(from - this.first, to - from, op); }
else { this.iterN(this.first, this.first + this.size, from); }
},
// Non-public interface for adding and removing lines.
insert: function(at, lines) {
var height = 0;
for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
this.insertInner(at - this.first, lines, height);
},
remove: function(at, n) { this.removeInner(at - this.first, n); },
// From here, the methods are part of the public interface. Most
// are also available from CodeMirror (editor) instances.
getValue: function(lineSep) {
var lines = getLines(this, this.first, this.first + this.size);
if (lineSep === false) { return lines }
return lines.join(lineSep || this.lineSeparator())
},
setValue: docMethodOp(function(code) {
var top = Pos(this.first, 0), last = this.first + this.size - 1;
makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
text: this.splitLines(code), origin: "setValue", full: true}, true);
if (this.cm) { scrollToCoords(this.cm, 0, 0); }
setSelection(this, simpleSelection(top), sel_dontScroll);
}),
replaceRange: function(code, from, to, origin) {
from = clipPos(this, from);
to = to ? clipPos(this, to) : from;
replaceRange(this, code, from, to, origin);
},
getRange: function(from, to, lineSep) {
var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
if (lineSep === false) { return lines }
return lines.join(lineSep || this.lineSeparator())
},
getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
getLineNumber: function(line) {return lineNo(line)},
getLineHandleVisualStart: function(line) {
if (typeof line == "number") { line = getLine(this, line); }
return visualLine(line)
},
lineCount: function() {return this.size},
firstLine: function() {return this.first},
lastLine: function() {return this.first + this.size - 1},
clipPos: function(pos) {return clipPos(this, pos)},
getCursor: function(start) {
var range = this.sel.primary(), pos;
if (start == null || start == "head") { pos = range.head; }
else if (start == "anchor") { pos = range.anchor; }
else if (start == "end" || start == "to" || start === false) { pos = range.to(); }
else { pos = range.from(); }
return pos
},
listSelections: function() { return this.sel.ranges },
somethingSelected: function() {return this.sel.somethingSelected()},
setCursor: docMethodOp(function(line, ch, options) {
setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
}),
setSelection: docMethodOp(function(anchor, head, options) {
setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
}),
extendSelection: docMethodOp(function(head, other, options) {
extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
}),
extendSelections: docMethodOp(function(heads, options) {
extendSelections(this, clipPosArray(this, heads), options);
}),
extendSelectionsBy: docMethodOp(function(f, options) {
var heads = map(this.sel.ranges, f);
extendSelections(this, clipPosArray(this, heads), options);
}),
setSelections: docMethodOp(function(ranges, primary, options) {
if (!ranges.length) { return }
var out = [];
for (var i = 0; i < ranges.length; i++)
{ out[i] = new Range(clipPos(this, ranges[i].anchor),
clipPos(this, ranges[i].head)); }
if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
setSelection(this, normalizeSelection(this.cm, out, primary), options);
}),
addSelection: docMethodOp(function(anchor, head, options) {
var ranges = this.sel.ranges.slice(0);
ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
}),
getSelection: function(lineSep) {
var ranges = this.sel.ranges, lines;
for (var i = 0; i < ranges.length; i++) {
var sel = getBetween(this, ranges[i].from(), ranges[i].to());
lines = lines ? lines.concat(sel) : sel;
}
if (lineSep === false) { return lines }
else { return lines.join(lineSep || this.lineSeparator()) }
},
getSelections: function(lineSep) {
var parts = [], ranges = this.sel.ranges;
for (var i = 0; i < ranges.length; i++) {
var sel = getBetween(this, ranges[i].from(), ranges[i].to());
if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); }
parts[i] = sel;
}
return parts
},
replaceSelection: function(code, collapse, origin) {
var dup = [];
for (var i = 0; i < this.sel.ranges.length; i++)
{ dup[i] = code; }
this.replaceSelections(dup, collapse, origin || "+input");
},
replaceSelections: docMethodOp(function(code, collapse, origin) {
var changes = [], sel = this.sel;
for (var i = 0; i < sel.ranges.length; i++) {
var range = sel.ranges[i];
changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
}
var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
{ makeChange(this, changes[i$1]); }
if (newSel) { setSelectionReplaceHistory(this, newSel); }
else if (this.cm) { ensureCursorVisible(this.cm); }
}),
undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
setExtending: function(val) {this.extend = val;},
getExtending: function() {return this.extend},
historySize: function() {
var hist = this.history, done = 0, undone = 0;
for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
return {undo: done, redo: undone}
},
clearHistory: function() {
var this$1 = this;
this.history = new History(this.history.maxGeneration);
linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true);
},
markClean: function() {
this.cleanGeneration = this.changeGeneration(true);
},
changeGeneration: function(forceSplit) {
if (forceSplit)
{ this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
return this.history.generation
},
isClean: function (gen) {
return this.history.generation == (gen || this.cleanGeneration)
},
getHistory: function() {
return {done: copyHistoryArray(this.history.done),
undone: copyHistoryArray(this.history.undone)}
},
setHistory: function(histData) {
var hist = this.history = new History(this.history.maxGeneration);
hist.done = copyHistoryArray(histData.done.slice(0), null, true);
hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
},
setGutterMarker: docMethodOp(function(line, gutterID, value) {
return changeLine(this, line, "gutter", function (line) {
var markers = line.gutterMarkers || (line.gutterMarkers = {});
markers[gutterID] = value;
if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
return true
})
}),
clearGutter: docMethodOp(function(gutterID) {
var this$1 = this;
this.iter(function (line) {
if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
changeLine(this$1, line, "gutter", function () {
line.gutterMarkers[gutterID] = null;
if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
return true
});
}
});
}),
lineInfo: function(line) {
var n;
if (typeof line == "number") {
if (!isLine(this, line)) { return null }
n = line;
line = getLine(this, line);
if (!line) { return null }
} else {
n = lineNo(line);
if (n == null) { return null }
}
return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
widgets: line.widgets}
},
addLineClass: docMethodOp(function(handle, where, cls) {
return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
var prop = where == "text" ? "textClass"
: where == "background" ? "bgClass"
: where == "gutter" ? "gutterClass" : "wrapClass";
if (!line[prop]) { line[prop] = cls; }
else if (classTest(cls).test(line[prop])) { return false }
else { line[prop] += " " + cls; }
return true
})
}),
removeLineClass: docMethodOp(function(handle, where, cls) {
return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
var prop = where == "text" ? "textClass"
: where == "background" ? "bgClass"
: where == "gutter" ? "gutterClass" : "wrapClass";
var cur = line[prop];
if (!cur) { return false }
else if (cls == null) { line[prop] = null; }
else {
var found = cur.match(classTest(cls));
if (!found) { return false }
var end = found.index + found[0].length;
line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
}
return true
})
}),
addLineWidget: docMethodOp(function(handle, node, options) {
return addLineWidget(this, handle, node, options)
}),
removeLineWidget: function(widget) { widget.clear(); },
markText: function(from, to, options) {
return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
},
setBookmark: function(pos, options) {
var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
insertLeft: options && options.insertLeft,
clearWhenEmpty: false, shared: options && options.shared,
handleMouseEvents: options && options.handleMouseEvents};
pos = clipPos(this, pos);
return markText(this, pos, pos, realOpts, "bookmark")
},
findMarksAt: function(pos) {
pos = clipPos(this, pos);
var markers = [], spans = getLine(this, pos.line).markedSpans;
if (spans) { for (var i = 0; i < spans.length; ++i) {
var span = spans[i];
if ((span.from == null || span.from <= pos.ch) &&
(span.to == null || span.to >= pos.ch))
{ markers.push(span.marker.parent || span.marker); }
} }
return markers
},
findMarks: function(from, to, filter) {
from = clipPos(this, from); to = clipPos(this, to);
var found = [], lineNo = from.line;
this.iter(from.line, to.line + 1, function (line) {
var spans = line.markedSpans;
if (spans) { for (var i = 0; i < spans.length; i++) {
var span = spans[i];
if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
span.from == null && lineNo != from.line ||
span.from != null && lineNo == to.line && span.from >= to.ch) &&
(!filter || filter(span.marker)))
{ found.push(span.marker.parent || span.marker); }
} }
++lineNo;
});
return found
},
getAllMarks: function() {
var markers = [];
this.iter(function (line) {
var sps = line.markedSpans;
if (sps) { for (var i = 0; i < sps.length; ++i)
{ if (sps[i].from != null) { markers.push(sps[i].marker); } } }
});
return markers
},
posFromIndex: function(off) {
var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
this.iter(function (line) {
var sz = line.text.length + sepSize;
if (sz > off) { ch = off; return true }
off -= sz;
++lineNo;
});
return clipPos(this, Pos(lineNo, ch))
},
indexFromPos: function (coords) {
coords = clipPos(this, coords);
var index = coords.ch;
if (coords.line < this.first || coords.ch < 0) { return 0 }
var sepSize = this.lineSeparator().length;
this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
index += line.text.length + sepSize;
});
return index
},
copy: function(copyHistory) {
var doc = new Doc(getLines(this, this.first, this.first + this.size),
this.modeOption, this.first, this.lineSep, this.direction);
doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
doc.sel = this.sel;
doc.extend = false;
if (copyHistory) {
doc.history.undoDepth = this.history.undoDepth;
doc.setHistory(this.getHistory());
}
return doc
},
linkedDoc: function(options) {
if (!options) { options = {}; }
var from = this.first, to = this.first + this.size;
if (options.from != null && options.from > from) { from = options.from; }
if (options.to != null && options.to < to) { to = options.to; }
var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
if (options.sharedHist) { copy.history = this.history
; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
copySharedMarkers(copy, findSharedMarkers(this));
return copy
},
unlinkDoc: function(other) {
if (other instanceof CodeMirror) { other = other.doc; }
if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
var link = this.linked[i];
if (link.doc != other) { continue }
this.linked.splice(i, 1);
other.unlinkDoc(this);
detachSharedMarkers(findSharedMarkers(this));
break
} }
// If the histories were shared, split them again
if (other.history == this.history) {
var splitIds = [other.id];
linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
other.history = new History(null);
other.history.done = copyHistoryArray(this.history.done, splitIds);
other.history.undone = copyHistoryArray(this.history.undone, splitIds);
}
},
iterLinkedDocs: function(f) {linkedDocs(this, f);},
getMode: function() {return this.mode},
getEditor: function() {return this.cm},
splitLines: function(str) {
if (this.lineSep) { return str.split(this.lineSep) }
return splitLinesAuto(str)
},
lineSeparator: function() { return this.lineSep || "\n" },
setDirection: docMethodOp(function (dir) {
if (dir != "rtl") { dir = "ltr"; }
if (dir == this.direction) { return }
this.direction = dir;
this.iter(function (line) { return line.order = null; });
if (this.cm) { directionChanged(this.cm); }
})
});
// Public alias.
Doc.prototype.eachLine = Doc.prototype.iter;
// Kludge to work around strange IE behavior where it'll sometimes
// re-fire a series of drag-related events right after the drop (#1551)
var lastDrop = 0;
function onDrop(e) {
var cm = this;
clearDragCursor(cm);
if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
{ return }
e_preventDefault(e);
if (ie) { lastDrop = +new Date; }
var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
if (!pos || cm.isReadOnly()) { return }
// Might be a file drop, in which case we simply extract the text
// and insert it.
if (files && files.length && window.FileReader && window.File) {
var n = files.length, text = Array(n), read = 0;
var markAsReadAndPasteIfAllFilesAreRead = function () {
if (++read == n) {
operation(cm, function () {
pos = clipPos(cm.doc, pos);
var change = {from: pos, to: pos,
text: cm.doc.splitLines(
text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())),
origin: "paste"};
makeChange(cm.doc, change);
setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
})();
}
};
var readTextFromFile = function (file, i) {
if (cm.options.allowDropFileTypes &&
indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
markAsReadAndPasteIfAllFilesAreRead();
return
}
var reader = new FileReader;
reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); };
reader.onload = function () {
var content = reader.result;
if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
markAsReadAndPasteIfAllFilesAreRead();
return
}
text[i] = content;
markAsReadAndPasteIfAllFilesAreRead();
};
reader.readAsText(file);
};
for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); }
} else { // Normal drop
// Don't do a replace if the drop happened inside of the selected text.
if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
cm.state.draggingText(e);
// Ensure the editor is re-focused
setTimeout(function () { return cm.display.input.focus(); }, 20);
return
}
try {
var text$1 = e.dataTransfer.getData("Text");
if (text$1) {
var selected;
if (cm.state.draggingText && !cm.state.draggingText.copy)
{ selected = cm.listSelections(); }
setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
{ replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
cm.replaceSelection(text$1, "around", "paste");
cm.display.input.focus();
}
}
catch(e$1){}
}
}
function onDragStart(cm, e) {
if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
e.dataTransfer.setData("Text", cm.getSelection());
e.dataTransfer.effectAllowed = "copyMove";
// Use dummy image instead of default browsers image.
// Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
if (e.dataTransfer.setDragImage && !safari) {
var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
if (presto) {
img.width = img.height = 1;
cm.display.wrapper.appendChild(img);
// Force a relayout, or Opera won't use our image for some obscure reason
img._top = img.offsetTop;
}
e.dataTransfer.setDragImage(img, 0, 0);
if (presto) { img.parentNode.removeChild(img); }
}
}
function onDragOver(cm, e) {
var pos = posFromMouse(cm, e);
if (!pos) { return }
var frag = document.createDocumentFragment();
drawSelectionCursor(cm, pos, frag);
if (!cm.display.dragCursor) {
cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
}
removeChildrenAndAdd(cm.display.dragCursor, frag);
}
function clearDragCursor(cm) {
if (cm.display.dragCursor) {
cm.display.lineSpace.removeChild(cm.display.dragCursor);
cm.display.dragCursor = null;
}
}
// These must be handled carefully, because naively registering a
// handler for each editor will cause the editors to never be
// garbage collected.
function forEachCodeMirror(f) {
if (!document.getElementsByClassName) { return }
var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
for (var i = 0; i < byClass.length; i++) {
var cm = byClass[i].CodeMirror;
if (cm) { editors.push(cm); }
}
if (editors.length) { editors[0].operation(function () {
for (var i = 0; i < editors.length; i++) { f(editors[i]); }
}); }
}
var globalsRegistered = false;
function ensureGlobalHandlers() {
if (globalsRegistered) { return }
registerGlobalHandlers();
globalsRegistered = true;
}
function registerGlobalHandlers() {
// When the window resizes, we need to refresh active editors.
var resizeTimer;
on(window, "resize", function () {
if (resizeTimer == null) { resizeTimer = setTimeout(function () {
resizeTimer = null;
forEachCodeMirror(onResize);
}, 100); }
});
// When the window loses focus, we want to show the editor as blurred
on(window, "blur", function () { return forEachCodeMirror(onBlur); });
}
// Called when the window resizes
function onResize(cm) {
var d = cm.display;
// Might be a text scaling operation, clear size caches.
d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
d.scrollbarsClipped = false;
cm.setSize();
}
var keyNames = {
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"
};
// Number keys
for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
// Alphabetic keys
for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
// Function keys
for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
var keyMap = {};
keyMap.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"
};
// Note that the save and find-related commands aren't defined by
// default. User code or addons can define them. Unknown commands
// are simply ignored.
keyMap.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"
};
// Very basic readline/emacs-style bindings, which are standard on Mac.
keyMap.emacsy = {
"Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
"Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
"Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
"Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
"Ctrl-O": "openLine"
};
keyMap.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"]
};
keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
// KEYMAP DISPATCH
function normalizeKeyName(name) {
var parts = name.split(/-(?!$)/);
name = parts[parts.length - 1];
var alt, ctrl, shift, cmd;
for (var i = 0; i < parts.length - 1; i++) {
var mod = parts[i];
if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
else if (/^a(lt)?$/i.test(mod)) { alt = true; }
else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
else if (/^s(hift)?$/i.test(mod)) { shift = true; }
else { throw new Error("Unrecognized modifier name: " + mod) }
}
if (alt) { name = "Alt-" + name; }
if (ctrl) { name = "Ctrl-" + name; }
if (cmd) { name = "Cmd-" + name; }
if (shift) { name = "Shift-" + name; }
return name
}
// This is a kludge to keep keymaps mostly working as raw objects
// (backwards compatibility) while at the same time support features
// like normalization and multi-stroke key bindings. It compiles a
// new normalized keymap, and then updates the old object to reflect
// this.
function normalizeKeyMap(keymap) {
var copy = {};
for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
var value = keymap[keyname];
if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
if (value == "...") { delete keymap[keyname]; continue }
var keys = map(keyname.split(" "), normalizeKeyName);
for (var i = 0; i < keys.length; i++) {
var val = (void 0), name = (void 0);
if (i == keys.length - 1) {
name = keys.join(" ");
val = value;
} else {
name = keys.slice(0, i + 1).join(" ");
val = "...";
}
var prev = copy[name];
if (!prev) { copy[name] = val; }
else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
}
delete keymap[keyname];
} }
for (var prop in copy) { keymap[prop] = copy[prop]; }
return keymap
}
function lookupKey(key, map, handle, context) {
map = getKeyMap(map);
var found = map.call ? map.call(key, context) : map[key];
if (found === false) { return "nothing" }
if (found === "...") { return "multi" }
if (found != null && handle(found)) { return "handled" }
if (map.fallthrough) {
if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
{ return lookupKey(key, map.fallthrough, handle, context) }
for (var i = 0; i < map.fallthrough.length; i++) {
var result = lookupKey(key, map.fallthrough[i], handle, context);
if (result) { return result }
}
}
}
// Modifier key presses don't count as 'real' key presses for the
// purpose of keymap fallthrough.
function isModifierKey(value) {
var name = typeof value == "string" ? value : keyNames[value.keyCode];
return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
}
function addModifierNames(name, event, noShift) {
var base = name;
if (event.altKey && base != "Alt") { name = "Alt-" + name; }
if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { name = "Cmd-" + name; }
if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
return name
}
// Look up the name of a key as indicated by an event object.
function keyName(event, noShift) {
if (presto && event.keyCode == 34 && event["char"]) { return false }
var name = keyNames[event.keyCode];
if (name == null || event.altGraphKey) { return false }
// Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
// so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
if (event.keyCode == 3 && event.code) { name = event.code; }
return addModifierNames(name, event, noShift)
}
function getKeyMap(val) {
return typeof val == "string" ? keyMap[val] : val
}
// Helper for deleting text near the selection(s), used to implement
// backspace, delete, and similar functionality.
function deleteNearSelection(cm, compute) {
var ranges = cm.doc.sel.ranges, kill = [];
// Build up a set of ranges to kill first, merging overlapping
// ranges.
for (var i = 0; i < ranges.length; i++) {
var toKill = compute(ranges[i]);
while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
var replaced = kill.pop();
if (cmp(replaced.from, toKill.from) < 0) {
toKill.from = replaced.from;
break
}
}
kill.push(toKill);
}
// Next, remove those actual ranges.
runInOp(cm, function () {
for (var i = kill.length - 1; i >= 0; i--)
{ replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
ensureCursorVisible(cm);
});
}
function moveCharLogically(line, ch, dir) {
var target = skipExtendingChars(line.text, ch + dir, dir);
return target < 0 || target > line.text.length ? null : target
}
function moveLogically(line, start, dir) {
var ch = moveCharLogically(line, start.ch, dir);
return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
}
function endOfLine(visually, cm, lineObj, lineNo, dir) {
if (visually) {
if (cm.doc.direction == "rtl") { dir = -dir; }
var order = getOrder(lineObj, cm.doc.direction);
if (order) {
var part = dir < 0 ? lst(order) : order[0];
var moveInStorageOrder = (dir < 0) == (part.level == 1);
var sticky = moveInStorageOrder ? "after" : "before";
var ch;
// With a wrapped rtl chunk (possibly spanning multiple bidi parts),
// it could be that the last bidi part is not on the last visual line,
// since visual lines contain content order-consecutive chunks.
// Thus, in rtl, we are looking for the first (content-order) character
// in the rtl chunk that is on the last line (that is, the same line
// as the last (content-order) character).
if (part.level > 0 || cm.doc.direction == "rtl") {
var prep = prepareMeasureForLine(cm, lineObj);
ch = dir < 0 ? lineObj.text.length - 1 : 0;
var targetTop = measureCharPrepared(cm, prep, ch).top;
ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
} else { ch = dir < 0 ? part.to : part.from; }
return new Pos(lineNo, ch, sticky)
}
}
return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
}
function moveVisually(cm, line, start, dir) {
var bidi = getOrder(line, cm.doc.direction);
if (!bidi) { return moveLogically(line, start, dir) }
if (start.ch >= line.text.length) {
start.ch = line.text.length;
start.sticky = "before";
} else if (start.ch <= 0) {
start.ch = 0;
start.sticky = "after";
}
var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
// Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
// nothing interesting happens.
return moveLogically(line, start, dir)
}
var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
var prep;
var getWrappedLineExtent = function (ch) {
if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
prep = prep || prepareMeasureForLine(cm, line);
return wrappedLineExtentChar(cm, line, prep, ch)
};
var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
if (cm.doc.direction == "rtl" || part.level == 1) {
var moveInStorageOrder = (part.level == 1) == (dir < 0);
var ch = mv(start, moveInStorageOrder ? 1 : -1);
if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
// Case 2: We move within an rtl part or in an rtl editor on the same visual line
var sticky = moveInStorageOrder ? "before" : "after";
return new Pos(start.line, ch, sticky)
}
}
// Case 3: Could not move within this bidi part in this visual line, so leave
// the current bidi part
var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
? new Pos(start.line, mv(ch, 1), "before")
: new Pos(start.line, ch, "after"); };
for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
var part = bidi[partPos];
var moveInStorageOrder = (dir > 0) == (part.level != 1);
var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
ch = moveInStorageOrder ? part.from : mv(part.to, -1);
if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
}
};
// Case 3a: Look for other bidi parts on the same visual line
var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
if (res) { return res }
// Case 3b: Look for other bidi parts on the next visual line
var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
if (res) { return res }
}
// Case 4: Nowhere to move
return null
}
// Commands are parameter-less actions that can be performed on an
// editor, mostly used for keybindings.
var commands = {
selectAll: selectAll,
singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
killLine: function (cm) { return deleteNearSelection(cm, function (range) {
if (range.empty()) {
var len = getLine(cm.doc, range.head.line).text.length;
if (range.head.ch == len && range.head.line < cm.lastLine())
{ return {from: range.head, to: Pos(range.head.line + 1, 0)} }
else
{ return {from: range.head, to: Pos(range.head.line, len)} }
} else {
return {from: range.from(), to: range.to()}
}
}); },
deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
from: Pos(range.from().line, 0),
to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
}); }); },
delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
from: Pos(range.from().line, 0), to: range.from()
}); }); },
delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
var top = cm.charCoords(range.head, "div").top + 5;
var leftPos = cm.coordsChar({left: 0, top: top}, "div");
return {from: leftPos, to: range.from()}
}); },
delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
var top = cm.charCoords(range.head, "div").top + 5;
var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
return {from: range.from(), to: rightPos }
}); },
undo: function (cm) { return cm.undo(); },
redo: function (cm) { return cm.redo(); },
undoSelection: function (cm) { return cm.undoSelection(); },
redoSelection: function (cm) { return cm.redoSelection(); },
goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
{origin: "+move", bias: 1}
); },
goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
{origin: "+move", bias: 1}
); },
goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
{origin: "+move", bias: -1}
); },
goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
var top = cm.cursorCoords(range.head, "div").top + 5;
return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
}, sel_move); },
goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
var top = cm.cursorCoords(range.head, "div").top + 5;
return cm.coordsChar({left: 0, top: top}, "div")
}, sel_move); },
goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
var top = cm.cursorCoords(range.head, "div").top + 5;
var pos = cm.coordsChar({left: 0, top: top}, "div");
if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
return pos
}, sel_move); },
goLineUp: function (cm) { return cm.moveV(-1, "line"); },
goLineDown: function (cm) { return cm.moveV(1, "line"); },
goPageUp: function (cm) { return cm.moveV(-1, "page"); },
goPageDown: function (cm) { return cm.moveV(1, "page"); },
goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
goCharRight: function (cm) { return cm.moveH(1, "char"); },
goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
goColumnRight: function (cm) { return cm.moveH(1, "column"); },
goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
goGroupRight: function (cm) { return cm.moveH(1, "group"); },
goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
goWordRight: function (cm) { return cm.moveH(1, "word"); },
delCharBefore: function (cm) { return cm.deleteH(-1, "codepoint"); },
delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
indentAuto: function (cm) { return cm.indentSelection("smart"); },
indentMore: function (cm) { return cm.indentSelection("add"); },
indentLess: function (cm) { return cm.indentSelection("subtract"); },
insertTab: function (cm) { return cm.replaceSelection("\t"); },
insertSoftTab: function (cm) {
var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
for (var i = 0; i < ranges.length; i++) {
var pos = ranges[i].from();
var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
spaces.push(spaceStr(tabSize - col % tabSize));
}
cm.replaceSelections(spaces);
},
defaultTab: function (cm) {
if (cm.somethingSelected()) { cm.indentSelection("add"); }
else { cm.execCommand("insertTab"); }
},
// Swap the two chars left and right of each selection's head.
// Move cursor behind the two swapped characters afterwards.
//
// Doesn't consider line feeds a character.
// Doesn't scan more than one line above to find a character.
// Doesn't do anything on an empty line.
// Doesn't do anything with non-empty selections.
transposeChars: function (cm) { return runInOp(cm, function () {
var ranges = cm.listSelections(), newSel = [];
for (var i = 0; i < ranges.length; i++) {
if (!ranges[i].empty()) { continue }
var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
if (line) {
if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
if (cur.ch > 0) {
cur = new Pos(cur.line, cur.ch + 1);
cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
Pos(cur.line, cur.ch - 2), cur, "+transpose");
} else if (cur.line > cm.doc.first) {
var prev = getLine(cm.doc, cur.line - 1).text;
if (prev) {
cur = new Pos(cur.line, 1);
cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
prev.charAt(prev.length - 1),
Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
}
}
}
newSel.push(new Range(cur, cur));
}
cm.setSelections(newSel);
}); },
newlineAndIndent: function (cm) { return runInOp(cm, function () {
var sels = cm.listSelections();
for (var i = sels.length - 1; i >= 0; i--)
{ cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
sels = cm.listSelections();
for (var i$1 = 0; i$1 < sels.length; i$1++)
{ cm.indentLine(sels[i$1].from().line, null, true); }
ensureCursorVisible(cm);
}); },
openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
};
function lineStart(cm, lineN) {
var line = getLine(cm.doc, lineN);
var visual = visualLine(line);
if (visual != line) { lineN = lineNo(visual); }
return endOfLine(true, cm, visual, lineN, 1)
}
function lineEnd(cm, lineN) {
var line = getLine(cm.doc, lineN);
var visual = visualLineEnd(line);
if (visual != line) { lineN = lineNo(visual); }
return endOfLine(true, cm, line, lineN, -1)
}
function lineStartSmart(cm, pos) {
var start = lineStart(cm, pos.line);
var line = getLine(cm.doc, start.line);
var order = getOrder(line, cm.doc.direction);
if (!order || order[0].level == 0) {
var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
}
return start
}
// Run a handler that was bound to a key.
function doHandleBinding(cm, bound, dropShift) {
if (typeof bound == "string") {
bound = commands[bound];
if (!bound) { return false }
}
// Ensure previous input has been read, so that the handler sees a
// consistent view of the document
cm.display.input.ensurePolled();
var prevShift = cm.display.shift, done = false;
try {
if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
if (dropShift) { cm.display.shift = false; }
done = bound(cm) != Pass;
} finally {
cm.display.shift = prevShift;
cm.state.suppressEdits = false;
}
return done
}
function lookupKeyForEditor(cm, name, handle) {
for (var i = 0; i < cm.state.keyMaps.length; i++) {
var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
if (result) { return result }
}
return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
|| lookupKey(name, cm.options.keyMap, handle, cm)
}
// Note that, despite the name, this function is also used to check
// for bound mouse clicks.
var stopSeq = new Delayed;
function dispatchKey(cm, name, e, handle) {
var seq = cm.state.keySeq;
if (seq) {
if (isModifierKey(name)) { return "handled" }
if (/\'$/.test(name))
{ cm.state.keySeq = null; }
else
{ stopSeq.set(50, function () {
if (cm.state.keySeq == seq) {
cm.state.keySeq = null;
cm.display.input.reset();
}
}); }
if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
}
return dispatchKeyInner(cm, name, e, handle)
}
function dispatchKeyInner(cm, name, e, handle) {
var result = lookupKeyForEditor(cm, name, handle);
if (result == "multi")
{ cm.state.keySeq = name; }
if (result == "handled")
{ signalLater(cm, "keyHandled", cm, name, e); }
if (result == "handled" || result == "multi") {
e_preventDefault(e);
restartBlink(cm);
}
return !!result
}
// Handle a key from the keydown event.
function handleKeyBinding(cm, e) {
var name = keyName(e, true);
if (!name) { return false }
if (e.shiftKey && !cm.state.keySeq) {
// First try to resolve full name (including 'Shift-'). Failing
// that, see if there is a cursor-motion command (starting with
// 'go') bound to the keyname without 'Shift-'.
return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
|| dispatchKey(cm, name, e, function (b) {
if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
{ return doHandleBinding(cm, b) }
})
} else {
return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
}
}
// Handle a key from the keypress event
function handleCharBinding(cm, e, ch) {
return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
}
var lastStoppedKey = null;
function onKeyDown(e) {
var cm = this;
if (e.target && e.target != cm.display.input.getField()) { return }
cm.curOp.focus = activeElt();
if (signalDOMEvent(cm, e)) { return }
// IE does strange things with escape.
if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
var code = e.keyCode;
cm.display.shift = code == 16 || e.shiftKey;
var handled = handleKeyBinding(cm, e);
if (presto) {
lastStoppedKey = handled ? code : null;
// Opera has no cut event... we try to at least catch the key combo
if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
{ cm.replaceSelection("", null, "cut"); }
}
if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand)
{ document.execCommand("cut"); }
// Turn mouse into crosshair when Alt is held on Mac.
if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
{ showCrossHair(cm); }
}
function showCrossHair(cm) {
var lineDiv = cm.display.lineDiv;
addClass(lineDiv, "CodeMirror-crosshair");
function up(e) {
if (e.keyCode == 18 || !e.altKey) {
rmClass(lineDiv, "CodeMirror-crosshair");
off(document, "keyup", up);
off(document, "mouseover", up);
}
}
on(document, "keyup", up);
on(document, "mouseover", up);
}
function onKeyUp(e) {
if (e.keyCode == 16) { this.doc.sel.shift = false; }
signalDOMEvent(this, e);
}
function onKeyPress(e) {
var cm = this;
if (e.target && e.target != cm.display.input.getField()) { return }
if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
var keyCode = e.keyCode, charCode = e.charCode;
if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
// Some browsers fire keypress events for backspace
if (ch == "\x08") { return }
if (handleCharBinding(cm, e, ch)) { return }
cm.display.input.onKeyPress(e);
}
var DOUBLECLICK_DELAY = 400;
var PastClick = function(time, pos, button) {
this.time = time;
this.pos = pos;
this.button = button;
};
PastClick.prototype.compare = function (time, pos, button) {
return this.time + DOUBLECLICK_DELAY > time &&
cmp(pos, this.pos) == 0 && button == this.button
};
var lastClick, lastDoubleClick;
function clickRepeat(pos, button) {
var now = +new Date;
if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
lastClick = lastDoubleClick = null;
return "triple"
} else if (lastClick && lastClick.compare(now, pos, button)) {
lastDoubleClick = new PastClick(now, pos, button);
lastClick = null;
return "double"
} else {
lastClick = new PastClick(now, pos, button);
lastDoubleClick = null;
return "single"
}
}
// A mouse down can be a single click, double click, triple click,
// start of selection drag, start of text drag, new cursor
// (ctrl-click), rectangle drag (alt-drag), or xwin
// middle-click-paste. Or it might be a click on something we should
// not interfere with, such as a scrollbar or widget.
function onMouseDown(e) {
var cm = this, display = cm.display;
if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
display.input.ensurePolled();
display.shift = e.shiftKey;
if (eventInWidget(display, e)) {
if (!webkit) {
// Briefly turn off draggability, to allow widgets to do
// normal dragging things.
display.scroller.draggable = false;
setTimeout(function () { return display.scroller.draggable = true; }, 100);
}
return
}
if (clickInGutter(cm, e)) { return }
var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
window.focus();
// #3261: make sure, that we're not starting a second selection
if (button == 1 && cm.state.selectingText)
{ cm.state.selectingText(e); }
if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
if (button == 1) {
if (pos) { leftButtonDown(cm, pos, repeat, e); }
else if (e_target(e) == display.scroller) { e_preventDefault(e); }
} else if (button == 2) {
if (pos) { extendSelection(cm.doc, pos); }
setTimeout(function () { return display.input.focus(); }, 20);
} else if (button == 3) {
if (captureRightClick) { cm.display.input.onContextMenu(e); }
else { delayBlurEvent(cm); }
}
}
function handleMappedButton(cm, button, pos, repeat, event) {
var name = "Click";
if (repeat == "double") { name = "Double" + name; }
else if (repeat == "triple") { name = "Triple" + name; }
name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
if (typeof bound == "string") { bound = commands[bound]; }
if (!bound) { return false }
var done = false;
try {
if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
done = bound(cm, pos) != Pass;
} finally {
cm.state.suppressEdits = false;
}
return done
})
}
function configureMouse(cm, repeat, event) {
var option = cm.getOption("configureMouse");
var value = option ? option(cm, repeat, event) : {};
if (value.unit == null) {
var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
}
if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
return value
}
function leftButtonDown(cm, pos, repeat, event) {
if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
else { cm.curOp.focus = activeElt(); }
var behavior = configureMouse(cm, repeat, event);
var sel = cm.doc.sel, contained;
if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
repeat == "single" && (contained = sel.contains(pos)) > -1 &&
(cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
(cmp(contained.to(), pos) > 0 || pos.xRel < 0))
{ leftButtonStartDrag(cm, event, pos, behavior); }
else
{ leftButtonSelect(cm, event, pos, behavior); }
}
// Start a text drag. When it ends, see if any dragging actually
// happen, and treat as a click if it didn't.
function leftButtonStartDrag(cm, event, pos, behavior) {
var display = cm.display, moved = false;
var dragEnd = operation(cm, function (e) {
if (webkit) { display.scroller.draggable = false; }
cm.state.draggingText = false;
off(display.wrapper.ownerDocument, "mouseup", dragEnd);
off(display.wrapper.ownerDocument, "mousemove", mouseMove);
off(display.scroller, "dragstart", dragStart);
off(display.scroller, "drop", dragEnd);
if (!moved) {
e_preventDefault(e);
if (!behavior.addNew)
{ extendSelection(cm.doc, pos, null, null, behavior.extend); }
// Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
if ((webkit && !safari) || ie && ie_version == 9)
{ setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); }
else
{ display.input.focus(); }
}
});
var mouseMove = function(e2) {
moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
};
var dragStart = function () { return moved = true; };
// Let the drag handler handle this.
if (webkit) { display.scroller.draggable = true; }
cm.state.draggingText = dragEnd;
dragEnd.copy = !behavior.moveOnDrag;
// IE's approach to draggable
if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
on(display.wrapper.ownerDocument, "mouseup", dragEnd);
on(display.wrapper.ownerDocument, "mousemove", mouseMove);
on(display.scroller, "dragstart", dragStart);
on(display.scroller, "drop", dragEnd);
delayBlurEvent(cm);
setTimeout(function () { return display.input.focus(); }, 20);
}
function rangeForUnit(cm, pos, unit) {
if (unit == "char") { return new Range(pos, pos) }
if (unit == "word") { return cm.findWordAt(pos) }
if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
var result = unit(cm, pos);
return new Range(result.from, result.to)
}
// Normal selection, as opposed to text dragging.
function leftButtonSelect(cm, event, start, behavior) {
var display = cm.display, doc = cm.doc;
e_preventDefault(event);
var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
if (behavior.addNew && !behavior.extend) {
ourIndex = doc.sel.contains(start);
if (ourIndex > -1)
{ ourRange = ranges[ourIndex]; }
else
{ ourRange = new Range(start, start); }
} else {
ourRange = doc.sel.primary();
ourIndex = doc.sel.primIndex;
}
if (behavior.unit == "rectangle") {
if (!behavior.addNew) { ourRange = new Range(start, start); }
start = posFromMouse(cm, event, true, true);
ourIndex = -1;
} else {
var range = rangeForUnit(cm, start, behavior.unit);
if (behavior.extend)
{ ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); }
else
{ ourRange = range; }
}
if (!behavior.addNew) {
ourIndex = 0;
setSelection(doc, new Selection([ourRange], 0), sel_mouse);
startSel = doc.sel;
} else if (ourIndex == -1) {
ourIndex = ranges.length;
setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
{scroll: false, origin: "*mouse"});
} else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
{scroll: false, origin: "*mouse"});
startSel = doc.sel;
} else {
replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
}
var lastPos = start;
function extendTo(pos) {
if (cmp(lastPos, pos) == 0) { return }
lastPos = pos;
if (behavior.unit == "rectangle") {
var ranges = [], tabSize = cm.options.tabSize;
var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
line <= end; line++) {
var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
if (left == right)
{ ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
else if (text.length > leftPos)
{ ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
}
if (!ranges.length) { ranges.push(new Range(start, start)); }
setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
{origin: "*mouse", scroll: false});
cm.scrollIntoView(pos);
} else {
var oldRange = ourRange;
var range = rangeForUnit(cm, pos, behavior.unit);
var anchor = oldRange.anchor, head;
if (cmp(range.anchor, anchor) > 0) {
head = range.head;
anchor = minPos(oldRange.from(), range.anchor);
} else {
head = range.anchor;
anchor = maxPos(oldRange.to(), range.head);
}
var ranges$1 = startSel.ranges.slice(0);
ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
}
}
var editorSize = display.wrapper.getBoundingClientRect();
// Used to ensure timeout re-tries don't fire when another extend
// happened in the meantime (clearTimeout isn't reliable -- at
// least on Chrome, the timeouts still happen even when cleared,
// if the clear happens after their scheduled firing time).
var counter = 0;
function extend(e) {
var curCount = ++counter;
var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
if (!cur) { return }
if (cmp(cur, lastPos) != 0) {
cm.curOp.focus = activeElt();
extendTo(cur);
var visible = visibleLines(display, doc);
if (cur.line >= visible.to || cur.line < visible.from)
{ setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
} else {
var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
if (outside) { setTimeout(operation(cm, function () {
if (counter != curCount) { return }
display.scroller.scrollTop += outside;
extend(e);
}), 50); }
}
}
function done(e) {
cm.state.selectingText = false;
counter = Infinity;
// If e is null or undefined we interpret this as someone trying
// to explicitly cancel the selection rather than the user
// letting go of the mouse button.
if (e) {
e_preventDefault(e);
display.input.focus();
}
off(display.wrapper.ownerDocument, "mousemove", move);
off(display.wrapper.ownerDocument, "mouseup", up);
doc.history.lastSelOrigin = null;
}
var move = operation(cm, function (e) {
if (e.buttons === 0 || !e_button(e)) { done(e); }
else { extend(e); }
});
var up = operation(cm, done);
cm.state.selectingText = up;
on(display.wrapper.ownerDocument, "mousemove", move);
on(display.wrapper.ownerDocument, "mouseup", up);
}
// Used when mouse-selecting to adjust the anchor to the proper side
// of a bidi jump depending on the visual position of the head.
function bidiSimplify(cm, range) {
var anchor = range.anchor;
var head = range.head;
var anchorLine = getLine(cm.doc, anchor.line);
if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
var order = getOrder(anchorLine);
if (!order) { return range }
var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
if (part.from != anchor.ch && part.to != anchor.ch) { return range }
var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
if (boundary == 0 || boundary == order.length) { return range }
// Compute the relative visual position of the head compared to the
// anchor (<0 is to the left, >0 to the right)
var leftSide;
if (head.line != anchor.line) {
leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
} else {
var headIndex = getBidiPartAt(order, head.ch, head.sticky);
var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
if (headIndex == boundary - 1 || headIndex == boundary)
{ leftSide = dir < 0; }
else
{ leftSide = dir > 0; }
}
var usePart = order[boundary + (leftSide ? -1 : 0)];
var from = leftSide == (usePart.level == 1);
var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
}
// Determines whether an event happened in the gutter, and fires the
// handlers for the corresponding event.
function gutterEvent(cm, e, type, prevent) {
var mX, mY;
if (e.touches) {
mX = e.touches[0].clientX;
mY = e.touches[0].clientY;
} else {
try { mX = e.clientX; mY = e.clientY; }
catch(e$1) { return false }
}
if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
if (prevent) { e_preventDefault(e); }
var display = cm.display;
var lineBox = display.lineDiv.getBoundingClientRect();
if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
mY -= lineBox.top - display.viewOffset;
for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
var g = display.gutters.childNodes[i];
if (g && g.getBoundingClientRect().right >= mX) {
var line = lineAtHeight(cm.doc, mY);
var gutter = cm.display.gutterSpecs[i];
signal(cm, type, cm, line, gutter.className, e);
return e_defaultPrevented(e)
}
}
}
function clickInGutter(cm, e) {
return gutterEvent(cm, e, "gutterClick", true)
}
// CONTEXT MENU HANDLING
// To make the context menu work, we need to briefly unhide the
// textarea (making it as unobtrusive as possible) to let the
// right-click take effect on it.
function onContextMenu(cm, e) {
if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
if (signalDOMEvent(cm, e, "contextmenu")) { return }
if (!captureRightClick) { cm.display.input.onContextMenu(e); }
}
function contextMenuInGutter(cm, e) {
if (!hasHandler(cm, "gutterContextMenu")) { return false }
return gutterEvent(cm, e, "gutterContextMenu", false)
}
function themeChanged(cm) {
cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
clearCaches(cm);
}
var Init = {toString: function(){return "CodeMirror.Init"}};
var defaults = {};
var optionHandlers = {};
function defineOptions(CodeMirror) {
var optionHandlers = CodeMirror.optionHandlers;
function option(name, deflt, handle, notOnInit) {
CodeMirror.defaults[name] = deflt;
if (handle) { optionHandlers[name] =
notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
}
CodeMirror.defineOption = option;
// Passed to option handlers when there is no old value.
CodeMirror.Init = Init;
// These two are, on init, called from the constructor because they
// have to be initialized before the editor can start at all.
option("value", "", function (cm, val) { return cm.setValue(val); }, true);
option("mode", null, function (cm, val) {
cm.doc.modeOption = val;
loadMode(cm);
}, true);
option("indentUnit", 2, loadMode, true);
option("indentWithTabs", false);
option("smartIndent", true);
option("tabSize", 4, function (cm) {
resetModeState(cm);
clearCaches(cm);
regChange(cm);
}, true);
option("lineSeparator", null, function (cm, val) {
cm.doc.lineSep = val;
if (!val) { return }
var newBreaks = [], lineNo = cm.doc.first;
cm.doc.iter(function (line) {
for (var pos = 0;;) {
var found = line.text.indexOf(val, pos);
if (found == -1) { break }
pos = found + val.length;
newBreaks.push(Pos(lineNo, found));
}
lineNo++;
});
for (var i = newBreaks.length - 1; i >= 0; i--)
{ replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
});
option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200c\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
if (old != Init) { cm.refresh(); }
});
option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
option("electricChars", true);
option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
}, true);
option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
option("rtlMoveVisually", !windows);
option("wholeLineUpdateBefore", true);
option("theme", "default", function (cm) {
themeChanged(cm);
updateGutters(cm);
}, true);
option("keyMap", "default", function (cm, val, old) {
var next = getKeyMap(val);
var prev = old != Init && getKeyMap(old);
if (prev && prev.detach) { prev.detach(cm, next); }
if (next.attach) { next.attach(cm, prev || null); }
});
option("extraKeys", null);
option("configureMouse", null);
option("lineWrapping", false, wrappingChanged, true);
option("gutters", [], function (cm, val) {
cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
updateGutters(cm);
}, true);
option("fixedGutter", true, function (cm, val) {
cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
cm.refresh();
}, true);
option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
option("scrollbarStyle", "native", function (cm) {
initScrollbars(cm);
updateScrollbars(cm);
cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
}, true);
option("lineNumbers", false, function (cm, val) {
cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
updateGutters(cm);
}, true);
option("firstLineNumber", 1, updateGutters, true);
option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
option("showCursorWhenSelecting", false, updateSelection, true);
option("resetSelectionOnContextMenu", true);
option("lineWiseCopyCut", true);
option("pasteLinesPerSelection", true);
option("selectionsMayTouch", false);
option("readOnly", false, function (cm, val) {
if (val == "nocursor") {
onBlur(cm);
cm.display.input.blur();
}
cm.display.input.readOnlyChanged(val);
});
option("screenReaderLabel", null, function (cm, val) {
val = (val === '') ? null : val;
cm.display.input.screenReaderLabelChanged(val);
});
option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
option("dragDrop", true, dragDropChanged);
option("allowDropFileTypes", null);
option("cursorBlinkRate", 530);
option("cursorScrollMargin", 0);
option("cursorHeight", 1, updateSelection, true);
option("singleCursorHeightPerLine", true, updateSelection, true);
option("workTime", 100);
option("workDelay", 100);
option("flattenSpans", true, resetModeState, true);
option("addModeClass", false, resetModeState, true);
option("pollInterval", 100);
option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
option("historyEventDelay", 1250);
option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
option("maxHighlightLength", 10000, resetModeState, true);
option("moveInputWithCursor", true, function (cm, val) {
if (!val) { cm.display.input.resetPosition(); }
});
option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
option("autofocus", null);
option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
option("phrases", null);
}
function dragDropChanged(cm, value, old) {
var wasOn = old && old != Init;
if (!value != !wasOn) {
var funcs = cm.display.dragFunctions;
var toggle = value ? on : off;
toggle(cm.display.scroller, "dragstart", funcs.start);
toggle(cm.display.scroller, "dragenter", funcs.enter);
toggle(cm.display.scroller, "dragover", funcs.over);
toggle(cm.display.scroller, "dragleave", funcs.leave);
toggle(cm.display.scroller, "drop", funcs.drop);
}
}
function wrappingChanged(cm) {
if (cm.options.lineWrapping) {
addClass(cm.display.wrapper, "CodeMirror-wrap");
cm.display.sizer.style.minWidth = "";
cm.display.sizerWidth = null;
} else {
rmClass(cm.display.wrapper, "CodeMirror-wrap");
findMaxLine(cm);
}
estimateLineHeights(cm);
regChange(cm);
clearCaches(cm);
setTimeout(function () { return updateScrollbars(cm); }, 100);
}
// A CodeMirror instance represents an editor. This is the object
// that user code is usually dealing with.
function CodeMirror(place, options) {
var this$1 = this;
if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
this.options = options = options ? copyObj(options) : {};
// Determine effective options based on given values and defaults.
copyObj(defaults, options, false);
var doc = options.value;
if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
else if (options.mode) { doc.modeOption = options.mode; }
this.doc = doc;
var input = new CodeMirror.inputStyles[options.inputStyle](this);
var display = this.display = new Display(place, doc, input, options);
display.wrapper.CodeMirror = this;
themeChanged(this);
if (options.lineWrapping)
{ this.display.wrapper.className += " CodeMirror-wrap"; }
initScrollbars(this);
this.state = {
keyMaps: [], // stores maps added by addKeyMap
overlays: [], // highlighting overlays, as added by addOverlay
modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
overwrite: false,
delayingBlurEvent: false,
focused: false,
suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
selectingText: false,
draggingText: false,
highlight: new Delayed(), // stores highlight worker timeout
keySeq: null, // Unfinished key sequence
specialChars: null
};
if (options.autofocus && !mobile) { display.input.focus(); }
// Override magic textarea content restore that IE sometimes does
// on our hidden textarea on reload
if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
registerEventHandlers(this);
ensureGlobalHandlers();
startOperation(this);
this.curOp.forceUpdate = true;
attachDoc(this, doc);
if ((options.autofocus && !mobile) || this.hasFocus())
{ setTimeout(function () {
if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); }
}, 20); }
else
{ onBlur(this); }
for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
{ optionHandlers[opt](this, options[opt], Init); } }
maybeUpdateLineNumberWidth(this);
if (options.finishInit) { options.finishInit(this); }
for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }
endOperation(this);
// Suppress optimizelegibility in Webkit, since it breaks text
// measuring on line wrapping boundaries.
if (webkit && options.lineWrapping &&
getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
{ display.lineDiv.style.textRendering = "auto"; }
}
// The default configuration options.
CodeMirror.defaults = defaults;
// Functions to run when options are changed.
CodeMirror.optionHandlers = optionHandlers;
// Attach the necessary event handlers when initializing the editor
function registerEventHandlers(cm) {
var d = cm.display;
on(d.scroller, "mousedown", operation(cm, onMouseDown));
// Older IE's will not fire a second mousedown for a double click
if (ie && ie_version < 11)
{ on(d.scroller, "dblclick", operation(cm, function (e) {
if (signalDOMEvent(cm, e)) { return }
var pos = posFromMouse(cm, e);
if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
e_preventDefault(e);
var word = cm.findWordAt(pos);
extendSelection(cm.doc, word.anchor, word.head);
})); }
else
{ on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
// Some browsers fire contextmenu *after* opening the menu, at
// which point we can't mess with it anymore. Context menu is
// handled in onMouseDown for these browsers.
on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
on(d.input.getField(), "contextmenu", function (e) {
if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); }
});
// Used to suppress mouse event handling when a touch happens
var touchFinished, prevTouch = {end: 0};
function finishTouch() {
if (d.activeTouch) {
touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
prevTouch = d.activeTouch;
prevTouch.end = +new Date;
}
}
function isMouseLikeTouchEvent(e) {
if (e.touches.length != 1) { return false }
var touch = e.touches[0];
return touch.radiusX <= 1 && touch.radiusY <= 1
}
function farAway(touch, other) {
if (other.left == null) { return true }
var dx = other.left - touch.left, dy = other.top - touch.top;
return dx * dx + dy * dy > 20 * 20
}
on(d.scroller, "touchstart", function (e) {
if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
d.input.ensurePolled();
clearTimeout(touchFinished);
var now = +new Date;
d.activeTouch = {start: now, moved: false,
prev: now - prevTouch.end <= 300 ? prevTouch : null};
if (e.touches.length == 1) {
d.activeTouch.left = e.touches[0].pageX;
d.activeTouch.top = e.touches[0].pageY;
}
}
});
on(d.scroller, "touchmove", function () {
if (d.activeTouch) { d.activeTouch.moved = true; }
});
on(d.scroller, "touchend", function (e) {
var touch = d.activeTouch;
if (touch && !eventInWidget(d, e) && touch.left != null &&
!touch.moved && new Date - touch.start < 300) {
var pos = cm.coordsChar(d.activeTouch, "page"), range;
if (!touch.prev || farAway(touch, touch.prev)) // Single tap
{ range = new Range(pos, pos); }
else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
{ range = cm.findWordAt(pos); }
else // Triple tap
{ range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
cm.setSelection(range.anchor, range.head);
cm.focus();
e_preventDefault(e);
}
finishTouch();
});
on(d.scroller, "touchcancel", finishTouch);
// Sync scrolling between fake scrollbars and real scrollable
// area, ensure viewport is updated when scrolling.
on(d.scroller, "scroll", function () {
if (d.scroller.clientHeight) {
updateScrollTop(cm, d.scroller.scrollTop);
setScrollLeft(cm, d.scroller.scrollLeft, true);
signal(cm, "scroll", cm);
}
});
// Listen to wheel events in order to try and update the viewport on time.
on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
// Prevent wrapper from ever scrolling
on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
d.dragFunctions = {
enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
start: function (e) { return onDragStart(cm, e); },
drop: operation(cm, onDrop),
leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
};
var inp = d.input.getField();
on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
on(inp, "keydown", operation(cm, onKeyDown));
on(inp, "keypress", operation(cm, onKeyPress));
on(inp, "focus", function (e) { return onFocus(cm, e); });
on(inp, "blur", function (e) { return onBlur(cm, e); });
}
var initHooks = [];
CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
// Indent the given line. The how parameter can be "smart",
// "add"/null, "subtract", or "prev". When aggressive is false
// (typically set to true for forced single-line indents), empty
// lines are not indented, and places where the mode returns Pass
// are left alone.
function indentLine(cm, n, how, aggressive) {
var doc = cm.doc, state;
if (how == null) { how = "add"; }
if (how == "smart") {
// Fall back to "prev" when the mode doesn't have an indentation
// method.
if (!doc.mode.indent) { how = "prev"; }
else { state = getContextBefore(cm, n).state; }
}
var tabSize = cm.options.tabSize;
var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
if (line.stateAfter) { line.stateAfter = null; }
var curSpaceString = line.text.match(/^\s*/)[0], indentation;
if (!aggressive && !/\S/.test(line.text)) {
indentation = 0;
how = "not";
} else if (how == "smart") {
indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
if (indentation == Pass || indentation > 150) {
if (!aggressive) { return }
how = "prev";
}
}
if (how == "prev") {
if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
else { indentation = 0; }
} else if (how == "add") {
indentation = curSpace + cm.options.indentUnit;
} else if (how == "subtract") {
indentation = curSpace - cm.options.indentUnit;
} else if (typeof how == "number") {
indentation = curSpace + how;
}
indentation = Math.max(0, indentation);
var indentString = "", pos = 0;
if (cm.options.indentWithTabs)
{ for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
if (pos < indentation) { indentString += spaceStr(indentation - pos); }
if (indentString != curSpaceString) {
replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
line.stateAfter = null;
return true
} else {
// Ensure that, if the cursor was in the whitespace at the start
// of the line, it is moved to the end of that space.
for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
var range = doc.sel.ranges[i$1];
if (range.head.line == n && range.head.ch < curSpaceString.length) {
var pos$1 = Pos(n, curSpaceString.length);
replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
break
}
}
}
}
// This will be set to a {lineWise: bool, text: [string]} object, so
// that, when pasting, we know what kind of selections the copied
// text was made out of.
var lastCopied = null;
function setLastCopied(newLastCopied) {
lastCopied = newLastCopied;
}
function applyTextInput(cm, inserted, deleted, sel, origin) {
var doc = cm.doc;
cm.display.shift = false;
if (!sel) { sel = doc.sel; }
var recent = +new Date - 200;
var paste = origin == "paste" || cm.state.pasteIncoming > recent;
var textLines = splitLinesAuto(inserted), multiPaste = null;
// When pasting N lines into N selections, insert one line per selection
if (paste && sel.ranges.length > 1) {
if (lastCopied && lastCopied.text.join("\n") == inserted) {
if (sel.ranges.length % lastCopied.text.length == 0) {
multiPaste = [];
for (var i = 0; i < lastCopied.text.length; i++)
{ multiPaste.push(doc.splitLines(lastCopied.text[i])); }
}
} else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
multiPaste = map(textLines, function (l) { return [l]; });
}
}
var updateInput = cm.curOp.updateInput;
// Normal behavior is to insert the new text into every selection
for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
var range = sel.ranges[i$1];
var from = range.from(), to = range.to();
if (range.empty()) {
if (deleted && deleted > 0) // Handle deletion
{ from = Pos(from.line, from.ch - deleted); }
else if (cm.state.overwrite && !paste) // Handle overwrite
{ to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n"))
{ from = to = Pos(from.line, 0); }
}
var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
makeChange(cm.doc, changeEvent);
signalLater(cm, "inputRead", cm, changeEvent);
}
if (inserted && !paste)
{ triggerElectric(cm, inserted); }
ensureCursorVisible(cm);
if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
cm.curOp.typing = true;
cm.state.pasteIncoming = cm.state.cutIncoming = -1;
}
function handlePaste(e, cm) {
var pasted = e.clipboardData && e.clipboardData.getData("Text");
if (pasted) {
e.preventDefault();
if (!cm.isReadOnly() && !cm.options.disableInput)
{ runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
return true
}
}
function triggerElectric(cm, inserted) {
// When an 'electric' character is inserted, immediately trigger a reindent
if (!cm.options.electricChars || !cm.options.smartIndent) { return }
var sel = cm.doc.sel;
for (var i = sel.ranges.length - 1; i >= 0; i--) {
var range = sel.ranges[i];
if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
var mode = cm.getModeAt(range.head);
var indented = false;
if (mode.electricChars) {
for (var j = 0; j < mode.electricChars.length; j++)
{ if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
indented = indentLine(cm, range.head.line, "smart");
break
} }
} else if (mode.electricInput) {
if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
{ indented = indentLine(cm, range.head.line, "smart"); }
}
if (indented) { signalLater(cm, "electricInput", cm, range.head.line); }
}
}
function copyableRanges(cm) {
var text = [], ranges = [];
for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
var line = cm.doc.sel.ranges[i].head.line;
var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
ranges.push(lineRange);
text.push(cm.getRange(lineRange.anchor, lineRange.head));
}
return {text: text, ranges: ranges}
}
function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
field.setAttribute("autocorrect", autocorrect ? "" : "off");
field.setAttribute("autocapitalize", autocapitalize ? "" : "off");
field.setAttribute("spellcheck", !!spellcheck);
}
function hiddenTextarea() {
var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
// The textarea is kept positioned near the cursor to prevent the
// fact that it'll be scrolled into view on input from scrolling
// our fake cursor out of view. On webkit, when wrap=off, paste is
// very slow. So make the area wide instead.
if (webkit) { te.style.width = "1000px"; }
else { te.setAttribute("wrap", "off"); }
// If border: 0; -- iOS fails to open keyboard (issue #1287)
if (ios) { te.style.border = "1px solid black"; }
disableBrowserMagic(te);
return div
}
// The publicly visible API. Note that methodOp(f) means
// 'wrap f in an operation, performed on its `this` parameter'.
// This is not the complete set of editor methods. Most of the
// methods defined on the Doc type are also injected into
// CodeMirror.prototype, for backwards compatibility and
// convenience.
function addEditorMethods(CodeMirror) {
var optionHandlers = CodeMirror.optionHandlers;
var helpers = CodeMirror.helpers = {};
CodeMirror.prototype = {
constructor: CodeMirror,
focus: function(){window.focus(); this.display.input.focus();},
setOption: function(option, value) {
var options = this.options, old = options[option];
if (options[option] == value && option != "mode") { return }
options[option] = value;
if (optionHandlers.hasOwnProperty(option))
{ operation(this, optionHandlers[option])(this, value, old); }
signal(this, "optionChange", this, option);
},
getOption: function(option) {return this.options[option]},
getDoc: function() {return this.doc},
addKeyMap: function(map, bottom) {
this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
},
removeKeyMap: function(map) {
var maps = this.state.keyMaps;
for (var i = 0; i < maps.length; ++i)
{ if (maps[i] == map || maps[i].name == map) {
maps.splice(i, 1);
return true
} }
},
addOverlay: methodOp(function(spec, options) {
var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
if (mode.startState) { throw new Error("Overlays may not be stateful.") }
insertSorted(this.state.overlays,
{mode: mode, modeSpec: spec, opaque: options && options.opaque,
priority: (options && options.priority) || 0},
function (overlay) { return overlay.priority; });
this.state.modeGen++;
regChange(this);
}),
removeOverlay: methodOp(function(spec) {
var overlays = this.state.overlays;
for (var i = 0; i < overlays.length; ++i) {
var cur = overlays[i].modeSpec;
if (cur == spec || typeof spec == "string" && cur.name == spec) {
overlays.splice(i, 1);
this.state.modeGen++;
regChange(this);
return
}
}
}),
indentLine: methodOp(function(n, dir, aggressive) {
if (typeof dir != "string" && typeof dir != "number") {
if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
else { dir = dir ? "add" : "subtract"; }
}
if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
}),
indentSelection: methodOp(function(how) {
var ranges = this.doc.sel.ranges, end = -1;
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (!range.empty()) {
var from = range.from(), to = range.to();
var start = Math.max(end, from.line);
end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
for (var j = start; j < end; ++j)
{ indentLine(this, j, how); }
var newRanges = this.doc.sel.ranges;
if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
{ replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
} else if (range.head.line > end) {
indentLine(this, range.head.line, how, true);
end = range.head.line;
if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); }
}
}
}),
// Fetch the parser token for a given character. Useful for hacks
// that want to inspect the mode state (say, for completion).
getTokenAt: function(pos, precise) {
return takeToken(this, pos, precise)
},
getLineTokens: function(line, precise) {
return takeToken(this, Pos(line), precise, true)
},
getTokenTypeAt: function(pos) {
pos = clipPos(this.doc, pos);
var styles = getLineStyles(this, getLine(this.doc, pos.line));
var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
var type;
if (ch == 0) { type = styles[2]; }
else { for (;;) {
var mid = (before + after) >> 1;
if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
else { type = styles[mid * 2 + 2]; break }
} }
var cut = type ? type.indexOf("overlay ") : -1;
return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
},
getModeAt: function(pos) {
var mode = this.doc.mode;
if (!mode.innerMode) { return mode }
return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
},
getHelper: function(pos, type) {
return this.getHelpers(pos, type)[0]
},
getHelpers: function(pos, type) {
var found = [];
if (!helpers.hasOwnProperty(type)) { return found }
var help = helpers[type], mode = this.getModeAt(pos);
if (typeof mode[type] == "string") {
if (help[mode[type]]) { found.push(help[mode[type]]); }
} else if (mode[type]) {
for (var i = 0; i < mode[type].length; i++) {
var val = help[mode[type][i]];
if (val) { found.push(val); }
}
} else if (mode.helperType && help[mode.helperType]) {
found.push(help[mode.helperType]);
} else if (help[mode.name]) {
found.push(help[mode.name]);
}
for (var i$1 = 0; i$1 < help._global.length; i$1++) {
var cur = help._global[i$1];
if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
{ found.push(cur.val); }
}
return found
},
getStateAfter: function(line, precise) {
var doc = this.doc;
line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
return getContextBefore(this, line + 1, precise).state
},
cursorCoords: function(start, mode) {
var pos, range = this.doc.sel.primary();
if (start == null) { pos = range.head; }
else if (typeof start == "object") { pos = clipPos(this.doc, start); }
else { pos = start ? range.from() : range.to(); }
return cursorCoords(this, pos, mode || "page")
},
charCoords: function(pos, mode) {
return charCoords(this, clipPos(this.doc, pos), mode || "page")
},
coordsChar: function(coords, mode) {
coords = fromCoordSystem(this, coords, mode || "page");
return coordsChar(this, coords.left, coords.top)
},
lineAtHeight: function(height, mode) {
height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
return lineAtHeight(this.doc, height + this.display.viewOffset)
},
heightAtLine: function(line, mode, includeWidgets) {
var end = false, lineObj;
if (typeof line == "number") {
var last = this.doc.first + this.doc.size - 1;
if (line < this.doc.first) { line = this.doc.first; }
else if (line > last) { line = last; end = true; }
lineObj = getLine(this.doc, line);
} else {
lineObj = line;
}
return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
(end ? this.doc.height - heightAtLine(lineObj) : 0)
},
defaultTextHeight: function() { return textHeight(this.display) },
defaultCharWidth: function() { return charWidth(this.display) },
getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
addWidget: function(pos, node, scroll, vert, horiz) {
var display = this.display;
pos = cursorCoords(this, clipPos(this.doc, pos));
var top = pos.bottom, left = pos.left;
node.style.position = "absolute";
node.setAttribute("cm-ignore-events", "true");
this.display.input.setUneditable(node);
display.sizer.appendChild(node);
if (vert == "over") {
top = pos.top;
} else if (vert == "above" || vert == "near") {
var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
// Default to positioning above (if specified and possible); otherwise default to positioning below
if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
{ top = pos.top - node.offsetHeight; }
else if (pos.bottom + node.offsetHeight <= vspace)
{ top = pos.bottom; }
if (left + node.offsetWidth > hspace)
{ left = hspace - node.offsetWidth; }
}
node.style.top = top + "px";
node.style.left = node.style.right = "";
if (horiz == "right") {
left = display.sizer.clientWidth - node.offsetWidth;
node.style.right = "0px";
} else {
if (horiz == "left") { left = 0; }
else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
node.style.left = left + "px";
}
if (scroll)
{ scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
},
triggerOnKeyDown: methodOp(onKeyDown),
triggerOnKeyPress: methodOp(onKeyPress),
triggerOnKeyUp: onKeyUp,
triggerOnMouseDown: methodOp(onMouseDown),
execCommand: function(cmd) {
if (commands.hasOwnProperty(cmd))
{ return commands[cmd].call(null, this) }
},
triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
findPosH: function(from, amount, unit, visually) {
var dir = 1;
if (amount < 0) { dir = -1; amount = -amount; }
var cur = clipPos(this.doc, from);
for (var i = 0; i < amount; ++i) {
cur = findPosH(this.doc, cur, dir, unit, visually);
if (cur.hitSide) { break }
}
return cur
},
moveH: methodOp(function(dir, unit) {
var this$1 = this;
this.extendSelectionsBy(function (range) {
if (this$1.display.shift || this$1.doc.extend || range.empty())
{ return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
else
{ return dir < 0 ? range.from() : range.to() }
}, sel_move);
}),
deleteH: methodOp(function(dir, unit) {
var sel = this.doc.sel, doc = this.doc;
if (sel.somethingSelected())
{ doc.replaceSelection("", null, "+delete"); }
else
{ deleteNearSelection(this, function (range) {
var other = findPosH(doc, range.head, dir, unit, false);
return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
}); }
}),
findPosV: function(from, amount, unit, goalColumn) {
var dir = 1, x = goalColumn;
if (amount < 0) { dir = -1; amount = -amount; }
var cur = clipPos(this.doc, from);
for (var i = 0; i < amount; ++i) {
var coords = cursorCoords(this, cur, "div");
if (x == null) { x = coords.left; }
else { coords.left = x; }
cur = findPosV(this, coords, dir, unit);
if (cur.hitSide) { break }
}
return cur
},
moveV: methodOp(function(dir, unit) {
var this$1 = this;
var doc = this.doc, goals = [];
var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
doc.extendSelectionsBy(function (range) {
if (collapse)
{ return dir < 0 ? range.from() : range.to() }
var headPos = cursorCoords(this$1, range.head, "div");
if (range.goalColumn != null) { headPos.left = range.goalColumn; }
goals.push(headPos.left);
var pos = findPosV(this$1, headPos, dir, unit);
if (unit == "page" && range == doc.sel.primary())
{ addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
return pos
}, sel_move);
if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
{ doc.sel.ranges[i].goalColumn = goals[i]; } }
}),
// Find the word at the given position (as returned by coordsChar).
findWordAt: function(pos) {
var doc = this.doc, line = getLine(doc, pos.line).text;
var start = pos.ch, end = pos.ch;
if (line) {
var helper = this.getHelper(pos, "wordChars");
if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
var startChar = line.charAt(start);
var check = isWordChar(startChar, helper)
? function (ch) { return isWordChar(ch, helper); }
: /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
: function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
while (start > 0 && check(line.charAt(start - 1))) { --start; }
while (end < line.length && check(line.charAt(end))) { ++end; }
}
return new Range(Pos(pos.line, start), Pos(pos.line, end))
},
toggleOverwrite: function(value) {
if (value != null && value == this.state.overwrite) { return }
if (this.state.overwrite = !this.state.overwrite)
{ addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
else
{ rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
signal(this, "overwriteToggle", this, this.state.overwrite);
},
hasFocus: function() { return this.display.input.getField() == activeElt() },
isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
getScrollInfo: function() {
var scroller = this.display.scroller;
return {left: scroller.scrollLeft, top: scroller.scrollTop,
height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
},
scrollIntoView: methodOp(function(range, margin) {
if (range == null) {
range = {from: this.doc.sel.primary().head, to: null};
if (margin == null) { margin = this.options.cursorScrollMargin; }
} else if (typeof range == "number") {
range = {from: Pos(range, 0), to: null};
} else if (range.from == null) {
range = {from: range, to: null};
}
if (!range.to) { range.to = range.from; }
range.margin = margin || 0;
if (range.from.line != null) {
scrollToRange(this, range);
} else {
scrollToCoordsRange(this, range.from, range.to, range.margin);
}
}),
setSize: methodOp(function(width, height) {
var this$1 = this;
var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
if (width != null) { this.display.wrapper.style.width = interpret(width); }
if (height != null) { this.display.wrapper.style.height = interpret(height); }
if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
var lineNo = this.display.viewFrom;
this.doc.iter(lineNo, this.display.viewTo, function (line) {
if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
{ if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
++lineNo;
});
this.curOp.forceUpdate = true;
signal(this, "refresh", this);
}),
operation: function(f){return runInOp(this, f)},
startOperation: function(){return startOperation(this)},
endOperation: function(){return endOperation(this)},
refresh: methodOp(function() {
var oldHeight = this.display.cachedTextHeight;
regChange(this);
this.curOp.forceUpdate = true;
clearCaches(this);
scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
updateGutterSpace(this.display);
if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping)
{ estimateLineHeights(this); }
signal(this, "refresh", this);
}),
swapDoc: methodOp(function(doc) {
var old = this.doc;
old.cm = null;
// Cancel the current text selection if any (#5821)
if (this.state.selectingText) { this.state.selectingText(); }
attachDoc(this, doc);
clearCaches(this);
this.display.input.reset();
scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
this.curOp.forceScroll = true;
signalLater(this, "swapDoc", this, old);
return old
}),
phrase: function(phraseText) {
var phrases = this.options.phrases;
return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
},
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}
};
eventMixin(CodeMirror);
CodeMirror.registerHelper = function(type, name, value) {
if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
helpers[type][name] = value;
};
CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
CodeMirror.registerHelper(type, name, value);
helpers[type]._global.push({pred: predicate, val: value});
};
}
// Used for horizontal relative motion. Dir is -1 or 1 (left or
// right), unit can be "codepoint", "char", "column" (like char, but
// doesn't cross line boundaries), "word" (across next word), or
// "group" (to the start of next group of word or
// non-word-non-whitespace chars). The visually param controls
// whether, in right-to-left text, direction 1 means to move towards
// the next index in the string, or towards the character to the right
// of the current position. The resulting position will have a
// hitSide=true property if it reached the end of the document.
function findPosH(doc, pos, dir, unit, visually) {
var oldPos = pos;
var origDir = dir;
var lineObj = getLine(doc, pos.line);
var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
function findNextLine() {
var l = pos.line + lineDir;
if (l < doc.first || l >= doc.first + doc.size) { return false }
pos = new Pos(l, pos.ch, pos.sticky);
return lineObj = getLine(doc, l)
}
function moveOnce(boundToLine) {
var next;
if (unit == "codepoint") {
var ch = lineObj.text.charCodeAt(pos.ch + (unit > 0 ? 0 : -1));
if (isNaN(ch)) { next = null; }
else { next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (ch >= 0xD800 && ch < 0xDC00 ? 2 : 1))),
-dir); }
} else if (visually) {
next = moveVisually(doc.cm, lineObj, pos, dir);
} else {
next = moveLogically(lineObj, pos, dir);
}
if (next == null) {
if (!boundToLine && findNextLine())
{ pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); }
else
{ return false }
} else {
pos = next;
}
return true
}
if (unit == "char" || unit == "codepoint") {
moveOnce();
} else if (unit == "column") {
moveOnce(true);
} else if (unit == "word" || unit == "group") {
var sawType = null, group = unit == "group";
var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
for (var first = true;; first = false) {
if (dir < 0 && !moveOnce(!first)) { break }
var cur = lineObj.text.charAt(pos.ch) || "\n";
var type = isWordChar(cur, helper) ? "w"
: group && cur == "\n" ? "n"
: !group || /\s/.test(cur) ? null
: "p";
if (group && !first && !type) { type = "s"; }
if (sawType && sawType != type) {
if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
break
}
if (type) { sawType = type; }
if (dir > 0 && !moveOnce(!first)) { break }
}
}
var result = skipAtomic(doc, pos, oldPos, origDir, true);
if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
return result
}
// For relative vertical movement. Dir may be -1 or 1. Unit can be
// "page" or "line". The resulting position will have a hitSide=true
// property if it reached the end of the document.
function findPosV(cm, pos, dir, unit) {
var doc = cm.doc, x = pos.left, y;
if (unit == "page") {
var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
} else if (unit == "line") {
y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
}
var target;
for (;;) {
target = coordsChar(cm, x, y);
if (!target.outside) { break }
if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
y += dir * 5;
}
return target
}
// CONTENTEDITABLE INPUT STYLE
var ContentEditableInput = function(cm) {
this.cm = cm;
this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
this.polling = new Delayed();
this.composing = null;
this.gracePeriod = false;
this.readDOMTimeout = null;
};
ContentEditableInput.prototype.init = function (display) {
var this$1 = this;
var input = this, cm = input.cm;
var div = input.div = display.lineDiv;
disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
function belongsToInput(e) {
for (var t = e.target; t; t = t.parentNode) {
if (t == div) { return true }
if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break }
}
return false
}
on(div, "paste", function (e) {
if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
// IE doesn't fire input events, so we schedule a read for the pasted content in this way
if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
});
on(div, "compositionstart", function (e) {
this$1.composing = {data: e.data, done: false};
});
on(div, "compositionupdate", function (e) {
if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
});
on(div, "compositionend", function (e) {
if (this$1.composing) {
if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
this$1.composing.done = true;
}
});
on(div, "touchstart", function () { return input.forceCompositionEnd(); });
on(div, "input", function () {
if (!this$1.composing) { this$1.readFromDOMSoon(); }
});
function onCopyCut(e) {
if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return }
if (cm.somethingSelected()) {
setLastCopied({lineWise: false, text: cm.getSelections()});
if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
} else if (!cm.options.lineWiseCopyCut) {
return
} else {
var ranges = copyableRanges(cm);
setLastCopied({lineWise: true, text: ranges.text});
if (e.type == "cut") {
cm.operation(function () {
cm.setSelections(ranges.ranges, 0, sel_dontScroll);
cm.replaceSelection("", null, "cut");
});
}
}
if (e.clipboardData) {
e.clipboardData.clearData();
var content = lastCopied.text.join("\n");
// iOS exposes the clipboard API, but seems to discard content inserted into it
e.clipboardData.setData("Text", content);
if (e.clipboardData.getData("Text") == content) {
e.preventDefault();
return
}
}
// Old-fashioned briefly-focus-a-textarea hack
var kludge = hiddenTextarea(), te = kludge.firstChild;
cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
te.value = lastCopied.text.join("\n");
var hadFocus = document.activeElement;
selectInput(te);
setTimeout(function () {
cm.display.lineSpace.removeChild(kludge);
hadFocus.focus();
if (hadFocus == div) { input.showPrimarySelection(); }
}, 50);
}
on(div, "copy", onCopyCut);
on(div, "cut", onCopyCut);
};
ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
// Label for screenreaders, accessibility
if(label) {
this.div.setAttribute('aria-label', label);
} else {
this.div.removeAttribute('aria-label');
}
};
ContentEditableInput.prototype.prepareSelection = function () {
var result = prepareSelection(this.cm, false);
result.focus = document.activeElement == this.div;
return result
};
ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
if (!info || !this.cm.display.view.length) { return }
if (info.focus || takeFocus) { this.showPrimarySelection(); }
this.showMultipleSelections(info);
};
ContentEditableInput.prototype.getSelection = function () {
return this.cm.display.wrapper.ownerDocument.getSelection()
};
ContentEditableInput.prototype.showPrimarySelection = function () {
var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
var from = prim.from(), to = prim.to();
if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
sel.removeAllRanges();
return
}
var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
cmp(minPos(curAnchor, curFocus), from) == 0 &&
cmp(maxPos(curAnchor, curFocus), to) == 0)
{ return }
var view = cm.display.view;
var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
{node: view[0].measure.map[2], offset: 0};
var end = to.line < cm.display.viewTo && posToDOM(cm, to);
if (!end) {
var measure = view[view.length - 1].measure;
var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
}
if (!start || !end) {
sel.removeAllRanges();
return
}
var old = sel.rangeCount && sel.getRangeAt(0), rng;
try { rng = range(start.node, start.offset, end.offset, end.node); }
catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
if (rng) {
if (!gecko && cm.state.focused) {
sel.collapse(start.node, start.offset);
if (!rng.collapsed) {
sel.removeAllRanges();
sel.addRange(rng);
}
} else {
sel.removeAllRanges();
sel.addRange(rng);
}
if (old && sel.anchorNode == null) { sel.addRange(old); }
else if (gecko) { this.startGracePeriod(); }
}
this.rememberSelection();
};
ContentEditableInput.prototype.startGracePeriod = function () {
var this$1 = this;
clearTimeout(this.gracePeriod);
this.gracePeriod = setTimeout(function () {
this$1.gracePeriod = false;
if (this$1.selectionChanged())
{ this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
}, 20);
};
ContentEditableInput.prototype.showMultipleSelections = function (info) {
removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
};
ContentEditableInput.prototype.rememberSelection = function () {
var sel = this.getSelection();
this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
};
ContentEditableInput.prototype.selectionInEditor = function () {
var sel = this.getSelection();
if (!sel.rangeCount) { return false }
var node = sel.getRangeAt(0).commonAncestorContainer;
return contains(this.div, node)
};
ContentEditableInput.prototype.focus = function () {
if (this.cm.options.readOnly != "nocursor") {
if (!this.selectionInEditor() || document.activeElement != this.div)
{ this.showSelection(this.prepareSelection(), true); }
this.div.focus();
}
};
ContentEditableInput.prototype.blur = function () { this.div.blur(); };
ContentEditableInput.prototype.getField = function () { return this.div };
ContentEditableInput.prototype.supportsTouch = function () { return true };
ContentEditableInput.prototype.receivedFocus = function () {
var input = this;
if (this.selectionInEditor())
{ this.pollSelection(); }
else
{ runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
function poll() {
if (input.cm.state.focused) {
input.pollSelection();
input.polling.set(input.cm.options.pollInterval, poll);
}
}
this.polling.set(this.cm.options.pollInterval, poll);
};
ContentEditableInput.prototype.selectionChanged = function () {
var sel = this.getSelection();
return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
};
ContentEditableInput.prototype.pollSelection = function () {
if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
var sel = this.getSelection(), cm = this.cm;
// On Android Chrome (version 56, at least), backspacing into an
// uneditable block element will put the cursor in that element,
// and then, because it's not editable, hide the virtual keyboard.
// Because Android doesn't allow us to actually detect backspace
// presses in a sane way, this code checks for when that happens
// and simulates a backspace press in this case.
if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
this.blur();
this.focus();
return
}
if (this.composing) { return }
this.rememberSelection();
var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
var head = domToPos(cm, sel.focusNode, sel.focusOffset);
if (anchor && head) { runInOp(cm, function () {
setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
}); }
};
ContentEditableInput.prototype.pollContent = function () {
if (this.readDOMTimeout != null) {
clearTimeout(this.readDOMTimeout);
this.readDOMTimeout = null;
}
var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
var from = sel.from(), to = sel.to();
if (from.ch == 0 && from.line > cm.firstLine())
{ from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
{ to = Pos(to.line + 1, 0); }
if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
var fromIndex, fromLine, fromNode;
if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
fromLine = lineNo(display.view[0].line);
fromNode = display.view[0].node;
} else {
fromLine = lineNo(display.view[fromIndex].line);
fromNode = display.view[fromIndex - 1].node.nextSibling;
}
var toIndex = findViewIndex(cm, to.line);
var toLine, toNode;
if (toIndex == display.view.length - 1) {
toLine = display.viewTo - 1;
toNode = display.lineDiv.lastChild;
} else {
toLine = lineNo(display.view[toIndex + 1].line) - 1;
toNode = display.view[toIndex + 1].node.previousSibling;
}
if (!fromNode) { return false }
var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
while (newText.length > 1 && oldText.length > 1) {
if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
else { break }
}
var cutFront = 0, cutEnd = 0;
var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
{ ++cutFront; }
var newBot = lst(newText), oldBot = lst(oldText);
var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
oldBot.length - (oldText.length == 1 ? cutFront : 0));
while (cutEnd < maxCutEnd &&
newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
{ ++cutEnd; }
// Try to move start of change to start of selection if ambiguous
if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
while (cutFront && cutFront > from.ch &&
newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
cutFront--;
cutEnd++;
}
}
newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
var chFrom = Pos(fromLine, cutFront);
var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
replaceRange(cm.doc, newText, chFrom, chTo, "+input");
return true
}
};
ContentEditableInput.prototype.ensurePolled = function () {
this.forceCompositionEnd();
};
ContentEditableInput.prototype.reset = function () {
this.forceCompositionEnd();
};
ContentEditableInput.prototype.forceCompositionEnd = function () {
if (!this.composing) { return }
clearTimeout(this.readDOMTimeout);
this.composing = null;
this.updateFromDOM();
this.div.blur();
this.div.focus();
};
ContentEditableInput.prototype.readFromDOMSoon = function () {
var this$1 = this;
if (this.readDOMTimeout != null) { return }
this.readDOMTimeout = setTimeout(function () {
this$1.readDOMTimeout = null;
if (this$1.composing) {
if (this$1.composing.done) { this$1.composing = null; }
else { return }
}
this$1.updateFromDOM();
}, 80);
};
ContentEditableInput.prototype.updateFromDOM = function () {
var this$1 = this;
if (this.cm.isReadOnly() || !this.pollContent())
{ runInOp(this.cm, function () { return regChange(this$1.cm); }); }
};
ContentEditableInput.prototype.setUneditable = function (node) {
node.contentEditable = "false";
};
ContentEditableInput.prototype.onKeyPress = function (e) {
if (e.charCode == 0 || this.composing) { return }
e.preventDefault();
if (!this.cm.isReadOnly())
{ operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
};
ContentEditableInput.prototype.readOnlyChanged = function (val) {
this.div.contentEditable = String(val != "nocursor");
};
ContentEditableInput.prototype.onContextMenu = function () {};
ContentEditableInput.prototype.resetPosition = function () {};
ContentEditableInput.prototype.needsContentAttribute = true;
function posToDOM(cm, pos) {
var view = findViewForLine(cm, pos.line);
if (!view || view.hidden) { return null }
var line = getLine(cm.doc, pos.line);
var info = mapFromLineView(view, line, pos.line);
var order = getOrder(line, cm.doc.direction), side = "left";
if (order) {
var partPos = getBidiPartAt(order, pos.ch);
side = partPos % 2 ? "right" : "left";
}
var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
result.offset = result.collapse == "right" ? result.end : result.start;
return result
}
function isInGutter(node) {
for (var scan = node; scan; scan = scan.parentNode)
{ if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
return false
}
function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
function domTextBetween(cm, from, to, fromLine, toLine) {
var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
function close() {
if (closing) {
text += lineSep;
if (extraLinebreak) { text += lineSep; }
closing = extraLinebreak = false;
}
}
function addText(str) {
if (str) {
close();
text += str;
}
}
function walk(node) {
if (node.nodeType == 1) {
var cmText = node.getAttribute("cm-text");
if (cmText) {
addText(cmText);
return
}
var markerID = node.getAttribute("cm-marker"), range;
if (markerID) {
var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
if (found.length && (range = found[0].find(0)))
{ addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); }
return
}
if (node.getAttribute("contenteditable") == "false") { return }
var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
if (isBlock) { close(); }
for (var i = 0; i < node.childNodes.length; i++)
{ walk(node.childNodes[i]); }
if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
if (isBlock) { closing = true; }
} else if (node.nodeType == 3) {
addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
}
}
for (;;) {
walk(from);
if (from == to) { break }
from = from.nextSibling;
extraLinebreak = false;
}
return text
}
function domToPos(cm, node, offset) {
var lineNode;
if (node == cm.display.lineDiv) {
lineNode = cm.display.lineDiv.childNodes[offset];
if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
node = null; offset = 0;
} else {
for (lineNode = node;; lineNode = lineNode.parentNode) {
if (!lineNode || lineNode == cm.display.lineDiv) { return null }
if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
}
}
for (var i = 0; i < cm.display.view.length; i++) {
var lineView = cm.display.view[i];
if (lineView.node == lineNode)
{ return locateNodeInLineView(lineView, node, offset) }
}
}
function locateNodeInLineView(lineView, node, offset) {
var wrapper = lineView.text.firstChild, bad = false;
if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
if (node == wrapper) {
bad = true;
node = wrapper.childNodes[offset];
offset = 0;
if (!node) {
var line = lineView.rest ? lst(lineView.rest) : lineView.line;
return badPos(Pos(lineNo(line), line.text.length), bad)
}
}
var textNode = node.nodeType == 3 ? node : null, topNode = node;
if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
textNode = node.firstChild;
if (offset) { offset = textNode.nodeValue.length; }
}
while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
var measure = lineView.measure, maps = measure.maps;
function find(textNode, topNode, offset) {
for (var i = -1; i < (maps ? maps.length : 0); i++) {
var map = i < 0 ? measure.map : maps[i];
for (var j = 0; j < map.length; j += 3) {
var curNode = map[j + 2];
if (curNode == textNode || curNode == topNode) {
var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
var ch = map[j] + offset;
if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; }
return Pos(line, ch)
}
}
}
}
var found = find(textNode, topNode, offset);
if (found) { return badPos(found, bad) }
// FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
found = find(after, after.firstChild, 0);
if (found)
{ return badPos(Pos(found.line, found.ch - dist), bad) }
else
{ dist += after.textContent.length; }
}
for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
found = find(before, before.firstChild, -1);
if (found)
{ return badPos(Pos(found.line, found.ch + dist$1), bad) }
else
{ dist$1 += before.textContent.length; }
}
}
// TEXTAREA INPUT STYLE
var TextareaInput = function(cm) {
this.cm = cm;
// See input.poll and input.reset
this.prevInput = "";
// Flag that indicates whether we expect input to appear real soon
// now (after some event like 'keypress' or 'input') and are
// polling intensively.
this.pollingFast = false;
// Self-resetting timeout for the poller
this.polling = new Delayed();
// Used to work around IE issue with selection being forgotten when focus moves away from textarea
this.hasSelection = false;
this.composing = null;
};
TextareaInput.prototype.init = function (display) {
var this$1 = this;
var input = this, cm = this.cm;
this.createField(display);
var te = this.textarea;
display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
// Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
if (ios) { te.style.width = "0px"; }
on(te, "input", function () {
if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
input.poll();
});
on(te, "paste", function (e) {
if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
cm.state.pasteIncoming = +new Date;
input.fastPoll();
});
function prepareCopyCut(e) {
if (signalDOMEvent(cm, e)) { return }
if (cm.somethingSelected()) {
setLastCopied({lineWise: false, text: cm.getSelections()});
} else if (!cm.options.lineWiseCopyCut) {
return
} else {
var ranges = copyableRanges(cm);
setLastCopied({lineWise: true, text: ranges.text});
if (e.type == "cut") {
cm.setSelections(ranges.ranges, null, sel_dontScroll);
} else {
input.prevInput = "";
te.value = ranges.text.join("\n");
selectInput(te);
}
}
if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
}
on(te, "cut", prepareCopyCut);
on(te, "copy", prepareCopyCut);
on(display.scroller, "paste", function (e) {
if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
if (!te.dispatchEvent) {
cm.state.pasteIncoming = +new Date;
input.focus();
return
}
// Pass the `paste` event to the textarea so it's handled by its event listener.
var event = new Event("paste");
event.clipboardData = e.clipboardData;
te.dispatchEvent(event);
});
// Prevent normal selection in the editor (we handle our own)
on(display.lineSpace, "selectstart", function (e) {
if (!eventInWidget(display, e)) { e_preventDefault(e); }
});
on(te, "compositionstart", function () {
var start = cm.getCursor("from");
if (input.composing) { input.composing.range.clear(); }
input.composing = {
start: start,
range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
};
});
on(te, "compositionend", function () {
if (input.composing) {
input.poll();
input.composing.range.clear();
input.composing = null;
}
});
};
TextareaInput.prototype.createField = function (_display) {
// Wraps and hides input textarea
this.wrapper = hiddenTextarea();
// The semihidden textarea that is focused when the editor is
// focused, and receives input.
this.textarea = this.wrapper.firstChild;
};
TextareaInput.prototype.screenReaderLabelChanged = function (label) {
// Label for screenreaders, accessibility
if(label) {
this.textarea.setAttribute('aria-label', label);
} else {
this.textarea.removeAttribute('aria-label');
}
};
TextareaInput.prototype.prepareSelection = function () {
// Redraw the selection and/or cursor
var cm = this.cm, display = cm.display, doc = cm.doc;
var result = prepareSelection(cm);
// Move the hidden textarea near the cursor to prevent scrolling artifacts
if (cm.options.moveInputWithCursor) {
var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
headPos.top + lineOff.top - wrapOff.top));
result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
headPos.left + lineOff.left - wrapOff.left));
}
return result
};
TextareaInput.prototype.showSelection = function (drawn) {
var cm = this.cm, display = cm.display;
removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
removeChildrenAndAdd(display.selectionDiv, drawn.selection);
if (drawn.teTop != null) {
this.wrapper.style.top = drawn.teTop + "px";
this.wrapper.style.left = drawn.teLeft + "px";
}
};
// Reset the input to correspond to the selection (or to be empty,
// when not typing and nothing is selected)
TextareaInput.prototype.reset = function (typing) {
if (this.contextMenuPending || this.composing) { return }
var cm = this.cm;
if (cm.somethingSelected()) {
this.prevInput = "";
var content = cm.getSelection();
this.textarea.value = content;
if (cm.state.focused) { selectInput(this.textarea); }
if (ie && ie_version >= 9) { this.hasSelection = content; }
} else if (!typing) {
this.prevInput = this.textarea.value = "";
if (ie && ie_version >= 9) { this.hasSelection = null; }
}
};
TextareaInput.prototype.getField = function () { return this.textarea };
TextareaInput.prototype.supportsTouch = function () { return false };
TextareaInput.prototype.focus = function () {
if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
try { this.textarea.focus(); }
catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
}
};
TextareaInput.prototype.blur = function () { this.textarea.blur(); };
TextareaInput.prototype.resetPosition = function () {
this.wrapper.style.top = this.wrapper.style.left = 0;
};
TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
// Poll for input changes, using the normal rate of polling. This
// runs as long as the editor is focused.
TextareaInput.prototype.slowPoll = function () {
var this$1 = this;
if (this.pollingFast) { return }
this.polling.set(this.cm.options.pollInterval, function () {
this$1.poll();
if (this$1.cm.state.focused) { this$1.slowPoll(); }
});
};
// When an event has just come in that is likely to add or change
// something in the input textarea, we poll faster, to ensure that
// the change appears on the screen quickly.
TextareaInput.prototype.fastPoll = function () {
var missed = false, input = this;
input.pollingFast = true;
function p() {
var changed = input.poll();
if (!changed && !missed) {missed = true; input.polling.set(60, p);}
else {input.pollingFast = false; input.slowPoll();}
}
input.polling.set(20, p);
};
// Read input from the textarea, and update the document to match.
// When something is selected, it is present in the textarea, and
// selected (unless it is huge, in which case a placeholder is
// used). When nothing is selected, the cursor sits after previously
// seen text (can be empty), which is stored in prevInput (we must
// not reset the textarea when typing, because that breaks IME).
TextareaInput.prototype.poll = function () {
var this$1 = this;
var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
// Since this is called a *lot*, try to bail out as cheaply as
// possible when it is clear that nothing happened. hasSelection
// will be the case when there is a lot of text in the textarea,
// in which case reading its value would be expensive.
if (this.contextMenuPending || !cm.state.focused ||
(hasSelection(input) && !prevInput && !this.composing) ||
cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
{ return false }
var text = input.value;
// If nothing changed, bail.
if (text == prevInput && !cm.somethingSelected()) { return false }
// Work around nonsensical selection resetting in IE9/10, and
// inexplicable appearance of private area unicode characters on
// some key combos in Mac (#2689).
if (ie && ie_version >= 9 && this.hasSelection === text ||
mac && /[\uf700-\uf7ff]/.test(text)) {
cm.display.input.reset();
return false
}
if (cm.doc.sel == cm.display.selForContextMenu) {
var first = text.charCodeAt(0);
if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
}
// Find the part of the input that is actually new
var same = 0, l = Math.min(prevInput.length, text.length);
while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
runInOp(cm, function () {
applyTextInput(cm, text.slice(same), prevInput.length - same,
null, this$1.composing ? "*compose" : null);
// Don't leave long text in the textarea, since it makes further polling slow
if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
else { this$1.prevInput = text; }
if (this$1.composing) {
this$1.composing.range.clear();
this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
{className: "CodeMirror-composing"});
}
});
return true
};
TextareaInput.prototype.ensurePolled = function () {
if (this.pollingFast && this.poll()) { this.pollingFast = false; }
};
TextareaInput.prototype.onKeyPress = function () {
if (ie && ie_version >= 9) { this.hasSelection = null; }
this.fastPoll();
};
TextareaInput.prototype.onContextMenu = function (e) {
var input = this, cm = input.cm, display = cm.display, te = input.textarea;
if (input.contextMenuPending) { input.contextMenuPending(); }
var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
if (!pos || presto) { return } // Opera is difficult.
// Reset the current text selection only if the click is done outside of the selection
// and 'resetSelectionOnContextMenu' option is true.
var reset = cm.options.resetSelectionOnContextMenu;
if (reset && cm.doc.sel.contains(pos) == -1)
{ operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
input.wrapper.style.cssText = "position: static";
te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
var oldScrollY;
if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
display.input.focus();
if (webkit) { window.scrollTo(null, oldScrollY); }
display.input.reset();
// Adds "Select all" to context menu in FF
if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
input.contextMenuPending = rehide;
display.selForContextMenu = cm.doc.sel;
clearTimeout(display.detectingSelectAll);
// Select-all will be greyed out if there's nothing to select, so
// this adds a zero-width space so that we can later check whether
// it got selected.
function prepareSelectAllHack() {
if (te.selectionStart != null) {
var selected = cm.somethingSelected();
var extval = "\u200b" + (selected ? te.value : "");
te.value = "\u21da"; // Used to catch context-menu undo
te.value = extval;
input.prevInput = selected ? "" : "\u200b";
te.selectionStart = 1; te.selectionEnd = extval.length;
// Re-set this, in case some other handler touched the
// selection in the meantime.
display.selForContextMenu = cm.doc.sel;
}
}
function rehide() {
if (input.contextMenuPending != rehide) { return }
input.contextMenuPending = false;
input.wrapper.style.cssText = oldWrapperCSS;
te.style.cssText = oldCSS;
if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
// Try to detect the user choosing select-all
if (te.selectionStart != null) {
if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
var i = 0, poll = function () {
if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
te.selectionEnd > 0 && input.prevInput == "\u200b") {
operation(cm, selectAll)(cm);
} else if (i++ < 10) {
display.detectingSelectAll = setTimeout(poll, 500);
} else {
display.selForContextMenu = null;
display.input.reset();
}
};
display.detectingSelectAll = setTimeout(poll, 200);
}
}
if (ie && ie_version >= 9) { prepareSelectAllHack(); }
if (captureRightClick) {
e_stop(e);
var mouseup = function () {
off(window, "mouseup", mouseup);
setTimeout(rehide, 20);
};
on(window, "mouseup", mouseup);
} else {
setTimeout(rehide, 50);
}
};
TextareaInput.prototype.readOnlyChanged = function (val) {
if (!val) { this.reset(); }
this.textarea.disabled = val == "nocursor";
this.textarea.readOnly = !!val;
};
TextareaInput.prototype.setUneditable = function () {};
TextareaInput.prototype.needsContentAttribute = false;
function fromTextArea(textarea, options) {
options = options ? copyObj(options) : {};
options.value = textarea.value;
if (!options.tabindex && textarea.tabIndex)
{ options.tabindex = textarea.tabIndex; }
if (!options.placeholder && textarea.placeholder)
{ options.placeholder = textarea.placeholder; }
// Set autofocus to true if this textarea is focused, or if it has
// autofocus and no other element is focused.
if (options.autofocus == null) {
var hasFocus = activeElt();
options.autofocus = hasFocus == textarea ||
textarea.getAttribute("autofocus") != null && hasFocus == document.body;
}
function save() {textarea.value = cm.getValue();}
var realSubmit;
if (textarea.form) {
on(textarea.form, "submit", save);
// Deplorable hack to make the submit method do the right thing.
if (!options.leaveSubmitMethodAlone) {
var form = textarea.form;
realSubmit = form.submit;
try {
var wrappedSubmit = form.submit = function () {
save();
form.submit = realSubmit;
form.submit();
form.submit = wrappedSubmit;
};
} catch(e) {}
}
}
options.finishInit = function (cm) {
cm.save = save;
cm.getTextArea = function () { return textarea; };
cm.toTextArea = function () {
cm.toTextArea = isNaN; // Prevent this from being ran twice
save();
textarea.parentNode.removeChild(cm.getWrapperElement());
textarea.style.display = "";
if (textarea.form) {
off(textarea.form, "submit", save);
if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function")
{ textarea.form.submit = realSubmit; }
}
};
};
textarea.style.display = "none";
var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
options);
return cm
}
function addLegacyProps(CodeMirror) {
CodeMirror.off = off;
CodeMirror.on = on;
CodeMirror.wheelEventPixels = wheelEventPixels;
CodeMirror.Doc = Doc;
CodeMirror.splitLines = splitLinesAuto;
CodeMirror.countColumn = countColumn;
CodeMirror.findColumn = findColumn;
CodeMirror.isWordChar = isWordCharBasic;
CodeMirror.Pass = Pass;
CodeMirror.signal = signal;
CodeMirror.Line = Line;
CodeMirror.changeEnd = changeEnd;
CodeMirror.scrollbarModel = scrollbarModel;
CodeMirror.Pos = Pos;
CodeMirror.cmpPos = cmp;
CodeMirror.modes = modes;
CodeMirror.mimeModes = mimeModes;
CodeMirror.resolveMode = resolveMode;
CodeMirror.getMode = getMode;
CodeMirror.modeExtensions = modeExtensions;
CodeMirror.extendMode = extendMode;
CodeMirror.copyState = copyState;
CodeMirror.startState = startState;
CodeMirror.innerMode = innerMode;
CodeMirror.commands = commands;
CodeMirror.keyMap = keyMap;
CodeMirror.keyName = keyName;
CodeMirror.isModifierKey = isModifierKey;
CodeMirror.lookupKey = lookupKey;
CodeMirror.normalizeKeyMap = normalizeKeyMap;
CodeMirror.StringStream = StringStream;
CodeMirror.SharedTextMarker = SharedTextMarker;
CodeMirror.TextMarker = TextMarker;
CodeMirror.LineWidget = LineWidget;
CodeMirror.e_preventDefault = e_preventDefault;
CodeMirror.e_stopPropagation = e_stopPropagation;
CodeMirror.e_stop = e_stop;
CodeMirror.addClass = addClass;
CodeMirror.contains = contains;
CodeMirror.rmClass = rmClass;
CodeMirror.keyNames = keyNames;
}
// EDITOR CONSTRUCTOR
defineOptions(CodeMirror);
addEditorMethods(CodeMirror);
// Set up methods on CodeMirror's prototype to redirect to the editor's document.
var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
{ CodeMirror.prototype[prop] = (function(method) {
return function() {return method.apply(this.doc, arguments)}
})(Doc.prototype[prop]); } }
eventMixin(Doc);
CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
// Extra arguments are stored as the mode's dependencies, which is
// used by (legacy) mechanisms like loadmode.js to automatically
// load a mode. (Preferred mechanism is the require/define calls.)
CodeMirror.defineMode = function(name/*, mode, …*/) {
if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
defineMode.apply(this, arguments);
};
CodeMirror.defineMIME = defineMIME;
// Minimal default mode.
CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
CodeMirror.defineMIME("text/plain", "null");
// EXTENSIONS
CodeMirror.defineExtension = function (name, func) {
CodeMirror.prototype[name] = func;
};
CodeMirror.defineDocExtension = function (name, func) {
Doc.prototype[name] = func;
};
CodeMirror.fromTextArea = fromTextArea;
addLegacyProps(CodeMirror);
CodeMirror.version = "5.58.2";
return CodeMirror;
})));
});
var xml = createCommonjsModule(function (module, exports) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
mod(codemirror);
})(function(CodeMirror) {
var htmlConfig = {
autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
'track': true, 'wbr': true, 'menuitem': true},
implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
'th': true, 'tr': true},
contextGrabbers: {
'dd': {'dd': true, 'dt': true},
'dt': {'dd': true, 'dt': true},
'li': {'li': true},
'option': {'option': true, 'optgroup': true},
'optgroup': {'optgroup': true},
'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
'rp': {'rp': true, 'rt': true},
'rt': {'rp': true, 'rt': true},
'tbody': {'tbody': true, 'tfoot': true},
'td': {'td': true, 'th': true},
'tfoot': {'tbody': true},
'th': {'td': true, 'th': true},
'thead': {'tbody': true, 'tfoot': true},
'tr': {'tr': true}
},
doNotIndent: {"pre": true},
allowUnquoted: true,
allowMissing: true,
caseFold: true
};
var xmlConfig = {
autoSelfClosers: {},
implicitlyClosed: {},
contextGrabbers: {},
doNotIndent: {},
allowUnquoted: false,
allowMissing: false,
allowMissingTagName: false,
caseFold: false
};
CodeMirror.defineMode("xml", function(editorConf, config_) {
var indentUnit = editorConf.indentUnit;
var config = {};
var defaults = config_.htmlMode ? htmlConfig : xmlConfig;
for (var prop in defaults) config[prop] = defaults[prop];
for (var prop in config_) config[prop] = config_[prop];
// Return variables for tokenizers
var type, setStyle;
function inText(stream, state) {
function chain(parser) {
state.tokenize = parser;
return parser(stream, state);
}
var ch = stream.next();
if (ch == "<") {
if (stream.eat("!")) {
if (stream.eat("[")) {
if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
else return null;
} else if (stream.match("--")) {
return chain(inBlock("comment", "-->"));
} else if (stream.match("DOCTYPE", true, true)) {
stream.eatWhile(/[\w\._\-]/);
return chain(doctype(1));
} else {
return null;
}
} else if (stream.eat("?")) {
stream.eatWhile(/[\w\._\-]/);
state.tokenize = inBlock("meta", "?>");
return "meta";
} else {
type = stream.eat("/") ? "closeTag" : "openTag";
state.tokenize = inTag;
return "tag bracket";
}
} else if (ch == "&") {
var ok;
if (stream.eat("#")) {
if (stream.eat("x")) {
ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
} else {
ok = stream.eatWhile(/[\d]/) && stream.eat(";");
}
} else {
ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
}
return ok ? "atom" : "error";
} else {
stream.eatWhile(/[^&<]/);
return null;
}
}
inText.isInText = true;
function inTag(stream, state) {
var ch = stream.next();
if (ch == ">" || (ch == "/" && stream.eat(">"))) {
state.tokenize = inText;
type = ch == ">" ? "endTag" : "selfcloseTag";
return "tag bracket";
} else if (ch == "=") {
type = "equals";
return null;
} else if (ch == "<") {
state.tokenize = inText;
state.state = baseState;
state.tagName = state.tagStart = null;
var next = state.tokenize(stream, state);
return next ? next + " tag error" : "tag error";
} else if (/[\'\"]/.test(ch)) {
state.tokenize = inAttribute(ch);
state.stringStartCol = stream.column();
return state.tokenize(stream, state);
} else {
stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
return "word";
}
}
function inAttribute(quote) {
var closure = function(stream, state) {
while (!stream.eol()) {
if (stream.next() == quote) {
state.tokenize = inTag;
break;
}
}
return "string";
};
closure.isInAttribute = true;
return closure;
}
function inBlock(style, terminator) {
return function(stream, state) {
while (!stream.eol()) {
if (stream.match(terminator)) {
state.tokenize = inText;
break;
}
stream.next();
}
return style;
}
}
function doctype(depth) {
return function(stream, state) {
var ch;
while ((ch = stream.next()) != null) {
if (ch == "<") {
state.tokenize = doctype(depth + 1);
return state.tokenize(stream, state);
} else if (ch == ">") {
if (depth == 1) {
state.tokenize = inText;
break;
} else {
state.tokenize = doctype(depth - 1);
return state.tokenize(stream, state);
}
}
}
return "meta";
};
}
function Context(state, tagName, startOfLine) {
this.prev = state.context;
this.tagName = tagName;
this.indent = state.indented;
this.startOfLine = startOfLine;
if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
this.noIndent = true;
}
function popContext(state) {
if (state.context) state.context = state.context.prev;
}
function maybePopContext(state, nextTagName) {
var parentTagName;
while (true) {
if (!state.context) {
return;
}
parentTagName = state.context.tagName;
if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||
!config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
return;
}
popContext(state);
}
}
function baseState(type, stream, state) {
if (type == "openTag") {
state.tagStart = stream.column();
return tagNameState;
} else if (type == "closeTag") {
return closeTagNameState;
} else {
return baseState;
}
}
function tagNameState(type, stream, state) {
if (type == "word") {
state.tagName = stream.current();
setStyle = "tag";
return attrState;
} else if (config.allowMissingTagName && type == "endTag") {
setStyle = "tag bracket";
return attrState(type, stream, state);
} else {
setStyle = "error";
return tagNameState;
}
}
function closeTagNameState(type, stream, state) {
if (type == "word") {
var tagName = stream.current();
if (state.context && state.context.tagName != tagName &&
config.implicitlyClosed.hasOwnProperty(state.context.tagName))
popContext(state);
if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {
setStyle = "tag";
return closeState;
} else {
setStyle = "tag error";
return closeStateErr;
}
} else if (config.allowMissingTagName && type == "endTag") {
setStyle = "tag bracket";
return closeState(type, stream, state);
} else {
setStyle = "error";
return closeStateErr;
}
}
function closeState(type, _stream, state) {
if (type != "endTag") {
setStyle = "error";
return closeState;
}
popContext(state);
return baseState;
}
function closeStateErr(type, stream, state) {
setStyle = "error";
return closeState(type, stream, state);
}
function attrState(type, _stream, state) {
if (type == "word") {
setStyle = "attribute";
return attrEqState;
} else if (type == "endTag" || type == "selfcloseTag") {
var tagName = state.tagName, tagStart = state.tagStart;
state.tagName = state.tagStart = null;
if (type == "selfcloseTag" ||
config.autoSelfClosers.hasOwnProperty(tagName)) {
maybePopContext(state, tagName);
} else {
maybePopContext(state, tagName);
state.context = new Context(state, tagName, tagStart == state.indented);
}
return baseState;
}
setStyle = "error";
return attrState;
}
function attrEqState(type, stream, state) {
if (type == "equals") return attrValueState;
if (!config.allowMissing) setStyle = "error";
return attrState(type, stream, state);
}
function attrValueState(type, stream, state) {
if (type == "string") return attrContinuedState;
if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;}
setStyle = "error";
return attrState(type, stream, state);
}
function attrContinuedState(type, stream, state) {
if (type == "string") return attrContinuedState;
return attrState(type, stream, state);
}
return {
startState: function(baseIndent) {
var state = {tokenize: inText,
state: baseState,
indented: baseIndent || 0,
tagName: null, tagStart: null,
context: null};
if (baseIndent != null) state.baseIndent = baseIndent;
return state
},
token: function(stream, state) {
if (!state.tagName && stream.sol())
state.indented = stream.indentation();
if (stream.eatSpace()) return null;
type = null;
var style = state.tokenize(stream, state);
if ((style || type) && style != "comment") {
setStyle = null;
state.state = state.state(type || style, stream, state);
if (setStyle)
style = setStyle == "error" ? style + " error" : setStyle;
}
return style;
},
indent: function(state, textAfter, fullLine) {
var context = state.context;
// Indent multi-line strings (e.g. css).
if (state.tokenize.isInAttribute) {
if (state.tagStart == state.indented)
return state.stringStartCol + 1;
else
return state.indented + indentUnit;
}
if (context && context.noIndent) return CodeMirror.Pass;
if (state.tokenize != inTag && state.tokenize != inText)
return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
// Indent the starts of attribute names.
if (state.tagName) {
if (config.multilineTagIndentPastTag !== false)
return state.tagStart + state.tagName.length + 2;
else
return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
}
if (config.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
if (tagAfter && tagAfter[1]) { // Closing tag spotted
while (context) {
if (context.tagName == tagAfter[2]) {
context = context.prev;
break;
} else if (config.implicitlyClosed.hasOwnProperty(context.tagName)) {
context = context.prev;
} else {
break;
}
}
} else if (tagAfter) { // Opening tag spotted
while (context) {
var grabbers = config.contextGrabbers[context.tagName];
if (grabbers && grabbers.hasOwnProperty(tagAfter[2]))
context = context.prev;
else
break;
}
}
while (context && context.prev && !context.startOfLine)
context = context.prev;
if (context) return context.indent + indentUnit;
else return state.baseIndent || 0;
},
electricInput: /<\/[\s\w:]+>$/,
blockCommentStart: "<!--",
blockCommentEnd: "-->",
configuration: config.htmlMode ? "html" : "xml",
helperType: config.htmlMode ? "html" : "xml",
skipAttribute: function(state) {
if (state.state == attrValueState)
state.state = attrState;
},
xmlCurrentTag: function(state) {
return state.tagName ? {name: state.tagName, close: state.type == "closeTag"} : null
},
xmlCurrentContext: function(state) {
var context = [];
for (var cx = state.context; cx; cx = cx.prev)
if (cx.tagName) context.push(cx.tagName);
return context.reverse()
}
};
});
CodeMirror.defineMIME("text/xml", "xml");
CodeMirror.defineMIME("application/xml", "xml");
if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
});
});
var meta = createCommonjsModule(function (module, exports) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
mod(codemirror);
})(function(CodeMirror) {
CodeMirror.modeInfo = [
{name: "APL", mime: "text/apl", mode: "apl", ext: ["dyalog", "apl"]},
{name: "PGP", mimes: ["application/pgp", "application/pgp-encrypted", "application/pgp-keys", "application/pgp-signature"], mode: "asciiarmor", ext: ["asc", "pgp", "sig"]},
{name: "ASN.1", mime: "text/x-ttcn-asn", mode: "asn.1", ext: ["asn", "asn1"]},
{name: "Asterisk", mime: "text/x-asterisk", mode: "asterisk", file: /^extensions\.conf$/i},
{name: "Brainfuck", mime: "text/x-brainfuck", mode: "brainfuck", ext: ["b", "bf"]},
{name: "C", mime: "text/x-csrc", mode: "clike", ext: ["c", "h", "ino"]},
{name: "C++", mime: "text/x-c++src", mode: "clike", ext: ["cpp", "c++", "cc", "cxx", "hpp", "h++", "hh", "hxx"], alias: ["cpp"]},
{name: "Cobol", mime: "text/x-cobol", mode: "cobol", ext: ["cob", "cpy"]},
{name: "C#", mime: "text/x-csharp", mode: "clike", ext: ["cs"], alias: ["csharp", "cs"]},
{name: "Clojure", mime: "text/x-clojure", mode: "clojure", ext: ["clj", "cljc", "cljx"]},
{name: "ClojureScript", mime: "text/x-clojurescript", mode: "clojure", ext: ["cljs"]},
{name: "Closure Stylesheets (GSS)", mime: "text/x-gss", mode: "css", ext: ["gss"]},
{name: "CMake", mime: "text/x-cmake", mode: "cmake", ext: ["cmake", "cmake.in"], file: /^CMakeLists\.txt$/},
{name: "CoffeeScript", mimes: ["application/vnd.coffeescript", "text/coffeescript", "text/x-coffeescript"], mode: "coffeescript", ext: ["coffee"], alias: ["coffee", "coffee-script"]},
{name: "Common Lisp", mime: "text/x-common-lisp", mode: "commonlisp", ext: ["cl", "lisp", "el"], alias: ["lisp"]},
{name: "Cypher", mime: "application/x-cypher-query", mode: "cypher", ext: ["cyp", "cypher"]},
{name: "Cython", mime: "text/x-cython", mode: "python", ext: ["pyx", "pxd", "pxi"]},
{name: "Crystal", mime: "text/x-crystal", mode: "crystal", ext: ["cr"]},
{name: "CSS", mime: "text/css", mode: "css", ext: ["css"]},
{name: "CQL", mime: "text/x-cassandra", mode: "sql", ext: ["cql"]},
{name: "D", mime: "text/x-d", mode: "d", ext: ["d"]},
{name: "Dart", mimes: ["application/dart", "text/x-dart"], mode: "dart", ext: ["dart"]},
{name: "diff", mime: "text/x-diff", mode: "diff", ext: ["diff", "patch"]},
{name: "Django", mime: "text/x-django", mode: "django"},
{name: "Dockerfile", mime: "text/x-dockerfile", mode: "dockerfile", file: /^Dockerfile$/},
{name: "DTD", mime: "application/xml-dtd", mode: "dtd", ext: ["dtd"]},
{name: "Dylan", mime: "text/x-dylan", mode: "dylan", ext: ["dylan", "dyl", "intr"]},
{name: "EBNF", mime: "text/x-ebnf", mode: "ebnf"},
{name: "ECL", mime: "text/x-ecl", mode: "ecl", ext: ["ecl"]},
{name: "edn", mime: "application/edn", mode: "clojure", ext: ["edn"]},
{name: "Eiffel", mime: "text/x-eiffel", mode: "eiffel", ext: ["e"]},
{name: "Elm", mime: "text/x-elm", mode: "elm", ext: ["elm"]},
{name: "Embedded Javascript", mime: "application/x-ejs", mode: "htmlembedded", ext: ["ejs"]},
{name: "Embedded Ruby", mime: "application/x-erb", mode: "htmlembedded", ext: ["erb"]},
{name: "Erlang", mime: "text/x-erlang", mode: "erlang", ext: ["erl"]},
{name: "Esper", mime: "text/x-esper", mode: "sql"},
{name: "Factor", mime: "text/x-factor", mode: "factor", ext: ["factor"]},
{name: "FCL", mime: "text/x-fcl", mode: "fcl"},
{name: "Forth", mime: "text/x-forth", mode: "forth", ext: ["forth", "fth", "4th"]},
{name: "Fortran", mime: "text/x-fortran", mode: "fortran", ext: ["f", "for", "f77", "f90", "f95"]},
{name: "F#", mime: "text/x-fsharp", mode: "mllike", ext: ["fs"], alias: ["fsharp"]},
{name: "Gas", mime: "text/x-gas", mode: "gas", ext: ["s"]},
{name: "Gherkin", mime: "text/x-feature", mode: "gherkin", ext: ["feature"]},
{name: "GitHub Flavored Markdown", mime: "text/x-gfm", mode: "gfm", file: /^(readme|contributing|history)\.md$/i},
{name: "Go", mime: "text/x-go", mode: "go", ext: ["go"]},
{name: "Groovy", mime: "text/x-groovy", mode: "groovy", ext: ["groovy", "gradle"], file: /^Jenkinsfile$/},
{name: "HAML", mime: "text/x-haml", mode: "haml", ext: ["haml"]},
{name: "Haskell", mime: "text/x-haskell", mode: "haskell", ext: ["hs"]},
{name: "Haskell (Literate)", mime: "text/x-literate-haskell", mode: "haskell-literate", ext: ["lhs"]},
{name: "Haxe", mime: "text/x-haxe", mode: "haxe", ext: ["hx"]},
{name: "HXML", mime: "text/x-hxml", mode: "haxe", ext: ["hxml"]},
{name: "ASP.NET", mime: "application/x-aspx", mode: "htmlembedded", ext: ["aspx"], alias: ["asp", "aspx"]},
{name: "HTML", mime: "text/html", mode: "htmlmixed", ext: ["html", "htm", "handlebars", "hbs"], alias: ["xhtml"]},
{name: "HTTP", mime: "message/http", mode: "http"},
{name: "IDL", mime: "text/x-idl", mode: "idl", ext: ["pro"]},
{name: "Pug", mime: "text/x-pug", mode: "pug", ext: ["jade", "pug"], alias: ["jade"]},
{name: "Java", mime: "text/x-java", mode: "clike", ext: ["java"]},
{name: "Java Server Pages", mime: "application/x-jsp", mode: "htmlembedded", ext: ["jsp"], alias: ["jsp"]},
{name: "JavaScript", mimes: ["text/javascript", "text/ecmascript", "application/javascript", "application/x-javascript", "application/ecmascript"],
mode: "javascript", ext: ["js"], alias: ["ecmascript", "js", "node"]},
{name: "JSON", mimes: ["application/json", "application/x-json"], mode: "javascript", ext: ["json", "map"], alias: ["json5"]},
{name: "JSON-LD", mime: "application/ld+json", mode: "javascript", ext: ["jsonld"], alias: ["jsonld"]},
{name: "JSX", mime: "text/jsx", mode: "jsx", ext: ["jsx"]},
{name: "Jinja2", mime: "text/jinja2", mode: "jinja2", ext: ["j2", "jinja", "jinja2"]},
{name: "Julia", mime: "text/x-julia", mode: "julia", ext: ["jl"]},
{name: "Kotlin", mime: "text/x-kotlin", mode: "clike", ext: ["kt"]},
{name: "LESS", mime: "text/x-less", mode: "css", ext: ["less"]},
{name: "LiveScript", mime: "text/x-livescript", mode: "livescript", ext: ["ls"], alias: ["ls"]},
{name: "Lua", mime: "text/x-lua", mode: "lua", ext: ["lua"]},
{name: "Markdown", mime: "text/x-markdown", mode: "markdown", ext: ["markdown", "md", "mkd"]},
{name: "mIRC", mime: "text/mirc", mode: "mirc"},
{name: "MariaDB SQL", mime: "text/x-mariadb", mode: "sql"},
{name: "Mathematica", mime: "text/x-mathematica", mode: "mathematica", ext: ["m", "nb", "wl", "wls"]},
{name: "Modelica", mime: "text/x-modelica", mode: "modelica", ext: ["mo"]},
{name: "MUMPS", mime: "text/x-mumps", mode: "mumps", ext: ["mps"]},
{name: "MS SQL", mime: "text/x-mssql", mode: "sql"},
{name: "mbox", mime: "application/mbox", mode: "mbox", ext: ["mbox"]},
{name: "MySQL", mime: "text/x-mysql", mode: "sql"},
{name: "Nginx", mime: "text/x-nginx-conf", mode: "nginx", file: /nginx.*\.conf$/i},
{name: "NSIS", mime: "text/x-nsis", mode: "nsis", ext: ["nsh", "nsi"]},
{name: "NTriples", mimes: ["application/n-triples", "application/n-quads", "text/n-triples"],
mode: "ntriples", ext: ["nt", "nq"]},
{name: "Objective-C", mime: "text/x-objectivec", mode: "clike", ext: ["m"], alias: ["objective-c", "objc"]},
{name: "Objective-C++", mime: "text/x-objectivec++", mode: "clike", ext: ["mm"], alias: ["objective-c++", "objc++"]},
{name: "OCaml", mime: "text/x-ocaml", mode: "mllike", ext: ["ml", "mli", "mll", "mly"]},
{name: "Octave", mime: "text/x-octave", mode: "octave", ext: ["m"]},
{name: "Oz", mime: "text/x-oz", mode: "oz", ext: ["oz"]},
{name: "Pascal", mime: "text/x-pascal", mode: "pascal", ext: ["p", "pas"]},
{name: "PEG.js", mime: "null", mode: "pegjs", ext: ["jsonld"]},
{name: "Perl", mime: "text/x-perl", mode: "perl", ext: ["pl", "pm"]},
{name: "PHP", mimes: ["text/x-php", "application/x-httpd-php", "application/x-httpd-php-open"], mode: "php", ext: ["php", "php3", "php4", "php5", "php7", "phtml"]},
{name: "Pig", mime: "text/x-pig", mode: "pig", ext: ["pig"]},
{name: "Plain Text", mime: "text/plain", mode: "null", ext: ["txt", "text", "conf", "def", "list", "log"]},
{name: "PLSQL", mime: "text/x-plsql", mode: "sql", ext: ["pls"]},
{name: "PostgreSQL", mime: "text/x-pgsql", mode: "sql"},
{name: "PowerShell", mime: "application/x-powershell", mode: "powershell", ext: ["ps1", "psd1", "psm1"]},
{name: "Properties files", mime: "text/x-properties", mode: "properties", ext: ["properties", "ini", "in"], alias: ["ini", "properties"]},
{name: "ProtoBuf", mime: "text/x-protobuf", mode: "protobuf", ext: ["proto"]},
{name: "Python", mime: "text/x-python", mode: "python", ext: ["BUILD", "bzl", "py", "pyw"], file: /^(BUCK|BUILD)$/},
{name: "Puppet", mime: "text/x-puppet", mode: "puppet", ext: ["pp"]},
{name: "Q", mime: "text/x-q", mode: "q", ext: ["q"]},
{name: "R", mime: "text/x-rsrc", mode: "r", ext: ["r", "R"], alias: ["rscript"]},
{name: "reStructuredText", mime: "text/x-rst", mode: "rst", ext: ["rst"], alias: ["rst"]},
{name: "RPM Changes", mime: "text/x-rpm-changes", mode: "rpm"},
{name: "RPM Spec", mime: "text/x-rpm-spec", mode: "rpm", ext: ["spec"]},
{name: "Ruby", mime: "text/x-ruby", mode: "ruby", ext: ["rb"], alias: ["jruby", "macruby", "rake", "rb", "rbx"]},
{name: "Rust", mime: "text/x-rustsrc", mode: "rust", ext: ["rs"]},
{name: "SAS", mime: "text/x-sas", mode: "sas", ext: ["sas"]},
{name: "Sass", mime: "text/x-sass", mode: "sass", ext: ["sass"]},
{name: "Scala", mime: "text/x-scala", mode: "clike", ext: ["scala"]},
{name: "Scheme", mime: "text/x-scheme", mode: "scheme", ext: ["scm", "ss"]},
{name: "SCSS", mime: "text/x-scss", mode: "css", ext: ["scss"]},
{name: "Shell", mimes: ["text/x-sh", "application/x-sh"], mode: "shell", ext: ["sh", "ksh", "bash"], alias: ["bash", "sh", "zsh"], file: /^PKGBUILD$/},
{name: "Sieve", mime: "application/sieve", mode: "sieve", ext: ["siv", "sieve"]},
{name: "Slim", mimes: ["text/x-slim", "application/x-slim"], mode: "slim", ext: ["slim"]},
{name: "Smalltalk", mime: "text/x-stsrc", mode: "smalltalk", ext: ["st"]},
{name: "Smarty", mime: "text/x-smarty", mode: "smarty", ext: ["tpl"]},
{name: "Solr", mime: "text/x-solr", mode: "solr"},
{name: "SML", mime: "text/x-sml", mode: "mllike", ext: ["sml", "sig", "fun", "smackspec"]},
{name: "Soy", mime: "text/x-soy", mode: "soy", ext: ["soy"], alias: ["closure template"]},
{name: "SPARQL", mime: "application/sparql-query", mode: "sparql", ext: ["rq", "sparql"], alias: ["sparul"]},
{name: "Spreadsheet", mime: "text/x-spreadsheet", mode: "spreadsheet", alias: ["excel", "formula"]},
{name: "SQL", mime: "text/x-sql", mode: "sql", ext: ["sql"]},
{name: "SQLite", mime: "text/x-sqlite", mode: "sql"},
{name: "Squirrel", mime: "text/x-squirrel", mode: "clike", ext: ["nut"]},
{name: "Stylus", mime: "text/x-styl", mode: "stylus", ext: ["styl"]},
{name: "Swift", mime: "text/x-swift", mode: "swift", ext: ["swift"]},
{name: "sTeX", mime: "text/x-stex", mode: "stex"},
{name: "LaTeX", mime: "text/x-latex", mode: "stex", ext: ["text", "ltx", "tex"], alias: ["tex"]},
{name: "SystemVerilog", mime: "text/x-systemverilog", mode: "verilog", ext: ["v", "sv", "svh"]},
{name: "Tcl", mime: "text/x-tcl", mode: "tcl", ext: ["tcl"]},
{name: "Textile", mime: "text/x-textile", mode: "textile", ext: ["textile"]},
{name: "TiddlyWiki", mime: "text/x-tiddlywiki", mode: "tiddlywiki"},
{name: "Tiki wiki", mime: "text/tiki", mode: "tiki"},
{name: "TOML", mime: "text/x-toml", mode: "toml", ext: ["toml"]},
{name: "Tornado", mime: "text/x-tornado", mode: "tornado"},
{name: "troff", mime: "text/troff", mode: "troff", ext: ["1", "2", "3", "4", "5", "6", "7", "8", "9"]},
{name: "TTCN", mime: "text/x-ttcn", mode: "ttcn", ext: ["ttcn", "ttcn3", "ttcnpp"]},
{name: "TTCN_CFG", mime: "text/x-ttcn-cfg", mode: "ttcn-cfg", ext: ["cfg"]},
{name: "Turtle", mime: "text/turtle", mode: "turtle", ext: ["ttl"]},
{name: "TypeScript", mime: "application/typescript", mode: "javascript", ext: ["ts"], alias: ["ts"]},
{name: "TypeScript-JSX", mime: "text/typescript-jsx", mode: "jsx", ext: ["tsx"], alias: ["tsx"]},
{name: "Twig", mime: "text/x-twig", mode: "twig"},
{name: "Web IDL", mime: "text/x-webidl", mode: "webidl", ext: ["webidl"]},
{name: "VB.NET", mime: "text/x-vb", mode: "vb", ext: ["vb"]},
{name: "VBScript", mime: "text/vbscript", mode: "vbscript", ext: ["vbs"]},
{name: "Velocity", mime: "text/velocity", mode: "velocity", ext: ["vtl"]},
{name: "Verilog", mime: "text/x-verilog", mode: "verilog", ext: ["v"]},
{name: "VHDL", mime: "text/x-vhdl", mode: "vhdl", ext: ["vhd", "vhdl"]},
{name: "Vue.js Component", mimes: ["script/x-vue", "text/x-vue"], mode: "vue", ext: ["vue"]},
{name: "XML", mimes: ["application/xml", "text/xml"], mode: "xml", ext: ["xml", "xsl", "xsd", "svg"], alias: ["rss", "wsdl", "xsd"]},
{name: "XQuery", mime: "application/xquery", mode: "xquery", ext: ["xy", "xquery"]},
{name: "Yacas", mime: "text/x-yacas", mode: "yacas", ext: ["ys"]},
{name: "YAML", mimes: ["text/x-yaml", "text/yaml"], mode: "yaml", ext: ["yaml", "yml"], alias: ["yml"]},
{name: "Z80", mime: "text/x-z80", mode: "z80", ext: ["z80"]},
{name: "mscgen", mime: "text/x-mscgen", mode: "mscgen", ext: ["mscgen", "mscin", "msc"]},
{name: "xu", mime: "text/x-xu", mode: "mscgen", ext: ["xu"]},
{name: "msgenny", mime: "text/x-msgenny", mode: "mscgen", ext: ["msgenny"]},
{name: "WebAssembly", mime: "text/webassembly", mode: "wast", ext: ["wat", "wast"]},
];
// Ensure all modes have a mime property for backwards compatibility
for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
var info = CodeMirror.modeInfo[i];
if (info.mimes) info.mime = info.mimes[0];
}
CodeMirror.findModeByMIME = function(mime) {
mime = mime.toLowerCase();
for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
var info = CodeMirror.modeInfo[i];
if (info.mime == mime) return info;
if (info.mimes) for (var j = 0; j < info.mimes.length; j++)
if (info.mimes[j] == mime) return info;
}
if (/\+xml$/.test(mime)) return CodeMirror.findModeByMIME("application/xml")
if (/\+json$/.test(mime)) return CodeMirror.findModeByMIME("application/json")
};
CodeMirror.findModeByExtension = function(ext) {
ext = ext.toLowerCase();
for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
var info = CodeMirror.modeInfo[i];
if (info.ext) for (var j = 0; j < info.ext.length; j++)
if (info.ext[j] == ext) return info;
}
};
CodeMirror.findModeByFileName = function(filename) {
for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
var info = CodeMirror.modeInfo[i];
if (info.file && info.file.test(filename)) return info;
}
var dot = filename.lastIndexOf(".");
var ext = dot > -1 && filename.substring(dot + 1, filename.length);
if (ext) return CodeMirror.findModeByExtension(ext);
};
CodeMirror.findModeByName = function(name) {
name = name.toLowerCase();
for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
var info = CodeMirror.modeInfo[i];
if (info.name.toLowerCase() == name) return info;
if (info.alias) for (var j = 0; j < info.alias.length; j++)
if (info.alias[j].toLowerCase() == name) return info;
}
};
});
});
var markdown = createCommonjsModule(function (module, exports) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
mod(codemirror, xml, meta);
})(function(CodeMirror) {
CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) {
var htmlMode = CodeMirror.getMode(cmCfg, "text/html");
var htmlModeMissing = htmlMode.name == "null";
function getMode(name) {
if (CodeMirror.findModeByName) {
var found = CodeMirror.findModeByName(name);
if (found) name = found.mime || found.mimes[0];
}
var mode = CodeMirror.getMode(cmCfg, name);
return mode.name == "null" ? null : mode;
}
// Should characters that affect highlighting be highlighted separate?
// Does not include characters that will be output (such as `1.` and `-` for lists)
if (modeCfg.highlightFormatting === undefined)
modeCfg.highlightFormatting = false;
// Maximum number of nested blockquotes. Set to 0 for infinite nesting.
// Excess `>` will emit `error` token.
if (modeCfg.maxBlockquoteDepth === undefined)
modeCfg.maxBlockquoteDepth = 0;
// Turn on task lists? ("- [ ] " and "- [x] ")
if (modeCfg.taskLists === undefined) modeCfg.taskLists = false;
// Turn on strikethrough syntax
if (modeCfg.strikethrough === undefined)
modeCfg.strikethrough = false;
if (modeCfg.emoji === undefined)
modeCfg.emoji = false;
if (modeCfg.fencedCodeBlockHighlighting === undefined)
modeCfg.fencedCodeBlockHighlighting = true;
if (modeCfg.fencedCodeBlockDefaultMode === undefined)
modeCfg.fencedCodeBlockDefaultMode = 'text/plain';
if (modeCfg.xml === undefined)
modeCfg.xml = true;
// Allow token types to be overridden by user-provided token types.
if (modeCfg.tokenTypeOverrides === undefined)
modeCfg.tokenTypeOverrides = {};
var tokenTypes = {
header: "header",
code: "comment",
quote: "quote",
list1: "variable-2",
list2: "variable-3",
list3: "keyword",
hr: "hr",
image: "image",
imageAltText: "image-alt-text",
imageMarker: "image-marker",
formatting: "formatting",
linkInline: "link",
linkEmail: "link",
linkText: "link",
linkHref: "string",
em: "em",
strong: "strong",
strikethrough: "strikethrough",
emoji: "builtin"
};
for (var tokenType in tokenTypes) {
if (tokenTypes.hasOwnProperty(tokenType) && modeCfg.tokenTypeOverrides[tokenType]) {
tokenTypes[tokenType] = modeCfg.tokenTypeOverrides[tokenType];
}
}
var hrRE = /^([*\-_])(?:\s*\1){2,}\s*$/
, listRE = /^(?:[*\-+]|^[0-9]+([.)]))\s+/
, taskListRE = /^\[(x| )\](?=\s)/i // Must follow listRE
, atxHeaderRE = modeCfg.allowAtxHeaderWithoutSpace ? /^(#+)/ : /^(#+)(?: |$)/
, setextHeaderRE = /^ {0,3}(?:\={1,}|-{2,})\s*$/
, textRE = /^[^#!\[\]*_\\<>` "'(~:]+/
, fencedCodeRE = /^(~~~+|```+)[ \t]*([\w\/+#-]*)[^\n`]*$/
, linkDefRE = /^\s*\[[^\]]+?\]:.*$/ // naive link-definition
, punctuation = /[!"#$%&'()*+,\-.\/:;<=>?@\[\\\]^_`{|}~\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E42\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC9\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDF3C-\uDF3E]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]/
, expandedTab = " "; // CommonMark specifies tab as 4 spaces
function switchInline(stream, state, f) {
state.f = state.inline = f;
return f(stream, state);
}
function switchBlock(stream, state, f) {
state.f = state.block = f;
return f(stream, state);
}
function lineIsEmpty(line) {
return !line || !/\S/.test(line.string)
}
// Blocks
function blankLine(state) {
// Reset linkTitle state
state.linkTitle = false;
state.linkHref = false;
state.linkText = false;
// Reset EM state
state.em = false;
// Reset STRONG state
state.strong = false;
// Reset strikethrough state
state.strikethrough = false;
// Reset state.quote
state.quote = 0;
// Reset state.indentedCode
state.indentedCode = false;
if (state.f == htmlBlock) {
var exit = htmlModeMissing;
if (!exit) {
var inner = CodeMirror.innerMode(htmlMode, state.htmlState);
exit = inner.mode.name == "xml" && inner.state.tagStart === null &&
(!inner.state.context && inner.state.tokenize.isInText);
}
if (exit) {
state.f = inlineNormal;
state.block = blockNormal;
state.htmlState = null;
}
}
// Reset state.trailingSpace
state.trailingSpace = 0;
state.trailingSpaceNewLine = false;
// Mark this line as blank
state.prevLine = state.thisLine;
state.thisLine = {stream: null};
return null;
}
function blockNormal(stream, state) {
var firstTokenOnLine = stream.column() === state.indentation;
var prevLineLineIsEmpty = lineIsEmpty(state.prevLine.stream);
var prevLineIsIndentedCode = state.indentedCode;
var prevLineIsHr = state.prevLine.hr;
var prevLineIsList = state.list !== false;
var maxNonCodeIndentation = (state.listStack[state.listStack.length - 1] || 0) + 3;
state.indentedCode = false;
var lineIndentation = state.indentation;
// compute once per line (on first token)
if (state.indentationDiff === null) {
state.indentationDiff = state.indentation;
if (prevLineIsList) {
state.list = null;
// While this list item's marker's indentation is less than the deepest
// list item's content's indentation,pop the deepest list item
// indentation off the stack, and update block indentation state
while (lineIndentation < state.listStack[state.listStack.length - 1]) {
state.listStack.pop();
if (state.listStack.length) {
state.indentation = state.listStack[state.listStack.length - 1];
// less than the first list's indent -> the line is no longer a list
} else {
state.list = false;
}
}
if (state.list !== false) {
state.indentationDiff = lineIndentation - state.listStack[state.listStack.length - 1];
}
}
}
// not comprehensive (currently only for setext detection purposes)
var allowsInlineContinuation = (
!prevLineLineIsEmpty && !prevLineIsHr && !state.prevLine.header &&
(!prevLineIsList || !prevLineIsIndentedCode) &&
!state.prevLine.fencedCodeEnd
);
var isHr = (state.list === false || prevLineIsHr || prevLineLineIsEmpty) &&
state.indentation <= maxNonCodeIndentation && stream.match(hrRE);
var match = null;
if (state.indentationDiff >= 4 && (prevLineIsIndentedCode || state.prevLine.fencedCodeEnd ||
state.prevLine.header || prevLineLineIsEmpty)) {
stream.skipToEnd();
state.indentedCode = true;
return tokenTypes.code;
} else if (stream.eatSpace()) {
return null;
} else if (firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(atxHeaderRE)) && match[1].length <= 6) {
state.quote = 0;
state.header = match[1].length;
state.thisLine.header = true;
if (modeCfg.highlightFormatting) state.formatting = "header";
state.f = state.inline;
return getType(state);
} else if (state.indentation <= maxNonCodeIndentation && stream.eat('>')) {
state.quote = firstTokenOnLine ? 1 : state.quote + 1;
if (modeCfg.highlightFormatting) state.formatting = "quote";
stream.eatSpace();
return getType(state);
} else if (!isHr && !state.setext && firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(listRE))) {
var listType = match[1] ? "ol" : "ul";
state.indentation = lineIndentation + stream.current().length;
state.list = true;
state.quote = 0;
// Add this list item's content's indentation to the stack
state.listStack.push(state.indentation);
// Reset inline styles which shouldn't propagate aross list items
state.em = false;
state.strong = false;
state.code = false;
state.strikethrough = false;
if (modeCfg.taskLists && stream.match(taskListRE, false)) {
state.taskList = true;
}
state.f = state.inline;
if (modeCfg.highlightFormatting) state.formatting = ["list", "list-" + listType];
return getType(state);
} else if (firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(fencedCodeRE, true))) {
state.quote = 0;
state.fencedEndRE = new RegExp(match[1] + "+ *$");
// try switching mode
state.localMode = modeCfg.fencedCodeBlockHighlighting && getMode(match[2] || modeCfg.fencedCodeBlockDefaultMode );
if (state.localMode) state.localState = CodeMirror.startState(state.localMode);
state.f = state.block = local;
if (modeCfg.highlightFormatting) state.formatting = "code-block";
state.code = -1;
return getType(state);
// SETEXT has lowest block-scope precedence after HR, so check it after
// the others (code, blockquote, list...)
} else if (
// if setext set, indicates line after ---/===
state.setext || (
// line before ---/===
(!allowsInlineContinuation || !prevLineIsList) && !state.quote && state.list === false &&
!state.code && !isHr && !linkDefRE.test(stream.string) &&
(match = stream.lookAhead(1)) && (match = match.match(setextHeaderRE))
)
) {
if ( !state.setext ) {
state.header = match[0].charAt(0) == '=' ? 1 : 2;
state.setext = state.header;
} else {
state.header = state.setext;
// has no effect on type so we can reset it now
state.setext = 0;
stream.skipToEnd();
if (modeCfg.highlightFormatting) state.formatting = "header";
}
state.thisLine.header = true;
state.f = state.inline;
return getType(state);
} else if (isHr) {
stream.skipToEnd();
state.hr = true;
state.thisLine.hr = true;
return tokenTypes.hr;
} else if (stream.peek() === '[') {
return switchInline(stream, state, footnoteLink);
}
return switchInline(stream, state, state.inline);
}
function htmlBlock(stream, state) {
var style = htmlMode.token(stream, state.htmlState);
if (!htmlModeMissing) {
var inner = CodeMirror.innerMode(htmlMode, state.htmlState);
if ((inner.mode.name == "xml" && inner.state.tagStart === null &&
(!inner.state.context && inner.state.tokenize.isInText)) ||
(state.md_inside && stream.current().indexOf(">") > -1)) {
state.f = inlineNormal;
state.block = blockNormal;
state.htmlState = null;
}
}
return style;
}
function local(stream, state) {
var currListInd = state.listStack[state.listStack.length - 1] || 0;
var hasExitedList = state.indentation < currListInd;
var maxFencedEndInd = currListInd + 3;
if (state.fencedEndRE && state.indentation <= maxFencedEndInd && (hasExitedList || stream.match(state.fencedEndRE))) {
if (modeCfg.highlightFormatting) state.formatting = "code-block";
var returnType;
if (!hasExitedList) returnType = getType(state);
state.localMode = state.localState = null;
state.block = blockNormal;
state.f = inlineNormal;
state.fencedEndRE = null;
state.code = 0;
state.thisLine.fencedCodeEnd = true;
if (hasExitedList) return switchBlock(stream, state, state.block);
return returnType;
} else if (state.localMode) {
return state.localMode.token(stream, state.localState);
} else {
stream.skipToEnd();
return tokenTypes.code;
}
}
// Inline
function getType(state) {
var styles = [];
if (state.formatting) {
styles.push(tokenTypes.formatting);
if (typeof state.formatting === "string") state.formatting = [state.formatting];
for (var i = 0; i < state.formatting.length; i++) {
styles.push(tokenTypes.formatting + "-" + state.formatting[i]);
if (state.formatting[i] === "header") {
styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.header);
}
// Add `formatting-quote` and `formatting-quote-#` for blockquotes
// Add `error` instead if the maximum blockquote nesting depth is passed
if (state.formatting[i] === "quote") {
if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.quote);
} else {
styles.push("error");
}
}
}
}
if (state.taskOpen) {
styles.push("meta");
return styles.length ? styles.join(' ') : null;
}
if (state.taskClosed) {
styles.push("property");
return styles.length ? styles.join(' ') : null;
}
if (state.linkHref) {
styles.push(tokenTypes.linkHref, "url");
} else { // Only apply inline styles to non-url text
if (state.strong) { styles.push(tokenTypes.strong); }
if (state.em) { styles.push(tokenTypes.em); }
if (state.strikethrough) { styles.push(tokenTypes.strikethrough); }
if (state.emoji) { styles.push(tokenTypes.emoji); }
if (state.linkText) { styles.push(tokenTypes.linkText); }
if (state.code) { styles.push(tokenTypes.code); }
if (state.image) { styles.push(tokenTypes.image); }
if (state.imageAltText) { styles.push(tokenTypes.imageAltText, "link"); }
if (state.imageMarker) { styles.push(tokenTypes.imageMarker); }
}
if (state.header) { styles.push(tokenTypes.header, tokenTypes.header + "-" + state.header); }
if (state.quote) {
styles.push(tokenTypes.quote);
// Add `quote-#` where the maximum for `#` is modeCfg.maxBlockquoteDepth
if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
styles.push(tokenTypes.quote + "-" + state.quote);
} else {
styles.push(tokenTypes.quote + "-" + modeCfg.maxBlockquoteDepth);
}
}
if (state.list !== false) {
var listMod = (state.listStack.length - 1) % 3;
if (!listMod) {
styles.push(tokenTypes.list1);
} else if (listMod === 1) {
styles.push(tokenTypes.list2);
} else {
styles.push(tokenTypes.list3);
}
}
if (state.trailingSpaceNewLine) {
styles.push("trailing-space-new-line");
} else if (state.trailingSpace) {
styles.push("trailing-space-" + (state.trailingSpace % 2 ? "a" : "b"));
}
return styles.length ? styles.join(' ') : null;
}
function handleText(stream, state) {
if (stream.match(textRE, true)) {
return getType(state);
}
return undefined;
}
function inlineNormal(stream, state) {
var style = state.text(stream, state);
if (typeof style !== 'undefined')
return style;
if (state.list) { // List marker (*, +, -, 1., etc)
state.list = null;
return getType(state);
}
if (state.taskList) {
var taskOpen = stream.match(taskListRE, true)[1] === " ";
if (taskOpen) state.taskOpen = true;
else state.taskClosed = true;
if (modeCfg.highlightFormatting) state.formatting = "task";
state.taskList = false;
return getType(state);
}
state.taskOpen = false;
state.taskClosed = false;
if (state.header && stream.match(/^#+$/, true)) {
if (modeCfg.highlightFormatting) state.formatting = "header";
return getType(state);
}
var ch = stream.next();
// Matches link titles present on next line
if (state.linkTitle) {
state.linkTitle = false;
var matchCh = ch;
if (ch === '(') {
matchCh = ')';
}
matchCh = (matchCh+'').replace(/([.?*+^\[\]\\(){}|-])/g, "\\$1");
var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh;
if (stream.match(new RegExp(regex), true)) {
return tokenTypes.linkHref;
}
}
// If this block is changed, it may need to be updated in GFM mode
if (ch === '`') {
var previousFormatting = state.formatting;
if (modeCfg.highlightFormatting) state.formatting = "code";
stream.eatWhile('`');
var count = stream.current().length;
if (state.code == 0 && (!state.quote || count == 1)) {
state.code = count;
return getType(state)
} else if (count == state.code) { // Must be exact
var t = getType(state);
state.code = 0;
return t
} else {
state.formatting = previousFormatting;
return getType(state)
}
} else if (state.code) {
return getType(state);
}
if (ch === '\\') {
stream.next();
if (modeCfg.highlightFormatting) {
var type = getType(state);
var formattingEscape = tokenTypes.formatting + "-escape";
return type ? type + " " + formattingEscape : formattingEscape;
}
}
if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) {
state.imageMarker = true;
state.image = true;
if (modeCfg.highlightFormatting) state.formatting = "image";
return getType(state);
}
if (ch === '[' && state.imageMarker && stream.match(/[^\]]*\](\(.*?\)| ?\[.*?\])/, false)) {
state.imageMarker = false;
state.imageAltText = true;
if (modeCfg.highlightFormatting) state.formatting = "image";
return getType(state);
}
if (ch === ']' && state.imageAltText) {
if (modeCfg.highlightFormatting) state.formatting = "image";
var type = getType(state);
state.imageAltText = false;
state.image = false;
state.inline = state.f = linkHref;
return type;
}
if (ch === '[' && !state.image) {
if (state.linkText && stream.match(/^.*?\]/)) return getType(state)
state.linkText = true;
if (modeCfg.highlightFormatting) state.formatting = "link";
return getType(state);
}
if (ch === ']' && state.linkText) {
if (modeCfg.highlightFormatting) state.formatting = "link";
var type = getType(state);
state.linkText = false;
state.inline = state.f = stream.match(/\(.*?\)| ?\[.*?\]/, false) ? linkHref : inlineNormal;
return type;
}
if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) {
state.f = state.inline = linkInline;
if (modeCfg.highlightFormatting) state.formatting = "link";
var type = getType(state);
if (type){
type += " ";
} else {
type = "";
}
return type + tokenTypes.linkInline;
}
if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) {
state.f = state.inline = linkInline;
if (modeCfg.highlightFormatting) state.formatting = "link";
var type = getType(state);
if (type){
type += " ";
} else {
type = "";
}
return type + tokenTypes.linkEmail;
}
if (modeCfg.xml && ch === '<' && stream.match(/^(!--|\?|!\[CDATA\[|[a-z][a-z0-9-]*(?:\s+[a-z_:.\-]+(?:\s*=\s*[^>]+)?)*\s*(?:>|$))/i, false)) {
var end = stream.string.indexOf(">", stream.pos);
if (end != -1) {
var atts = stream.string.substring(stream.start, end);
if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) state.md_inside = true;
}
stream.backUp(1);
state.htmlState = CodeMirror.startState(htmlMode);
return switchBlock(stream, state, htmlBlock);
}
if (modeCfg.xml && ch === '<' && stream.match(/^\/\w*?>/)) {
state.md_inside = false;
return "tag";
} else if (ch === "*" || ch === "_") {
var len = 1, before = stream.pos == 1 ? " " : stream.string.charAt(stream.pos - 2);
while (len < 3 && stream.eat(ch)) len++;
var after = stream.peek() || " ";
// See http://spec.commonmark.org/0.27/#emphasis-and-strong-emphasis
var leftFlanking = !/\s/.test(after) && (!punctuation.test(after) || /\s/.test(before) || punctuation.test(before));
var rightFlanking = !/\s/.test(before) && (!punctuation.test(before) || /\s/.test(after) || punctuation.test(after));
var setEm = null, setStrong = null;
if (len % 2) { // Em
if (!state.em && leftFlanking && (ch === "*" || !rightFlanking || punctuation.test(before)))
setEm = true;
else if (state.em == ch && rightFlanking && (ch === "*" || !leftFlanking || punctuation.test(after)))
setEm = false;
}
if (len > 1) { // Strong
if (!state.strong && leftFlanking && (ch === "*" || !rightFlanking || punctuation.test(before)))
setStrong = true;
else if (state.strong == ch && rightFlanking && (ch === "*" || !leftFlanking || punctuation.test(after)))
setStrong = false;
}
if (setStrong != null || setEm != null) {
if (modeCfg.highlightFormatting) state.formatting = setEm == null ? "strong" : setStrong == null ? "em" : "strong em";
if (setEm === true) state.em = ch;
if (setStrong === true) state.strong = ch;
var t = getType(state);
if (setEm === false) state.em = false;
if (setStrong === false) state.strong = false;
return t
}
} else if (ch === ' ') {
if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces
if (stream.peek() === ' ') { // Surrounded by spaces, ignore
return getType(state);
} else { // Not surrounded by spaces, back up pointer
stream.backUp(1);
}
}
}
if (modeCfg.strikethrough) {
if (ch === '~' && stream.eatWhile(ch)) {
if (state.strikethrough) {// Remove strikethrough
if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
var t = getType(state);
state.strikethrough = false;
return t;
} else if (stream.match(/^[^\s]/, false)) {// Add strikethrough
state.strikethrough = true;
if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
return getType(state);
}
} else if (ch === ' ') {
if (stream.match(/^~~/, true)) { // Probably surrounded by space
if (stream.peek() === ' ') { // Surrounded by spaces, ignore
return getType(state);
} else { // Not surrounded by spaces, back up pointer
stream.backUp(2);
}
}
}
}
if (modeCfg.emoji && ch === ":" && stream.match(/^(?:[a-z_\d+][a-z_\d+-]*|\-[a-z_\d+][a-z_\d+-]*):/)) {
state.emoji = true;
if (modeCfg.highlightFormatting) state.formatting = "emoji";
var retType = getType(state);
state.emoji = false;
return retType;
}
if (ch === ' ') {
if (stream.match(/^ +$/, false)) {
state.trailingSpace++;
} else if (state.trailingSpace) {
state.trailingSpaceNewLine = true;
}
}
return getType(state);
}
function linkInline(stream, state) {
var ch = stream.next();
if (ch === ">") {
state.f = state.inline = inlineNormal;
if (modeCfg.highlightFormatting) state.formatting = "link";
var type = getType(state);
if (type){
type += " ";
} else {
type = "";
}
return type + tokenTypes.linkInline;
}
stream.match(/^[^>]+/, true);
return tokenTypes.linkInline;
}
function linkHref(stream, state) {
// Check if space, and return NULL if so (to avoid marking the space)
if(stream.eatSpace()){
return null;
}
var ch = stream.next();
if (ch === '(' || ch === '[') {
state.f = state.inline = getLinkHrefInside(ch === "(" ? ")" : "]");
if (modeCfg.highlightFormatting) state.formatting = "link-string";
state.linkHref = true;
return getType(state);
}
return 'error';
}
var linkRE = {
")": /^(?:[^\\\(\)]|\\.|\((?:[^\\\(\)]|\\.)*\))*?(?=\))/,
"]": /^(?:[^\\\[\]]|\\.|\[(?:[^\\\[\]]|\\.)*\])*?(?=\])/
};
function getLinkHrefInside(endChar) {
return function(stream, state) {
var ch = stream.next();
if (ch === endChar) {
state.f = state.inline = inlineNormal;
if (modeCfg.highlightFormatting) state.formatting = "link-string";
var returnState = getType(state);
state.linkHref = false;
return returnState;
}
stream.match(linkRE[endChar]);
state.linkHref = true;
return getType(state);
};
}
function footnoteLink(stream, state) {
if (stream.match(/^([^\]\\]|\\.)*\]:/, false)) {
state.f = footnoteLinkInside;
stream.next(); // Consume [
if (modeCfg.highlightFormatting) state.formatting = "link";
state.linkText = true;
return getType(state);
}
return switchInline(stream, state, inlineNormal);
}
function footnoteLinkInside(stream, state) {
if (stream.match(/^\]:/, true)) {
state.f = state.inline = footnoteUrl;
if (modeCfg.highlightFormatting) state.formatting = "link";
var returnType = getType(state);
state.linkText = false;
return returnType;
}
stream.match(/^([^\]\\]|\\.)+/, true);
return tokenTypes.linkText;
}
function footnoteUrl(stream, state) {
// Check if space, and return NULL if so (to avoid marking the space)
if(stream.eatSpace()){
return null;
}
// Match URL
stream.match(/^[^\s]+/, true);
// Check for link title
if (stream.peek() === undefined) { // End of line, set flag to check next line
state.linkTitle = true;
} else { // More content on line, check if link title
stream.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/, true);
}
state.f = state.inline = inlineNormal;
return tokenTypes.linkHref + " url";
}
var mode = {
startState: function() {
return {
f: blockNormal,
prevLine: {stream: null},
thisLine: {stream: null},
block: blockNormal,
htmlState: null,
indentation: 0,
inline: inlineNormal,
text: handleText,
formatting: false,
linkText: false,
linkHref: false,
linkTitle: false,
code: 0,
em: false,
strong: false,
header: 0,
setext: 0,
hr: false,
taskList: false,
list: false,
listStack: [],
quote: 0,
trailingSpace: 0,
trailingSpaceNewLine: false,
strikethrough: false,
emoji: false,
fencedEndRE: null
};
},
copyState: function(s) {
return {
f: s.f,
prevLine: s.prevLine,
thisLine: s.thisLine,
block: s.block,
htmlState: s.htmlState && CodeMirror.copyState(htmlMode, s.htmlState),
indentation: s.indentation,
localMode: s.localMode,
localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null,
inline: s.inline,
text: s.text,
formatting: false,
linkText: s.linkText,
linkTitle: s.linkTitle,
linkHref: s.linkHref,
code: s.code,
em: s.em,
strong: s.strong,
strikethrough: s.strikethrough,
emoji: s.emoji,
header: s.header,
setext: s.setext,
hr: s.hr,
taskList: s.taskList,
list: s.list,
listStack: s.listStack.slice(0),
quote: s.quote,
indentedCode: s.indentedCode,
trailingSpace: s.trailingSpace,
trailingSpaceNewLine: s.trailingSpaceNewLine,
md_inside: s.md_inside,
fencedEndRE: s.fencedEndRE
};
},
token: function(stream, state) {
// Reset state.formatting
state.formatting = false;
if (stream != state.thisLine.stream) {
state.header = 0;
state.hr = false;
if (stream.match(/^\s*$/, true)) {
blankLine(state);
return null;
}
state.prevLine = state.thisLine;
state.thisLine = {stream: stream};
// Reset state.taskList
state.taskList = false;
// Reset state.trailingSpace
state.trailingSpace = 0;
state.trailingSpaceNewLine = false;
if (!state.localState) {
state.f = state.block;
if (state.f != htmlBlock) {
var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, expandedTab).length;
state.indentation = indentation;
state.indentationDiff = null;
if (indentation > 0) return null;
}
}
}
return state.f(stream, state);
},
innerMode: function(state) {
if (state.block == htmlBlock) return {state: state.htmlState, mode: htmlMode};
if (state.localState) return {state: state.localState, mode: state.localMode};
return {state: state, mode: mode};
},
indent: function(state, textAfter, line) {
if (state.block == htmlBlock && htmlMode.indent) return htmlMode.indent(state.htmlState, textAfter, line)
if (state.localState && state.localMode.indent) return state.localMode.indent(state.localState, textAfter, line)
return CodeMirror.Pass
},
blankLine: blankLine,
getType: getType,
blockCommentStart: "<!--",
blockCommentEnd: "-->",
closeBrackets: "()[]{}''\"\"``",
fold: "markdown"
};
return mode;
}, "xml");
CodeMirror.defineMIME("text/markdown", "markdown");
CodeMirror.defineMIME("text/x-markdown", "markdown");
});
});
var overlay = createCommonjsModule(function (module, exports) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
// Utility function that allows modes to be combined. The mode given
// as the base argument takes care of most of the normal mode
// functionality, but a second (typically simple) mode is used, which
// can override the style of text. Both modes get to parse all of the
// text, but when both assign a non-null style to a piece of code, the
// overlay wins, unless the combine argument was true and not overridden,
// or state.overlay.combineTokens was true, in which case the styles are
// combined.
(function(mod) {
mod(codemirror);
})(function(CodeMirror) {
CodeMirror.overlayMode = function(base, overlay, combine) {
return {
startState: function() {
return {
base: CodeMirror.startState(base),
overlay: CodeMirror.startState(overlay),
basePos: 0, baseCur: null,
overlayPos: 0, overlayCur: null,
streamSeen: null
};
},
copyState: function(state) {
return {
base: CodeMirror.copyState(base, state.base),
overlay: CodeMirror.copyState(overlay, state.overlay),
basePos: state.basePos, baseCur: null,
overlayPos: state.overlayPos, overlayCur: null
};
},
token: function(stream, state) {
if (stream != state.streamSeen ||
Math.min(state.basePos, state.overlayPos) < stream.start) {
state.streamSeen = stream;
state.basePos = state.overlayPos = stream.start;
}
if (stream.start == state.basePos) {
state.baseCur = base.token(stream, state.base);
state.basePos = stream.pos;
}
if (stream.start == state.overlayPos) {
stream.pos = stream.start;
state.overlayCur = overlay.token(stream, state.overlay);
state.overlayPos = stream.pos;
}
stream.pos = Math.min(state.basePos, state.overlayPos);
// state.overlay.combineTokens always takes precedence over combine,
// unless set to null
if (state.overlayCur == null) return state.baseCur;
else if (state.baseCur != null &&
state.overlay.combineTokens ||
combine && state.overlay.combineTokens == null)
return state.baseCur + " " + state.overlayCur;
else return state.overlayCur;
},
indent: base.indent && function(state, textAfter, line) {
return base.indent(state.base, textAfter, line);
},
electricChars: base.electricChars,
innerMode: function(state) { return {state: state.base, mode: base}; },
blankLine: function(state) {
var baseToken, overlayToken;
if (base.blankLine) baseToken = base.blankLine(state.base);
if (overlay.blankLine) overlayToken = overlay.blankLine(state.overlay);
return overlayToken == null ?
baseToken :
(combine && baseToken != null ? baseToken + " " + overlayToken : overlayToken);
}
};
};
});
});
var gfm = createCommonjsModule(function (module, exports) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
mod(codemirror, markdown, overlay);
})(function(CodeMirror) {
var urlRE = /^((?:(?:aaas?|about|acap|adiumxtra|af[ps]|aim|apt|attachment|aw|beshare|bitcoin|bolo|callto|cap|chrome(?:-extension)?|cid|coap|com-eventbrite-attendee|content|crid|cvs|data|dav|dict|dlna-(?:playcontainer|playsingle)|dns|doi|dtn|dvb|ed2k|facetime|feed|file|finger|fish|ftp|geo|gg|git|gizmoproject|go|gopher|gtalk|h323|hcp|https?|iax|icap|icon|im|imap|info|ipn|ipp|irc[6s]?|iris(?:\.beep|\.lwz|\.xpc|\.xpcs)?|itms|jar|javascript|jms|keyparc|lastfm|ldaps?|magnet|mailto|maps|market|message|mid|mms|ms-help|msnim|msrps?|mtqp|mumble|mupdate|mvn|news|nfs|nih?|nntp|notes|oid|opaquelocktoken|palm|paparazzi|platform|pop|pres|proxy|psyc|query|res(?:ource)?|rmi|rsync|rtmp|rtsp|secondlife|service|session|sftp|sgn|shttp|sieve|sips?|skype|sm[bs]|snmp|soap\.beeps?|soldat|spotify|ssh|steam|svn|tag|teamspeak|tel(?:net)?|tftp|things|thismessage|tip|tn3270|tv|udp|unreal|urn|ut2004|vemmi|ventrilo|view-source|webcal|wss?|wtai|wyciwyg|xcon(?:-userid)?|xfire|xmlrpc\.beeps?|xmpp|xri|ymsgr|z39\.50[rs]?):(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]|\([^\s()<>]*\))+(?:\([^\s()<>]*\)|[^\s`*!()\[\]{};:'".,<>?«»“”‘’]))/i;
CodeMirror.defineMode("gfm", function(config, modeConfig) {
var codeDepth = 0;
function blankLine(state) {
state.code = false;
return null;
}
var gfmOverlay = {
startState: function() {
return {
code: false,
codeBlock: false,
ateSpace: false
};
},
copyState: function(s) {
return {
code: s.code,
codeBlock: s.codeBlock,
ateSpace: s.ateSpace
};
},
token: function(stream, state) {
state.combineTokens = null;
// Hack to prevent formatting override inside code blocks (block and inline)
if (state.codeBlock) {
if (stream.match(/^```+/)) {
state.codeBlock = false;
return null;
}
stream.skipToEnd();
return null;
}
if (stream.sol()) {
state.code = false;
}
if (stream.sol() && stream.match(/^```+/)) {
stream.skipToEnd();
state.codeBlock = true;
return null;
}
// If this block is changed, it may need to be updated in Markdown mode
if (stream.peek() === '`') {
stream.next();
var before = stream.pos;
stream.eatWhile('`');
var difference = 1 + stream.pos - before;
if (!state.code) {
codeDepth = difference;
state.code = true;
} else {
if (difference === codeDepth) { // Must be exact
state.code = false;
}
}
return null;
} else if (state.code) {
stream.next();
return null;
}
// Check if space. If so, links can be formatted later on
if (stream.eatSpace()) {
state.ateSpace = true;
return null;
}
if (stream.sol() || state.ateSpace) {
state.ateSpace = false;
if (modeConfig.gitHubSpice !== false) {
if(stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+@)?(?=.{0,6}\d)(?:[a-f0-9]{7,40}\b)/)) {
// User/Project@SHA
// User@SHA
// SHA
state.combineTokens = true;
return "link";
} else if (stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+)?#[0-9]+\b/)) {
// User/Project#Num
// User#Num
// #Num
state.combineTokens = true;
return "link";
}
}
}
if (stream.match(urlRE) &&
stream.string.slice(stream.start - 2, stream.start) != "](" &&
(stream.start == 0 || /\W/.test(stream.string.charAt(stream.start - 1)))) {
// URLs
// Taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls
// And then (issue #1160) simplified to make it not crash the Chrome Regexp engine
// And then limited url schemes to the CommonMark list, so foo:bar isn't matched as a URL
state.combineTokens = true;
return "link";
}
stream.next();
return null;
},
blankLine: blankLine
};
var markdownConfig = {
taskLists: true,
strikethrough: true,
emoji: true
};
for (var attr in modeConfig) {
markdownConfig[attr] = modeConfig[attr];
}
markdownConfig.name = "markdown";
return CodeMirror.overlayMode(CodeMirror.getMode(config, markdownConfig), gfmOverlay);
}, "markdown");
CodeMirror.defineMIME("text/x-gfm", "gfm");
});
});
var continuelist = createCommonjsModule(function (module, exports) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
mod(codemirror);
})(function(CodeMirror) {
var listRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]\s|[*+-]\s|(\d+)([.)]))(\s*)/,
emptyListRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]|[*+-]|(\d+)[.)])(\s*)$/,
unorderedListRE = /[*+-]\s/;
CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) {
if (cm.getOption("disableInput")) return CodeMirror.Pass;
var ranges = cm.listSelections(), replacements = [];
for (var i = 0; i < ranges.length; i++) {
var pos = ranges[i].head;
// If we're not in Markdown mode, fall back to normal newlineAndIndent
var eolState = cm.getStateAfter(pos.line);
var inner = CodeMirror.innerMode(cm.getMode(), eolState);
if (inner.mode.name !== "markdown") {
cm.execCommand("newlineAndIndent");
return;
} else {
eolState = inner.state;
}
var inList = eolState.list !== false;
var inQuote = eolState.quote !== 0;
var line = cm.getLine(pos.line), match = listRE.exec(line);
var cursorBeforeBullet = /^\s*$/.test(line.slice(0, pos.ch));
if (!ranges[i].empty() || (!inList && !inQuote) || !match || cursorBeforeBullet) {
cm.execCommand("newlineAndIndent");
return;
}
if (emptyListRE.test(line)) {
var endOfQuote = inQuote && />\s*$/.test(line);
var endOfList = !/>\s*$/.test(line);
if (endOfQuote || endOfList) cm.replaceRange("", {
line: pos.line, ch: 0
}, {
line: pos.line, ch: pos.ch + 1
});
replacements[i] = "\n";
} else {
var indent = match[1], after = match[5];
var numbered = !(unorderedListRE.test(match[2]) || match[2].indexOf(">") >= 0);
var bullet = numbered ? (parseInt(match[3], 10) + 1) + match[4] : match[2].replace("x", " ");
replacements[i] = "\n" + indent + bullet + after;
if (numbered) incrementRemainingMarkdownListNumbers(cm, pos);
}
}
cm.replaceSelections(replacements);
};
// Auto-updating Markdown list numbers when a new item is added to the
// middle of a list
function incrementRemainingMarkdownListNumbers(cm, pos) {
var startLine = pos.line, lookAhead = 0, skipCount = 0;
var startItem = listRE.exec(cm.getLine(startLine)), startIndent = startItem[1];
do {
lookAhead += 1;
var nextLineNumber = startLine + lookAhead;
var nextLine = cm.getLine(nextLineNumber), nextItem = listRE.exec(nextLine);
if (nextItem) {
var nextIndent = nextItem[1];
var newNumber = (parseInt(startItem[3], 10) + lookAhead - skipCount);
var nextNumber = (parseInt(nextItem[3], 10)), itemNumber = nextNumber;
if (startIndent === nextIndent && !isNaN(nextNumber)) {
if (newNumber === nextNumber) itemNumber = nextNumber + 1;
if (newNumber > nextNumber) itemNumber = newNumber + 1;
cm.replaceRange(
nextLine.replace(listRE, nextIndent + itemNumber + nextItem[4] + nextItem[5]),
{
line: nextLineNumber, ch: 0
}, {
line: nextLineNumber, ch: nextLine.length
});
} else {
if (startIndent.length > nextIndent.length) return;
// This doesn't run if the next line immediatley indents, as it is
// not clear of the users intention (new indented item or same level)
if ((startIndent.length < nextIndent.length) && (lookAhead === 1)) return;
skipCount += 1;
}
}
} while (nextItem);
}
});
});
var xmlFold = createCommonjsModule(function (module, exports) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
mod(codemirror);
})(function(CodeMirror) {
var Pos = CodeMirror.Pos;
function cmp(a, b) { return a.line - b.line || a.ch - b.ch; }
var nameStartChar = "A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
var nameChar = nameStartChar + "\-\:\.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
var xmlTagStart = new RegExp("<(/?)([" + nameStartChar + "][" + nameChar + "]*)", "g");
function Iter(cm, line, ch, range) {
this.line = line; this.ch = ch;
this.cm = cm; this.text = cm.getLine(line);
this.min = range ? Math.max(range.from, cm.firstLine()) : cm.firstLine();
this.max = range ? Math.min(range.to - 1, cm.lastLine()) : cm.lastLine();
}
function tagAt(iter, ch) {
var type = iter.cm.getTokenTypeAt(Pos(iter.line, ch));
return type && /\btag\b/.test(type);
}
function nextLine(iter) {
if (iter.line >= iter.max) return;
iter.ch = 0;
iter.text = iter.cm.getLine(++iter.line);
return true;
}
function prevLine(iter) {
if (iter.line <= iter.min) return;
iter.text = iter.cm.getLine(--iter.line);
iter.ch = iter.text.length;
return true;
}
function toTagEnd(iter) {
for (;;) {
var gt = iter.text.indexOf(">", iter.ch);
if (gt == -1) { if (nextLine(iter)) continue; else return; }
if (!tagAt(iter, gt + 1)) { iter.ch = gt + 1; continue; }
var lastSlash = iter.text.lastIndexOf("/", gt);
var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt));
iter.ch = gt + 1;
return selfClose ? "selfClose" : "regular";
}
}
function toTagStart(iter) {
for (;;) {
var lt = iter.ch ? iter.text.lastIndexOf("<", iter.ch - 1) : -1;
if (lt == -1) { if (prevLine(iter)) continue; else return; }
if (!tagAt(iter, lt + 1)) { iter.ch = lt; continue; }
xmlTagStart.lastIndex = lt;
iter.ch = lt;
var match = xmlTagStart.exec(iter.text);
if (match && match.index == lt) return match;
}
}
function toNextTag(iter) {
for (;;) {
xmlTagStart.lastIndex = iter.ch;
var found = xmlTagStart.exec(iter.text);
if (!found) { if (nextLine(iter)) continue; else return; }
if (!tagAt(iter, found.index + 1)) { iter.ch = found.index + 1; continue; }
iter.ch = found.index + found[0].length;
return found;
}
}
function toPrevTag(iter) {
for (;;) {
var gt = iter.ch ? iter.text.lastIndexOf(">", iter.ch - 1) : -1;
if (gt == -1) { if (prevLine(iter)) continue; else return; }
if (!tagAt(iter, gt + 1)) { iter.ch = gt; continue; }
var lastSlash = iter.text.lastIndexOf("/", gt);
var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt));
iter.ch = gt + 1;
return selfClose ? "selfClose" : "regular";
}
}
function findMatchingClose(iter, tag) {
var stack = [];
for (;;) {
var next = toNextTag(iter), end, startLine = iter.line, startCh = iter.ch - (next ? next[0].length : 0);
if (!next || !(end = toTagEnd(iter))) return;
if (end == "selfClose") continue;
if (next[1]) { // closing tag
for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == next[2]) {
stack.length = i;
break;
}
if (i < 0 && (!tag || tag == next[2])) return {
tag: next[2],
from: Pos(startLine, startCh),
to: Pos(iter.line, iter.ch)
};
} else { // opening tag
stack.push(next[2]);
}
}
}
function findMatchingOpen(iter, tag) {
var stack = [];
for (;;) {
var prev = toPrevTag(iter);
if (!prev) return;
if (prev == "selfClose") { toTagStart(iter); continue; }
var endLine = iter.line, endCh = iter.ch;
var start = toTagStart(iter);
if (!start) return;
if (start[1]) { // closing tag
stack.push(start[2]);
} else { // opening tag
for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == start[2]) {
stack.length = i;
break;
}
if (i < 0 && (!tag || tag == start[2])) return {
tag: start[2],
from: Pos(iter.line, iter.ch),
to: Pos(endLine, endCh)
};
}
}
}
CodeMirror.registerHelper("fold", "xml", function(cm, start) {
var iter = new Iter(cm, start.line, 0);
for (;;) {
var openTag = toNextTag(iter);
if (!openTag || iter.line != start.line) return
var end = toTagEnd(iter);
if (!end) return
if (!openTag[1] && end != "selfClose") {
var startPos = Pos(iter.line, iter.ch);
var endPos = findMatchingClose(iter, openTag[2]);
return endPos && cmp(endPos.from, startPos) > 0 ? {from: startPos, to: endPos.from} : null
}
}
});
CodeMirror.findMatchingTag = function(cm, pos, range) {
var iter = new Iter(cm, pos.line, pos.ch, range);
if (iter.text.indexOf(">") == -1 && iter.text.indexOf("<") == -1) return;
var end = toTagEnd(iter), to = end && Pos(iter.line, iter.ch);
var start = end && toTagStart(iter);
if (!end || !start || cmp(iter, pos) > 0) return;
var here = {from: Pos(iter.line, iter.ch), to: to, tag: start[2]};
if (end == "selfClose") return {open: here, close: null, at: "open"};
if (start[1]) { // closing tag
return {open: findMatchingOpen(iter, start[2]), close: here, at: "close"};
} else { // opening tag
iter = new Iter(cm, to.line, to.ch, range);
return {open: here, close: findMatchingClose(iter, start[2]), at: "open"};
}
};
CodeMirror.findEnclosingTag = function(cm, pos, range, tag) {
var iter = new Iter(cm, pos.line, pos.ch, range);
for (;;) {
var open = findMatchingOpen(iter, tag);
if (!open) break;
var forward = new Iter(cm, pos.line, pos.ch, range);
var close = findMatchingClose(forward, open.tag);
if (close) return {open: open, close: close};
}
};
// Used by addon/edit/closetag.js
CodeMirror.scanForClosingTag = function(cm, pos, name, end) {
var iter = new Iter(cm, pos.line, pos.ch, end ? {from: 0, to: end} : null);
return findMatchingClose(iter, name);
};
});
});
var closetag = createCommonjsModule(function (module, exports) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
/**
* Tag-closer extension for CodeMirror.
*
* This extension adds an "autoCloseTags" option that can be set to
* either true to get the default behavior, or an object to further
* configure its behavior.
*
* These are supported options:
*
* `whenClosing` (default true)
* Whether to autoclose when the '/' of a closing tag is typed.
* `whenOpening` (default true)
* Whether to autoclose the tag when the final '>' of an opening
* tag is typed.
* `dontCloseTags` (default is empty tags for HTML, none for XML)
* An array of tag names that should not be autoclosed.
* `indentTags` (default is block tags for HTML, none for XML)
* An array of tag names that should, when opened, cause a
* blank line to be added inside the tag, and the blank line and
* closing line to be indented.
* `emptyTags` (default is none)
* An array of XML tag names that should be autoclosed with '/>'.
*
* See demos/closetag.html for a usage example.
*/
(function(mod) {
mod(codemirror, xmlFold);
})(function(CodeMirror) {
CodeMirror.defineOption("autoCloseTags", false, function(cm, val, old) {
if (old != CodeMirror.Init && old)
cm.removeKeyMap("autoCloseTags");
if (!val) return;
var map = {name: "autoCloseTags"};
if (typeof val != "object" || val.whenClosing !== false)
map["'/'"] = function(cm) { return autoCloseSlash(cm); };
if (typeof val != "object" || val.whenOpening !== false)
map["'>'"] = function(cm) { return autoCloseGT(cm); };
cm.addKeyMap(map);
});
var htmlDontClose = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param",
"source", "track", "wbr"];
var htmlIndent = ["applet", "blockquote", "body", "button", "div", "dl", "fieldset", "form", "frameset", "h1", "h2", "h3", "h4",
"h5", "h6", "head", "html", "iframe", "layer", "legend", "object", "ol", "p", "select", "table", "ul"];
function autoCloseGT(cm) {
if (cm.getOption("disableInput")) return CodeMirror.Pass;
var ranges = cm.listSelections(), replacements = [];
var opt = cm.getOption("autoCloseTags");
for (var i = 0; i < ranges.length; i++) {
if (!ranges[i].empty()) return CodeMirror.Pass;
var pos = ranges[i].head, tok = cm.getTokenAt(pos);
var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;
var tagInfo = inner.mode.xmlCurrentTag && inner.mode.xmlCurrentTag(state);
var tagName = tagInfo && tagInfo.name;
if (!tagName) return CodeMirror.Pass
var html = inner.mode.configuration == "html";
var dontCloseTags = (typeof opt == "object" && opt.dontCloseTags) || (html && htmlDontClose);
var indentTags = (typeof opt == "object" && opt.indentTags) || (html && htmlIndent);
if (tok.end > pos.ch) tagName = tagName.slice(0, tagName.length - tok.end + pos.ch);
var lowerTagName = tagName.toLowerCase();
// Don't process the '>' at the end of an end-tag or self-closing tag
if (!tagName ||
tok.type == "string" && (tok.end != pos.ch || !/[\"\']/.test(tok.string.charAt(tok.string.length - 1)) || tok.string.length == 1) ||
tok.type == "tag" && tagInfo.close ||
tok.string.indexOf("/") == (pos.ch - tok.start - 1) || // match something like <someTagName />
dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1 ||
closingTagExists(cm, inner.mode.xmlCurrentContext && inner.mode.xmlCurrentContext(state) || [], tagName, pos, true))
return CodeMirror.Pass;
var emptyTags = typeof opt == "object" && opt.emptyTags;
if (emptyTags && indexOf(emptyTags, tagName) > -1) {
replacements[i] = { text: "/>", newPos: CodeMirror.Pos(pos.line, pos.ch + 2) };
continue;
}
var indent = indentTags && indexOf(indentTags, lowerTagName) > -1;
replacements[i] = {indent: indent,
text: ">" + (indent ? "\n\n" : "") + "</" + tagName + ">",
newPos: indent ? CodeMirror.Pos(pos.line + 1, 0) : CodeMirror.Pos(pos.line, pos.ch + 1)};
}
var dontIndentOnAutoClose = (typeof opt == "object" && opt.dontIndentOnAutoClose);
for (var i = ranges.length - 1; i >= 0; i--) {
var info = replacements[i];
cm.replaceRange(info.text, ranges[i].head, ranges[i].anchor, "+insert");
var sel = cm.listSelections().slice(0);
sel[i] = {head: info.newPos, anchor: info.newPos};
cm.setSelections(sel);
if (!dontIndentOnAutoClose && info.indent) {
cm.indentLine(info.newPos.line, null, true);
cm.indentLine(info.newPos.line + 1, null, true);
}
}
}
function autoCloseCurrent(cm, typingSlash) {
var ranges = cm.listSelections(), replacements = [];
var head = typingSlash ? "/" : "</";
var opt = cm.getOption("autoCloseTags");
var dontIndentOnAutoClose = (typeof opt == "object" && opt.dontIndentOnSlash);
for (var i = 0; i < ranges.length; i++) {
if (!ranges[i].empty()) return CodeMirror.Pass;
var pos = ranges[i].head, tok = cm.getTokenAt(pos);
var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;
if (typingSlash && (tok.type == "string" || tok.string.charAt(0) != "<" ||
tok.start != pos.ch - 1))
return CodeMirror.Pass;
// Kludge to get around the fact that we are not in XML mode
// when completing in JS/CSS snippet in htmlmixed mode. Does not
// work for other XML embedded languages (there is no general
// way to go from a mixed mode to its current XML state).
var replacement, mixed = inner.mode.name != "xml" && cm.getMode().name == "htmlmixed";
if (mixed && inner.mode.name == "javascript") {
replacement = head + "script";
} else if (mixed && inner.mode.name == "css") {
replacement = head + "style";
} else {
var context = inner.mode.xmlCurrentContext && inner.mode.xmlCurrentContext(state);
if (!context || (context.length && closingTagExists(cm, context, context[context.length - 1], pos)))
return CodeMirror.Pass;
replacement = head + context[context.length - 1];
}
if (cm.getLine(pos.line).charAt(tok.end) != ">") replacement += ">";
replacements[i] = replacement;
}
cm.replaceSelections(replacements);
ranges = cm.listSelections();
if (!dontIndentOnAutoClose) {
for (var i = 0; i < ranges.length; i++)
if (i == ranges.length - 1 || ranges[i].head.line < ranges[i + 1].head.line)
cm.indentLine(ranges[i].head.line);
}
}
function autoCloseSlash(cm) {
if (cm.getOption("disableInput")) return CodeMirror.Pass;
return autoCloseCurrent(cm, true);
}
CodeMirror.commands.closeTag = function(cm) { return autoCloseCurrent(cm); };
function indexOf(collection, elt) {
if (collection.indexOf) return collection.indexOf(elt);
for (var i = 0, e = collection.length; i < e; ++i)
if (collection[i] == elt) return i;
return -1;
}
// If xml-fold is loaded, we use its functionality to try and verify
// whether a given tag is actually unclosed.
function closingTagExists(cm, context, tagName, pos, newTag) {
if (!CodeMirror.scanForClosingTag) return false;
var end = Math.min(cm.lastLine() + 1, pos.line + 500);
var nextClose = CodeMirror.scanForClosingTag(cm, pos, null, end);
if (!nextClose || nextClose.tag != tagName) return false;
// If the immediate wrapping context contains onCx instances of
// the same tag, a closing tag only exists if there are at least
// that many closing tags of that type following.
var onCx = newTag ? 1 : 0;
for (var i = context.length - 1; i >= 0; i--) {
if (context[i] == tagName) ++onCx;
else break
}
pos = nextClose.to;
for (var i = 1; i < onCx; i++) {
var next = CodeMirror.scanForClosingTag(cm, pos, null, end);
if (!next || next.tag != tagName) return false;
pos = next.to;
}
return true;
}
});
});
var matchtags = createCommonjsModule(function (module, exports) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
mod(codemirror, xmlFold);
})(function(CodeMirror) {
CodeMirror.defineOption("matchTags", false, function(cm, val, old) {
if (old && old != CodeMirror.Init) {
cm.off("cursorActivity", doMatchTags);
cm.off("viewportChange", maybeUpdateMatch);
clear(cm);
}
if (val) {
cm.state.matchBothTags = typeof val == "object" && val.bothTags;
cm.on("cursorActivity", doMatchTags);
cm.on("viewportChange", maybeUpdateMatch);
doMatchTags(cm);
}
});
function clear(cm) {
if (cm.state.tagHit) cm.state.tagHit.clear();
if (cm.state.tagOther) cm.state.tagOther.clear();
cm.state.tagHit = cm.state.tagOther = null;
}
function doMatchTags(cm) {
cm.state.failedTagMatch = false;
cm.operation(function() {
clear(cm);
if (cm.somethingSelected()) return;
var cur = cm.getCursor(), range = cm.getViewport();
range.from = Math.min(range.from, cur.line); range.to = Math.max(cur.line + 1, range.to);
var match = CodeMirror.findMatchingTag(cm, cur, range);
if (!match) return;
if (cm.state.matchBothTags) {
var hit = match.at == "open" ? match.open : match.close;
if (hit) cm.state.tagHit = cm.markText(hit.from, hit.to, {className: "CodeMirror-matchingtag"});
}
var other = match.at == "close" ? match.open : match.close;
if (other)
cm.state.tagOther = cm.markText(other.from, other.to, {className: "CodeMirror-matchingtag"});
else
cm.state.failedTagMatch = true;
});
}
function maybeUpdateMatch(cm) {
if (cm.state.failedTagMatch) doMatchTags(cm);
}
CodeMirror.commands.toMatchingTag = function(cm) {
var found = CodeMirror.findMatchingTag(cm, cm.getCursor());
if (found) {
var other = found.at == "close" ? found.open : found.close;
if (other) cm.extendSelection(other.to, other.from);
}
};
});
});
var searchcursor = createCommonjsModule(function (module, exports) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
mod(codemirror);
})(function(CodeMirror) {
var Pos = CodeMirror.Pos;
function regexpFlags(regexp) {
var flags = regexp.flags;
return flags != null ? flags : (regexp.ignoreCase ? "i" : "")
+ (regexp.global ? "g" : "")
+ (regexp.multiline ? "m" : "")
}
function ensureFlags(regexp, flags) {
var current = regexpFlags(regexp), target = current;
for (var i = 0; i < flags.length; i++) if (target.indexOf(flags.charAt(i)) == -1)
target += flags.charAt(i);
return current == target ? regexp : new RegExp(regexp.source, target)
}
function maybeMultiline(regexp) {
return /\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source)
}
function searchRegexpForward(doc, regexp, start) {
regexp = ensureFlags(regexp, "g");
for (var line = start.line, ch = start.ch, last = doc.lastLine(); line <= last; line++, ch = 0) {
regexp.lastIndex = ch;
var string = doc.getLine(line), match = regexp.exec(string);
if (match)
return {from: Pos(line, match.index),
to: Pos(line, match.index + match[0].length),
match: match}
}
}
function searchRegexpForwardMultiline(doc, regexp, start) {
if (!maybeMultiline(regexp)) return searchRegexpForward(doc, regexp, start)
regexp = ensureFlags(regexp, "gm");
var string, chunk = 1;
for (var line = start.line, last = doc.lastLine(); line <= last;) {
// This grows the search buffer in exponentially-sized chunks
// between matches, so that nearby matches are fast and don't
// require concatenating the whole document (in case we're
// searching for something that has tons of matches), but at the
// same time, the amount of retries is limited.
for (var i = 0; i < chunk; i++) {
if (line > last) break
var curLine = doc.getLine(line++);
string = string == null ? curLine : string + "\n" + curLine;
}
chunk = chunk * 2;
regexp.lastIndex = start.ch;
var match = regexp.exec(string);
if (match) {
var before = string.slice(0, match.index).split("\n"), inside = match[0].split("\n");
var startLine = start.line + before.length - 1, startCh = before[before.length - 1].length;
return {from: Pos(startLine, startCh),
to: Pos(startLine + inside.length - 1,
inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length),
match: match}
}
}
}
function lastMatchIn(string, regexp, endMargin) {
var match, from = 0;
while (from <= string.length) {
regexp.lastIndex = from;
var newMatch = regexp.exec(string);
if (!newMatch) break
var end = newMatch.index + newMatch[0].length;
if (end > string.length - endMargin) break
if (!match || end > match.index + match[0].length)
match = newMatch;
from = newMatch.index + 1;
}
return match
}
function searchRegexpBackward(doc, regexp, start) {
regexp = ensureFlags(regexp, "g");
for (var line = start.line, ch = start.ch, first = doc.firstLine(); line >= first; line--, ch = -1) {
var string = doc.getLine(line);
var match = lastMatchIn(string, regexp, ch < 0 ? 0 : string.length - ch);
if (match)
return {from: Pos(line, match.index),
to: Pos(line, match.index + match[0].length),
match: match}
}
}
function searchRegexpBackwardMultiline(doc, regexp, start) {
if (!maybeMultiline(regexp)) return searchRegexpBackward(doc, regexp, start)
regexp = ensureFlags(regexp, "gm");
var string, chunkSize = 1, endMargin = doc.getLine(start.line).length - start.ch;
for (var line = start.line, first = doc.firstLine(); line >= first;) {
for (var i = 0; i < chunkSize && line >= first; i++) {
var curLine = doc.getLine(line--);
string = string == null ? curLine : curLine + "\n" + string;
}
chunkSize *= 2;
var match = lastMatchIn(string, regexp, endMargin);
if (match) {
var before = string.slice(0, match.index).split("\n"), inside = match[0].split("\n");
var startLine = line + before.length, startCh = before[before.length - 1].length;
return {from: Pos(startLine, startCh),
to: Pos(startLine + inside.length - 1,
inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length),
match: match}
}
}
}
var doFold, noFold;
if (String.prototype.normalize) {
doFold = function(str) { return str.normalize("NFD").toLowerCase() };
noFold = function(str) { return str.normalize("NFD") };
} else {
doFold = function(str) { return str.toLowerCase() };
noFold = function(str) { return str };
}
// Maps a position in a case-folded line back to a position in the original line
// (compensating for codepoints increasing in number during folding)
function adjustPos(orig, folded, pos, foldFunc) {
if (orig.length == folded.length) return pos
for (var min = 0, max = pos + Math.max(0, orig.length - folded.length);;) {
if (min == max) return min
var mid = (min + max) >> 1;
var len = foldFunc(orig.slice(0, mid)).length;
if (len == pos) return mid
else if (len > pos) max = mid;
else min = mid + 1;
}
}
function searchStringForward(doc, query, start, caseFold) {
// Empty string would match anything and never progress, so we
// define it to match nothing instead.
if (!query.length) return null
var fold = caseFold ? doFold : noFold;
var lines = fold(query).split(/\r|\n\r?/);
search: for (var line = start.line, ch = start.ch, last = doc.lastLine() + 1 - lines.length; line <= last; line++, ch = 0) {
var orig = doc.getLine(line).slice(ch), string = fold(orig);
if (lines.length == 1) {
var found = string.indexOf(lines[0]);
if (found == -1) continue search
var start = adjustPos(orig, string, found, fold) + ch;
return {from: Pos(line, adjustPos(orig, string, found, fold) + ch),
to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold) + ch)}
} else {
var cutFrom = string.length - lines[0].length;
if (string.slice(cutFrom) != lines[0]) continue search
for (var i = 1; i < lines.length - 1; i++)
if (fold(doc.getLine(line + i)) != lines[i]) continue search
var end = doc.getLine(line + lines.length - 1), endString = fold(end), lastLine = lines[lines.length - 1];
if (endString.slice(0, lastLine.length) != lastLine) continue search
return {from: Pos(line, adjustPos(orig, string, cutFrom, fold) + ch),
to: Pos(line + lines.length - 1, adjustPos(end, endString, lastLine.length, fold))}
}
}
}
function searchStringBackward(doc, query, start, caseFold) {
if (!query.length) return null
var fold = caseFold ? doFold : noFold;
var lines = fold(query).split(/\r|\n\r?/);
search: for (var line = start.line, ch = start.ch, first = doc.firstLine() - 1 + lines.length; line >= first; line--, ch = -1) {
var orig = doc.getLine(line);
if (ch > -1) orig = orig.slice(0, ch);
var string = fold(orig);
if (lines.length == 1) {
var found = string.lastIndexOf(lines[0]);
if (found == -1) continue search
return {from: Pos(line, adjustPos(orig, string, found, fold)),
to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold))}
} else {
var lastLine = lines[lines.length - 1];
if (string.slice(0, lastLine.length) != lastLine) continue search
for (var i = 1, start = line - lines.length + 1; i < lines.length - 1; i++)
if (fold(doc.getLine(start + i)) != lines[i]) continue search
var top = doc.getLine(line + 1 - lines.length), topString = fold(top);
if (topString.slice(topString.length - lines[0].length) != lines[0]) continue search
return {from: Pos(line + 1 - lines.length, adjustPos(top, topString, top.length - lines[0].length, fold)),
to: Pos(line, adjustPos(orig, string, lastLine.length, fold))}
}
}
}
function SearchCursor(doc, query, pos, options) {
this.atOccurrence = false;
this.doc = doc;
pos = pos ? doc.clipPos(pos) : Pos(0, 0);
this.pos = {from: pos, to: pos};
var caseFold;
if (typeof options == "object") {
caseFold = options.caseFold;
} else { // Backwards compat for when caseFold was the 4th argument
caseFold = options;
options = null;
}
if (typeof query == "string") {
if (caseFold == null) caseFold = false;
this.matches = function(reverse, pos) {
return (reverse ? searchStringBackward : searchStringForward)(doc, query, pos, caseFold)
};
} else {
query = ensureFlags(query, "gm");
if (!options || options.multiline !== false)
this.matches = function(reverse, pos) {
return (reverse ? searchRegexpBackwardMultiline : searchRegexpForwardMultiline)(doc, query, pos)
};
else
this.matches = function(reverse, pos) {
return (reverse ? searchRegexpBackward : searchRegexpForward)(doc, query, pos)
};
}
}
SearchCursor.prototype = {
findNext: function() {return this.find(false)},
findPrevious: function() {return this.find(true)},
find: function(reverse) {
var result = this.matches(reverse, this.doc.clipPos(reverse ? this.pos.from : this.pos.to));
// Implements weird auto-growing behavior on null-matches for
// backwards-compatibility with the vim code (unfortunately)
while (result && CodeMirror.cmpPos(result.from, result.to) == 0) {
if (reverse) {
if (result.from.ch) result.from = Pos(result.from.line, result.from.ch - 1);
else if (result.from.line == this.doc.firstLine()) result = null;
else result = this.matches(reverse, this.doc.clipPos(Pos(result.from.line - 1)));
} else {
if (result.to.ch < this.doc.getLine(result.to.line).length) result.to = Pos(result.to.line, result.to.ch + 1);
else if (result.to.line == this.doc.lastLine()) result = null;
else result = this.matches(reverse, Pos(result.to.line + 1, 0));
}
}
if (result) {
this.pos = result;
this.atOccurrence = true;
return this.pos.match || true
} else {
var end = Pos(reverse ? this.doc.firstLine() : this.doc.lastLine() + 1, 0);
this.pos = {from: end, to: end};
return this.atOccurrence = false
}
},
from: function() {if (this.atOccurrence) return this.pos.from},
to: function() {if (this.atOccurrence) return this.pos.to},
replace: function(newText, origin) {
if (!this.atOccurrence) return
var lines = CodeMirror.splitLines(newText);
this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin);
this.pos.to = Pos(this.pos.from.line + lines.length - 1,
lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0));
}
};
CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
return new SearchCursor(this.doc, query, pos, caseFold)
});
CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) {
return new SearchCursor(this, query, pos, caseFold)
});
CodeMirror.defineExtension("selectMatches", function(query, caseFold) {
var ranges = [];
var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold);
while (cur.findNext()) {
if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break
ranges.push({anchor: cur.from(), head: cur.to()});
}
if (ranges.length)
this.setSelections(ranges, 0);
});
});
});
var placeholder = createCommonjsModule(function (module, exports) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
mod(codemirror);
})(function(CodeMirror) {
CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
var prev = old && old != CodeMirror.Init;
if (val && !prev) {
cm.on("blur", onBlur);
cm.on("change", onChange);
cm.on("swapDoc", onChange);
CodeMirror.on(cm.getInputField(), "compositionupdate", cm.state.placeholderCompose = function() { onComposition(cm); });
onChange(cm);
} else if (!val && prev) {
cm.off("blur", onBlur);
cm.off("change", onChange);
cm.off("swapDoc", onChange);
CodeMirror.off(cm.getInputField(), "compositionupdate", cm.state.placeholderCompose);
clearPlaceholder(cm);
var wrapper = cm.getWrapperElement();
wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
}
if (val && !cm.hasFocus()) onBlur(cm);
});
function clearPlaceholder(cm) {
if (cm.state.placeholder) {
cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
cm.state.placeholder = null;
}
}
function setPlaceholder(cm) {
clearPlaceholder(cm);
var elt = cm.state.placeholder = document.createElement("pre");
elt.style.cssText = "height: 0; overflow: visible";
elt.style.direction = cm.getOption("direction");
elt.className = "CodeMirror-placeholder CodeMirror-line-like";
var placeHolder = cm.getOption("placeholder");
if (typeof placeHolder == "string") placeHolder = document.createTextNode(placeHolder);
elt.appendChild(placeHolder);
cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
}
function onComposition(cm) {
setTimeout(function() {
var empty = false, input = cm.getInputField();
if (input.nodeName == "TEXTAREA")
empty = !input.value;
else if (cm.lineCount() == 1)
empty = !/[^\u200b]/.test(input.querySelector(".CodeMirror-line").textContent);
if (empty) setPlaceholder(cm);
else clearPlaceholder(cm);
}, 20);
}
function onBlur(cm) {
if (isEmpty(cm)) setPlaceholder(cm);
}
function onChange(cm) {
var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
if (empty) setPlaceholder(cm);
else clearPlaceholder(cm);
}
function isEmpty(cm) {
return (cm.lineCount() === 1) && (cm.getLine(0) === "");
}
});
});
var matchbrackets = createCommonjsModule(function (module, exports) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
mod(codemirror);
})(function(CodeMirror) {
var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
(document.documentMode == null || document.documentMode < 8);
var Pos = CodeMirror.Pos;
var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<", "<": ">>", ">": "<<"};
function bracketRegex(config) {
return config && config.bracketRegex || /[(){}[\]]/
}
function findMatchingBracket(cm, where, config) {
var line = cm.getLineHandle(where.line), pos = where.ch - 1;
var afterCursor = config && config.afterCursor;
if (afterCursor == null)
afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className);
var re = bracketRegex(config);
// A cursor is defined as between two characters, but in in vim command mode
// (i.e. not insert mode), the cursor is visually represented as a
// highlighted box on top of the 2nd character. Otherwise, we allow matches
// from before or after the cursor.
var match = (!afterCursor && pos >= 0 && re.test(line.text.charAt(pos)) && matching[line.text.charAt(pos)]) ||
re.test(line.text.charAt(pos + 1)) && matching[line.text.charAt(++pos)];
if (!match) return null;
var dir = match.charAt(1) == ">" ? 1 : -1;
if (config && config.strict && (dir > 0) != (pos == where.ch)) return null;
var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));
var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config);
if (found == null) return null;
return {from: Pos(where.line, pos), to: found && found.pos,
match: found && found.ch == match.charAt(0), forward: dir > 0};
}
// bracketRegex is used to specify which type of bracket to scan
// should be a regexp, e.g. /[[\]]/
//
// Note: If "where" is on an open bracket, then this bracket is ignored.
//
// Returns false when no bracket was found, null when it reached
// maxScanLines and gave up
function scanForBracket(cm, where, dir, style, config) {
var maxScanLen = (config && config.maxScanLineLength) || 10000;
var maxScanLines = (config && config.maxScanLines) || 1000;
var stack = [];
var re = bracketRegex(config);
var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1)
: Math.max(cm.firstLine() - 1, where.line - maxScanLines);
for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) {
var line = cm.getLine(lineNo);
if (!line) continue;
var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1;
if (line.length > maxScanLen) continue;
if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0);
for (; pos != end; pos += dir) {
var ch = line.charAt(pos);
if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) {
var match = matching[ch];
if (match && (match.charAt(1) == ">") == (dir > 0)) stack.push(ch);
else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch};
else stack.pop();
}
}
}
return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;
}
function matchBrackets(cm, autoclear, config) {
// Disable brace matching in long lines, since it'll cause hugely slow updates
var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;
var marks = [], ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, config);
if (match && cm.getLine(match.from.line).length <= maxHighlightLen) {
var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style}));
if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen)
marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style}));
}
}
if (marks.length) {
// Kludge to work around the IE bug from issue #1193, where text
// input stops going to the textare whever this fires.
if (ie_lt8 && cm.state.focused) cm.focus();
var clear = function() {
cm.operation(function() {
for (var i = 0; i < marks.length; i++) marks[i].clear();
});
};
if (autoclear) setTimeout(clear, 800);
else return clear;
}
}
function doMatchBrackets(cm) {
cm.operation(function() {
if (cm.state.matchBrackets.currentlyHighlighted) {
cm.state.matchBrackets.currentlyHighlighted();
cm.state.matchBrackets.currentlyHighlighted = null;
}
cm.state.matchBrackets.currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);
});
}
CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
function clear(cm) {
if (cm.state.matchBrackets && cm.state.matchBrackets.currentlyHighlighted) {
cm.state.matchBrackets.currentlyHighlighted();
cm.state.matchBrackets.currentlyHighlighted = null;
}
}
if (old && old != CodeMirror.Init) {
cm.off("cursorActivity", doMatchBrackets);
cm.off("focus", doMatchBrackets);
cm.off("blur", clear);
clear(cm);
}
if (val) {
cm.state.matchBrackets = typeof val == "object" ? val : {};
cm.on("cursorActivity", doMatchBrackets);
cm.on("focus", doMatchBrackets);
cm.on("blur", clear);
}
});
CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);});
CodeMirror.defineExtension("findMatchingBracket", function(pos, config, oldConfig){
// Backwards-compatibility kludge
if (oldConfig || typeof config == "boolean") {
if (!oldConfig) {
config = config ? {strict: true} : null;
} else {
oldConfig.strict = config;
config = oldConfig;
}
}
return findMatchingBracket(this, pos, config)
});
CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){
return scanForBracket(this, pos, dir, style, config);
});
});
});
var sublime = createCommonjsModule(function (module, exports) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
// A rough approximation of Sublime Text's keybindings
// Depends on addon/search/searchcursor.js and optionally addon/dialog/dialogs.js
(function(mod) {
mod(codemirror, searchcursor, matchbrackets);
})(function(CodeMirror) {
var cmds = CodeMirror.commands;
var Pos = CodeMirror.Pos;
// This is not exactly Sublime's algorithm. I couldn't make heads or tails of that.
function findPosSubword(doc, start, dir) {
if (dir < 0 && start.ch == 0) return doc.clipPos(Pos(start.line - 1));
var line = doc.getLine(start.line);
if (dir > 0 && start.ch >= line.length) return doc.clipPos(Pos(start.line + 1, 0));
var state = "start", type, startPos = start.ch;
for (var pos = startPos, e = dir < 0 ? 0 : line.length, i = 0; pos != e; pos += dir, i++) {
var next = line.charAt(dir < 0 ? pos - 1 : pos);
var cat = next != "_" && CodeMirror.isWordChar(next) ? "w" : "o";
if (cat == "w" && next.toUpperCase() == next) cat = "W";
if (state == "start") {
if (cat != "o") { state = "in"; type = cat; }
else startPos = pos + dir;
} else if (state == "in") {
if (type != cat) {
if (type == "w" && cat == "W" && dir < 0) pos--;
if (type == "W" && cat == "w" && dir > 0) { // From uppercase to lowercase
if (pos == startPos + 1) { type = "w"; continue; }
else pos--;
}
break;
}
}
}
return Pos(start.line, pos);
}
function moveSubword(cm, dir) {
cm.extendSelectionsBy(function(range) {
if (cm.display.shift || cm.doc.extend || range.empty())
return findPosSubword(cm.doc, range.head, dir);
else
return dir < 0 ? range.from() : range.to();
});
}
cmds.goSubwordLeft = function(cm) { moveSubword(cm, -1); };
cmds.goSubwordRight = function(cm) { moveSubword(cm, 1); };
cmds.scrollLineUp = function(cm) {
var info = cm.getScrollInfo();
if (!cm.somethingSelected()) {
var visibleBottomLine = cm.lineAtHeight(info.top + info.clientHeight, "local");
if (cm.getCursor().line >= visibleBottomLine)
cm.execCommand("goLineUp");
}
cm.scrollTo(null, info.top - cm.defaultTextHeight());
};
cmds.scrollLineDown = function(cm) {
var info = cm.getScrollInfo();
if (!cm.somethingSelected()) {
var visibleTopLine = cm.lineAtHeight(info.top, "local")+1;
if (cm.getCursor().line <= visibleTopLine)
cm.execCommand("goLineDown");
}
cm.scrollTo(null, info.top + cm.defaultTextHeight());
};
cmds.splitSelectionByLine = function(cm) {
var ranges = cm.listSelections(), lineRanges = [];
for (var i = 0; i < ranges.length; i++) {
var from = ranges[i].from(), to = ranges[i].to();
for (var line = from.line; line <= to.line; ++line)
if (!(to.line > from.line && line == to.line && to.ch == 0))
lineRanges.push({anchor: line == from.line ? from : Pos(line, 0),
head: line == to.line ? to : Pos(line)});
}
cm.setSelections(lineRanges, 0);
};
cmds.singleSelectionTop = function(cm) {
var range = cm.listSelections()[0];
cm.setSelection(range.anchor, range.head, {scroll: false});
};
cmds.selectLine = function(cm) {
var ranges = cm.listSelections(), extended = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
extended.push({anchor: Pos(range.from().line, 0),
head: Pos(range.to().line + 1, 0)});
}
cm.setSelections(extended);
};
function insertLine(cm, above) {
if (cm.isReadOnly()) return CodeMirror.Pass
cm.operation(function() {
var len = cm.listSelections().length, newSelection = [], last = -1;
for (var i = 0; i < len; i++) {
var head = cm.listSelections()[i].head;
if (head.line <= last) continue;
var at = Pos(head.line + (above ? 0 : 1), 0);
cm.replaceRange("\n", at, null, "+insertLine");
cm.indentLine(at.line, null, true);
newSelection.push({head: at, anchor: at});
last = head.line + 1;
}
cm.setSelections(newSelection);
});
cm.execCommand("indentAuto");
}
cmds.insertLineAfter = function(cm) { return insertLine(cm, false); };
cmds.insertLineBefore = function(cm) { return insertLine(cm, true); };
function wordAt(cm, pos) {
var start = pos.ch, end = start, line = cm.getLine(pos.line);
while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start;
while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) ++end;
return {from: Pos(pos.line, start), to: Pos(pos.line, end), word: line.slice(start, end)};
}
cmds.selectNextOccurrence = function(cm) {
var from = cm.getCursor("from"), to = cm.getCursor("to");
var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel;
if (CodeMirror.cmpPos(from, to) == 0) {
var word = wordAt(cm, from);
if (!word.word) return;
cm.setSelection(word.from, word.to);
fullWord = true;
} else {
var text = cm.getRange(from, to);
var query = fullWord ? new RegExp("\\b" + text + "\\b") : text;
var cur = cm.getSearchCursor(query, to);
var found = cur.findNext();
if (!found) {
cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0));
found = cur.findNext();
}
if (!found || isSelectedRange(cm.listSelections(), cur.from(), cur.to())) return
cm.addSelection(cur.from(), cur.to());
}
if (fullWord)
cm.state.sublimeFindFullWord = cm.doc.sel;
};
cmds.skipAndSelectNextOccurrence = function(cm) {
var prevAnchor = cm.getCursor("anchor"), prevHead = cm.getCursor("head");
cmds.selectNextOccurrence(cm);
if (CodeMirror.cmpPos(prevAnchor, prevHead) != 0) {
cm.doc.setSelections(cm.doc.listSelections()
.filter(function (sel) {
return sel.anchor != prevAnchor || sel.head != prevHead;
}));
}
};
function addCursorToSelection(cm, dir) {
var ranges = cm.listSelections(), newRanges = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
var newAnchor = cm.findPosV(
range.anchor, dir, "line", range.anchor.goalColumn);
var newHead = cm.findPosV(
range.head, dir, "line", range.head.goalColumn);
newAnchor.goalColumn = range.anchor.goalColumn != null ?
range.anchor.goalColumn : cm.cursorCoords(range.anchor, "div").left;
newHead.goalColumn = range.head.goalColumn != null ?
range.head.goalColumn : cm.cursorCoords(range.head, "div").left;
var newRange = {anchor: newAnchor, head: newHead};
newRanges.push(range);
newRanges.push(newRange);
}
cm.setSelections(newRanges);
}
cmds.addCursorToPrevLine = function(cm) { addCursorToSelection(cm, -1); };
cmds.addCursorToNextLine = function(cm) { addCursorToSelection(cm, 1); };
function isSelectedRange(ranges, from, to) {
for (var i = 0; i < ranges.length; i++)
if (CodeMirror.cmpPos(ranges[i].from(), from) == 0 &&
CodeMirror.cmpPos(ranges[i].to(), to) == 0) return true
return false
}
var mirror = "(){}[]";
function selectBetweenBrackets(cm) {
var ranges = cm.listSelections(), newRanges = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i], pos = range.head, opening = cm.scanForBracket(pos, -1);
if (!opening) return false;
for (;;) {
var closing = cm.scanForBracket(pos, 1);
if (!closing) return false;
if (closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1)) {
var startPos = Pos(opening.pos.line, opening.pos.ch + 1);
if (CodeMirror.cmpPos(startPos, range.from()) == 0 &&
CodeMirror.cmpPos(closing.pos, range.to()) == 0) {
opening = cm.scanForBracket(opening.pos, -1);
if (!opening) return false;
} else {
newRanges.push({anchor: startPos, head: closing.pos});
break;
}
}
pos = Pos(closing.pos.line, closing.pos.ch + 1);
}
}
cm.setSelections(newRanges);
return true;
}
cmds.selectScope = function(cm) {
selectBetweenBrackets(cm) || cm.execCommand("selectAll");
};
cmds.selectBetweenBrackets = function(cm) {
if (!selectBetweenBrackets(cm)) return CodeMirror.Pass;
};
function puncType(type) {
return !type ? null : /\bpunctuation\b/.test(type) ? type : undefined
}
cmds.goToBracket = function(cm) {
cm.extendSelectionsBy(function(range) {
var next = cm.scanForBracket(range.head, 1, puncType(cm.getTokenTypeAt(range.head)));
if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) return next.pos;
var prev = cm.scanForBracket(range.head, -1, puncType(cm.getTokenTypeAt(Pos(range.head.line, range.head.ch + 1))));
return prev && Pos(prev.pos.line, prev.pos.ch + 1) || range.head;
});
};
cmds.swapLineUp = function(cm) {
if (cm.isReadOnly()) return CodeMirror.Pass
var ranges = cm.listSelections(), linesToMove = [], at = cm.firstLine() - 1, newSels = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i], from = range.from().line - 1, to = range.to().line;
newSels.push({anchor: Pos(range.anchor.line - 1, range.anchor.ch),
head: Pos(range.head.line - 1, range.head.ch)});
if (range.to().ch == 0 && !range.empty()) --to;
if (from > at) linesToMove.push(from, to);
else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to;
at = to;
}
cm.operation(function() {
for (var i = 0; i < linesToMove.length; i += 2) {
var from = linesToMove[i], to = linesToMove[i + 1];
var line = cm.getLine(from);
cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine");
if (to > cm.lastLine())
cm.replaceRange("\n" + line, Pos(cm.lastLine()), null, "+swapLine");
else
cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine");
}
cm.setSelections(newSels);
cm.scrollIntoView();
});
};
cmds.swapLineDown = function(cm) {
if (cm.isReadOnly()) return CodeMirror.Pass
var ranges = cm.listSelections(), linesToMove = [], at = cm.lastLine() + 1;
for (var i = ranges.length - 1; i >= 0; i--) {
var range = ranges[i], from = range.to().line + 1, to = range.from().line;
if (range.to().ch == 0 && !range.empty()) from--;
if (from < at) linesToMove.push(from, to);
else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to;
at = to;
}
cm.operation(function() {
for (var i = linesToMove.length - 2; i >= 0; i -= 2) {
var from = linesToMove[i], to = linesToMove[i + 1];
var line = cm.getLine(from);
if (from == cm.lastLine())
cm.replaceRange("", Pos(from - 1), Pos(from), "+swapLine");
else
cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine");
cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine");
}
cm.scrollIntoView();
});
};
cmds.toggleCommentIndented = function(cm) {
cm.toggleComment({ indent: true });
};
cmds.joinLines = function(cm) {
var ranges = cm.listSelections(), joined = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i], from = range.from();
var start = from.line, end = range.to().line;
while (i < ranges.length - 1 && ranges[i + 1].from().line == end)
end = ranges[++i].to().line;
joined.push({start: start, end: end, anchor: !range.empty() && from});
}
cm.operation(function() {
var offset = 0, ranges = [];
for (var i = 0; i < joined.length; i++) {
var obj = joined[i];
var anchor = obj.anchor && Pos(obj.anchor.line - offset, obj.anchor.ch), head;
for (var line = obj.start; line <= obj.end; line++) {
var actual = line - offset;
if (line == obj.end) head = Pos(actual, cm.getLine(actual).length + 1);
if (actual < cm.lastLine()) {
cm.replaceRange(" ", Pos(actual), Pos(actual + 1, /^\s*/.exec(cm.getLine(actual + 1))[0].length));
++offset;
}
}
ranges.push({anchor: anchor || head, head: head});
}
cm.setSelections(ranges, 0);
});
};
cmds.duplicateLine = function(cm) {
cm.operation(function() {
var rangeCount = cm.listSelections().length;
for (var i = 0; i < rangeCount; i++) {
var range = cm.listSelections()[i];
if (range.empty())
cm.replaceRange(cm.getLine(range.head.line) + "\n", Pos(range.head.line, 0));
else
cm.replaceRange(cm.getRange(range.from(), range.to()), range.from());
}
cm.scrollIntoView();
});
};
function sortLines(cm, caseSensitive) {
if (cm.isReadOnly()) return CodeMirror.Pass
var ranges = cm.listSelections(), toSort = [], selected;
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (range.empty()) continue;
var from = range.from().line, to = range.to().line;
while (i < ranges.length - 1 && ranges[i + 1].from().line == to)
to = ranges[++i].to().line;
if (!ranges[i].to().ch) to--;
toSort.push(from, to);
}
if (toSort.length) selected = true;
else toSort.push(cm.firstLine(), cm.lastLine());
cm.operation(function() {
var ranges = [];
for (var i = 0; i < toSort.length; i += 2) {
var from = toSort[i], to = toSort[i + 1];
var start = Pos(from, 0), end = Pos(to);
var lines = cm.getRange(start, end, false);
if (caseSensitive)
lines.sort();
else
lines.sort(function(a, b) {
var au = a.toUpperCase(), bu = b.toUpperCase();
if (au != bu) { a = au; b = bu; }
return a < b ? -1 : a == b ? 0 : 1;
});
cm.replaceRange(lines, start, end);
if (selected) ranges.push({anchor: start, head: Pos(to + 1, 0)});
}
if (selected) cm.setSelections(ranges, 0);
});
}
cmds.sortLines = function(cm) { sortLines(cm, true); };
cmds.sortLinesInsensitive = function(cm) { sortLines(cm, false); };
cmds.nextBookmark = function(cm) {
var marks = cm.state.sublimeBookmarks;
if (marks) while (marks.length) {
var current = marks.shift();
var found = current.find();
if (found) {
marks.push(current);
return cm.setSelection(found.from, found.to);
}
}
};
cmds.prevBookmark = function(cm) {
var marks = cm.state.sublimeBookmarks;
if (marks) while (marks.length) {
marks.unshift(marks.pop());
var found = marks[marks.length - 1].find();
if (!found)
marks.pop();
else
return cm.setSelection(found.from, found.to);
}
};
cmds.toggleBookmark = function(cm) {
var ranges = cm.listSelections();
var marks = cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []);
for (var i = 0; i < ranges.length; i++) {
var from = ranges[i].from(), to = ranges[i].to();
var found = ranges[i].empty() ? cm.findMarksAt(from) : cm.findMarks(from, to);
for (var j = 0; j < found.length; j++) {
if (found[j].sublimeBookmark) {
found[j].clear();
for (var k = 0; k < marks.length; k++)
if (marks[k] == found[j])
marks.splice(k--, 1);
break;
}
}
if (j == found.length)
marks.push(cm.markText(from, to, {sublimeBookmark: true, clearWhenEmpty: false}));
}
};
cmds.clearBookmarks = function(cm) {
var marks = cm.state.sublimeBookmarks;
if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear();
marks.length = 0;
};
cmds.selectBookmarks = function(cm) {
var marks = cm.state.sublimeBookmarks, ranges = [];
if (marks) for (var i = 0; i < marks.length; i++) {
var found = marks[i].find();
if (!found)
marks.splice(i--, 0);
else
ranges.push({anchor: found.from, head: found.to});
}
if (ranges.length)
cm.setSelections(ranges, 0);
};
function modifyWordOrSelection(cm, mod) {
cm.operation(function() {
var ranges = cm.listSelections(), indices = [], replacements = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (range.empty()) { indices.push(i); replacements.push(""); }
else replacements.push(mod(cm.getRange(range.from(), range.to())));
}
cm.replaceSelections(replacements, "around", "case");
for (var i = indices.length - 1, at; i >= 0; i--) {
var range = ranges[indices[i]];
if (at && CodeMirror.cmpPos(range.head, at) > 0) continue;
var word = wordAt(cm, range.head);
at = word.from;
cm.replaceRange(mod(word.word), word.from, word.to);
}
});
}
cmds.smartBackspace = function(cm) {
if (cm.somethingSelected()) return CodeMirror.Pass;
cm.operation(function() {
var cursors = cm.listSelections();
var indentUnit = cm.getOption("indentUnit");
for (var i = cursors.length - 1; i >= 0; i--) {
var cursor = cursors[i].head;
var toStartOfLine = cm.getRange({line: cursor.line, ch: 0}, cursor);
var column = CodeMirror.countColumn(toStartOfLine, null, cm.getOption("tabSize"));
// Delete by one character by default
var deletePos = cm.findPosH(cursor, -1, "char", false);
if (toStartOfLine && !/\S/.test(toStartOfLine) && column % indentUnit == 0) {
var prevIndent = new Pos(cursor.line,
CodeMirror.findColumn(toStartOfLine, column - indentUnit, indentUnit));
// Smart delete only if we found a valid prevIndent location
if (prevIndent.ch != cursor.ch) deletePos = prevIndent;
}
cm.replaceRange("", deletePos, cursor, "+delete");
}
});
};
cmds.delLineRight = function(cm) {
cm.operation(function() {
var ranges = cm.listSelections();
for (var i = ranges.length - 1; i >= 0; i--)
cm.replaceRange("", ranges[i].anchor, Pos(ranges[i].to().line), "+delete");
cm.scrollIntoView();
});
};
cmds.upcaseAtCursor = function(cm) {
modifyWordOrSelection(cm, function(str) { return str.toUpperCase(); });
};
cmds.downcaseAtCursor = function(cm) {
modifyWordOrSelection(cm, function(str) { return str.toLowerCase(); });
};
cmds.setSublimeMark = function(cm) {
if (cm.state.sublimeMark) cm.state.sublimeMark.clear();
cm.state.sublimeMark = cm.setBookmark(cm.getCursor());
};
cmds.selectToSublimeMark = function(cm) {
var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
if (found) cm.setSelection(cm.getCursor(), found);
};
cmds.deleteToSublimeMark = function(cm) {
var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
if (found) {
var from = cm.getCursor(), to = found;
if (CodeMirror.cmpPos(from, to) > 0) { var tmp = to; to = from; from = tmp; }
cm.state.sublimeKilled = cm.getRange(from, to);
cm.replaceRange("", from, to);
}
};
cmds.swapWithSublimeMark = function(cm) {
var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
if (found) {
cm.state.sublimeMark.clear();
cm.state.sublimeMark = cm.setBookmark(cm.getCursor());
cm.setCursor(found);
}
};
cmds.sublimeYank = function(cm) {
if (cm.state.sublimeKilled != null)
cm.replaceSelection(cm.state.sublimeKilled, null, "paste");
};
cmds.showInCenter = function(cm) {
var pos = cm.cursorCoords(null, "local");
cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2);
};
function getTarget(cm) {
var from = cm.getCursor("from"), to = cm.getCursor("to");
if (CodeMirror.cmpPos(from, to) == 0) {
var word = wordAt(cm, from);
if (!word.word) return;
from = word.from;
to = word.to;
}
return {from: from, to: to, query: cm.getRange(from, to), word: word};
}
function findAndGoTo(cm, forward) {
var target = getTarget(cm);
if (!target) return;
var query = target.query;
var cur = cm.getSearchCursor(query, forward ? target.to : target.from);
if (forward ? cur.findNext() : cur.findPrevious()) {
cm.setSelection(cur.from(), cur.to());
} else {
cur = cm.getSearchCursor(query, forward ? Pos(cm.firstLine(), 0)
: cm.clipPos(Pos(cm.lastLine())));
if (forward ? cur.findNext() : cur.findPrevious())
cm.setSelection(cur.from(), cur.to());
else if (target.word)
cm.setSelection(target.from, target.to);
}
} cmds.findUnder = function(cm) { findAndGoTo(cm, true); };
cmds.findUnderPrevious = function(cm) { findAndGoTo(cm,false); };
cmds.findAllUnder = function(cm) {
var target = getTarget(cm);
if (!target) return;
var cur = cm.getSearchCursor(target.query);
var matches = [];
var primaryIndex = -1;
while (cur.findNext()) {
matches.push({anchor: cur.from(), head: cur.to()});
if (cur.from().line <= target.from.line && cur.from().ch <= target.from.ch)
primaryIndex++;
}
cm.setSelections(matches, primaryIndex);
};
var keyMap = CodeMirror.keyMap;
keyMap.macSublime = {
"Cmd-Left": "goLineStartSmart",
"Shift-Tab": "indentLess",
"Shift-Ctrl-K": "deleteLine",
"Alt-Q": "wrapLines",
"Ctrl-Left": "goSubwordLeft",
"Ctrl-Right": "goSubwordRight",
"Ctrl-Alt-Up": "scrollLineUp",
"Ctrl-Alt-Down": "scrollLineDown",
"Cmd-L": "selectLine",
"Shift-Cmd-L": "splitSelectionByLine",
"Esc": "singleSelectionTop",
"Cmd-Enter": "insertLineAfter",
"Shift-Cmd-Enter": "insertLineBefore",
"Cmd-D": "selectNextOccurrence",
"Shift-Cmd-Space": "selectScope",
"Shift-Cmd-M": "selectBetweenBrackets",
"Cmd-M": "goToBracket",
"Cmd-Ctrl-Up": "swapLineUp",
"Cmd-Ctrl-Down": "swapLineDown",
"Cmd-/": "toggleCommentIndented",
"Cmd-J": "joinLines",
"Shift-Cmd-D": "duplicateLine",
"F5": "sortLines",
"Cmd-F5": "sortLinesInsensitive",
"F2": "nextBookmark",
"Shift-F2": "prevBookmark",
"Cmd-F2": "toggleBookmark",
"Shift-Cmd-F2": "clearBookmarks",
"Alt-F2": "selectBookmarks",
"Backspace": "smartBackspace",
"Cmd-K Cmd-D": "skipAndSelectNextOccurrence",
"Cmd-K Cmd-K": "delLineRight",
"Cmd-K Cmd-U": "upcaseAtCursor",
"Cmd-K Cmd-L": "downcaseAtCursor",
"Cmd-K Cmd-Space": "setSublimeMark",
"Cmd-K Cmd-A": "selectToSublimeMark",
"Cmd-K Cmd-W": "deleteToSublimeMark",
"Cmd-K Cmd-X": "swapWithSublimeMark",
"Cmd-K Cmd-Y": "sublimeYank",
"Cmd-K Cmd-C": "showInCenter",
"Cmd-K Cmd-G": "clearBookmarks",
"Cmd-K Cmd-Backspace": "delLineLeft",
"Cmd-K Cmd-1": "foldAll",
"Cmd-K Cmd-0": "unfoldAll",
"Cmd-K Cmd-J": "unfoldAll",
"Ctrl-Shift-Up": "addCursorToPrevLine",
"Ctrl-Shift-Down": "addCursorToNextLine",
"Cmd-F3": "findUnder",
"Shift-Cmd-F3": "findUnderPrevious",
"Alt-F3": "findAllUnder",
"Shift-Cmd-[": "fold",
"Shift-Cmd-]": "unfold",
"Cmd-I": "findIncremental",
"Shift-Cmd-I": "findIncrementalReverse",
"Cmd-H": "replace",
"F3": "findNext",
"Shift-F3": "findPrev",
"fallthrough": "macDefault"
};
CodeMirror.normalizeKeyMap(keyMap.macSublime);
keyMap.pcSublime = {
"Shift-Tab": "indentLess",
"Shift-Ctrl-K": "deleteLine",
"Alt-Q": "wrapLines",
"Ctrl-T": "transposeChars",
"Alt-Left": "goSubwordLeft",
"Alt-Right": "goSubwordRight",
"Ctrl-Up": "scrollLineUp",
"Ctrl-Down": "scrollLineDown",
"Ctrl-L": "selectLine",
"Shift-Ctrl-L": "splitSelectionByLine",
"Esc": "singleSelectionTop",
"Ctrl-Enter": "insertLineAfter",
"Shift-Ctrl-Enter": "insertLineBefore",
"Ctrl-D": "selectNextOccurrence",
"Shift-Ctrl-Space": "selectScope",
"Shift-Ctrl-M": "selectBetweenBrackets",
"Ctrl-M": "goToBracket",
"Shift-Ctrl-Up": "swapLineUp",
"Shift-Ctrl-Down": "swapLineDown",
"Ctrl-/": "toggleCommentIndented",
"Ctrl-J": "joinLines",
"Shift-Ctrl-D": "duplicateLine",
"F9": "sortLines",
"Ctrl-F9": "sortLinesInsensitive",
"F2": "nextBookmark",
"Shift-F2": "prevBookmark",
"Ctrl-F2": "toggleBookmark",
"Shift-Ctrl-F2": "clearBookmarks",
"Alt-F2": "selectBookmarks",
"Backspace": "smartBackspace",
"Ctrl-K Ctrl-D": "skipAndSelectNextOccurrence",
"Ctrl-K Ctrl-K": "delLineRight",
"Ctrl-K Ctrl-U": "upcaseAtCursor",
"Ctrl-K Ctrl-L": "downcaseAtCursor",
"Ctrl-K Ctrl-Space": "setSublimeMark",
"Ctrl-K Ctrl-A": "selectToSublimeMark",
"Ctrl-K Ctrl-W": "deleteToSublimeMark",
"Ctrl-K Ctrl-X": "swapWithSublimeMark",
"Ctrl-K Ctrl-Y": "sublimeYank",
"Ctrl-K Ctrl-C": "showInCenter",
"Ctrl-K Ctrl-G": "clearBookmarks",
"Ctrl-K Ctrl-Backspace": "delLineLeft",
"Ctrl-K Ctrl-1": "foldAll",
"Ctrl-K Ctrl-0": "unfoldAll",
"Ctrl-K Ctrl-J": "unfoldAll",
"Ctrl-Alt-Up": "addCursorToPrevLine",
"Ctrl-Alt-Down": "addCursorToNextLine",
"Ctrl-F3": "findUnder",
"Shift-Ctrl-F3": "findUnderPrevious",
"Alt-F3": "findAllUnder",
"Shift-Ctrl-[": "fold",
"Shift-Ctrl-]": "unfold",
"Ctrl-I": "findIncremental",
"Shift-Ctrl-I": "findIncrementalReverse",
"Ctrl-H": "replace",
"F3": "findNext",
"Shift-F3": "findPrev",
"fallthrough": "pcDefault"
};
CodeMirror.normalizeKeyMap(keyMap.pcSublime);
var mac = keyMap.default == keyMap.macDefault;
keyMap.sublime = mac ? keyMap.macSublime : keyMap.pcSublime;
});
});
var search = createCommonjsModule(function (module, exports) {
(function (mod) {
mod(codemirror);
})(function (CodeMirror) {
var Search;
CodeMirror.defineOption("searchbox", false, function (cm) {
cm.addKeyMap({
"Ctrl-F": function () {
var cmEle = cm.display.wrapper;
if (!Search || !cmEle.parentElement.contains(Search.searchBox)) {
Search = new SearchBox(cm);
}
var isReplace = false;
if (cmEle.parentElement.querySelector("[action=toggleReplace]")) {
isReplace =
cmEle.parentElement.querySelector("[action=toggleReplace]")
.innerText === "-";
}
Search.show(cm.getSelection(), isReplace);
},
Esc: function () {
if (!Search || !Search.isVisible()) return CodeMirror.Pass;
Search.hide();
if (typeof event !== "undefined") event.stopPropagation();
},
"Cmd-F": function () {
if (!Search) Search = new SearchBox(cm);
Search.show();
},
});
});
function SearchBox(cm) {
var self = this;
init();
function initElements(el) {
self.searchBox = el.querySelector(".ace_search_form");
self.replaceBox = el.querySelector(".ace_replace_form");
self.searchOptions = el.querySelector(".ace_search_options");
self.regExpOption = el.querySelector("[action=toggleRegexpMode]");
self.caseSensitiveOption = el.querySelector(
"[action=toggleCaseSensitive]"
);
self.wholeWordOption = el.querySelector("[action=toggleWholeWords]");
self.searchInput = self.searchBox.querySelector(".ace_search_field");
self.replaceInput = self.replaceBox.querySelector(".ace_search_field");
}
function init() {
var el = (self.element = addHtml());
addStyle();
initElements(el);
bindKeys();
el.addEventListener("mousedown", function (e) {
setTimeout(function () {
self.activeInput.focus();
}, 0);
e.stopPropagation();
});
el.addEventListener("click", function (e) {
var t = e.target || e.srcElement;
var action = t.getAttribute("action");
if (action && self[action]) self[action]();
else if (self.commands[action]) self.commands[action]();
e.stopPropagation();
});
self.searchInput.addEventListener("input", function () {
self.$onChange.schedule(20);
});
self.searchInput.addEventListener("focus", function () {
self.activeInput = self.searchInput;
});
self.replaceInput.addEventListener("focus", function () {
self.activeInput = self.replaceInput;
});
self.$onChange = delayedCall(function () {
self.find(false, false);
});
}
function bindKeys() {
var sb = self,
obj = {
"Ctrl-F|Cmd-F|Ctrl-H|Command-Alt-F": function () {
var isReplace = (sb.isReplace = !sb.isReplace);
sb.replaceBox.style.display = isReplace ? "" : "none";
sb[isReplace ? "replaceInput" : "searchInput"].focus();
},
"Ctrl-G|Cmd-G": function () {
sb.findNext();
},
"Ctrl-Shift-G|Cmd-Shift-G": function () {
sb.findPrev();
},
Esc: function () {
setTimeout(function () {
sb.hide();
});
},
Enter: function () {
if (sb.activeInput === sb.replaceInput) sb.replace();
sb.findNext();
},
"Shift-Enter": function () {
if (sb.activeInput === sb.replaceInput) sb.replace();
sb.findPrev();
},
"Alt-Enter": function () {
if (sb.activeInput === sb.replaceInput) sb.replaceAll();
sb.findAll();
},
Tab: function () {
if (self.activeInput === self.replaceInput)
self.searchInput.focus();
else self.replaceInput.focus();
},
};
self.element.addEventListener("keydown", function (event) {
Object.keys(obj).some(function (name) {
var is = key(name, event);
if (is) {
event.stopPropagation();
event.preventDefault();
obj[name](event);
}
return is;
});
});
}
this.commands = {
toggleRegexpMode: function () {
self.regExpOption.checked = !self.regExpOption.checked;
self.$syncOptions();
},
toggleCaseSensitive: function () {
self.caseSensitiveOption.checked = !self.caseSensitiveOption.checked;
self.$syncOptions();
},
toggleWholeWords: function () {
self.wholeWordOption.checked = !self.wholeWordOption.checked;
self.$syncOptions();
},
};
this.$syncOptions = function () {
setCssClass(this.regExpOption, "checked", this.regExpOption.checked);
setCssClass(
this.wholeWordOption,
"checked",
this.wholeWordOption.checked
);
setCssClass(
this.caseSensitiveOption,
"checked",
this.caseSensitiveOption.checked
);
this.find(false, false);
};
this.find = function (skipCurrent, backwards) {
var value = this.searchInput.value,
options = {
skipCurrent: skipCurrent,
backwards: backwards,
regExp: this.regExpOption.checked,
caseSensitive: this.caseSensitiveOption.checked,
wholeWord: this.wholeWordOption.checked,
};
find(value, options, function (searchCursor) {
var current = searchCursor.matches(false, searchCursor.from());
cm.setSelection(current.from, current.to);
});
};
function find(value, options, callback) {
if (!value) {
clearSearch(cm);
updateCount();
return;
}
var done,
noMatch,
searchCursor,
next,
prev,
matches,
cursor,
position,
val = value,
o = options,
is = true,
caseSensitive = o.caseSensitive,
regExp = o.regExp,
wholeWord = o.wholeWord;
if (regExp) {
val = val.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
if (wholeWord) {
if (caseSensitive) {
val = val = RegExp("\\b" + val + "\\b");
} else {
val = RegExp("\\b" + val + "\\b", "i");
}
}
if (regExp) {
val = RegExp(val);
}
clearSearch(cm);
doSearch(cm, val, caseSensitive);
updateCount();
if (o.backwards) position = o.skipCurrent ? "from" : "to";
else position = o.skipCurrent ? "to" : "from";
cursor = cm.getCursor(position);
searchCursor = cm.getSearchCursor(val, cursor, !caseSensitive);
(next = searchCursor.findNext.bind(searchCursor)),
(prev = searchCursor.findPrevious.bind(searchCursor)),
(matches = searchCursor.matches.bind(searchCursor));
if (o.backwards && !prev()) {
is = next();
if (is) {
cm.setCursor(cm.doc.size - 1, 0);
find(value, options, callback);
done = true;
}
} else if (!o.backwards && !next()) {
is = prev();
if (is) {
cm.setCursor(0, 0);
find(value, options, callback);
done = true;
}
}
noMatch = !is && self.searchInput.value;
setCssClass(self.searchBox, "ace_nomatch", noMatch);
if (!done && is) callback(searchCursor);
}
this.findNext = function () {
this.find(true, false);
};
this.findPrev = function () {
this.find(true, true);
};
this.findAll = function () {
var value = this.searchInput.value,
noMatch = this.searchInput.value;
setCssClass(this.searchBox, "ace_nomatch", noMatch);
if (cm.showMatchesOnScrollbar) cm.showMatchesOnScrollbar(value);
this.hide();
};
this.replace = function () {
var readOnly = cm.getOption("readOnly"),
isSelection = !!cm.getSelection();
if (!readOnly && isSelection)
cm.replaceSelection(this.replaceInput.value, "start");
updateCount();
};
this.replaceAndFindNext = function () {
var readOnly = cm.getOption("readOnly");
if (!readOnly) {
this.replace();
this.findNext();
}
};
this.replaceAll = function () {
var value,
cursor,
from = this.searchInput.value,
to = this.replaceInput.value,
reg = RegExp(from, this.caseSensitiveOption.checked ? "g" : "gi");
if (this.wholeWordOption.checked && !this.regExpOption.checked) {
if (this.caseSensitiveOption.checked) {
reg = RegExp("\\b" + from + "\\b", 'g');
} else {
reg = RegExp("\\b" + from + "\\b", "gi");
}
}
if (!cm.getOption("readOnly") && cm.getSelection()) {
cursor = cm.getCursor();
value = cm.getValue();
value = value.replace(reg, to);
cm.setValue(value);
cm.setCursor(cursor);
}
updateCount();
};
this.toggleReplace = function () {
var cmEle = cm.display.wrapper;
if (
cmEle.parentElement.querySelector("[action=toggleReplace]")
.innerText === "+"
) {
cmEle.parentElement.querySelector("[action=toggleReplace]").innerText =
"-";
this.replaceBox.style.display = "";
this.isReplace = true;
} else {
cmEle.parentElement.querySelector("[action=toggleReplace]").innerText =
"+";
this.replaceBox.style.display = "none";
this.isReplace = false;
}
};
this.hide = function () {
clearSearch(cm);
var cmEle = cm.getWrapperElement();
Search = null;
cmEle.removeChild(this.element);
cm.focus();
};
this.isVisible = function () {
var is = this.element.style.display === "";
return is;
};
this.show = function (value, isReplace) {
this.element.style.display = "";
if (!isReplace) {
this.replaceBox.style.display = isReplace ? "" : "none";
}
this.isReplace = isReplace;
if (value) {
this.searchInput.value = value;
this.find(false, false);
}
this.searchInput.focus();
this.searchInput.select();
};
this.isFocused = function () {
var el = document.activeElement;
return el === this.searchInput || el === this.replaceInput;
};
function doSearch(cm, value, caseSensitive) {
var state = getSearchState(cm);
var query = value;
if (query && query !== state.queryText) {
startSearch(cm, state, query, caseSensitive);
state.posFrom = state.posTo = cm.getCursor();
}
}
function parseString(string) {
return string.replace(/\\([nrt\\])/g, function (match, ch) {
if (ch == "n") return "\n";
if (ch == "r") return "\r";
if (ch == "t") return "\t";
if (ch == "\\") return "\\";
return match;
});
}
function parseQuery(query) {
var reStr = typeof query === "object" ? query.toString() : query;
var isRE = reStr.match(/^\/(.*)\/([a-z]*)$/);
if (isRE) {
try {
query = new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i");
} catch (e) {} // Not a regular expression after all, do a string search
} else {
query = parseString(query);
}
if (typeof query == "string" ? query == "" : query.test("")) query = /x^/;
return query;
}
function startSearch(cm, state, query, caseSensitive) {
state.queryText = query;
state.query = parseQuery(query);
cm.removeOverlay(
state.overlay,
queryCaseInsensitive(state.query, caseSensitive)
);
state.overlay = searchOverlay(
state.query,
queryCaseInsensitive(state.query, caseSensitive)
);
cm.addOverlay(state.overlay);
if (cm.showMatchesOnScrollbar) {
if (state.annotate) {
state.annotate.clear();
state.annotate = null;
}
state.annotate = cm.showMatchesOnScrollbar(
state.query,
queryCaseInsensitive(state.query, caseSensitive)
);
}
}
function queryCaseInsensitive(query, caseSensitive) {
return typeof query == "string" && !caseSensitive;
}
function searchOverlay(query, caseInsensitive) {
if (typeof query == "string")
query = new RegExp(
query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"),
caseInsensitive ? "gi" : "g"
);
else if (!query.global)
query = new RegExp(query.source, query.ignoreCase ? "gi" : "g");
return {
token: function (stream) {
query.lastIndex = stream.pos;
var match = query.exec(stream.string);
if (match && match.index == stream.pos) {
stream.pos += match[0].length || 1;
return "searching";
} else if (match) {
stream.pos = match.index;
} else {
stream.skipToEnd();
}
},
};
}
function SearchState() {
this.posFrom = this.posTo = this.lastQuery = this.query = null;
this.overlay = null;
}
function getSearchState(cm) {
return cm.state.search || (cm.state.search = new SearchState());
}
function clearSearch(cm) {
cm.operation(function () {
var state = getSearchState(cm);
state.lastQuery = state.query;
if (!state.query) return;
state.query = state.queryText = null;
cm.removeOverlay(state.overlay);
if (state.annotate) {
state.annotate.clear();
state.annotate = null;
}
});
}
function updateCount() {
var val = self.searchInput.value;
var matches = [];
if (val) {
val = val.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
var reg;
if (self.caseSensitiveOption.checked) {
reg = RegExp(val, "g");
} else {
reg = RegExp(val, "gi");
}
if (self.wholeWordOption.checked) {
if (self.caseSensitiveOption.checked) {
reg = RegExp("\\b" + val + "\\b", "g");
} else {
reg = RegExp("\\b" + val + "\\b", "gi");
}
}
if (self.regExpOption.checked) {
reg = RegExp(val, "gi");
}
matches = cm.getValue().match(reg);
}
var count = matches ? matches.length : 0;
var cmEle = cm.display.wrapper;
var countEle = cmEle.parentElement.querySelector(".ace_search_counter");
if (countEle) {
countEle.innerText = count + " matches found.";
}
if (count === 0){
cm.setSelection({ch: 0, line: 0},{ch: 0, line: 0});
}
}
function addStyle() {
var style = document.createElement("style"),
css = [
".ace_search {",
"color: black;",
"background-color: #ddd;",
"border: 1px solid #cbcbcb;",
"border-top: 0 none;",
"max-width: 325px;",
"overflow: hidden;",
"margin: 0;",
"padding: 4px;",
"padding-right: 6px;",
"padding-bottom: 0;",
"position: absolute;",
"top: 0px;",
"z-index: 99;",
"white-space: normal;",
"font-size: 12px;",
"}",
".ace_search.left {",
"border-left: 0 none;",
"border-radius: 0px 0px 5px 0px;",
"left: 0;",
"}",
".ace_search.right {",
"border-radius: 0px 0px 0px 5px;",
"border-right: 0 none;",
"right: 0;",
"}",
".ace_search_form, .ace_replace_form {",
"border-radius: 3px;",
"border: 1px solid #cbcbcb;",
"float: left;",
"margin-bottom: 4px;",
"overflow: hidden;",
"}",
".ace_search_form.ace_nomatch {",
"outline: 1px solid red;",
"}",
".ace_search_field {",
"background-color: white;",
"border-right: 1px solid #cbcbcb;",
"border: 0 none;",
"-webkit-box-sizing: border-box;",
"-moz-box-sizing: border-box;",
"box-sizing: border-box;",
"float: left;",
"height: 22px;",
"outline: 0;",
"padding: 0 7px;",
"width: 238px;",
"margin: 0;",
"}",
".ace_searchbtn,",
".ace_replacebtn {",
"background: #fff;",
"border: 0 none;",
"border-left: 1px solid #dcdcdc;",
"cursor: pointer;",
"float: left;",
"height: 22px;",
"padding: 0 5px;",
"margin: 0;",
"position: relative;",
"}",
".ace_searchbtn:last-child,",
".ace_replacebtn:last-child {",
"border-top-right-radius: 3px;",
"border-bottom-right-radius: 3px;",
"}",
".ace_searchbtn:disabled {",
"background: none;",
"cursor: default;",
"}",
".ace_searchbtn {",
"background-position: 50% 50%;",
"background-repeat: no-repeat;",
"width: 27px;",
"}",
".ace_searchbtn.prev {",
"background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAFCAYAAAB4ka1VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADFJREFUeNpiSU1NZUAC/6E0I0yACYskCpsJiySKIiY0SUZk40FyTEgCjGgKwTRAgAEAQJUIPCE+qfkAAAAASUVORK5CYII=); ",
"}",
".ace_searchbtn.next {",
"background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAFCAYAAAB4ka1VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADRJREFUeNpiTE1NZQCC/0DMyIAKwGJMUAYDEo3M/s+EpvM/mkKwCQxYjIeLMaELoLMBAgwAU7UJObTKsvAAAAAASUVORK5CYII=); ",
"}",
".ace_searchbtn_close {",
"background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAcCAYAAABRVo5BAAAAZ0lEQVR42u2SUQrAMAhDvazn8OjZBilCkYVVxiis8H4CT0VrAJb4WHT3C5xU2a2IQZXJjiQIRMdkEoJ5Q2yMqpfDIo+XY4k6h+YXOyKqTIj5REaxloNAd0xiKmAtsTHqW8sR2W5f7gCu5nWFUpVjZwAAAABJRU5ErkJggg==) no-repeat 50% 0;",
"border-radius: 50%;",
"border: 0 none;",
"color: #656565;",
"cursor: pointer;",
"float: right;",
"font: 16px/16px Arial;",
"height: 14px;",
"margin: 5px 1px 9px 5px;",
"padding: 0;",
"text-align: center;",
"width: 14px;",
"}",
".ace_searchbtn_close:hover {",
"background-color: #656565;",
"background-position: 50% 100%;",
"color: white;",
"}",
".ace_replacebtn.prev {",
"width: 54px",
"}",
".ace_replacebtn.next {",
"width: 27px",
"}",
".ace_button {",
"margin-left: 2px;",
"cursor: pointer;",
"-webkit-user-select: none;",
"-moz-user-select: none;",
"-o-user-select: none;",
"-ms-user-select: none;",
"user-select: none;",
"overflow: hidden;",
"opacity: 0.7;",
"border: 1px solid rgba(100,100,100,0.23);",
"padding: 1px;",
"-moz-box-sizing: border-box;",
"box-sizing: border-box;",
"color: black;",
"}",
".ace_button:hover {",
"background-color: #eee;",
"opacity:1;",
"}",
".ace_button:active {",
"background-color: #ddd;",
"}",
".ace_button.checked {",
"border-color: #3399ff;",
"opacity:1;",
"}",
".ace_search_options{",
"clear: both;",
"margin: 4px 0;",
"text-align: right;",
"-webkit-user-select: none;",
"-moz-user-select: none;",
"-o-user-select: none;",
"-ms-user-select: none;",
"user-select: none;",
"}",
".replace_toggle{",
"float: left;",
"margin-top: -2px;",
"padding: 0 5px;",
" }",
".ace_search_counter{",
"float: left;",
"font-family: arial;",
"padding: 0 8px;",
"}",
"button svg,path {",
"pointer-events: none;",
"}",
].join("");
style.setAttribute("data-name", "js-searchbox");
style.textContent = css;
document.head.appendChild(style);
}
function addHtml() {
var elSearch,
el = cm.getWrapperElement(),
div = document.createElement("div"),
html = [
'<div class="ace_search right">',
'<button type="button" action="hide" class="ace_searchbtn_close"></button>',
'<div class="ace_search_form">',
'<input class="ace_search_field" placeholder="Search for" spellcheck="false"></input>',
'<button type="button" action="findNext" class="ace_searchbtn next"></button>',
'<button type="button" action="findPrev" class="ace_searchbtn prev"></button>',
"</div>",
'<div class="ace_replace_form">',
'<input class="ace_search_field" placeholder="Replace with" spellcheck="false"></input>',
'<button type="button" action="replaceAndFindNext" title="Replace" class="ace_replacebtn">',
'<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">',
'<path fill-rule="evenodd" clip-rule="evenodd" d="M3.221 3.739L5.482 6.008L7.7 3.784L7 3.084L5.988 4.091L5.98 2.491C5.97909 2.35567 6.03068 2.22525 6.12392 2.12716C6.21716 2.02908 6.3448 1.97095 6.48 1.965H8V1H6.48C6.28496 1.00026 6.09189 1.03902 5.91186 1.11405C5.73183 1.18908 5.56838 1.29892 5.43088 1.43725C5.29338 1.57558 5.18455 1.73969 5.11061 1.92018C5.03667 2.10066 4.99908 2.29396 5 2.489V4.1L3.927 3.033L3.221 3.739ZM9.89014 5.53277H9.90141C10.0836 5.84426 10.3521 6 10.707 6C11.0995 6 11.4131 5.83236 11.6479 5.49708C11.8826 5.1618 12 4.71728 12 4.16353C12 3.65304 11.8995 3.2507 11.6986 2.95652C11.4977 2.66234 11.2113 2.51525 10.8394 2.51525C10.4338 2.51525 10.1211 2.70885 9.90141 3.09604H9.89014V1H9V5.91888H9.89014V5.53277ZM9.87606 4.47177V4.13108C9.87606 3.88449 9.93427 3.6844 10.0507 3.53082C10.169 3.37724 10.3174 3.30045 10.4958 3.30045C10.6854 3.30045 10.831 3.37833 10.9324 3.53407C11.0357 3.68765 11.0873 3.9018 11.0873 4.17651C11.0873 4.50746 11.031 4.76379 10.9183 4.94549C10.8075 5.12503 10.6507 5.2148 10.4479 5.2148C10.2808 5.2148 10.1437 5.14449 10.0366 5.00389C9.92958 4.86329 9.87606 4.68592 9.87606 4.47177ZM9 12.7691C8.74433 12.923 8.37515 13 7.89247 13C7.32855 13 6.87216 12.8225 6.5233 12.4674C6.17443 12.1124 6 11.6543 6 11.0931C6 10.4451 6.18638 9.93484 6.55914 9.5624C6.93429 9.18747 7.43489 9.00001 8.06093 9.00001C8.49343 9.00001 8.80645 9.0596 9 9.17878V10.1769C8.76344 9.99319 8.4994 9.90132 8.20789 9.90132C7.88292 9.90132 7.62485 10.0006 7.43369 10.1993C7.24492 10.3954 7.15054 10.6673 7.15054 11.0149C7.15054 11.3526 7.24134 11.6183 7.42294 11.8119C7.60454 12.0031 7.85424 12.0987 8.17204 12.0987C8.454 12.0987 8.72999 12.0068 9 11.8231V12.7691ZM4 7L3 8V14L4 15H11L12 14V8L11 7H4ZM4 8H5H10H11V9V13V14H10H5H4V13V9V8Z" fill="#656565"/>',
"</svg></button>",
'<button type="button" action="replaceAll" title="Replace All" class="ace_replacebtn">',
'<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">',
'<path fill-rule="evenodd" clip-rule="evenodd" d="M11.6009 2.67683C11.7474 2.36708 11.9559 2.2122 12.2263 2.2122C12.4742 2.2122 12.6651 2.32987 12.7991 2.56522C12.933 2.80056 13 3.12243 13 3.53082C13 3.97383 12.9218 4.32944 12.7653 4.59766C12.6088 4.86589 12.3997 5 12.138 5C11.9014 5 11.7224 4.87541 11.6009 4.62622H11.5934V4.93511H11V1H11.5934V2.67683H11.6009ZM11.584 3.77742C11.584 3.94873 11.6197 4.09063 11.6911 4.20311C11.7624 4.3156 11.8538 4.37184 11.9653 4.37184C12.1005 4.37184 12.205 4.30002 12.2789 4.15639C12.354 4.01103 12.3915 3.80597 12.3915 3.54121C12.3915 3.32144 12.3571 3.15012 12.2883 3.02726C12.2207 2.90266 12.1236 2.84036 11.9972 2.84036C11.8782 2.84036 11.7793 2.9018 11.7005 3.02466C11.6228 3.14752 11.584 3.30759 11.584 3.50487V3.77742ZM4.11969 7.695L2 5.56781L2.66188 4.90594L3.66781 5.90625V4.39594C3.66695 4.21309 3.70219 4.03187 3.7715 3.86266C3.84082 3.69346 3.94286 3.53961 4.07176 3.40992C4.20066 3.28023 4.3539 3.17727 4.52268 3.10692C4.69146 3.03658 4.87246 3.00024 5.05531 3H7.39906V3.90469H5.05531C4.92856 3.91026 4.8089 3.96476 4.72149 4.05672C4.63408 4.14868 4.58571 4.27094 4.58656 4.39781L4.59406 5.89781L5.54281 4.95375L6.19906 5.61L4.11969 7.695ZM9.3556 4.93017H10V3.22067C10 2.40689 9.68534 2 9.05603 2C8.92098 2 8.77083 2.02421 8.6056 2.07263C8.44181 2.12104 8.3125 2.17691 8.21767 2.24022V2.90503C8.45474 2.70205 8.70474 2.60056 8.96767 2.60056C9.22917 2.60056 9.35991 2.75698 9.35991 3.06983L8.76078 3.17318C8.25359 3.25885 8 3.57914 8 4.13408C8 4.39665 8.06106 4.60708 8.18319 4.76536C8.30675 4.92179 8.47557 5 8.68966 5C8.97989 5 9.19899 4.83985 9.34698 4.51955H9.3556V4.93017ZM9.35991 3.57542V3.76816C9.35991 3.9432 9.31968 4.08845 9.23922 4.20391C9.15876 4.3175 9.0546 4.3743 8.92672 4.3743C8.83477 4.3743 8.76149 4.34264 8.7069 4.27933C8.65374 4.21415 8.62716 4.13128 8.62716 4.03073C8.62716 3.80912 8.73779 3.6797 8.95905 3.64246L9.35991 3.57542ZM7 12.9302H6.3556V12.5196H6.34698C6.19899 12.8399 5.97989 13 5.68966 13C5.47557 13 5.30675 12.9218 5.18319 12.7654C5.06106 12.6071 5 12.3966 5 12.1341C5 11.5791 5.25359 11.2588 5.76078 11.1732L6.35991 11.0698C6.35991 10.757 6.22917 10.6006 5.96767 10.6006C5.70474 10.6006 5.45474 10.702 5.21767 10.905V10.2402C5.3125 10.1769 5.44181 10.121 5.6056 10.0726C5.77083 10.0242 5.92098 10 6.05603 10C6.68534 10 7 10.4069 7 11.2207V12.9302ZM6.35991 11.7682V11.5754L5.95905 11.6425C5.73779 11.6797 5.62716 11.8091 5.62716 12.0307C5.62716 12.1313 5.65374 12.2142 5.7069 12.2793C5.76149 12.3426 5.83477 12.3743 5.92672 12.3743C6.0546 12.3743 6.15876 12.3175 6.23922 12.2039C6.31968 12.0885 6.35991 11.9432 6.35991 11.7682ZM9.26165 13C9.58343 13 9.82955 12.9423 10 12.8268V12.1173C9.81999 12.2551 9.636 12.324 9.44803 12.324C9.23616 12.324 9.06969 12.2523 8.94863 12.1089C8.82756 11.9637 8.76702 11.7644 8.76702 11.5112C8.76702 11.2505 8.82995 11.0466 8.95579 10.8994C9.08323 10.7505 9.25528 10.676 9.47192 10.676C9.66627 10.676 9.84229 10.7449 10 10.8827V10.1341C9.87097 10.0447 9.66229 10 9.37395 10C8.95659 10 8.62286 10.1406 8.37276 10.4218C8.12425 10.7011 8 11.0838 8 11.5698C8 11.9907 8.11629 12.3343 8.34887 12.6006C8.58144 12.8669 8.8857 13 9.26165 13ZM2 9L3 8H12L13 9V14L12 15H3L2 14V9ZM3 9V14H12V9H3ZM6 7L7 6H14L15 7V12L14 13V12V7H7H6Z" fill="#656565"/>',
"</svg></button>",
"</div>",
'<div class="ace_search_options">',
'<span action="toggleReplace" class="ace_button replace_toggle">+</span>',
'<span class="ace_search_counter">0 matches found.</span>',
'<span action="toggleRegexpMode" title="RegExp Search"></span>',
'<span action="toggleCaseSensitive" class="ace_button" title="CaseSensitive Search">Aa</span>',
'<span action="toggleWholeWords" title="Whole Word Search"></span>',
"</div>",
"</div>",
].join("");
div.innerHTML = html;
elSearch = div.firstChild;
el.appendChild(elSearch);
return elSearch;
}
}
function setCssClass(el, className, condition) {
var list = el.classList;
list[condition ? "add" : "remove"](className);
}
function delayedCall(fcn, defaultTimeout) {
var timer,
callback = function () {
timer = null;
fcn();
},
_self = function (timeout) {
if (!timer) timer = setTimeout(callback, timeout || defaultTimeout);
};
_self.delay = function (timeout) {
timer && clearTimeout(timer);
timer = setTimeout(callback, timeout || defaultTimeout);
};
_self.schedule = _self;
_self.call = function () {
this.cancel();
fcn();
};
_self.cancel = function () {
timer && clearTimeout(timer);
timer = null;
};
_self.isPending = function () {
return timer;
};
return _self;
}
/* https://github.com/coderaiser/key */
function key(str, event) {
var right,
KEY = {
BACKSPACE: 8,
TAB: 9,
ENTER: 13,
ESC: 27,
SPACE: 32,
PAGE_UP: 33,
PAGE_DOWN: 34,
END: 35,
HOME: 36,
UP: 38,
DOWN: 40,
INSERT: 45,
DELETE: 46,
INSERT_MAC: 96,
ASTERISK: 106,
PLUS: 107,
MINUS: 109,
F1: 112,
F2: 113,
F3: 114,
F4: 115,
F5: 116,
F6: 117,
F7: 118,
F8: 119,
F9: 120,
F10: 121,
SLASH: 191,
TRA: 192 /* Typewritten Reverse Apostrophe (`) */,
BACKSLASH: 220,
};
keyCheck(str, event);
right = str.split("|").some(function (combination) {
var wrong;
wrong = combination.split("-").some(function (key) {
var right;
switch (key) {
case "Ctrl":
right = event.ctrlKey;
break;
case "Shift":
right = event.shiftKey;
break;
case "Alt":
right = event.altKey;
break;
case "Cmd":
right = event.metaKey;
break;
default:
if (key.length === 1) right = event.keyCode === key.charCodeAt(0);
else
Object.keys(KEY).some(function (name) {
var up = key.toUpperCase();
if (up === name) right = event.keyCode === KEY[name];
});
break;
}
return !right;
});
return !wrong;
});
return right;
}
function keyCheck(str, event) {
if (typeof str !== "string") throw Error("str should be string!");
if (typeof event !== "object") throw Error("event should be object!");
}
});
});
var annotatescrollbar = createCommonjsModule(function (module, exports) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
mod(codemirror);
})(function(CodeMirror) {
CodeMirror.defineExtension("annotateScrollbar", function(options) {
if (typeof options == "string") options = {className: options};
return new Annotation(this, options);
});
CodeMirror.defineOption("scrollButtonHeight", 0);
function Annotation(cm, options) {
this.cm = cm;
this.options = options;
this.buttonHeight = options.scrollButtonHeight || cm.getOption("scrollButtonHeight");
this.annotations = [];
this.doRedraw = this.doUpdate = null;
this.div = cm.getWrapperElement().appendChild(document.createElement("div"));
this.div.style.cssText = "position: absolute; right: 0; top: 0; z-index: 7; pointer-events: none";
this.computeScale();
function scheduleRedraw(delay) {
clearTimeout(self.doRedraw);
self.doRedraw = setTimeout(function() { self.redraw(); }, delay);
}
var self = this;
cm.on("refresh", this.resizeHandler = function() {
clearTimeout(self.doUpdate);
self.doUpdate = setTimeout(function() {
if (self.computeScale()) scheduleRedraw(20);
}, 100);
});
cm.on("markerAdded", this.resizeHandler);
cm.on("markerCleared", this.resizeHandler);
if (options.listenForChanges !== false)
cm.on("changes", this.changeHandler = function() {
scheduleRedraw(250);
});
}
Annotation.prototype.computeScale = function() {
var cm = this.cm;
var hScale = (cm.getWrapperElement().clientHeight - cm.display.barHeight - this.buttonHeight * 2) /
cm.getScrollerElement().scrollHeight;
if (hScale != this.hScale) {
this.hScale = hScale;
return true;
}
};
Annotation.prototype.update = function(annotations) {
this.annotations = annotations;
this.redraw();
};
Annotation.prototype.redraw = function(compute) {
if (compute !== false) this.computeScale();
var cm = this.cm, hScale = this.hScale;
var frag = document.createDocumentFragment(), anns = this.annotations;
var wrapping = cm.getOption("lineWrapping");
var singleLineH = wrapping && cm.defaultTextHeight() * 1.5;
var curLine = null, curLineObj = null;
function getY(pos, top) {
if (curLine != pos.line) {
curLine = pos.line;
curLineObj = cm.getLineHandle(pos.line);
var visual = cm.getLineHandleVisualStart(curLineObj);
if (visual != curLineObj) {
curLine = cm.getLineNumber(visual);
curLineObj = visual;
}
}
if ((curLineObj.widgets && curLineObj.widgets.length) ||
(wrapping && curLineObj.height > singleLineH))
return cm.charCoords(pos, "local")[top ? "top" : "bottom"];
var topY = cm.heightAtLine(curLineObj, "local");
return topY + (top ? 0 : curLineObj.height);
}
var lastLine = cm.lastLine();
if (cm.display.barWidth) for (var i = 0, nextTop; i < anns.length; i++) {
var ann = anns[i];
if (ann.to.line > lastLine) continue;
var top = nextTop || getY(ann.from, true) * hScale;
var bottom = getY(ann.to, false) * hScale;
while (i < anns.length - 1) {
if (anns[i + 1].to.line > lastLine) break;
nextTop = getY(anns[i + 1].from, true) * hScale;
if (nextTop > bottom + .9) break;
ann = anns[++i];
bottom = getY(ann.to, false) * hScale;
}
if (bottom == top) continue;
var height = Math.max(bottom - top, 3);
var elt = frag.appendChild(document.createElement("div"));
elt.style.cssText = "position: absolute; right: 0px; width: " + Math.max(cm.display.barWidth - 1, 2) + "px; top: "
+ (top + this.buttonHeight) + "px; height: " + height + "px";
elt.className = this.options.className;
if (ann.id) {
elt.setAttribute("annotation-id", ann.id);
}
}
this.div.textContent = "";
this.div.appendChild(frag);
};
Annotation.prototype.clear = function() {
this.cm.off("refresh", this.resizeHandler);
this.cm.off("markerAdded", this.resizeHandler);
this.cm.off("markerCleared", this.resizeHandler);
if (this.changeHandler) this.cm.off("changes", this.changeHandler);
this.div.parentNode.removeChild(this.div);
};
});
});
var matchesonscrollbar = createCommonjsModule(function (module, exports) {
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
(function(mod) {
mod(codemirror, searchcursor, annotatescrollbar);
})(function(CodeMirror) {
CodeMirror.defineExtension("showMatchesOnScrollbar", function(query, caseFold, options) {
if (typeof options == "string") options = {className: options};
if (!options) options = {};
return new SearchAnnotation(this, query, caseFold, options);
});
function SearchAnnotation(cm, query, caseFold, options) {
this.cm = cm;
this.options = options;
var annotateOptions = {listenForChanges: false};
for (var prop in options) annotateOptions[prop] = options[prop];
if (!annotateOptions.className) annotateOptions.className = "CodeMirror-search-match";
this.annotation = cm.annotateScrollbar(annotateOptions);
this.query = query;
this.caseFold = caseFold;
this.gap = {from: cm.firstLine(), to: cm.lastLine() + 1};
this.matches = [];
this.update = null;
this.findMatches();
this.annotation.update(this.matches);
var self = this;
cm.on("change", this.changeHandler = function(_cm, change) { self.onChange(change); });
}
var MAX_MATCHES = 1000;
SearchAnnotation.prototype.findMatches = function() {
if (!this.gap) return;
for (var i = 0; i < this.matches.length; i++) {
var match = this.matches[i];
if (match.from.line >= this.gap.to) break;
if (match.to.line >= this.gap.from) this.matches.splice(i--, 1);
}
var cursor = this.cm.getSearchCursor(this.query, CodeMirror.Pos(this.gap.from, 0), {caseFold: this.caseFold, multiline: this.options.multiline});
var maxMatches = this.options && this.options.maxMatches || MAX_MATCHES;
while (cursor.findNext()) {
var match = {from: cursor.from(), to: cursor.to()};
if (match.from.line >= this.gap.to) break;
this.matches.splice(i++, 0, match);
if (this.matches.length > maxMatches) break;
}
this.gap = null;
};
function offsetLine(line, changeStart, sizeChange) {
if (line <= changeStart) return line;
return Math.max(changeStart, line + sizeChange);
}
SearchAnnotation.prototype.onChange = function(change) {
var startLine = change.from.line;
var endLine = CodeMirror.changeEnd(change).line;
var sizeChange = endLine - change.to.line;
if (this.gap) {
this.gap.from = Math.min(offsetLine(this.gap.from, startLine, sizeChange), change.from.line);
this.gap.to = Math.max(offsetLine(this.gap.to, startLine, sizeChange), change.from.line);
} else {
this.gap = {from: change.from.line, to: endLine + 1};
}
if (sizeChange) for (var i = 0; i < this.matches.length; i++) {
var match = this.matches[i];
var newFrom = offsetLine(match.from.line, startLine, sizeChange);
if (newFrom != match.from.line) match.from = CodeMirror.Pos(newFrom, match.from.ch);
var newTo = offsetLine(match.to.line, startLine, sizeChange);
if (newTo != match.to.line) match.to = CodeMirror.Pos(newTo, match.to.ch);
}
clearTimeout(this.update);
var self = this;
this.update = setTimeout(function() { self.updateAfterChange(); }, 250);
};
SearchAnnotation.prototype.updateAfterChange = function() {
this.findMatches();
this.annotation.update(this.matches);
};
SearchAnnotation.prototype.clear = function() {
this.cm.off("change", this.changeHandler);
this.annotation.clear();
};
});
});
// `Array.isArray` method
// https://tc39.es/ecma262/#sec-array.isarray
_export({ target: 'Array', stat: true }, {
isArray: isArray
});
var isArray$2 = path.Array.isArray;
var isArray$3 = isArray$2;
var isArray$4 = isArray$3;
var isArray$5 = isArray$4;
var isArray$6 = isArray$5;
var isArray$7 = isArray$6;
var arrayWithHoles = createCommonjsModule(function (module) {
function _arrayWithHoles(arr) {
if (isArray$7(arr)) return arr;
}
module.exports = _arrayWithHoles, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(arrayWithHoles);
var getIteratorMethod_1 = getIteratorMethod;
var getIteratorMethod$1 = getIteratorMethod_1;
var getIteratorMethod$2 = getIteratorMethod$1;
var getIteratorMethod$3 = getIteratorMethod$2;
var getIteratorMethod$4 = getIteratorMethod$3;
var getIteratorMethod$5 = getIteratorMethod$4;
var iterableToArrayLimit = createCommonjsModule(function (module) {
function _iterableToArrayLimit(arr, i) {
var _i = arr == null ? null : typeof symbol$5 !== "undefined" && getIteratorMethod$5(arr) || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
module.exports = _iterableToArrayLimit, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(iterableToArrayLimit);
var HAS_SPECIES_SUPPORT$1 = arrayMethodHasSpeciesSupport('slice');
var SPECIES$2 = wellKnownSymbol('species');
var Array$4 = global_1.Array;
var max$2 = Math.max;
// `Array.prototype.slice` method
// https://tc39.es/ecma262/#sec-array.prototype.slice
// fallback for not array-like ES3 strings and DOM objects
_export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$1 }, {
slice: function slice(start, end) {
var O = toIndexedObject(this);
var length = lengthOfArrayLike(O);
var k = toAbsoluteIndex(start, length);
var fin = toAbsoluteIndex(end === undefined ? length : end, length);
// inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible
var Constructor, result, n;
if (isArray(O)) {
Constructor = O.constructor;
// cross-realm fallback
if (isConstructor(Constructor) && (Constructor === Array$4 || isArray(Constructor.prototype))) {
Constructor = undefined;
} else if (isObject(Constructor)) {
Constructor = Constructor[SPECIES$2];
if (Constructor === null) Constructor = undefined;
}
if (Constructor === Array$4 || Constructor === undefined) {
return arraySlice(O, k, fin);
}
}
result = new (Constructor === undefined ? Array$4 : Constructor)(max$2(fin - k, 0));
for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]);
result.length = n;
return result;
}
});
var slice = entryVirtual('Array').slice;
var ArrayPrototype$6 = Array.prototype;
var slice$1 = function (it) {
var own = it.slice;
return it === ArrayPrototype$6 || (objectIsPrototypeOf(ArrayPrototype$6, it) && own === ArrayPrototype$6.slice) ? slice : own;
};
var slice$2 = slice$1;
var slice$3 = slice$2;
var slice$4 = slice$3;
var slice$5 = slice$4;
var slice$6 = slice$5;
var from_1$3 = from_1$1;
var from_1$4 = from_1$3;
var from_1$5 = from_1$4;
var from_1$6 = from_1$5;
var arrayLikeToArray = createCommonjsModule(function (module) {
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(arrayLikeToArray);
var unsupportedIterableToArray = createCommonjsModule(function (module) {
function _unsupportedIterableToArray(o, minLen) {
var _context;
if (!o) return;
if (typeof o === "string") return arrayLikeToArray(o, minLen);
var n = slice$6(_context = Object.prototype.toString.call(o)).call(_context, 8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return from_1$6(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);
}
module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(unsupportedIterableToArray);
var nonIterableRest = createCommonjsModule(function (module) {
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
module.exports = _nonIterableRest, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(nonIterableRest);
var slicedToArray = createCommonjsModule(function (module) {
function _slicedToArray(arr, i) {
return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();
}
module.exports = _slicedToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
var _slicedToArray = unwrapExports(slicedToArray);
var indexOf$8 = indexOf$3;
var create$6 = create$1;
var slice$7 = slice$2;
var trim$4 = stringTrim.trim;
var $parseInt = global_1.parseInt;
var Symbol$3 = global_1.Symbol;
var ITERATOR$5 = Symbol$3 && Symbol$3.iterator;
var hex = /^[+-]?0x/i;
var exec$2 = functionUncurryThis(hex.exec);
var FORCED$4 = $parseInt(whitespaces + '08') !== 8 || $parseInt(whitespaces + '0x16') !== 22
// MS Edge 18- broken with boxed symbols
|| (ITERATOR$5 && !fails(function () { $parseInt(Object(ITERATOR$5)); }));
// `parseInt` method
// https://tc39.es/ecma262/#sec-parseint-string-radix
var numberParseInt = FORCED$4 ? function parseInt(string, radix) {
var S = trim$4(toString_1(string));
return $parseInt(S, (radix >>> 0) || (exec$2(hex, S) ? 16 : 10));
} : $parseInt;
// `parseInt` method
// https://tc39.es/ecma262/#sec-parseint-string-radix
_export({ global: true, forced: parseInt != numberParseInt }, {
parseInt: numberParseInt
});
var _parseInt = path.parseInt;
var _parseInt$1 = _parseInt;
var _parseInt$2 = _parseInt$1;
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// @ts-nocheck
/**
* 将html内容转换成md内容的工具
* 调用方式为htmlParser.run(htmlStr)
* 主要流程为:
* 1、接收html字符串
* 2、根据html字符串生成html语法树
* 3、递归遍历语法树将标签替换为对应的markdown语法
**/
var htmlParser = {
/**
* 入口函数负责将传入的html字符串转成对应的markdown源码
* @param {string} htmlStr
* @returns {string} 对应的markdown源码
*/
run: function run(htmlStr) {
var _context;
var $htmlStr = "<div>".concat(htmlStr, "</div>"); // 挂载对应的格式化引擎这里挂载的是markdown逆向引擎后续可以扩展支持其他标记语言
this.tagParser.formatEngine = this.mdFormatEngine; // 去掉注释
$htmlStr = $htmlStr.replace(/<!--[\s\S]*?-->/g, ''); // 将html字符串解析成html语法树
var htmlparsedArrays = this.htmlParser.parseHtml($htmlStr); // 预处理,去掉一些不需要的样式、属性
htmlparsedArrays = this.paragraphStyleClear(htmlparsedArrays); // 核心逻辑遍历html语法树生成对应的markdown源码
return trim$3(_context = this.$dealHtml(htmlparsedArrays).replace(/\n{3,}/g, '\n\n\n').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&')).call(_context, '\n');
},
/**
* 解析html语法树
* @param {Array} arr
* @returns {string} 对应的markdown源码
*/
$dealHtml: function $dealHtml(arr) {
var ret = '';
for (var i = 0; i < arr.length; i++) {
var temObj = arr[i];
if (temObj.type === 'tag') ret = this.$handleTagObject(temObj, ret);else if (temObj.type === 'text' && temObj.content.length > 0) {
ret += temObj.content.replace(/&nbsp;/g, ' ').replace(/[\n]+/g, '\n').replace(/^[ \t\n]+\n\s*$/, '\n');
}
}
return ret;
},
/**
* 处理html标签内容
* @param {object} temObj
* @param {string} returnString
*/
$handleTagObject: function $handleTagObject(temObj, returnString) {
var ret = returnString;
if (temObj.attrs["class"] && /(ch-icon-square|ch-icon-check)/.test(temObj.attrs["class"])) {
var _context2;
// 针对checklist
if (indexOf$8(_context2 = temObj.attrs["class"]).call(_context2, 'ch-icon-check') >= 0) {
ret += '[x]';
} else {
ret += '[ ]';
}
} else if (temObj.attrs["class"] && /cherry-code-preview-lang-select/.test(temObj.attrs["class"])) {
// 如果是代码块的选择语言标签,则不做任何处理
ret += '';
} else {
// 如果是标签
ret += this.$dealTag(temObj);
}
return ret;
},
/**
* 解析具体的html标签
* @param {HTMLElement} obj
* @returns {string} 对应的markdown源码
*/
$dealTag: function $dealTag(obj) {
var self = this;
var tmpText = '';
if (obj.children) {
// 递归每一个子元素
tmpText = self.$dealHtml(obj.children);
}
if (obj.name === 'style') {
// 不解析样式属性,只处理行内样式
return '';
}
if (obj.name === 'code' || obj.name === 'pre') {
// 解析代码块 或 行内代码
// pre时强制转成代码块
return self.tagParser.codeParser(obj, self.$dealCodeTag(obj), obj.name === 'pre');
}
if (typeof self.tagParser["".concat(obj.name, "Parser")] === 'function') {
// 解析对应的具体标签
return self.tagParser["".concat(obj.name, "Parser")](obj, tmpText);
}
return tmpText;
},
/**
* 解析代码块
* 本函数认为代码块是由text标签和li标签组成的
* @param {HTMLElement} obj
* @returns {string} 对应的markdown源码
*/
$dealCodeTag: function $dealCodeTag(obj) {
var self = this;
if (obj.children.length < 0) {
return '';
}
var ret = '';
for (var i = 0; i < obj.children.length; i++) {
var temObj = obj.children[i];
if (temObj.type !== 'text') {
// 如果是非text标签则需要处理换行逻辑
if (temObj.name === 'li') {
ret += '\n';
}
if (temObj.name === 'br') {
ret += '\n';
} // 递归找到对应的代码文本
ret += self.$dealCodeTag(temObj);
} else {
ret += temObj.content;
}
}
return ret;
},
/** **
* html解析器
* 将html解析成对象数组
* https://github.com/HenrikJoreteg/html-parse-stringify
**/
htmlParser: {
attrRE: /([\w-]+)|['"]{1}([^'"]*)['"]{1}/g,
lookup: {
area: true,
base: true,
br: true,
col: true,
embed: true,
hr: true,
img: true,
video: true,
input: true,
keygen: true,
link: true,
menuitem: true,
meta: true,
param: true,
source: true,
track: true,
wbr: true
},
tagRE: /<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>/g,
empty: create$6 ? create$6(null) : {},
parseTags: function parseTags(tag) {
var self = this;
var i = 0;
var key;
var res = {
type: 'tag',
name: '',
voidElement: false,
attrs: {},
children: []
};
tag.replace(this.attrRE, function (match) {
if (i % 2) {
key = match;
} else {
if (i === 0) {
if (self.lookup[match] || tag.charAt(tag.length - 2) === '/') {
res.voidElement = true;
}
res.name = match;
} else {
res.attrs[key] = match.replace(/['"]/g, '');
}
}
i += 1;
});
return res;
},
parseHtml: function parseHtml(html, options) {
var self = this;
var $options = options || {};
$options.components || ($options.components = this.empty);
var result = [];
var current;
var level = -1;
var arr = [];
var byTag = {};
var inComponent = false;
html.replace(this.tagRE, function (tag, index) {
if (inComponent) {
if (tag !== "</".concat(current.name, ">")) {
return;
}
inComponent = false;
}
var isOpen = tag.charAt(1) !== '/';
var start = index + tag.length;
var nextChar = html.charAt(start);
var parent;
if (isOpen) {
level += 1;
current = self.parseTags(tag);
if (current.type === 'tag' && $options.components[current.name]) {
current.type = 'component';
inComponent = true;
}
if (!current.voidElement && !inComponent && nextChar && nextChar !== '<') {
current.children.push({
type: 'text',
content: slice$7(html).call(html, start, indexOf$8(html).call(html, '<', start))
});
}
byTag[current.tagName] = current; // if we're at root, push new base node
if (level === 0) {
result.push(current);
}
parent = arr[level - 1];
if (parent) {
parent.children.push(current);
}
arr[level] = current;
}
if (!isOpen || current.voidElement) {
level -= 1;
if (!inComponent && nextChar !== '<' && nextChar) {
// trailing text node
if (arr[level]) {
arr[level].children.push({
type: 'text',
content: slice$7(html).call(html, start, indexOf$8(html).call(html, '<', start))
});
}
}
}
});
return result;
}
},
/** **
* 标签解析器
* 解析对应的标签,并调用格式化引擎生成对应格式内容
**/
tagParser: {
// 挂载的解析引擎一次只能挂在一个解析引擎目前只实现和挂载了markdown解析引擎
formatEngine: {},
/**
* 解析p标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
pParser: function pParser(obj, str) {
var $str = str;
if (/\n$/.test($str)) {
return $str;
}
return "".concat($str, "\n");
},
/**
* 解析div标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
divParser: function divParser(obj, str) {
var $str = str;
if (/\n$/.test($str)) {
return $str;
}
return "".concat($str, "\n");
},
/**
* 解析span标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
spanParser: function spanParser(obj, str) {
var $str = str.replace(/\t/g, '').replace(/\n/g, ' '); // span标签里不应该有\n的有的话就转化成空格
if (obj.attrs && obj.attrs.style) ;
return $str;
},
/**
* 解析code标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @param {boolean} isBlock 是否强制为代码块
* @returns {string} str
*/
codeParser: function codeParser(obj, str) {
var isBlock = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
return this.formatEngine.convertCode(str, isBlock);
},
/**
* 解析br标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
brParser: function brParser(obj, str) {
return this.formatEngine.convertBr(str, '\n');
},
/**
* 解析img标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
imgParser: function imgParser(obj, str) {
if (obj.attrs && obj.attrs['data-control'] === 'tapd-graph') {
return this.formatEngine.convertGraph(obj.attrs.title, obj.attrs.src, obj.attrs['data-origin-xml'], obj);
}
if (obj.attrs && obj.attrs.src) {
return this.formatEngine.convertImg(obj.attrs.alt, obj.attrs.src);
}
},
/**
* 解析video标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
videoParser: function videoParser(obj, str) {
if (obj.attrs && obj.attrs.src) {
return this.formatEngine.convertVideo(str, obj.attrs.src, obj.attrs.poster, obj.attrs.title);
}
},
/**
* 解析b标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
bParser: function bParser(obj, str) {
var strArr = str.split('\n');
var ret = [];
for (var i = 0; i < strArr.length; i++) {
ret.push(this.formatEngine.convertB(strArr[i]));
}
return ret.join('\n');
},
/**
* 解析i标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
iParser: function iParser(obj, str) {
var strArr = str.split('\n');
var ret = [];
for (var i = 0; i < strArr.length; i++) {
ret.push(this.formatEngine.convertI(strArr[i]));
}
return ret.join('\n');
},
/**
* 解析strike标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
strikeParser: function strikeParser(obj, str) {
var strArr = str.split('\n');
var ret = [];
for (var i = 0; i < strArr.length; i++) {
ret.push(this.formatEngine.convertStrike(strArr[i]));
}
return ret.join('\n');
},
/**
* 解析del标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
delParser: function delParser(obj, str) {
var strArr = str.split('\n');
var ret = [];
for (var i = 0; i < strArr.length; i++) {
ret.push(this.formatEngine.convertDel(strArr[i]));
}
return ret.join('\n');
},
/**
* 解析u标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
uParser: function uParser(obj, str) {
var strArr = str.split('\n');
var ret = [];
for (var i = 0; i < strArr.length; i++) {
ret.push(this.formatEngine.convertU(strArr[i]));
}
return ret.join('\n');
},
/**
* 解析a标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
aParser: function aParser(obj, str) {
if (obj.attrs && obj.attrs.href) {
return this.formatEngine.convertA(str, obj.attrs.href);
}
return '';
},
/**
* 解析sup标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
supParser: function supParser(obj, str) {
return this.formatEngine.convertSup(str);
},
/**
* 解析sub标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
subParser: function subParser(obj, str) {
return this.formatEngine.convertSub(str);
},
/**
* 解析td标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
tdParser: function tdParser(obj, str) {
return this.formatEngine.convertTd(str);
},
/**
* 解析tr标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
trParser: function trParser(obj, str) {
return this.formatEngine.convertTr(str);
},
/**
* 解析th标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
thParser: function thParser(obj, str) {
return this.formatEngine.convertTh(str);
},
/**
* 解析thead标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
theadParser: function theadParser(obj, str) {
return this.formatEngine.convertThead(str);
},
/**
* 解析table标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
tableParser: function tableParser(obj, str) {
return this.formatEngine.convertTable(str);
},
/**
* 解析li标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
liParser: function liParser(obj, str) {
return this.formatEngine.convertLi(str);
},
/**
* 解析ul标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
ulParser: function ulParser(obj, str) {
return this.formatEngine.convertUl(str);
},
/**
* 解析ol标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
olParser: function olParser(obj, str) {
return this.formatEngine.convertOl(str);
},
/**
* 解析strong标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
strongParser: function strongParser(obj, str) {
return this.formatEngine.convertStrong(str);
},
/**
* 解析hr标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
hrParser: function hrParser(obj, str) {
return this.formatEngine.convertHr(str);
},
/**
* 解析h1标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
h1Parser: function h1Parser(obj, str) {
return this.formatEngine.convertH1(str);
},
/**
* 解析h2标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
h2Parser: function h2Parser(obj, str) {
return this.formatEngine.convertH2(str);
},
/**
* 解析h3标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
h3Parser: function h3Parser(obj, str) {
return this.formatEngine.convertH3(str);
},
/**
* 解析h4标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
h4Parser: function h4Parser(obj, str) {
return this.formatEngine.convertH4(str);
},
/**
* 解析h5标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
h5Parser: function h5Parser(obj, str) {
return this.formatEngine.convertH5(str);
},
/**
* 解析h6标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
h6Parser: function h6Parser(obj, str) {
return this.formatEngine.convertH6(str);
},
/**
* 解析blockquote标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
blockquoteParser: function blockquoteParser(obj, str) {
return this.formatEngine.convertBlockquote(str.replace(/\n+/g, '\n'));
},
/**
* 解析address标签
* @param {HTMLElement} obj
* @param {string} str 需要回填的字符串
* @returns {string} str
*/
addressParser: function addressParser(obj, str) {
return this.formatEngine.convertAddress(str.replace(/\n+/g, '\n'));
},
// 样式解析器
styleParser: {
// 识别字体颜色 color
colorAttrParser: function colorAttrParser(style) {
var color = style.match(/color:\s*(#[a-zA-Z0-9]{3,6});/);
if (color && color[1]) {
return color[1];
}
return '';
},
// 识别字体大小 font-size
sizeAttrParser: function sizeAttrParser(style) {
var fontSize = style.match(/font-size:\s*([a-zA-Z0-9-]+?);/);
if (fontSize && fontSize[1]) {
var size = 0;
if (/[0-9]+px/.test(fontSize[1])) {
var _context3;
size = trim$3(_context3 = fontSize[1].replace(/px/, '')).call(_context3);
} else {
switch (fontSize[1]) {
case 'x-small':
size = 10;
break;
case 'small':
size = 12;
break;
case 'medium':
size = 16;
break;
case 'large':
size = 18;
break;
case 'x-large':
size = 24;
break;
case 'xx-large':
size = 32;
break;
default:
size = '';
}
}
return size > 0 ? size : '';
}
return '';
},
// 识别字体背景颜色 background-color
bgColorAttrParser: function bgColorAttrParser(style) {
var color = style.match(/background-color:\s*([^;]+?);/);
if (color && color[1]) {
var bgColor = '';
if (/rgb\([ 0-9]+,[ 0-9]+,[ 0-9]+\)/.test(color[1])) {
var values = color[1].match(/rgb\(([ 0-9]+),([ 0-9]+),([ 0-9]+)\)/);
if (values[1] && values[2] && values[3]) {
var _context4, _context5, _context6, _context7, _context8;
values[1] = _parseInt$2(trim$3(_context4 = values[1]).call(_context4), 10);
values[2] = _parseInt$2(trim$3(_context5 = values[2]).call(_context5), 10);
values[3] = _parseInt$2(trim$3(_context6 = values[3]).call(_context6), 10);
bgColor = concat$5(_context7 = concat$5(_context8 = "#".concat(values[1].toString(16))).call(_context8, values[2].toString(16))).call(_context7, values[3].toString(16));
}
} else {
var _color = _slicedToArray(color, 2);
bgColor = _color[1];
}
return bgColor;
}
return '';
}
}
},
/**
* 一个格式化引擎
* 将字符串格式化成markdown语法的引擎
**/
mdFormatEngine: {
convertColor: function convertColor(str, attr) {
var _context9;
var $str = trim$3(str).call(str);
if (!$str || /\n/.test($str)) {
return $str;
}
return attr ? concat$5(_context9 = "!!".concat(attr, " ")).call(_context9, $str, "!!") : $str;
},
convertSize: function convertSize(str, attr) {
var _context10;
var $str = trim$3(str).call(str);
if (!$str || /\n/.test($str)) {
return $str;
}
return attr ? concat$5(_context10 = "!".concat(attr, " ")).call(_context10, $str, "!") : $str;
},
convertBgColor: function convertBgColor(str, attr) {
var _context11;
var $str = trim$3(str).call(str);
if (!$str || /\n/.test($str)) {
return $str;
}
return attr ? concat$5(_context11 = "!!!".concat(attr, " ")).call(_context11, $str, "!!!") : $str;
},
convertBr: function convertBr(str, attr) {
return str + attr;
},
convertCode: function convertCode(str) {
var isBlock = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (/\n/.test(str) || isBlock) {
return "```\n".concat(str.replace(/\n+$/, ''), "\n```");
}
return "`".concat(str.replace(/`/g, '\\`'), "`");
},
convertB: function convertB(str) {
return /^\s*$/.test(str) ? '' : "**".concat(str, "**");
},
convertI: function convertI(str) {
return /^\s*$/.test(str) ? '' : "*".concat(str, "*");
},
convertU: function convertU(str) {
return /^\s*$/.test(str) ? '' : " /".concat(str, "/ ");
},
convertImg: function convertImg(alt, src) {
var _context12;
var $alt = alt && alt.length > 0 ? alt : 'image';
return concat$5(_context12 = "![".concat($alt, "](")).call(_context12, src, ")");
},
convertGraph: function convertGraph(str, attr, data, obj) {
var _context15, _context16, _context17;
var $str = str && str.length > 0 ? str : 'graph';
var moreAttrs = '';
if (obj) {
try {
var _context13;
var attrs = obj.attrs;
forEach$3(_context13 = keys$3(attrs)).call(_context13, function (prop) {
if (Object.prototype.hasOwnProperty.call(attrs, prop)) {
if (indexOf$8(prop).call(prop, 'data-graph-') >= 0 && attrs[prop]) {
var _context14;
moreAttrs += concat$5(_context14 = " ".concat(prop, "=")).call(_context14, attrs[prop]);
}
}
});
} catch (error) {// console.log('error', error)
}
}
return concat$5(_context15 = concat$5(_context16 = concat$5(_context17 = "![".concat($str, "](")).call(_context17, attr, "){data-control=tapd-graph data-origin-xml=")).call(_context16, data)).call(_context15, moreAttrs, "}");
},
convertVideo: function convertVideo(str, src, poster, title) {
var _context18, _context19;
var $title = title && title.length > 0 ? title : 'video';
return concat$5(_context18 = concat$5(_context19 = "!video[".concat($title, "](")).call(_context19, src, "){poster=")).call(_context18, poster, "}");
},
convertA: function convertA(str, attr) {
var _context20;
if (str === attr) {
return "".concat(str, " ");
}
var $str = trim$3(str).call(str);
if (!$str) {
return $str;
}
return concat$5(_context20 = "[".concat($str, "](")).call(_context20, attr, ")");
},
convertSup: function convertSup(str) {
return "^".concat(trim$3(str).call(str).replace(/\^/g, '\\^'), "^");
},
convertSub: function convertSub(str) {
return "^^".concat(trim$3(str).call(str).replace(/\^\^/g, '\\^\\^'), "^^");
},
convertTd: function convertTd(str) {
return "~|".concat(trim$3(str).call(str).replace(/\n{1,}/g, '<br>'), " ~|");
},
convertTh: function convertTh(str) {
return "~|".concat(trim$3(str).call(str).replace(/\n{1,}/g, '<br>'), " ~|");
},
convertTr: function convertTr(str) {
return "".concat(str.replace(/\n/g, ''), "\n");
},
convertThead: function convertThead(str) {
return "".concat(str.replace(/~\|~\|/g, '~|').replace(/~\|/g, '|'), "|:--|\n");
},
convertTable: function convertTable(str) {
var ret = "\n".concat(str.replace(/~\|~\|/g, '~|').replace(/~\|/g, '|'), "\n").replace(/\n{2,}/g, '\n');
if (/\|:--\|/.test(ret)) {
return ret;
}
return "\n| |\n|:--|".concat(ret);
},
convertLi: function convertLi(str) {
return "- ".concat(str.replace(/^\n/, '').replace(/\n+$/, '').replace(/\n+/g, '\n\t'), "\n");
},
convertUl: function convertUl(str) {
return "".concat(str, "\n");
},
convertOl: function convertOl(str) {
var arr = str.split('\n');
var index = 1;
for (var i = 0; i < arr.length; i++) {
if (/^- /.test(arr[i])) {
arr[i] = arr[i].replace(/^- /, "".concat(index, ". "));
index += 1;
}
}
var $str = arr.join('\n');
return "".concat($str, "\n");
},
convertStrong: function convertStrong(str) {
return /^\s*$/.test(str) ? '' : "**".concat(str, "**");
},
convertStrike: function convertStrike(str) {
return /^\s*$/.test(str) ? '' : "~~".concat(str, "~~");
},
convertDel: function convertDel(str) {
return /^\s*$/.test(str) ? '' : "~~".concat(str, "~~");
},
convertHr: function convertHr(str) {
return /^\s*$/.test(str) ? '\n\n----\n' : "\n\n----\n".concat(str);
},
convertH1: function convertH1(str) {
return "# ".concat(trim$3(str).call(str).replace(/\n+$/, ''), "\n\n");
},
convertH2: function convertH2(str) {
return "## ".concat(trim$3(str).call(str).replace(/\n+$/, ''), "\n\n");
},
convertH3: function convertH3(str) {
return "### ".concat(trim$3(str).call(str).replace(/\n+$/, ''), "\n\n");
},
convertH4: function convertH4(str) {
return "#### ".concat(trim$3(str).call(str).replace(/\n+$/, ''), "\n\n");
},
convertH5: function convertH5(str) {
return "##### ".concat(trim$3(str).call(str).replace(/\n+$/, ''), "\n\n");
},
convertH6: function convertH6(str) {
return "###### ".concat(trim$3(str).call(str).replace(/\n+$/, ''), "\n\n");
},
convertBlockquote: function convertBlockquote(str) {
return ">".concat(trim$3(str).call(str), "\n\n");
},
convertAddress: function convertAddress(str) {
return ">".concat(trim$3(str).call(str), "\n\n");
}
},
/**
* 清除整段的样式、方便编辑
* 暂时先屏蔽字体色和背景色
* @param {Array} htmlparsedArrays 由HTMLElement组成的数组
*/
paragraphStyleClear: function paragraphStyleClear(htmlparsedArrays) {
for (var index = 0; index < htmlparsedArrays[0].children.length; index++) {
var htmlItem = htmlparsedArrays[0].children[index];
var stack = [htmlItem];
var paragraphs = [];
while (stack.length) {
var temp = stack.shift();
var childCount = this.notEmptyTagCount(temp);
if (childCount === 1) {
paragraphs.push(temp);
} else if (childCount > 1) {
for (var k = 0; k < temp.children.length; k++) {
stack.push(temp.children[k]);
}
} else {
if (paragraphs.length === 1) {
this.clearChildColorAttrs(paragraphs.pop());
}
paragraphs = [];
}
}
if (paragraphs.length === 1) {
this.clearChildColorAttrs(paragraphs.pop());
}
}
return htmlparsedArrays;
},
/**
* 非空子元素数量
*/
notEmptyTagCount: function notEmptyTagCount(htmlItem) {
if (!htmlItem || htmlItem.voidElement || htmlItem.type === 'tag' && !htmlItem.children.length || htmlItem.type === 'text' && !htmlItem.content.replace(/(\r|\n|\s)+/g, '')) {
return 0;
}
if (htmlItem.children && htmlItem.children.length) {
var res = 0;
for (var index = 0; index < htmlItem.children.length; index++) {
res += this.notEmptyTagCount(htmlItem.children[index]);
}
return res;
}
return 1;
},
clearChildColorAttrs: function clearChildColorAttrs(htmlItems) {
var self = this;
this.forEachHtmlParsedItems(htmlItems, function (htmlItem) {
self.clearSelfNodeColorAttrs(htmlItem);
});
},
clearSelfNodeColorAttrs: function clearSelfNodeColorAttrs(htmlItem) {
if (htmlItem.attrs && htmlItem.attrs.style) {
var styles = htmlItem.attrs.style.split(';');
var newStyles = [];
for (var index = 0; index < styles.length; index++) {
var _context21;
if (styles[index] && indexOf$8(_context21 = styles[index]).call(_context21, 'color') === -1) {
newStyles.push(styles[index]);
}
}
if (newStyles.length) {
htmlItem.attrs.style = "".concat(newStyles.join(';'), ";");
} else {
delete htmlItem.attrs.style;
}
}
},
forEachHtmlParsedItems: function forEachHtmlParsedItems(htmlItems, cb) {
if (htmlItems) {
cb(htmlItems);
if (htmlItems.children && htmlItems.children.length) {
for (var index = 0; index < htmlItems.children.length; index++) {
this.forEachHtmlParsedItems(htmlItems.children[index], cb);
}
}
}
}
};
var assign$3 = assign$1;
var assign$4 = assign$3;
var assign$5 = assign$4;
var assign$6 = assign$5;
var _extends_1 = createCommonjsModule(function (module) {
function _extends() {
module.exports = _extends = assign$6 || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
}, module.exports.__esModule = true, module.exports["default"] = module.exports;
return _extends.apply(this, arguments);
}
module.exports = _extends, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
var _extends = unwrapExports(_extends_1);
var trim$5 = stringTrim.trim;
var charAt$3 = functionUncurryThis(''.charAt);
var n$ParseFloat = global_1.parseFloat;
var Symbol$4 = global_1.Symbol;
var ITERATOR$6 = Symbol$4 && Symbol$4.iterator;
var FORCED$5 = 1 / n$ParseFloat(whitespaces + '-0') !== -Infinity
// MS Edge 18- broken with boxed symbols
|| (ITERATOR$6 && !fails(function () { n$ParseFloat(Object(ITERATOR$6)); }));
// `parseFloat` method
// https://tc39.es/ecma262/#sec-parsefloat-string
var numberParseFloat = FORCED$5 ? function parseFloat(string) {
var trimmedString = trim$5(toString_1(string));
var result = n$ParseFloat(trimmedString);
return result === 0 && charAt$3(trimmedString, 0) == '-' ? -0 : result;
} : n$ParseFloat;
// `parseFloat` method
// https://tc39.es/ecma262/#sec-parsefloat-string
_export({ global: true, forced: parseFloat != numberParseFloat }, {
parseFloat: numberParseFloat
});
var _parseFloat = path.parseFloat;
var _parseFloat$1 = _parseFloat;
var _parseFloat$2 = _parseFloat$1;
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function mergeMarginBottom(bottom, top) {
var currentBottom = _parseFloat$2(bottom);
var nextTop = _parseFloat$2(top);
if (nextTop >= 0) {
// 不受合并影响
return currentBottom;
}
if (currentBottom >= 0) {
return currentBottom + nextTop;
} // 同时为负数,取最小的
return Math.min(currentBottom, nextTop);
}
function mergeMarginTop(bottom, top) {
var prevBottom = _parseFloat$2(bottom);
var currentTop = _parseFloat$2(top);
if (currentTop < 0) {
// 负数的margin都被上一个区块吸收了
return 0;
}
if (prevBottom >= 0) {
// 如果当前margin-top比上一个margin-bottom要大则只合并部分反之合并全部归属于上一个区块
return Math.max(currentTop - prevBottom, 0);
} // 上一个margin-bottom为负数不受影响
return currentTop;
}
/**
* 用于解决块级元素边距合并问题
* @param {HTMLElement} element
*/
function getBlockTopAndHeightWithMargin(element) {
var prevSibling = element.previousElementSibling;
var nextSibling = element.nextElementSibling;
if (!prevSibling) {
var _style = getComputedStyle(element);
var _rect = element.getBoundingClientRect();
if (!nextSibling) {
return {
// marginBottom可能为负数
height: Math.max(_parseFloat$2(_style.marginTop) + _rect.height + _parseFloat$2(_style.marginBottom), 0),
offsetTop: element.offsetTop - Math.abs(_parseFloat$2(_style.marginTop))
};
}
var _nextSibStyle = getComputedStyle(nextSibling);
var _marginBottom = mergeMarginBottom(_style.marginBottom, _nextSibStyle.marginTop);
return {
height: Math.max(_parseFloat$2(_style.marginTop) + _rect.height + _marginBottom, 0),
// marginBottom可能为负数
offsetTop: element.offsetTop - Math.abs(_parseFloat$2(_style.marginTop))
};
}
var style = getComputedStyle(element);
var rect = element.getBoundingClientRect();
var prevSibStyle = getComputedStyle(prevSibling);
var marginTop = mergeMarginTop(prevSibStyle.marginBottom, style.marginTop);
if (!nextSibling) {
return {
height: Math.max(marginTop + rect.height + _parseFloat$2(style.marginBottom), 0),
// marginBottom可能为负数
offsetTop: element.offsetTop - Math.abs(_parseFloat$2(style.marginTop))
};
}
var nextSibStyle = getComputedStyle(nextSibling);
var marginBottom = mergeMarginBottom(style.marginBottom, nextSibStyle.marginTop);
return {
height: Math.max(marginTop + rect.height + marginBottom, 0),
// marginBottom可能为负数
offsetTop: element.offsetTop - Math.abs(marginTop)
};
}
/**
* document.elementsFromPoint polyfill
* ref: https://github.com/JSmith01/elementsfrompoint-polyfill/blob/master/index.js
* @param {number} x
* @param {number} y
*/
function elementsFromPoint(x, y) {
// see https://caniuse.com/#search=elementsFromPoint
if (typeof document.elementsFromPoint === 'function') {
return document.elementsFromPoint(x, y);
}
if (typeof
/** @type {any}*/
document.msElementsFromPoint === 'function') {
var nodeList =
/** @type {any}*/
document.msElementsFromPoint(x, y);
return nodeList !== null ? from_1$2(nodeList) : nodeList;
}
var elements = [];
var pointerEvents = [];
/** @type {HTMLElement} */
var ele;
do {
var currentElement =
/** @type {HTMLElement} */
document.elementFromPoint(x, y);
if (ele !== currentElement) {
ele = currentElement;
elements.push(ele);
pointerEvents.push(ele.style.pointerEvents);
ele.style.pointerEvents = 'none';
} else {
ele = null;
}
} while (ele);
forEach$3(elements).call(elements, function (e, index) {
e.style.pointerEvents = pointerEvents[index];
});
return elements;
}
function getHTML(who, deep) {
if (!who || !who.tagName) {
return '';
}
var txt;
var ax;
var el = document.createElement('div');
el.appendChild(who.cloneNode(false));
txt = el.innerHTML;
if (deep) {
ax = indexOf$8(txt).call(txt, '>') + 1;
txt = txt.substring(0, ax) + who.innerHTML + txt.substring(ax);
}
el = null;
return txt;
}
/**
* @template {keyof HTMLElementTagNameMap} K
* @param {K} tagName 标签名
* @param {string} className 元素类名
* @param {Record<string,string>} attributes 附加属性
* @returns {HTMLElementTagNameMap[K]}
*/
function createElement(tagName) {
var className = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var element = document.createElement(tagName);
element.className = className;
if (typeof attributes !== 'undefined') {
var _context;
forEach$3(_context = keys$3(attributes)).call(_context, function (key) {
var value = attributes[key];
if (startsWith$3(key).call(key, 'data-')) {
var dataName = key.replace(/^data-/, '');
element.dataset[dataName] = value;
return;
}
element.setAttribute(key, value);
});
}
return element;
}
var SAFE_AREA_MARGIN = 15;
/**
* Cherry实现了将粘贴的html内容转成对应的markdown源码的功能
* 本工具主要实现将粘贴html转成的markdown源码在编辑器中选中并给出切换按钮
* 可以切换为纯文本内容或者markdown内容
*/
var pasteHelper = {
/**
* 核心方法,粘贴后展示切换按钮
* 只有粘贴html时才会出现切换按钮
* @param {Object} currentCursor 当前的光标位置
* @param {Object} editor 编辑器对象
* @param {string} html html里的纯文本内容
* @param {string} md html对应的markdown源码
* @returns
*/
showSwitchBtnAfterPasteHtml: function showSwitchBtnAfterPasteHtml($cherry, currentCursor, editor, html, md) {
if (trim$3(html).call(html) === trim$3(md).call(md)) {
return;
}
this.init($cherry, currentCursor, editor, html, md);
this.setSelection();
this.bindListener();
this.initBubble();
this.showBubble(); // 默认粘贴成markdown格式如果用户上次选择粘贴为纯文本则需要切换为text
if (this.getTypeFromLocalStorage() === 'text') {
this.switchTextClick();
}
},
init: function init($cherry, currentCursor, editor, html, md) {
this.$cherry = $cherry;
this.html = html;
this.md = md;
this.codemirror = editor;
this.currentCursor = currentCursor;
this.locale = $cherry.locale;
},
/**
* 获取缓存中的复制粘贴类型
*/
getTypeFromLocalStorage: function getTypeFromLocalStorage() {
if (typeof localStorage === 'undefined') {
return 'md';
}
return localStorage.getItem('cherry-paste-type') || 'md';
},
/**
* 记忆最近一次用户选择的粘贴类型
*/
setTypeToLocalStorage: function setTypeToLocalStorage(type) {
if (typeof localStorage === 'undefined') {
return;
}
localStorage.setItem('cherry-paste-type', type);
},
/**
* 在编辑器中自动选中刚刚粘贴的内容
*/
setSelection: function setSelection() {
var _this$codemirror$getC = this.codemirror.getCursor(),
end = _extends({}, _this$codemirror$getC);
var begin = this.currentCursor;
this.codemirror.setSelection(begin, end);
},
/**
* 绑定事件
* 当编辑器选中区域改变、内容改变时,隐藏切换按钮
* 当编辑器滚动时,实时更新切换按钮的位置
* @returns null
*/
bindListener: function bindListener() {
var _this = this;
if (!this.hasBindListener) {
this.hasBindListener = true;
} else {
return true;
}
this.codemirror.on('beforeSelectionChange', function (codemirror, info) {
_this.hideBubble();
});
this.codemirror.on('beforeChange', function (codemirror, info) {
_this.hideBubble();
});
this.codemirror.on('scroll', function (codemirror) {
_this.updatePositionWhenScroll();
});
},
isHidden: function isHidden() {
return this.bubbleDom.style.display === 'none';
},
toggleBubbleDisplay: function toggleBubbleDisplay() {
if (this.isHidden()) {
this.bubbleDom.style.display = '';
return;
}
this.bubbleDom.style.display = 'none';
return;
},
hideBubble: function hideBubble() {
if (this.noHide) {
return true;
}
if (this.isHidden()) {
return;
}
this.toggleBubbleDisplay();
},
updatePositionWhenScroll: function updatePositionWhenScroll() {
if (this.isHidden()) {
return;
} // FIXME: update position when stick to the bottom
// const isStickToBottom = !this.bubbleDom.style.top;
var offset = this.bubbleDom.dataset.scrollTop - this.getScrollTop();
this.bubbleDom.style.marginTop = "".concat(offset, "px");
},
getScrollTop: function getScrollTop() {
return this.codemirror.getScrollInfo().top;
},
showBubble: function showBubble() {
var _this$getLastSelected = this.getLastSelectedPosition(),
top = _this$getLastSelected.top;
if (this.isHidden()) {
this.toggleBubbleDisplay();
this.bubbleDom.style.marginTop = '0';
this.bubbleDom.dataset.scrollTop = this.getScrollTop();
}
/**
* @type {HTMLDivElement}
*/
var codemirrorWrapper = this.codemirror.getWrapperElement();
var maxTop = codemirrorWrapper.clientHeight - this.bubbleDom.getBoundingClientRect().height - SAFE_AREA_MARGIN;
if (top > maxTop) {
this.bubbleDom.style.top = '';
this.bubbleDom.style.bottom = "".concat(SAFE_AREA_MARGIN, "px");
} else {
this.bubbleDom.style.top = "".concat(top, "px");
this.bubbleDom.style.bottom = '';
}
},
initBubble: function initBubble() {
var _context, _context2;
if (this.bubbleDom) {
this.bubbleDom.setAttribute('data-type', 'md');
return true;
}
var dom = createElement('div', 'cherry-bubble cherry-bubble--centered cherry-switch-paste');
dom.style.display = 'none';
var switchText = createElement('span', 'cherry-toolbar-button cherry-text-btn', {
title: this.locale.pastePlain
});
switchText.innerText = 'TEXT';
var switchMd = createElement('span', 'cherry-toolbar-button cherry-md-btn', {
title: this.locale.pasteMarkdown
});
switchMd.innerText = 'Markdown';
var switchBG = createElement('span', 'switch-btn--bg');
this.bubbleDom = dom;
this.switchText = switchText;
this.switchMd = switchMd;
this.switchBG = switchBG;
this.bubbleDom.appendChild(switchText);
this.bubbleDom.appendChild(switchMd);
this.bubbleDom.appendChild(switchBG);
this.bubbleDom.setAttribute('data-type', 'md');
this.codemirror.getWrapperElement().appendChild(this.bubbleDom);
this.switchMd.addEventListener('click', bind$5(_context = this.switchMDClick).call(_context, this));
this.switchText.addEventListener('click', bind$5(_context2 = this.switchTextClick).call(_context2, this));
},
switchMDClick: function switchMDClick(event) {
this.setTypeToLocalStorage('md');
if (this.bubbleDom.getAttribute('data-type') === 'md') {
return;
}
this.noHide = true;
this.bubbleDom.setAttribute('data-type', 'md');
this.codemirror.doc.replaceSelection(this.md);
this.setSelection();
this.showBubble();
this.noHide = false;
},
switchTextClick: function switchTextClick(event) {
this.setTypeToLocalStorage('text');
if (this.bubbleDom.getAttribute('data-type') === 'text') {
return;
}
this.noHide = true;
this.bubbleDom.setAttribute('data-type', 'text');
this.codemirror.doc.replaceSelection(this.html);
this.setSelection();
this.showBubble();
this.noHide = false;
},
getLastSelectedPosition: function getLastSelectedPosition() {
var selectedObjs = from_1$2(this.codemirror.getWrapperElement().getElementsByClassName('CodeMirror-selected'));
var width = 0;
var top = 0;
if (selectedObjs.length <= 0) {
this.hideBubble();
return {};
} // FIXME: remove redundant width calculation
for (var key = 0; key < selectedObjs.length; key++) {
var item = selectedObjs[key];
var position = item.getBoundingClientRect();
var tmpWidth = position.left + position.width / 2;
var tmpTop = position.top + position.height;
if (tmpTop > top && tmpWidth >= width) {
top = tmpTop;
}
if (tmpWidth > width) {
width = tmpWidth;
}
}
return {
top: top
};
}
};
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function addEvent(elm, evType, fn, useCapture) {
if (elm.addEventListener) {
elm.addEventListener(evType, fn, useCapture); // DOM2.0
return true;
}
if (elm.attachEvent) {
var r = elm.attachEvent("on".concat(evType), fn); // IE5+
return r;
}
elm["on".concat(evType)] = fn; // DOM 0
}
function removeEvent(elm, evType, fn, useCapture) {
if (elm.removeEventListener) {
elm.removeEventListener(evType, fn, useCapture); // DOM2.0
} else if (elm.detachEvent) {
var r = elm.detachEvent("on".concat(evType), fn); // IE5+
return r;
} else {
elm["on".concat(evType)] = null; // DOM 0
}
}
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// @ts-check
/** @type {Partial<Console>} */
var Logger = new Proxy({}, {
get: function get(target, prop, receiver) {
// @ts-ignore
if ( typeof console !== 'undefined' && prop in console) {
return console[prop];
}
return function () {};
}
});
function mitt(n){return {all:n=n||new Map,on:function(t,e){var i=n.get(t);i?i.push(e):n.set(t,[e]);},off:function(t,e){var i=n.get(t);i&&(e?i.splice(i.indexOf(e)>>>0,1):n.set(t,[]));},emit:function(t,e){var i=n.get(t);i&&i.slice().map(function(n){n(e);}),(i=n.get("*"))&&i.slice().map(function(n){n(t,e);});}}}
/**
* 事件管理
*/
var Event$1 = new ( /*#__PURE__*/function () {
function Event() {
_classCallCheck(this, Event);
_defineProperty(this, "Events", {
previewerClose: 'previewer:close',
previewerOpen: 'previewer:open',
editorClose: 'editor:close',
editorOpen: 'editor:open',
toolbarHide: 'toolbar:hide',
toolbarShow: 'toolbar:show',
cleanAllSubMenus: 'cleanAllSubMenus' // 清除所有子菜单弹窗
});
_defineProperty(this, "emitter", mitt());
}
_createClass(Event, [{
key: "on",
value:
/**
* 注册监听事件
* @param {string} instanceId 接收消息的频道
* @param {string} event 要注册监听的事件
* @param {(event: any) => void} handler 事件回调
*/
function on(instanceId, event, handler) {
var _context;
this.emitter.on(concat$5(_context = "".concat(instanceId, ":")).call(_context, event), handler);
}
/**
* 触发事件
* @param {string} instanceId 发送消息的频道
* @param {string} event 要触发的事件
*/
}, {
key: "emit",
value: function emit(instanceId, event) {
var _context2;
this.emitter.emit(concat$5(_context2 = "".concat(instanceId, ":")).call(_context2, event));
}
}]);
return Event;
}())();
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* 上传文件的逻辑如果有callback则不再走默认的替换文本的逻辑而是调用callback
* @param {string} type 上传文件的类型
*/
function handleUpload(editor) {
var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'image';
var accept = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '*';
// var callback = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
// type为上传文件类型 image|video|audio|pdf|word
var input = document.createElement('input');
input.type = 'file';
input.id = 'fileUpload';
input.value = '';
input.style.display = 'none';
input.accept = accept; // document.body.appendChild(input);
input.multiple = 'multiple';
input.addEventListener('change', function (event) {
// @ts-ignore
// var _event$target$files = _slicedToArray(event.target.files, 1),
// file = _event$target$files[0]; // 文件上传后的回调函数可以由调用方自己实现
// 3xxx 20240607
let files = event.target.files;
for (let i = 0; i < files.length; i++) {
var file = files[i]
editor.options.fileUpload(file, function (url) {
var callback = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
// 文件上传的默认回调行数,调用方可以完全不使用该函数
if (typeof url !== 'string' || !url) {
return;
}
if (callback) {
return callback(file.name, url, params);
}
var code = '';
if (type === 'image') {
var _context;
// 如果是图片则返回固定的图片markdown源码
code = concat$5(_context = "![".concat(file.name, "](")).call(_context, url, ")");
} else if (type === 'video') {
var _context2;
// 如果是视频则返回固定的视频markdown源码
code = concat$5(_context2 = "!video[".concat(file.name, "](")).call(_context2, url, ")");
} else if (type === 'audio') {
var _context3;
// 如果是音频则返回固定的音频markdown源码
code = concat$5(_context3 = "!audio[".concat(file.name, "](")).call(_context3, url, ")");
} else {
var _context4;
// 默认返回超链接
code = concat$5(_context4 = "[".concat(file.name, "](")).call(_context4, url, ")");
} // 替换选中区域
// @ts-ignore
editor.editor.doc.replaceSelection(code);
});
}
});
input.click();
}
/**
* 解析params参数
* @param params?.isBorder 是否有边框样式(图片场景下生效)
* @param params?.isShadow 是否有阴影样式(图片场景下生效)
* @param params?.isRadius 是否有圆角样式(图片场景下生效)
* @param params?.width 设置宽度,可以是像素、也可以是百分比(图片、视频场景下生效)
* @param params?.height 设置高度,可以是像素、也可以是百分比(图片、视频场景下生效)
*/
function handelParams(params) {
var ret = [];
if (params.isBorder) {
ret.push('#B');
}
if (params.isShadow) {
ret.push('#S');
}
if (params.isRadius) {
ret.push('#R');
}
if (params.width) {
ret.push("#".concat(params.width));
}
if (params.height) {
if (!params.width) {
ret.push('#auto');
}
ret.push("#".concat(params.height));
}
return ret.join(' ');
}
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function compileRegExp(obj, flags, allowExtendedFlags) {
var source = obj.begin + obj.content + obj.end;
if (allowExtendedFlags) {
// Extend \h for horizontal whitespace
source = source.replace(/\[\\h\]/g, HORIZONTAL_WHITESPACE).replace(/\\h/g, HORIZONTAL_WHITESPACE);
}
return new RegExp(source, flags || 'g');
}
function isLookbehindSupported() {
try {
new RegExp('(?<=.)');
return true;
} catch (ignore) {}
return false;
}
var HORIZONTAL_WHITESPACE = "[ \\t\\u00a0]"; // 仅适用非多行模式的正则
var ALLOW_WHITESPACE_MULTILINE = '(?:.*?)(?:(?:\\n.*?)*?)';
var DO_NOT_STARTS_AND_END_WITH_SPACES_MULTILINE_ALLOW_EMPTY = '(?:(?:\\S|(?:\\S.*?\\S))(?:[ \\t]*\\n.*?)*?)';
var NOT_ALL_WHITE_SPACES_INLINE = '(?:[^\\n]*?\\S[^\\n]*?)';
// !, ", #, $, %, &, ', (, ), *, +, ,, -, ., / (U+00212F),
// :, ;, <, =, >, ?, @ (U+003A0040),
// [, \, ], ^, _, ` (U+005B0060),
// {, |, }, or ~ (U+007B007E).
var PUNCTUATION = "[\\u0021-\\u002F\\u003a-\\u0040\\u005b-\\u0060\\u007b-\\u007e]"; // extra punctuations
var UNDERSCORE_EMPHASIS_BOUNDARY = '[' + "\\u0021-\\u002F\\u003a-\\u0040\\u005b\\u005d\\u005e\\u0060\\u007b-\\u007e" + // punctuations defined in commonmark
' ' + '\\t\\n' + '!“”¥‘’(),。—:;《》?【】「」·~|' + // chinese punctuations
']'; // https://html.spec.whatwg.org/multipage/input.html#e-mail-state-(type%3Demail)
var EMAIL_INLINE = new RegExp([/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+/.source, '@', /[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*/.source].join(''));
var EMAIL = new RegExp("^".concat(EMAIL_INLINE.source, "$")); // https://gist.github.com/dperini/729294
// [USERNAME[:PASSWORD]@](IP|HOST)[:PORT][/SOURCE_PATH?QUERY_PARAMS#HASH]
var URL_INLINE_NO_SLASH = new RegExp('' + // 针对eslint的特殊处理
'(?:\\S+(?::\\S*)?@)?' + '(?:' + // IP address exclusion
// IP address dotted notation octets
// excludes loopback network 0.0.0.0
// excludes reserved space >= 224.0.0.0
// excludes network & broadcast addresses
// (first & last IP address of each class)
'(?:1\\d\\d|2[01]\\d|22[0-3]|[1-9]\\d?)' + '(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}' + '(?:\\.(?:1\\d\\d|2[0-4]\\d|25[0-4]|[1-9]\\d?))' + '|' + // host & domain names, may end with dot
'(?![-_])(?:[-\\w\\xa1-\\xff]{0,63}[^-_]\\.)+' + // TLD identifier name, may end with dot
'(?:[a-zA-Z\\xa1-\\xff]{2,}\\.?)' + ')' + // port number (optional)
'(?::\\d{2,5})?' + // resource path (optional)
'(?:[/?#][^\\s<>\\x00-\\x1f"\\(\\)]*)?');
var URL_INLINE = new RegExp( // eslint特殊处理
// protocol identifier (optional)
// short syntax // still required
// '(?:(?:(?:https?|ftp):)?\\/\\/)' +
"(?:\\/\\/)".concat(URL_INLINE_NO_SLASH.source));
var URL_NO_SLASH = new RegExp("^".concat(URL_INLINE_NO_SLASH.source, "$"));
var URL$1 = new RegExp("^".concat(URL_INLINE.source, "$"));
function getTableRule() {
var _context;
var merge = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
// ^(\|[^\n]+\|\r?\n)((?:\|:?[-]+:?)+\|)(\n(?:\|[^\n]+\|\r?\n?)*)?$
// (\\|?[^\\n|]+\\|?\\n)(?:\\|?[\\s]*:?[-]{2,}:?[\\s]*
// (?:\\|[\\s]*:?[-]{2,}:?[\\s]*)+\\|?)(\\n\\|?(\\|[^\\n|]+)*\\|?)?
/**
* (\|[^\n]+\|\n) Headers
* ((\|[\s]*:?[-]{2,}:?[\s]*)+\|) Column Options
* ((?:\n\|[^\n]+\|)*) Rows
*/
var strict = {
begin: '(?:^|\\n)(\\n*)',
content: ['(\\h*\\|[^\\n]+\\|?\\h*)', // Header
'\\n', '(?:(?:\\h*\\|\\h*:?[-]{1,}:?\\h*)+\\|?\\h*)', // Column Options
'((\\n\\h*\\|[^\\n]+\\|?\\h*)*)' // Rows
].join(''),
end: '(?=$|\\n)'
};
strict.reg = compileRegExp(strict, 'g', true);
var loose = {
begin: '(?:^|\\n)(\\n*)',
content: ['(\\|?[^\\n|]+(\\|[^\\n|]+)+\\|?)', // Header
'\\n', '(?:\\|?\\h*:?[-]{1,}:?[\\h]*(?:\\|[\\h]*:?[-]{1,}:?\\h*)+\\|?)', // Column Options
'((\\n\\|?([^\\n|]+(\\|[^\\n|]*)+)\\|?)*)' // Rows
].join(''),
end: '(?=$|\\n)'
};
loose.reg = compileRegExp(loose, 'g', true);
if (merge === false) {
return {
strict: strict,
loose: loose
};
}
var regStr = concat$5(_context = "(?:".concat(strict.begin + strict.content + strict.end, "|")).call(_context, loose.begin + loose.content + loose.end, ")");
return compileRegExp({
begin: '',
content: regStr,
end: ''
}, 'g', true);
}
function getCodeBlockRule() {
var codeBlock = {
/**
* (?:^|\n)是区块的通用开头
* (\n*)捕获区块前的所有换行
* ((?:>\s*)*) 捕获代码块前面的引用("> > > " 这种东西)
* (?:[^\S\n]*)捕获```前置的空格字符
* 只要有连续3个及以上`并且前后`的数量相等,则认为是代码快语法
*/
begin: /(?:^|\n)(\n*((?:>[\t ]*)*)(?:[^\S\n]*))(`{3,})([^`]*?)\n/,
content: /([\w\W]*?)/,
// '([\\w\\W]*?)',
end: /[^\S\n]*\3[ \t]*(?=$|\n+)/ // '\\s*```[ \\t]*(?=$|\\n+)',
};
codeBlock.reg = new RegExp(codeBlock.begin.source + codeBlock.content.source + codeBlock.end.source, 'g');
return codeBlock;
}
/**
* 从selection里获取列表语法
* @param {*} selection
* @param {('ol'|'ul'|'checklist')} type 列表类型
* @returns {String}
*/
function getListFromStr(selection, type) {
var $selection = selection ? selection : 'Item 1\n Item 1.1\nItem 2';
$selection = $selection.replace(/^\n+/, '').replace(/\n+$/, '');
var pre = '1.';
switch (type) {
case 'ol':
pre = '1.';
break;
case 'ul':
pre = '-';
break;
case 'checklist':
pre = '- [x]';
break;
}
$selection = $selection.replace(/^(\s*)([0-9a-zA-Z]+\.|- \[x\]|- \[ \]|-) /gm, '$1'); // 对有序列表进行序号自增处理
if (pre === '1.') {
var listNum = {};
$selection = $selection.replace(/^(\s*)(\S[\s\S]*?)$/gm, function (match, p1, p2) {
var _p1$match, _context2, _context3;
var space = ((_p1$match = p1.match(/[ \t]/g)) === null || _p1$match === void 0 ? void 0 : _p1$match.length) || 0;
listNum[space] = listNum[space] ? listNum[space] + 1 : 1;
return concat$5(_context2 = concat$5(_context3 = "".concat(p1)).call(_context3, listNum[space], ". ")).call(_context2, p2);
});
} else {
$selection = $selection.replace(/^(\s*)(\S[\s\S]*?)$/gm, "$1".concat(pre, " $2"));
}
return $selection;
}
/**
* 信息面板的识别正则
* @returns {object}
*/
function getPanelRule() {
var ret = {
begin: /(?:^|\n)(\n*(?:[^\S\n]*)):::([^:][^\n]+?)\s*\n/,
content: /([\w\W]*?)/,
end: /\n[ \t]*:::[ \t]*(?=$|\n+)/
};
ret.reg = new RegExp(ret.begin.source + ret.content.source + ret.end.source, 'g');
return ret;
}
/**
* 手风琴/detail语法的识别正则
* 例:
* +++(-) 点击查看详情
* body
* body
* ++ 标题(默认收起内容)
* 内容
* ++- 标题(默认展开内容)
* 内容2
* +++
* @returns {object}
*/
function getDetailRule() {
var ret = {
begin: /(?:^|\n)(\n*(?:[^\S\n]*))\+\+\+([-]{0,1})\s+([^\n]+)\n/,
content: /([\w\W]+?)/,
end: /\n[ \t]*\+\+\+[ \t]*(?=$|\n+)/
};
ret.reg = new RegExp(ret.begin.source + ret.content.source + ret.end.source, 'g');
return ret;
} // 匹配图片URL里的base64
var imgBase64Reg = /(!\[[^\n]*?\]\(data:image\/png;base64,)([^)]+)\)/g; // 匹配图片{}里的data-xml属性
var imgDrawioXmlReg = /(!\[[^\n]*?\]\([^)]+\)\{[^}]* data-xml=)([^}]+)\}/g;
/**
* 匹配draw.io的图片语法
* 图片的语法为 ![alt](${base64}){data-type=drawio data-xml=${xml}}
*/
var imgDrawioReg = /(!\[[^\n]*?\]\(data:image\/png;base64,[^)]+\)\{data-type=drawio data-xml=[^}]+\})/g;
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @param {CodeMirror.Editor} cm
*/
function handleNewlineIndentList(cm) {
if (handleCherryList(cm)) return;
cm.execCommand('newlineAndIndentContinueMarkdownList');
}
function handleCherryList(cm) {
var cherryListRE = /^(\s*)([I一二三四五六七八九十]+)\.(\s+)/;
var cherryListEmptyRE = /^(\s*)([I一二三四五六七八九十]+)\.(\s+)$/;
if (cm.getOption('disableInput')) return false;
var ranges = cm.listSelections();
var replacements = [];
for (var i = 0; i < ranges.length; i++) {
var pos = ranges[i].head;
var line = cm.getLine(pos.line);
var match = cherryListRE.exec(line);
var cursorBeforeBullet = /^\s*$/.test(slice$7(line).call(line, 0, pos.ch));
if (!ranges[i].empty() || cursorBeforeBullet || !match) return;
if (cherryListEmptyRE.test(line)) {
cm.replaceRange('', {
line: pos.line,
ch: 0
}, {
line: pos.line,
ch: pos.ch + 1
});
replacements[i] = '\n';
} else {
var _context;
var indent = match[1];
var after = match[3];
replacements[i] = concat$5(_context = "\n".concat(indent, "I.")).call(_context, after);
}
}
cm.replaceSelections(replacements);
return true;
}
var _excluded = ["codemirror"];
/**
* @typedef {import('~types/editor').EditorConfiguration} EditorConfiguration
* @typedef {import('~types/editor').EditorEventCallback} EditorEventCallback
* @typedef {import('codemirror')} CodeMirror
*/
/** @type {import('~types/editor')} */
var Editor = /*#__PURE__*/function () {
/**
* @constructor
* @param {Partial<EditorConfiguration>} options
*/
function Editor(options) {
var _this = this;
_classCallCheck(this, Editor);
_defineProperty(this, "dealBigData", function () {
if (_this.noChange) {
_this.noChange = false;
return;
}
_this.formatBigData2Mark(imgBase64Reg, 'cm-url base64');
_this.formatBigData2Mark(imgDrawioXmlReg, 'cm-url drawio');
});
_defineProperty(this, "formatBigData2Mark", function (reg, className) {
var codemirror = _this.editor;
var searcher = codemirror.getSearchCursor(reg);
var oneSearch = searcher.findNext();
for (; oneSearch !== false; oneSearch = searcher.findNext()) {
var _oneSearch$, _oneSearch$2;
var target = searcher.from();
if (!target) {
continue;
}
var bigString = (_oneSearch$ = oneSearch[2]) !== null && _oneSearch$ !== void 0 ? _oneSearch$ : '';
var targetChFrom = target.ch + ((_oneSearch$2 = oneSearch[1]) === null || _oneSearch$2 === void 0 ? void 0 : _oneSearch$2.length);
var targetChTo = targetChFrom + bigString.length;
var targetLine = target.line;
var begin = {
line: targetLine,
ch: targetChFrom
};
var end = {
line: targetLine,
ch: targetChTo
}; // 如果所在区域已经有mark了则不再增加mark
if (codemirror.findMarks(begin, end).length > 0) {
continue;
}
var newSpan = createElement('span', "cm-string ".concat(className), {
title: bigString
});
newSpan.textContent = bigString;
_this.noChange = true;
codemirror.markText(begin, end, {
replacedWith: newSpan,
atomic: true
});
}
});
_defineProperty(this, "onKeyup", function (e, codemirror) {
var _codemirror$getCursor = codemirror.getCursor(),
targetLine = _codemirror$getCursor.line;
_this.previewer.highlightLine(targetLine + 1);
});
_defineProperty(this, "onScroll", function (codemirror) {
Event$1.emit(_this.instanceId, Event$1.Events.cleanAllSubMenus); // 滚动时清除所有子菜单这不应该在Bubble中处理我们关注的是编辑器的滚动 add by ufec
if (_this.disableScrollListener) {
_this.disableScrollListener = false;
return;
}
var scroller = codemirror.getScrollerElement();
if (scroller.scrollTop <= 0) {
_this.previewer.scrollToLineNum(0);
return;
}
if (scroller.scrollTop + scroller.clientHeight >= scroller.scrollHeight - 20) {
_this.previewer.scrollToLineNum(null); // 滚动到底
return;
}
var currentTop = codemirror.getScrollInfo().top;
var targetLine = codemirror.lineAtHeight(currentTop, 'local');
var lineRect = codemirror.charCoords({
line: targetLine,
ch: 0
}, 'local');
var lineHeight = codemirror.getLineHandle(targetLine).height;
var lineTop = lineRect.bottom - lineHeight; // 直接用lineRect.top在自动折行时计算的是最后一行的top
var percent = 100 * (currentTop - lineTop) / lineHeight / 100; // console.log(percent);
// codemirror中行号以0开始所以需要+1
_this.previewer.scrollToLineNum(targetLine + 1, percent);
});
_defineProperty(this, "onMouseDown", function (codemirror, evt) {
Event$1.emit(_this.instanceId, Event$1.Events.cleanAllSubMenus); // Bubble中处理需要考虑太多直接在编辑器中处理可包括Bubble中所有情况因为产生Bubble的前提是光标在编辑器中 add by ufec
var _codemirror$getCursor2 = codemirror.getCursor(),
targetLine = _codemirror$getCursor2.line;
var top = Math.abs(evt.y - codemirror.getWrapperElement().getBoundingClientRect().y);
_this.previewer.scrollToLineNumWithOffset(targetLine + 1, top);
});
_defineProperty(this, "onCursorActivity", function () {
_this.refreshWritingStatus();
});
/**
* @property
* @type {EditorConfiguration}
*/
this.options = {
id: 'code',
// textarea 的id属性值
name: 'code',
// textarea 的name属性值
autoSave2Textarea: false,
editorDom: document.createElement('div'),
wrapperDom: null,
autoScrollByCursor: true,
convertWhenPaste: true,
codemirror: {
lineNumbers: false,
// 显示行数
cursorHeight: 0.85,
// 光标高度0.85好看一些
indentUnit: 4,
// 缩进单位为4
tabSize: 4,
// 一个tab转换成的空格数量
// styleActiveLine: false, // 当前行背景高亮
// matchBrackets: true, // 括号匹配
mode: 'gfm',
// 从markdown模式改成gfm模式以使用默认高亮规则
lineWrapping: true,
// 自动换行
indentWithTabs: true,
// 缩进用tab表示
autofocus: true,
theme: 'default',
autoCloseTags: true,
// 输入html标签时自动补充闭合标签
extraKeys: {
Enter: handleNewlineIndentList
},
// 增加markdown回车自动补全
matchTags: {
bothTags: true
},
// 自动高亮选中的闭合html标签
placeholder: '',
// 设置为 contenteditable 对输入法定位更友好
// 但已知会影响某些悬浮菜单的定位如粘贴选择文本或markdown模式的菜单
// inputStyle: 'contenteditable',
keyMap: 'sublime'
},
toolbars: {},
onKeydown: function onKeydown() {},
onChange: function onChange() {},
onFocus: function onFocus() {},
onBlur: function onBlur() {},
onPaste: this.onPaste,
onScroll: this.onScroll
};
/**
* @property
* @private
* @type {{ timer?: number; destinationTop?: number }}
*/
this.animation = {};
var _codemirror = options.codemirror,
restOptions = _objectWithoutProperties(options, _excluded);
if (_codemirror) {
assign$2(this.options.codemirror, _codemirror);
}
assign$2(this.options, restOptions);
this.$cherry = this.options.$cherry;
this.instanceId = this.$cherry.getInstanceId();
}
/**
* 处理draw.io的xml数据和图片的base64数据对这种超大的数据增加省略号
*/
_createClass(Editor, [{
key: "onPaste",
value:
/**
*
* @param {ClipboardEvent} e
* @param {CodeMirror.Editor} codemirror
*/
function onPaste(e, codemirror) {
var clipboardData = e.clipboardData;
if (clipboardData) {
this.handlePaste(e, clipboardData, codemirror);
} else {
var _window = window;
clipboardData = _window.clipboardData;
this.handlePaste(e, clipboardData, codemirror);
}
}
/**
*
* @param {ClipboardEvent} event
* @param {ClipboardEvent['clipboardData']} clipboardData
* @param {CodeMirror.Editor} codemirror
* @returns {boolean | void}
*/
}, {
key: "handlePaste",
value: function handlePaste(event, clipboardData, codemirror) {
var _test$match;
var items = clipboardData.items;
var types = clipboardData.types || [];
var codemirrorDoc = codemirror.getDoc();
for (var i = 0; i < types.length; i++) {
var item = items[i]; // 判断是否为图片数据
if (item && item.kind === 'file' && item.type.match(/^image\//i)) {
// 读取该图片
var file = item.getAsFile();
this.options.fileUpload(file, function (url) {
if (typeof url !== 'string') {
return;
}
codemirrorDoc.replaceSelection("![enter image description here](".concat(url, ")"));
});
event.preventDefault();
}
} // 复制html转换markdown
var htmlText = clipboardData.getData('text/plain');
var html = clipboardData.getData('Text/Html');
if (!html || !this.options.convertWhenPaste) {
return true;
}
/**
* 这里需要处理一个特殊逻辑:
* 从excel中复制而来的内容剪切板里会有一张图片一个<img>元素)和一段纯文本,在这种场景下,需要丢掉图片,直接粘贴纯文本
* 与此同时当剪切板里有图片和其他html标签时从web页面上复制的内容则需要走下面的html转md的逻辑
* 基于上述两个场景,才有了下面四行奇葩的代码
*/
var test = html.replace(/<(html|head|body|!)/g, '');
if (((_test$match = test.match(/<[a-zA-Z]/g)) === null || _test$match === void 0 ? void 0 : _test$match.length) <= 1 && /<img/.test(test)) {
return true;
}
var divObj = document.createElement('DIV');
divObj.innerHTML = html;
html = divObj.innerHTML;
var mdText = htmlParser.run(html);
if (typeof mdText === 'string' && trim$3(mdText).call(mdText).length > 0) {
var range = codemirror.listSelections();
if (codemirror.getSelections().length <= 1 && range[0] && range[0].anchor) {
var currentCursor = {};
currentCursor.line = range[0].anchor.line;
currentCursor.ch = range[0].anchor.ch;
codemirrorDoc.replaceSelection(mdText);
pasteHelper.showSwitchBtnAfterPasteHtml(this.$cherry, currentCursor, codemirror, htmlText, mdText);
} else {
codemirrorDoc.replaceSelection(mdText);
}
event.preventDefault();
}
divObj = null;
}
/**
*
* @param {CodeMirror.Editor} codemirror
*/
}, {
key: "init",
value:
/**
*
* @param {*} previewer
*/
function init(previewer) {
var _this2 = this;
var textArea = this.options.editorDom.querySelector("#".concat(this.options.id));
if (!(textArea instanceof HTMLTextAreaElement)) {
throw new Error('The specific element is not a textarea.');
}
var editor = codemirror.fromTextArea(textArea, this.options.codemirror);
editor.addOverlay({
name: 'invisibles',
token: function nextToken(stream) {
var tokenClass;
var spaces = 0;
var peek = stream.peek() === ' ';
if (peek) {
while (peek && spaces < Number.MAX_VALUE) {
spaces += 1;
stream.next();
peek = stream.peek() === ' ';
}
tokenClass = "whitespace whitespace-".concat(spaces);
} else {
while (!stream.eol()) {
stream.next();
}
tokenClass = '';
}
return tokenClass;
}
});
this.previewer = previewer;
this.disableScrollListener = false;
if (this.options.value) {
editor.setOption('value', this.options.value);
}
editor.on('blur', function (codemirror, evt) {
_this2.options.onBlur(evt, codemirror);
});
editor.on('focus', function (codemirror, evt) {
_this2.options.onFocus(evt, codemirror);
});
editor.on('change', function (codemirror, evt) {
_this2.options.onChange(evt, codemirror);
_this2.dealBigData();
if (_this2.options.autoSave2Textarea) {
// @ts-ignore
// 将codemirror里的内容回写到textarea里
codemirror.save();
}
});
editor.on('keydown', function (codemirror, evt) {
_this2.options.onKeydown(evt, codemirror);
});
editor.on('keyup', function (codemirror, evt) {
_this2.onKeyup(evt, codemirror);
});
editor.on('paste', function (codemirror, evt) {
_this2.options.onPaste.call(_this2, evt, codemirror);
});
if (this.options.autoScrollByCursor) {
editor.on('mousedown', function (codemirror, evt) {
setTimeout$3(function () {
_this2.onMouseDown(codemirror, evt);
});
});
}
editor.on('drop', function (codemirror, evt) {
var files = evt.dataTransfer.files || [];
if (files && files.length > 0) {
// 增加延时让drop的位置变成codemirror的光标位置
setTimeout$3(function () {
var _loop = function _loop(i, _needBr) {
var file = files[i];
var fileType = file.type || ''; // 文本类型或者无类型的,直接读取内容,不做上传文件的操作
if (fileType === '' || /^text/i.test(fileType)) {
needBr = _needBr;
return "continue";
}
_this2.options.fileUpload(file, function (url) {
var _context, _context2, _context3, _context4;
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (typeof url !== 'string') {
needBr = _needBr;
return;
} // 拖拽上传文件时,强制改成没有文字选择区的状态
codemirror.setSelection(codemirror.getCursor());
var name = params.name ? params.name : file.name;
var type = '';
var poster = '';
if (/video/i.test(file.type)) {
type = '!video';
poster = params.poster ? "{poster=".concat(params.poster, "}") : '';
}
if (/audio/i.test(file.type)) {
type = '!audio';
}
if (/image/i.test(file.type)) {
type = '!';
}
var style = type ? handelParams(params) : '';
type = _needBr ? "\n".concat(type) : type;
var insertValue = concat$5(_context = concat$5(_context2 = concat$5(_context3 = concat$5(_context4 = "".concat(type, "[")).call(_context4, name)).call(_context3, style, "](")).call(_context2, url, ")")).call(_context, poster); // 当批量上传文件时,每个被插入的文件中间需要加个换行,但单个上传文件的时候不需要加换行
_needBr = true;
codemirror.replaceSelection(insertValue);
});
needBr = _needBr;
};
for (var i = 0, needBr = false; i < files.length; i++) {
var _ret = _loop(i, needBr);
if (_ret === "continue") continue;
}
}, 50);
}
});
editor.on('scroll', function (codemirror) {
_this2.options.onScroll(codemirror);
_this2.options.writingStyle === 'focus' && _this2.refreshWritingStatus();
});
editor.on('cursorActivity', function () {
_this2.onCursorActivity();
});
addEvent(this.getEditorDom(), 'wheel', function () {
// 鼠标滚轮滚动时,强制监听滚动事件
_this2.disableScrollListener = false; // 打断滚动动画
cancelAnimationFrame(_this2.animation.timer);
_this2.animation.timer = 0;
}, false);
/**
* @property
* @type {CodeMirror.Editor}
*/
this.editor = editor;
if (this.options.writingStyle !== 'normal') {
this.initWritingStyle();
}
}
/**
*
* @param {number | null} beginLine 起始行传入null时跳转到文档尾部
* @param {number} [endLine] 终止行
* @param {number} [percent] 百分比取值0~1
*/
}, {
key: "jumpToLine",
value: function jumpToLine(beginLine, endLine, percent) {
var _this3 = this;
if (beginLine === null) {
cancelAnimationFrame(this.animation.timer);
this.disableScrollListener = true;
this.editor.scrollIntoView({
line: this.editor.lineCount() - 1,
ch: 1
});
this.animation.timer = 0;
return;
}
var position = this.editor.charCoords({
line: beginLine,
ch: 0
}, 'local');
var top = position.top;
var positionEnd = this.editor.charCoords({
line: beginLine + endLine,
ch: 0
}, 'local');
var height = positionEnd.top - position.top;
top += height * percent;
this.animation.destinationTop = Math.ceil(top - 15);
if (this.animation.timer) {
return;
}
var animationHandler = function animationHandler() {
var currentTop = _this3.editor.getScrollInfo().top;
var delta = _this3.animation.destinationTop - currentTop; // 100毫秒内完成动画
var move = Math.ceil(Math.min(Math.abs(delta), Math.max(1, Math.abs(delta) / (100 / 16.7)))); // console.log('should scroll: ', move, delta, currentTop, this.animation.destinationTop);
if (delta > 0) {
if (currentTop >= _this3.animation.destinationTop) {
_this3.animation.timer = 0;
return;
}
_this3.disableScrollListener = true;
_this3.editor.scrollTo(null, currentTop + move);
} else if (delta < 0) {
if (currentTop <= _this3.animation.destinationTop || currentTop <= 0) {
_this3.animation.timer = 0;
return;
}
_this3.disableScrollListener = true;
_this3.editor.scrollTo(null, currentTop - move);
} else {
_this3.animation.timer = 0;
return;
} // 无法再继续滚动
if (currentTop === _this3.editor.getScrollInfo().top || move >= Math.abs(delta)) {
_this3.animation.timer = 0;
return;
}
_this3.animation.timer = requestAnimationFrame(animationHandler);
};
this.animation.timer = requestAnimationFrame(animationHandler);
}
/**
*
* @param {number | null} lineNum
* @param {number} [endLine]
* @param {number} [percent]
*/
}, {
key: "scrollToLineNum",
value: function scrollToLineNum(lineNum, endLine, percent) {
if (lineNum === null) {
this.jumpToLine(null);
return;
}
var $lineNum = Math.max(0, lineNum);
this.jumpToLine($lineNum, endLine, percent);
// Logger.log('滚动预览区域左侧应scroll to ', $lineNum);
}
/**
*
* @returns {HTMLElement}
*/
}, {
key: "getEditorDom",
value: function getEditorDom() {
return this.options.editorDom;
}
/**
*
* @param {string} event 事件名
* @param {EditorEventCallback} callback 回调函数
*/
}, {
key: "addListener",
value: function addListener(event, callback) {
this.editor.on(event, callback);
}
/**
* 初始化书写风格
*/
}, {
key: "initWritingStyle",
value: function initWritingStyle() {
var _context5, _context6;
var writingStyle = this.options.writingStyle;
var className = "cherry-editor-writing-style--".concat(writingStyle);
var editorDom = this.getEditorDom(); // 重置状态
forEach$3(_context5 = filter$3(_context6 = from_1$2(editorDom.classList)).call(_context6, function (className) {
return startsWith$3(className).call(className, 'cherry-editor-writing-style--');
})).call(_context5, function (className) {
return editorDom.classList.remove(className);
});
if (writingStyle === 'normal') {
return;
}
editorDom.classList.add(className);
this.refreshWritingStatus();
}
/**
* 刷新书写状态
*/
}, {
key: "refreshWritingStatus",
value: function refreshWritingStatus() {
var _context7, _context8;
var writingStyle = this.options.writingStyle;
var className = "cherry-editor-writing-style--".concat(writingStyle);
/**
* @type {HTMLStyleElement}
*/
var style = document.querySelector('#cherry-editor-writing-style') || document.createElement('style');
style.id = 'cherry-editor-writing-style';
find$3(_context7 = from_1$2(document.head.childNodes)).call(_context7, function (node) {
return node === style;
}) || document.head.appendChild(style);
var sheet = style.sheet;
forEach$3(_context8 = from_1$2(Array(sheet.cssRules.length))).call(_context8, function () {
return sheet.deleteRule(0);
});
if (writingStyle === 'focus') {
var _context9, _context10;
var editorDomRect = this.getEditorDom().getBoundingClientRect(); // 获取光标所在位置
var _this$editor$charCoor = this.editor.charCoords(this.editor.getCursor()),
top = _this$editor$charCoor.top,
bottom = _this$editor$charCoor.bottom; // 光标上部距离编辑器顶部距离(不包含菜单)
var topHeight = top - editorDomRect.top; // 光标下部距离编辑器底部距离
var bottomHeight = editorDomRect.height - (bottom - editorDomRect.top);
sheet.insertRule(concat$5(_context9 = ".".concat(className, "::before { height: ")).call(_context9, topHeight > 0 ? topHeight : 0, "px; }"), 0);
sheet.insertRule(concat$5(_context10 = ".".concat(className, "::after { height: ")).call(_context10, bottomHeight > 0 ? bottomHeight : 0, "px; }"), 0);
}
if (writingStyle === 'typewriter') {
var _context11, _context12;
// 编辑器顶/底部填充的空白高度 (用于内容不足时使光标所在行滚动到编辑器中央)
var height = this.editor.getScrollInfo().clientHeight / 2;
sheet.insertRule(concat$5(_context11 = ".".concat(className, " .CodeMirror-lines::before { height: ")).call(_context11, height, "px; }"), 0);
sheet.insertRule(concat$5(_context12 = ".".concat(className, " .CodeMirror-lines::after { height: ")).call(_context12, height, "px; }"), 0);
this.editor.scrollTo(null, this.editor.cursorCoords(null, 'local').top - height);
}
}
/**
* 修改书写风格
*/
}, {
key: "setWritingStyle",
value: function setWritingStyle(writingStyle) {
this.options.writingStyle = writingStyle;
this.initWritingStyle();
}
}]);
return Editor;
}();
var $findIndex = arrayIteration.findIndex;
var FIND_INDEX = 'findIndex';
var SKIPS_HOLES$1 = true;
// Shouldn't skip holes
if (FIND_INDEX in []) Array(1)[FIND_INDEX](function () { SKIPS_HOLES$1 = false; });
// `Array.prototype.findIndex` method
// https://tc39.es/ecma262/#sec-array.prototype.findindex
_export({ target: 'Array', proto: true, forced: SKIPS_HOLES$1 }, {
findIndex: function findIndex(callbackfn /* , that = undefined */) {
return $findIndex(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
var findIndex = entryVirtual('Array').findIndex;
var ArrayPrototype$7 = Array.prototype;
var findIndex$1 = function (it) {
var own = it.findIndex;
return it === ArrayPrototype$7 || (objectIsPrototypeOf(ArrayPrototype$7, it) && own === ArrayPrototype$7.findIndex) ? findIndex : own;
};
var findIndex$2 = findIndex$1;
var findIndex$3 = findIndex$2;
var HAS_SPECIES_SUPPORT$2 = arrayMethodHasSpeciesSupport('splice');
var TypeError$f = global_1.TypeError;
var max$3 = Math.max;
var min$3 = Math.min;
var MAX_SAFE_INTEGER$3 = 0x1FFFFFFFFFFFFF;
var MAXIMUM_ALLOWED_LENGTH_EXCEEDED = 'Maximum allowed length exceeded';
// `Array.prototype.splice` method
// https://tc39.es/ecma262/#sec-array.prototype.splice
// with adding support of @@species
_export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$2 }, {
splice: function splice(start, deleteCount /* , ...items */) {
var O = toObject(this);
var len = lengthOfArrayLike(O);
var actualStart = toAbsoluteIndex(start, len);
var argumentsLength = arguments.length;
var insertCount, actualDeleteCount, A, k, from, to;
if (argumentsLength === 0) {
insertCount = actualDeleteCount = 0;
} else if (argumentsLength === 1) {
insertCount = 0;
actualDeleteCount = len - actualStart;
} else {
insertCount = argumentsLength - 2;
actualDeleteCount = min$3(max$3(toIntegerOrInfinity(deleteCount), 0), len - actualStart);
}
if (len + insertCount - actualDeleteCount > MAX_SAFE_INTEGER$3) {
throw TypeError$f(MAXIMUM_ALLOWED_LENGTH_EXCEEDED);
}
A = arraySpeciesCreate(O, actualDeleteCount);
for (k = 0; k < actualDeleteCount; k++) {
from = actualStart + k;
if (from in O) createProperty(A, k, O[from]);
}
A.length = actualDeleteCount;
if (insertCount < actualDeleteCount) {
for (k = actualStart; k < len - actualDeleteCount; k++) {
from = k + actualDeleteCount;
to = k + insertCount;
if (from in O) O[to] = O[from];
else delete O[to];
}
for (k = len; k > len - actualDeleteCount + insertCount; k--) delete O[k - 1];
} else if (insertCount > actualDeleteCount) {
for (k = len - actualDeleteCount; k > actualStart; k--) {
from = k + actualDeleteCount - 1;
to = k + insertCount - 1;
if (from in O) O[to] = O[from];
else delete O[to];
}
}
for (k = 0; k < insertCount; k++) {
O[k + actualStart] = arguments[k + 2];
}
O.length = len - actualDeleteCount + insertCount;
return A;
}
});
var splice$1 = entryVirtual('Array').splice;
var ArrayPrototype$8 = Array.prototype;
var splice$2 = function (it) {
var own = it.splice;
return it === ArrayPrototype$8 || (objectIsPrototypeOf(ArrayPrototype$8, it) && own === ArrayPrototype$8.splice) ? splice$1 : own;
};
var splice$3 = splice$2;
var splice$4 = splice$3;
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @typedef {import('~types/syntax').HookType} HookType
* @typedef {import('~types/syntax').HookTypesList} HookTypesList
* @typedef {import('~types/syntax').EditorConfig} EditorConfig
* @typedef {import('~types/syntax').HookRegexpRule} HookRegexpRule
*/
/** @type {boolean} */
var isMathjaxConfig = false;
/**
* @type {HookTypesList}
*/
var HOOKS_TYPE_LIST = {
SEN: 'sentence',
PAR: 'paragraph',
DEFAULT: 'sentence'
};
var SyntaxBase = /*#__PURE__*/function () {
/**
* @static
* @type {string}
*/
/**
* @static
* @type {HookType}
*/
/**
* @protected
* @type {import('../Engine').default}
*/
/**
* @constructor
* @param {Partial<EditorConfig>} editorConfig
*/
function SyntaxBase(editorConfig) {
_classCallCheck(this, SyntaxBase);
_defineProperty(this, "$engine", void 0);
_defineProperty(this, "$locale", void 0);
// editorConfig.pageHooks: 已实例化的页面级hook
// editorConfig.syntaxOptions: 当前Hook的用户配置
// editorConfig.externals: 第三方库
this.RULE = this.rule(editorConfig);
}
_createClass(SyntaxBase, [{
key: "getType",
value: function getType() {
return (
/** @type {typeof SyntaxBase} */
this.constructor.HOOK_TYPE || HOOKS_TYPE_LIST.DEFAULT
);
}
}, {
key: "getName",
value: function getName() {
return (
/** @type {typeof SyntaxBase} */
this.constructor.HOOK_NAME
);
}
}, {
key: "afterInit",
value: function afterInit(callback) {
if (typeof callback === 'function') {
callback();
}
}
}, {
key: "setLocale",
value: function setLocale(locale) {
this.$locale = locale;
}
/**
* 生命周期函数
* @param {string} str 待处理的markdown文本
* @returns {string} 处理后的文本一般为html
*/
}, {
key: "beforeMakeHtml",
value: function beforeMakeHtml(str) {
return str;
}
/**
* 生命周期函数
* @param {string} str 待处理的markdown文本
* @returns {string} 处理后的文本一般为html
*/
}, {
key: "makeHtml",
value: function makeHtml(str) {
return str;
}
/**
* 生命周期函数
* @param {string} str 待处理的markdown文本
* @returns {string} 处理后的文本一般为html
*/
}, {
key: "afterMakeHtml",
value: function afterMakeHtml(str) {
return str;
} // getMakeHtml() {
// return this.makeHtml || false;
// }
/**
*
* @param {KeyboardEvent} e 触发事件
* @param {*} str
*/
}, {
key: "onKeyDown",
value: function onKeyDown(e, str) {}
}, {
key: "getOnKeyDown",
value: function getOnKeyDown() {
return this.onKeyDown || false;
}
}, {
key: "getAttributesTest",
value: function getAttributesTest() {
return /^(color|fontSize|font-size|id|title|class|target|underline|line-through|overline|sub|super)$/;
}
/**
*
* @param {string} attr
* @param {() => {}} func 回调函数
*/
}, {
key: "$testAttributes",
value: function $testAttributes(attr, func) {
if (this.getAttributesTest().test(attr)) {
func();
}
}
/**
* 提取属性
* @param {string} str 待提取字符串
* @returns {{attrs: Record<string,any>; str: string}}
*/
}, {
key: "getAttributes",
value: function getAttributes(str) {
var ret = {
attrs: {},
str: str
}; // if(/(?<=[^\\]){([a-zA-Z-]+=[0-9a-z-]+(?=;|\||}))+}$/.test(str)) {
// str.match(/(?<=[^\\]){[^\n]+?}$/)[0]
// .match(/([a-zA-Z-]+=[0-9a-z-]+(?=;|\||}))+/g)
// .foreach((one) => {
// one = one.split('=');
// this._testAttributes(one[0], ()=>{
// ret.attrs[one[0]] = one[1];
// });
// });
// ret.str = str.replace(/(?<=[^\\]){[^\n]+?}$/, '');
// }
return ret;
}
}, {
key: "test",
value:
/**
* 测试输入的字符串是否匹配当前Hook规则
* @param {string} str 待匹配文本
* @returns {boolean}
*/
function test(str) {
return this.RULE.reg ? this.RULE.reg.test(str) : false;
}
/**
*
* @param {Partial<EditorConfig>} editorConfig
* @returns {HookRegexpRule}
*/
}, {
key: "rule",
value: function rule(editorConfig) {
return {
begin: '',
end: '',
content: '',
reg: new RegExp('')
};
}
}, {
key: "mounted",
value: function mounted() {// console.log('base mounted');
}
}], [{
key: "getMathJaxConfig",
value: function getMathJaxConfig() {
return isMathjaxConfig;
}
/**
*
* @param {boolean} version 指定mathJax是否使用MathJax
*/
}, {
key: "setMathJaxConfig",
value: function setMathJaxConfig(version) {
isMathjaxConfig = version;
}
}]);
return SyntaxBase;
}();
_defineProperty(SyntaxBase, "HOOK_NAME", 'default');
_defineProperty(SyntaxBase, "HOOK_TYPE", HOOKS_TYPE_LIST.DEFAULT);
var $map = arrayIteration.map;
var HAS_SPECIES_SUPPORT$3 = arrayMethodHasSpeciesSupport('map');
// `Array.prototype.map` method
// https://tc39.es/ecma262/#sec-array.prototype.map
// with adding support of @@species
_export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$3 }, {
map: function map(callbackfn /* , thisArg */) {
return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
var map = entryVirtual('Array').map;
var ArrayPrototype$9 = Array.prototype;
var map$1 = function (it) {
var own = it.map;
return it === ArrayPrototype$9 || (objectIsPrototypeOf(ArrayPrototype$9, it) && own === ArrayPrototype$9.map) ? map : own;
};
var map$2 = map$1;
var map$3 = map$2;
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* 为段落前加换行符
* @param {string} match 匹配全文
* @param {string} processedContent 加入的内容
*/
function prependLineFeedForParagraph(match, processedContent) {
var canNestedInList = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (!/^\n/.test(match)) {
return processedContent;
}
if (canNestedInList) {
var _match$match$0$length, _match$match, _match$match$;
var leadingLinesCount = (_match$match$0$length = (_match$match = match.match(/^\n+/g)) === null || _match$match === void 0 ? void 0 : (_match$match$ = _match$match[0]) === null || _match$match$ === void 0 ? void 0 : _match$match$.length) !== null && _match$match$0$length !== void 0 ? _match$match$0$length : 0; // 前置换行符数量大于2时补充两个换行符否则只补充一个
if (leadingLinesCount > 1) {
return "\n\n".concat(processedContent);
}
return "\n".concat(processedContent);
}
return "\n\n".concat(processedContent);
}
/**
* 计算段落所占行数,必须传入通过 prependLineFeedForParagraph 方法处理后的内容,才能计算准确
* @param {string} preLinesMatch 前置匹配行
* @param {number} contentLines 实际内容行数
*/
function calculateLinesOfParagraph(preLinesMatch, contentLines) {
var preLineCount = (preLinesMatch.match(/\n/g) || []).length; // 前置行匹配文本为空,说明是全文开头
// 非全文开头前面必有两个从 prependLineFeed 方法新增加的换行符
if (preLinesMatch !== '') {
preLineCount -= 2;
}
return preLineCount + contentLines;
}
var isArray$8 = isArray$3;
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* 用于lodash.mergeWith的customizer
* @param {any} objValue
* @param {any} srcValue
* @returns
*/
function customizer(objValue, srcValue) {
if (isArray$8(srcValue)) {
return srcValue;
}
}
/**
* 检查本地有没有值
* @param {string} key
*/
function testKeyInLocal(key) {
if (typeof localStorage !== 'undefined') {
return localStorage.getItem("cherry-".concat(key)) !== null;
}
return false;
}
/**
* 保存是否经典换行
* @param {boolean} isClassicBr
*/
function saveIsClassicBrToLocal(isClassicBr) {
if (typeof localStorage !== 'undefined') {
localStorage.setItem('cherry-classicBr', isClassicBr ? 'true' : 'false');
}
}
/**
* 是否经典换行
*/
function getIsClassicBrFromLocal() {
var ret = 'false';
if (typeof localStorage !== 'undefined') {
ret = localStorage.getItem('cherry-classicBr');
}
return ret === 'true';
}
/**
* 保存当前主题
* @param {string} theme
*/
function saveThemeToLocal(theme) {
if (typeof localStorage !== 'undefined') {
localStorage.setItem('cherry-theme', theme);
}
}
/**
* 获取当前主题
* @returns {string} 主题名
*/
function getThemeFromLocal() {
var fullClass = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var ret = 'default';
if (typeof localStorage !== 'undefined') {
var localTheme = localStorage.getItem('cherry-theme');
if (localTheme) {
ret = localTheme;
}
}
return fullClass ? "theme__".concat(ret) : ret;
}
/**
* 修改主题
* @param {object} $cherry
* @param {string} theme 如果没有传theme则从本地缓存里取
*/
function changeTheme($cherry) {
var theme = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var newTheme = (theme ? theme : getThemeFromLocal()).replace(/^.*theme__/, '');
var newClass = " theme__".concat(newTheme);
$cherry.wrapperDom.className = $cherry.wrapperDom.className.replace(/ theme__[^ $]+?( |$)/g, '') + newClass;
$cherry.previewer.getDomContainer().className = $cherry.previewer.getDomContainer().className.replace(/ theme__[^ $]+?( |$)/g, '') + newClass;
saveThemeToLocal(newTheme);
}
var RangeError$1 = global_1.RangeError;
var fromCharCode = String.fromCharCode;
// eslint-disable-next-line es-x/no-string-fromcodepoint -- required for testing
var $fromCodePoint = String.fromCodePoint;
var join$1 = functionUncurryThis([].join);
// length should be 1, old FF problem
var INCORRECT_LENGTH = !!$fromCodePoint && $fromCodePoint.length != 1;
// `String.fromCodePoint` method
// https://tc39.es/ecma262/#sec-string.fromcodepoint
_export({ target: 'String', stat: true, arity: 1, forced: INCORRECT_LENGTH }, {
// eslint-disable-next-line no-unused-vars -- required for `.length`
fromCodePoint: function fromCodePoint(x) {
var elements = [];
var length = arguments.length;
var i = 0;
var code;
while (length > i) {
code = +arguments[i++];
if (toAbsoluteIndex(code, 0x10FFFF) !== code) throw RangeError$1(code + ' is not a valid code point');
elements[i] = code < 0x10000
? fromCharCode(code)
: fromCharCode(((code -= 0x10000) >> 10) + 0xD800, code % 0x400 + 0xDC00);
} return join$1(elements, '');
}
});
var fromCodePoint = path.String.fromCodePoint;
var fromCodePoint$1 = fromCodePoint;
var fromCodePoint$2 = fromCodePoint$1;
var _context, _context2;
function ownKeys$1(object, enumerableOnly) { var keys = keys$3(object); if (getOwnPropertySymbols$2) { var symbols = getOwnPropertySymbols$2(object); enumerableOnly && (symbols = filter$3(symbols).call(symbols, function (sym) { return getOwnPropertyDescriptor$3(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var _context3, _context4; var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? forEach$3(_context3 = ownKeys$1(Object(source), !0)).call(_context3, function (key) { _defineProperty(target, key, source[key]); }) : getOwnPropertyDescriptors$2 ? defineProperties$2(target, getOwnPropertyDescriptors$2(source)) : forEach$3(_context4 = ownKeys$1(Object(source))).call(_context4, function (key) { defineProperty$5(target, key, getOwnPropertyDescriptor$3(source, key)); }); } return target; }
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var escapeMap = {
'<': '&lt;',
'>': '&gt;',
'&': '&amp;',
'"': '&quot;',
"'": '&#x27;'
};
var unescapeMap = {
lt: '<',
gt: '>',
amp: '&',
quot: '"',
apos: "'"
}; // refs: https://www.freeformatter.com/html-entities.html
var ASCIICharacters = {
34: '&quot;',
38: '&amp;',
39: '&apos;',
60: '&lt;',
62: '&gt;'
};
var ISO88591Characters = {
192: '&Agrave;',
193: '&Aacute;',
194: '&Acirc;',
195: '&Atilde;',
196: '&Auml;',
197: '&Aring;',
198: '&AElig;',
199: '&Ccedil;',
200: '&Egrave;',
201: '&Eacute;',
202: '&Ecirc;',
203: '&Euml;',
204: '&Igrave;',
205: '&Iacute;',
206: '&Icirc;',
207: '&Iuml;',
208: '&ETH;',
209: '&Ntilde;',
210: '&Ograve;',
211: '&Oacute;',
212: '&Ocirc;',
213: '&Otilde;',
214: '&Ouml;',
216: '&Oslash;',
217: '&Ugrave;',
218: '&Uacute;',
219: '&Ucirc;',
220: '&Uuml;',
221: '&Yacute;',
222: '&THORN;',
223: '&szlig;',
224: '&agrave;',
225: '&aacute;',
226: '&acirc;',
227: '&atilde;',
228: '&auml;',
229: '&aring;',
230: '&aelig;',
231: '&ccedil;',
232: '&egrave;',
233: '&eacute;',
234: '&ecirc;',
235: '&euml;',
236: '&igrave;',
237: '&iacute;',
238: '&icirc;',
239: '&iuml;',
240: '&eth;',
241: '&ntilde;',
242: '&ograve;',
243: '&oacute;',
244: '&ocirc;',
245: '&otilde;',
246: '&ouml;',
248: '&oslash;',
249: '&ugrave;',
250: '&uacute;',
251: '&ucirc;',
252: '&uuml;',
253: '&yacute;',
254: '&thorn;',
255: '&yuml;'
};
var ISO88591Symbols = {
160: '&nbsp;',
161: '&iexcl;',
162: '&cent;',
163: '&pound;',
164: '&curren;',
165: '&yen;',
166: '&brvbar;',
167: '&sect;',
168: '&uml;',
169: '&copy;',
170: '&ordf;',
171: '&laquo;',
172: '&not;',
173: '&shy;',
174: '&reg;',
175: '&macr;',
176: '&deg;',
177: '&plusmn;',
178: '&sup2;',
179: '&sup3;',
180: '&acute;',
181: '&micro;',
182: '&para;',
184: '&cedil;',
185: '&sup1;',
186: '&ordm;',
187: '&raquo;',
188: '&frac14;',
189: '&frac12;',
190: '&frac34;',
191: '&iquest;',
215: '&times;',
247: '&divide;'
};
var MathSymbols = {
8704: '&forall;',
8706: '&part;',
8707: '&exist;',
8709: '&empty;',
8711: '&nabla;',
8712: '&isin;',
8713: '&notin;',
8715: '&ni;',
8719: '&prod;',
8721: '&sum;',
8722: '&minus;',
8727: '&lowast;',
8730: '&radic;',
8733: '&prop;',
8734: '&infin;',
8736: '&ang;',
8743: '&and;',
8744: '&or;',
8745: '&cap;',
8746: '&cup;',
8747: '&int;',
8756: '&there4;',
8764: '&sim;',
8773: '&cong;',
8776: '&asymp;',
8800: '&ne;',
8801: '&equiv;',
8804: '&le;',
8805: '&ge;',
8834: '&sub;',
8835: '&sup;',
8836: '&nsub;',
8838: '&sube;',
8839: '&supe;',
8853: '&oplus;',
8855: '&otimes;',
8869: '&perp;',
8901: '&sdot;'
};
var GreekLetters = {
913: '&Alpha;',
914: '&Beta;',
915: '&Gamma;',
916: '&Delta;',
917: '&Epsilon;',
918: '&Zeta;',
919: '&Eta;',
920: '&Theta;',
921: '&Iota;',
922: '&Kappa;',
923: '&Lambda;',
924: '&Mu;',
925: '&Nu;',
926: '&Xi;',
927: '&Omicron;',
928: '&Pi;',
929: '&Rho;',
931: '&Sigma;',
932: '&Tau;',
933: '&Upsilon;',
934: '&Phi;',
935: '&Chi;',
936: '&Psi;',
937: '&Omega;',
945: '&alpha;',
946: '&beta;',
947: '&gamma;',
948: '&delta;',
949: '&epsilon;',
950: '&zeta;',
951: '&eta;',
952: '&theta;',
953: '&iota;',
954: '&kappa;',
955: '&lambda;',
956: '&mu;',
957: '&nu;',
958: '&xi;',
959: '&omicron;',
960: '&pi;',
961: '&rho;',
962: '&sigmaf;',
963: '&sigma;',
964: '&tau;',
965: '&upsilon;',
966: '&phi;',
967: '&chi;',
968: '&psi;',
969: '&omega;',
977: '&thetasym;',
978: '&upsih;',
982: '&piv;'
};
var MiscellaneousHTMLEntities = {
338: '&OElig;',
339: '&oelig;',
352: '&Scaron;',
353: '&scaron;',
376: '&Yuml;',
402: '&fnof;',
710: '&circ;',
732: '&tilde;',
8194: '&ensp;',
8195: '&emsp;',
8201: '&thinsp;',
8204: '&zwnj;',
8205: '&zwj;',
8206: '&lrm;',
8207: '&rlm;',
8211: '&ndash;',
8212: '&mdash;',
8216: '&lsquo;',
8217: '&rsquo;',
8218: '&sbquo;',
8220: '&ldquo;',
8221: '&rdquo;',
8222: '&bdquo;',
8224: '&dagger;',
8225: '&Dagger;',
8226: '&bull;',
8230: '&hellip;',
8240: '&permil;',
8242: '&prime;',
8243: '&Prime;',
8249: '&lsaquo;',
8250: '&rsaquo;',
8254: '&oline;',
8364: '&euro;',
8482: '&trade;',
8592: '&larr;',
8593: '&uarr;',
8594: '&rarr;',
8595: '&darr;',
8596: '&harr;',
8629: '&crarr;',
8968: '&lceil;',
8969: '&rceil;',
8970: '&lfloor;',
8971: '&rfloor;',
9674: '&loz;',
9824: '&spades;',
9827: '&clubs;',
9829: '&hearts;',
9830: '&diams;'
}; // TODO: 使用whatwg的entities.json
var htmlEntitiesMap = _objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread({}, ASCIICharacters), ISO88591Characters), ISO88591Symbols), MathSymbols), GreekLetters), MiscellaneousHTMLEntities);
var htmlEntitiesCodePoint = keys$3(htmlEntitiesMap);
var htmlEntitiesWithoutSemicolon = map$3(htmlEntitiesCodePoint).call(htmlEntitiesCodePoint, function (code) {
return htmlEntitiesMap[code].replace(/^&(\w+);$/g, function (match, name) {
return name.toLowerCase();
});
});
/**
* 非字符串类型与长度为0的字符串都认为是空串
* @param {any} str 需要判断的字符串
* @returns {boolean}
*/
var isEmptyString = function isEmptyString(str) {
return typeof str !== 'string' || str.length <= 0;
};
var isValidStringCodePoint = function isValidStringCodePoint(codePoint) {
try {
var string = fromCodePoint$2(codePoint);
return !isEmptyString(string); // 如果转换的为空串说明CodePoint不合法
} catch (e) {
// 转换出错也是不合法的CodePoint
return false;
}
};
function escapeHTMLEntitiesWithoutSemicolon(content) {
if (typeof content !== 'string') {
return '';
} // 先处理字符实体
var namedRegex = /&(\w+);?/g;
var escaped = content.replace(namedRegex, function (match, name) {
// 不在合法列表里的全部转义,无分号的情况也转义
if (indexOf$8(match).call(match, ';') === -1 || indexOf$8(htmlEntitiesWithoutSemicolon).call(htmlEntitiesWithoutSemicolon, name.toLowerCase()) === -1) {
return match.replace(/&/g, '&amp;');
}
return match;
}); // 处理十进制数字实体需要防止误匹配16进制
var numericRegex = /&#(?!x)(\d*);?/gi;
escaped = escaped.replace(numericRegex, function (match, decimalCodePoint) {
// 不在合法列表里的全部转义,无分号的情况也转义
// 且位数不能大于7否则可能导致溢出: https://spec.commonmark.org/0.29/#decimal-numeric-character
if (isEmptyString(decimalCodePoint) || indexOf$8(match).call(match, ';') === -1 || decimalCodePoint.lenth > 7 || // Object.keys(htmlEntitiesMap).indexOf(+decimalCodePoint) === -1 ||
!isValidStringCodePoint(decimalCodePoint)) {
return match.replace(/&/g, '&amp;');
}
return match;
}); // 处理十六进制数字实体
var hexRegex = /&#x([0-9a-f]*);?/gi;
escaped = escaped.replace(hexRegex, function (match, hexCodePoint) {
if (isEmptyString(hexCodePoint)) {
return match.replace(/&/g, '&amp;');
}
var hexCode = "0x".concat(hexCodePoint);
var decimalCodePoint = _parseInt$2(hexCode, 16); // parseInt非数字、不在合法列表里、无分号的情况全部转义
// 且位数不能大于6: https://spec.commonmark.org/0.29/#hexadecimal-numeric-character
if (isNaN(decimalCodePoint) || indexOf$8(match).call(match, ';') === -1 || hexCodePoint.lenth > 6 || // Object.keys(htmlEntitiesMap).indexOf(decimalCodePoint) === -1
!isValidStringCodePoint(hexCode)) {
return match.replace(/&/g, '&amp;');
}
return match;
});
return escaped;
}
var blockNames = ['h1|h2|h3|h4|h5|h6', 'ul|ol|li|dd|dl|dt', 'table|thead|tbody|tfoot|col|colgroup|th|td|tr', 'div|article|section|footer|aside|details|summary|code|audio|video|canvas|figure', 'address|center|cite|p|pre|blockquote|marquee|caption|figcaption|track|source|output|svg'].join('|');
var inlineNames = ['span|a|link|b|s|i|del|u|em|strong|sup|sub|kbd', 'nav|font|bdi|samp|map|area|small|time|bdo|var|wbr|meter|dfn', 'ruby|rt|rp|mark|q|progress|input|textarea|select|ins'].join('|');
var inlineBlock = 'br|img|hr';
var whiteList = new RegExp(concat$5(_context = concat$5(_context2 = "^(".concat(blockNames, "|")).call(_context2, inlineNames, "|")).call(_context, inlineBlock, ")( |$|/)"), 'i');
function escapeHTMLSpecialChar(content, enableQuote) {
if (typeof content !== 'string') {
return '';
}
if (enableQuote) {
return content.replace(/[<>&]/g, function (_char) {
return escapeMap[_char] || _char;
});
}
return content.replace(/[<>&"']/g, function (_char2) {
return escapeMap[_char2] || _char2;
});
}
function unescapeHTMLSpecialChar(content) {
if (typeof content !== 'string') {
return '';
}
return content.replace(/&(\w+);?/g, function (escaped, name) {
return unescapeMap[name] || escaped;
});
}
function escapeHTMLSpecialCharOnce(content, enableQuote) {
if (typeof content !== 'string') {
return '';
}
var str = convertHTMLNumberToName(content);
str = unescapeHTMLSpecialChar(str);
return escapeHTMLSpecialChar(str, enableQuote);
}
function convertHTMLNumberToName(html) {
var entities = /&#(\d+);?/g;
return html.replace(entities, function (match, codePoint) {
return htmlEntitiesMap[codePoint] || match;
});
}
function unescapeHTMLNumberEntities(html) {
var entities = /&#(\d+);?/g;
return html.replace(entities, function (match, codePoint) {
try {
var escaped = fromCodePoint$2(codePoint);
return escaped;
} catch (e) {
return match;
}
});
}
function unescapeHTMLHexEntities(html) {
var entities = /&#x([0-9a-f]+);?/gi;
return html.replace(entities, function (match, codePoint) {
var hexCode = _parseInt$2("0x".concat(codePoint), 16);
try {
var escaped = fromCodePoint$2(hexCode);
return escaped;
} catch (e) {
return match;
}
});
}
function isValidScheme(url) {
var regex = /^\s*([\w\W]+?)(?=:)/i;
var match = unescapeHTMLHexEntities(unescapeHTMLNumberEntities(url)).match(regex);
if (!match) {
return true;
}
var SCHEME_BLACKLIST = ['javascript', 'data'];
var scheme = match[1].replace(/[\s]/g, ''); // 协议中间可能会出现空白字符绕过检查
if (indexOf$8(SCHEME_BLACKLIST).call(SCHEME_BLACKLIST, scheme.toLowerCase()) !== -1) {
return false;
}
return true;
}
/**
* ref: https://stackoverflow.com/questions/9245333/should-encodeuri-ever-be-used
* @param {string} str
*/
function encodeURIOnce(str) {
return encodeURI(str).replace(/[!'()*]/g, function (_char4) {
return "%".concat(_char4.charCodeAt(0).toString(16));
}).replace(/%25/g, '%');
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var cacheCounter = 0; // ~~C${cacheCounter}I${cacheIndex}$
// let cacheMap = {};
var ParagraphBase = /*#__PURE__*/function (_SyntaxBase) {
_inherits(ParagraphBase, _SyntaxBase);
var _super = _createSuper(ParagraphBase);
// 不需要排他的sign前缀如~~C0I${IN_PARAGRAPH_CACHE_KEY_PREFIX}sign$
function ParagraphBase() {
var _this;
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
needCache: false
},
needCache = _ref.needCache,
_ref$defaultCache = _ref.defaultCache,
defaultCache = _ref$defaultCache === void 0 ? {} : _ref$defaultCache;
_classCallCheck(this, ParagraphBase);
_this = _super.call(this, {});
_this.needCache = !!needCache;
_this.sign = '';
if (needCache) {
_this.cache = defaultCache || {};
_this.cacheKey = "~~C".concat(cacheCounter);
cacheCounter += 1;
}
return _this;
}
_createClass(ParagraphBase, [{
key: "initBrReg",
value: function initBrReg() {
var classicBr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
// 是否启用经典换行逻辑
// true一个换行会被忽略两个以上连续换行会分割成段落
// false 一个换行会转成<br>,两个连续换行会分割成段落,三个以上连续换行会转成<br>并分割段落
this.classicBr = testKeyInLocal('classicBr') ? getIsClassicBrFromLocal() : classicBr;
this.removeBrAfterBlock = null;
this.removeBrBeforeBlock = null;
this.removeNewlinesBetweenTags = null;
}
/**
* 处理经典换行问题
* @param {string} str markdown源码
* @returns markdown源码
*/
}, {
key: "$cleanParagraph",
value: function $cleanParagraph(str) {
// remove leading and trailing newlines
var trimedPar = str.replace(/^\n+/, '').replace(/\n+$/, '');
if (this.classicBr) {
return trimedPar;
}
var minifiedPar = this.joinRawHtml(trimedPar);
return minifiedPar.replace(/\n/g, '<br>').replace(/\r/g, '\n'); // recover \n from \r
}
/**
* remove all newlines in html text
*
* @param {string} textContainsHtml
*/
}, {
key: "joinRawHtml",
value: function joinRawHtml(textContainsHtml) {
if (!this.removeBrAfterBlock) {
var _this$$engine$htmlWhi, _this$$engine$htmlWhi2, _context, _context2;
// preprocess custom white list
var customTagWhiteList = (_this$$engine$htmlWhi = (_this$$engine$htmlWhi2 = this.$engine.htmlWhiteListAppend) === null || _this$$engine$htmlWhi2 === void 0 ? void 0 : _this$$engine$htmlWhi2.split('|')) !== null && _this$$engine$htmlWhi !== void 0 ? _this$$engine$htmlWhi : [];
customTagWhiteList = filter$3(_context = map$3(customTagWhiteList).call(customTagWhiteList, function (tag) {
if (/[a-z-]+/gi.test(tag)) {
return tag;
}
return null;
})).call(_context, function (tag) {
return tag !== null;
}); // concat all white list
var allBlockNames = concat$5(customTagWhiteList).call(customTagWhiteList, blockNames).join('|'); // 段落标签自然换行,所以去掉段落标签两边的换行符
/**
* remove newlines after start tag, and remove whitespaces before newline
* e.g.
* <p> \n text</p> => <p> text</p>
* ^^
* $1$2
*/
this.removeBrAfterBlock = new RegExp("<(".concat(allBlockNames, ")(>| [^>]*?>)[^\\S\\n]*?\\n"), 'ig');
/**
* remove newlines before end tag, and whitespaces before end tag will be preserved
* e.g.
* <p> text\n </p> => <p> text </p>
* ^
* $1
*/
this.removeBrBeforeBlock = new RegExp("\\n[^\\S\\n]*?<\\/(".concat(allBlockNames, ")>[^\\S\\n]*?\\n"), 'ig');
/**
* remove newlines between end tag & start tag
* e.g.
* </p> \n <p foo="bar"> => </p>\r <p foo="bar">
* ^ ^^ ^ ^^^^^^^^^^^^
* $1 $2 $3 $4
*/
this.removeNewlinesBetweenTags = new RegExp(concat$5(_context2 = "<\\/(".concat(allBlockNames, ")>[^\\S\\n]*?\\n([^\\S\\n]*?)<(")).call(_context2, allBlockNames, ")(>| [^>]*?>)"), 'ig');
}
return textContainsHtml.replace(this.removeBrAfterBlock, '<$1$2').replace(this.removeBrBeforeBlock, '</$1>').replace(this.removeNewlinesBetweenTags, '</$1>\r$2<$3$4'); // replace \n to \r
}
}, {
key: "toHtml",
value: function toHtml(str, sentenceMakeFunc) {
return str;
}
}, {
key: "makeHtml",
value: function makeHtml(str, sentenceMakeFunc) {
return sentenceMakeFunc(str).html;
}
}, {
key: "afterMakeHtml",
value: function afterMakeHtml(html) {
return this.restoreCache(html);
}
}, {
key: "isContainsCache",
value: function isContainsCache(str, fullMatch) {
if (fullMatch) {
// 如果是全匹配不能包含CherryINPRAGRAPH
var containsParagraphCache = /^(\s*~~C\d+I\w+\$\s*)+$/g.test(str);
var containsInParagraphCache = new RegExp("~~C\\d+I".concat(ParagraphBase.IN_PARAGRAPH_CACHE_KEY_PREFIX_REGEX, "\\w+\\$"), 'g').test(str);
return containsParagraphCache && !containsInParagraphCache;
} // 如果是局部匹配: 不能只包含CherryINPRAGRAPH
// const containsParagraphCache = /~~C\d+I\w+\$/g.test(str);
// const containsInParagraphCache = new RegExp(
// `~~C\\d+I${ParagraphBase.IN_PARAGRAPH_CACHE_KEY_PREFIX}\\w+\\$`, 'g').test(str);
var containsNonInParagraphCache = new RegExp("~~C\\d+I(?!".concat(ParagraphBase.IN_PARAGRAPH_CACHE_KEY_PREFIX_REGEX, ")\\w+\\$"), 'g').test(str);
return containsNonInParagraphCache; // return fullMatch ?
// /^(\s*~~C\d+I\w+\$\s*)+$/g.test(str) && !/^(\s*~~C\d+ICherryINPRAGRAPH\w+\$\s*)+$/g.test(str) :
// /~~C\d+I\w+\$/g.test(str) && !(/~~C\d+ICherryINPRAGRAPH\w+\$/g.test(str)
// && !/~~C\d+I(?!CherryINPRAGRAPH)\w+\$/g.test(str));
}
/**
*
* @param {string} html
* @return
*/
}, {
key: "$splitHtmlByCache",
value: function $splitHtmlByCache(html) {
// ~~C0I(?!prefix)sign$
var regex = new RegExp("\\n*~~C\\d+I(?!".concat(ParagraphBase.IN_PARAGRAPH_CACHE_KEY_PREFIX_REGEX, ")\\w+\\$\\n?"), 'g');
return {
caches: html.match(regex),
contents: html.split(regex)
};
}
}, {
key: "makeExcludingCached",
value: function makeExcludingCached(content, processor) {
var _this$$splitHtmlByCac = this.$splitHtmlByCache(content),
caches = _this$$splitHtmlByCac.caches,
contents = _this$$splitHtmlByCac.contents;
var paragraphs = map$3(contents).call(contents, processor);
var ret = '';
for (var i = 0; i < paragraphs.length; i++) {
ret += paragraphs[i];
if (caches && caches[i]) {
var _context3;
ret += trim$3(_context3 = caches[i]).call(_context3);
}
}
return ret;
}
/**
* 获取非捕获匹配丢掉的换行,适用于能被【嵌套】的段落语法
*
* @param {string} cache 需要返回的cache
* @param {string} md 原始的md字符串
* @param {boolean} alwaysAlone 是否能被【嵌套】true不能被嵌套如标题、注释等false能被嵌套如代码块、有序列表等
* @return {string} str
*/
}, {
key: "getCacheWithSpace",
value: function getCacheWithSpace(cache, md) {
var _md$match$, _md$match, _md$match$2, _md$match2, _context4, _context5;
var alwaysAlone = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var preSpace = (_md$match$ = (_md$match = md.match(/^\n+/)) === null || _md$match === void 0 ? void 0 : _md$match[0]) !== null && _md$match$ !== void 0 ? _md$match$ : '';
var afterSpace = (_md$match$2 = (_md$match2 = md.match(/\n+$/)) === null || _md$match2 === void 0 ? void 0 : _md$match2[0]) !== null && _md$match$2 !== void 0 ? _md$match$2 : '';
if (alwaysAlone) {
return prependLineFeedForParagraph(md, cache);
}
return concat$5(_context4 = concat$5(_context5 = "".concat(preSpace)).call(_context5, cache)).call(_context4, afterSpace);
}
/**
* 获取行号,只负责向上计算\n
* 会计算cache的行号
*
* @param {string} md md内容
* @param {string} preSpace 前置换行
* @return {number} 行数
*/
}, {
key: "getLineCount",
value: function getLineCount(md) {
var _preSpace$match$0$len, _preSpace$match, _preSpace$match$;
var preSpace = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var content = md;
/**
* 前置换行个数,【注意】:前置换行个数不包括上文的最后一个\n
* 例:
* - aa\n
* - bb\n
* \n
* cc\n
*
* cc的前置换行个数为 1bb后的\n不计算在内
* cc的正则为/(?:^|\n)(\n*)xxxxxx/
*/
var preLineCount = (_preSpace$match$0$len = (_preSpace$match = preSpace.match(/^\n+/g)) === null || _preSpace$match === void 0 ? void 0 : (_preSpace$match$ = _preSpace$match[0]) === null || _preSpace$match$ === void 0 ? void 0 : _preSpace$match$.length) !== null && _preSpace$match$0$len !== void 0 ? _preSpace$match$0$len : 0;
preLineCount = preLineCount === 1 ? 1 : 0; // 前置换行超过2个就交给BR进行渲染
content = content.replace(/^\n+/g, '');
var regex = new RegExp("\n*~~C\\d+I(?:".concat(ParagraphBase.IN_PARAGRAPH_CACHE_KEY_PREFIX_REGEX, ")?\\w+?_L(\\d+)\\$"), 'g');
var cacheLineCount = 0;
content = content.replace(regex, function (match, lineCount) {
cacheLineCount += _parseInt$2(lineCount, 10);
return match.replace(/^\n+/g, '');
});
return preLineCount + cacheLineCount + (content.match(/\n/g) || []).length + 1; // 实际内容所占行数至少为1行
}
/**
*
* @param {string} str 渲染后的内容
* @param {string} sign 签名
* @param {number} lineCount md原文的行数
* @return {string} cacheKey ~~C0I0_L1$
*/
}, {
key: "pushCache",
value: function pushCache(str) {
var _context6, _context7;
var sign = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var lineCount = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
if (!this.needCache) {
return;
}
var $sign = sign || this.$engine.md5(str);
this.cache[$sign] = {
content: str,
using: true
};
return concat$5(_context6 = concat$5(_context7 = "".concat(this.cacheKey, "I")).call(_context7, $sign, "_L")).call(_context6, lineCount, "$");
}
}, {
key: "popCache",
value: function popCache(sign) {
if (!this.needCache) {
return;
}
return this.cache[sign].content || '';
}
}, {
key: "resetCache",
value: function resetCache() {
if (!this.needCache) {
return;
}
for (var _i = 0, _Object$keys = keys$3(this.cache); _i < _Object$keys.length; _i++) {
var key = _Object$keys[_i];
if (!this.cache[key].using) delete this.cache[key];
}
for (var _i2 = 0, _Object$keys3 = keys$3(this.cache); _i2 < _Object$keys3.length; _i2++) {
var _key = _Object$keys3[_i2];
this.cache[_key].using = false;
}
}
}, {
key: "restoreCache",
value: function restoreCache(html) {
var _context8,
_this2 = this;
// restore cached content
if (!this.needCache) {
return html;
}
var regex = new RegExp(concat$5(_context8 = "".concat(this.cacheKey, "I((?:")).call(_context8, ParagraphBase.IN_PARAGRAPH_CACHE_KEY_PREFIX_REGEX, ")?\\w+)\\$"), 'g');
var $html = html.replace(regex, function (match, cacheSign) {
return _this2.popCache(cacheSign.replace(/_L\d+$/, ''));
});
this.resetCache();
return $html;
}
/**
*
* @param {string} wholeMatch whole match
*/
}, {
key: "checkCache",
value: function checkCache(wholeMatch, sentenceMakeFunc) {
var _context9, _context10;
var lineCount = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
this.sign = this.$engine.md5(wholeMatch); // miss cache
if (!this.cache[this.sign]) {
return this.toHtml(wholeMatch, sentenceMakeFunc);
} // hit & mark cache
this.cache[this.sign].using = true;
return concat$5(_context9 = concat$5(_context10 = "".concat(this.cacheKey, "I")).call(_context10, this.sign, "_L")).call(_context9, lineCount, "$");
}
}, {
key: "mounted",
value: function mounted() {// console.log('base mounted');
}
}, {
key: "signWithCache",
value: function signWithCache(html) {
return false;
}
}]);
return ParagraphBase;
}(SyntaxBase);
_defineProperty(ParagraphBase, "HOOK_TYPE", HOOKS_TYPE_LIST.PAR);
_defineProperty(ParagraphBase, "IN_PARAGRAPH_CACHE_KEY_PREFIX", '!');
_defineProperty(ParagraphBase, "IN_PARAGRAPH_CACHE_KEY_PREFIX_REGEX", '\\!');
// FF26- bug: ArrayBuffers are non-extensible, but Object.isExtensible does not report it
var arrayBufferNonExtensible = fails(function () {
if (typeof ArrayBuffer == 'function') {
var buffer = new ArrayBuffer(8);
// eslint-disable-next-line es-x/no-object-isextensible, es-x/no-object-defineproperty -- safe
if (Object.isExtensible(buffer)) Object.defineProperty(buffer, 'a', { value: 8 });
}
});
// eslint-disable-next-line es-x/no-object-isextensible -- safe
var $isExtensible = Object.isExtensible;
var FAILS_ON_PRIMITIVES$3 = fails(function () { $isExtensible(1); });
// `Object.isExtensible` method
// https://tc39.es/ecma262/#sec-object.isextensible
var objectIsExtensible = (FAILS_ON_PRIMITIVES$3 || arrayBufferNonExtensible) ? function isExtensible(it) {
if (!isObject(it)) return false;
if (arrayBufferNonExtensible && classofRaw(it) == 'ArrayBuffer') return false;
return $isExtensible ? $isExtensible(it) : true;
} : $isExtensible;
var freezing = !fails(function () {
// eslint-disable-next-line es-x/no-object-isextensible, es-x/no-object-preventextensions -- required for testing
return Object.isExtensible(Object.preventExtensions({}));
});
var internalMetadata = createCommonjsModule(function (module) {
var defineProperty = objectDefineProperty.f;
var REQUIRED = false;
var METADATA = uid('meta');
var id = 0;
var setMetadata = function (it) {
defineProperty(it, METADATA, { value: {
objectID: 'O' + id++, // object ID
weakData: {} // weak collections IDs
} });
};
var fastKey = function (it, create) {
// return a primitive with prefix
if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if (!hasOwnProperty_1(it, METADATA)) {
// can't set metadata to uncaught frozen object
if (!objectIsExtensible(it)) return 'F';
// not necessary to add metadata
if (!create) return 'E';
// add missing metadata
setMetadata(it);
// return object ID
} return it[METADATA].objectID;
};
var getWeakData = function (it, create) {
if (!hasOwnProperty_1(it, METADATA)) {
// can't set metadata to uncaught frozen object
if (!objectIsExtensible(it)) return true;
// not necessary to add metadata
if (!create) return false;
// add missing metadata
setMetadata(it);
// return the store of weak collections IDs
} return it[METADATA].weakData;
};
// add metadata on freeze-family methods calling
var onFreeze = function (it) {
if (freezing && REQUIRED && objectIsExtensible(it) && !hasOwnProperty_1(it, METADATA)) setMetadata(it);
return it;
};
var enable = function () {
meta.enable = function () { /* empty */ };
REQUIRED = true;
var getOwnPropertyNames = objectGetOwnPropertyNames.f;
var splice = functionUncurryThis([].splice);
var test = {};
test[METADATA] = 1;
// prevent exposing of metadata key
if (getOwnPropertyNames(test).length) {
objectGetOwnPropertyNames.f = function (it) {
var result = getOwnPropertyNames(it);
for (var i = 0, length = result.length; i < length; i++) {
if (result[i] === METADATA) {
splice(result, i, 1);
break;
}
} return result;
};
_export({ target: 'Object', stat: true, forced: true }, {
getOwnPropertyNames: objectGetOwnPropertyNamesExternal.f
});
}
};
var meta = module.exports = {
enable: enable,
fastKey: fastKey,
getWeakData: getWeakData,
onFreeze: onFreeze
};
hiddenKeys[METADATA] = true;
});
var internalMetadata_1 = internalMetadata.enable;
var internalMetadata_2 = internalMetadata.fastKey;
var internalMetadata_3 = internalMetadata.getWeakData;
var internalMetadata_4 = internalMetadata.onFreeze;
var TypeError$g = global_1.TypeError;
var Result = function (stopped, result) {
this.stopped = stopped;
this.result = result;
};
var ResultPrototype = Result.prototype;
var iterate = function (iterable, unboundFunction, options) {
var that = options && options.that;
var AS_ENTRIES = !!(options && options.AS_ENTRIES);
var IS_ITERATOR = !!(options && options.IS_ITERATOR);
var INTERRUPTED = !!(options && options.INTERRUPTED);
var fn = functionBindContext(unboundFunction, that);
var iterator, iterFn, index, length, result, next, step;
var stop = function (condition) {
if (iterator) iteratorClose(iterator, 'normal', condition);
return new Result(true, condition);
};
var callFn = function (value) {
if (AS_ENTRIES) {
anObject(value);
return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);
} return INTERRUPTED ? fn(value, stop) : fn(value);
};
if (IS_ITERATOR) {
iterator = iterable;
} else {
iterFn = getIteratorMethod(iterable);
if (!iterFn) throw TypeError$g(tryToString(iterable) + ' is not iterable');
// optimisation for array iterators
if (isArrayIteratorMethod(iterFn)) {
for (index = 0, length = lengthOfArrayLike(iterable); length > index; index++) {
result = callFn(iterable[index]);
if (result && objectIsPrototypeOf(ResultPrototype, result)) return result;
} return new Result(false);
}
iterator = getIterator(iterable, iterFn);
}
next = iterator.next;
while (!(step = functionCall(next, iterator)).done) {
try {
result = callFn(step.value);
} catch (error) {
iteratorClose(iterator, 'throw', error);
}
if (typeof result == 'object' && result && objectIsPrototypeOf(ResultPrototype, result)) return result;
} return new Result(false);
};
var TypeError$h = global_1.TypeError;
var anInstance = function (it, Prototype) {
if (objectIsPrototypeOf(Prototype, it)) return it;
throw TypeError$h('Incorrect invocation');
};
var defineProperty$d = objectDefineProperty.f;
var forEach$4 = arrayIteration.forEach;
var setInternalState$3 = internalState.set;
var internalStateGetterFor = internalState.getterFor;
var collection = function (CONSTRUCTOR_NAME, wrapper, common) {
var IS_MAP = CONSTRUCTOR_NAME.indexOf('Map') !== -1;
var IS_WEAK = CONSTRUCTOR_NAME.indexOf('Weak') !== -1;
var ADDER = IS_MAP ? 'set' : 'add';
var NativeConstructor = global_1[CONSTRUCTOR_NAME];
var NativePrototype = NativeConstructor && NativeConstructor.prototype;
var exported = {};
var Constructor;
if (!descriptors || !isCallable(NativeConstructor)
|| !(IS_WEAK || NativePrototype.forEach && !fails(function () { new NativeConstructor().entries().next(); }))
) {
// create collection constructor
Constructor = common.getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER);
internalMetadata.enable();
} else {
Constructor = wrapper(function (target, iterable) {
setInternalState$3(anInstance(target, Prototype), {
type: CONSTRUCTOR_NAME,
collection: new NativeConstructor()
});
if (iterable != undefined) iterate(iterable, target[ADDER], { that: target, AS_ENTRIES: IS_MAP });
});
var Prototype = Constructor.prototype;
var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME);
forEach$4(['add', 'clear', 'delete', 'forEach', 'get', 'has', 'set', 'keys', 'values', 'entries'], function (KEY) {
var IS_ADDER = KEY == 'add' || KEY == 'set';
if (KEY in NativePrototype && !(IS_WEAK && KEY == 'clear')) {
createNonEnumerableProperty(Prototype, KEY, function (a, b) {
var collection = getInternalState(this).collection;
if (!IS_ADDER && IS_WEAK && !isObject(a)) return KEY == 'get' ? undefined : false;
var result = collection[KEY](a === 0 ? 0 : a, b);
return IS_ADDER ? this : result;
});
}
});
IS_WEAK || defineProperty$d(Prototype, 'size', {
configurable: true,
get: function () {
return getInternalState(this).collection.size;
}
});
}
setToStringTag(Constructor, CONSTRUCTOR_NAME, false, true);
exported[CONSTRUCTOR_NAME] = Constructor;
_export({ global: true, forced: true }, exported);
if (!IS_WEAK) common.setStrong(Constructor, CONSTRUCTOR_NAME, IS_MAP);
return Constructor;
};
var defineBuiltIns = function (target, src, options) {
for (var key in src) {
if (options && options.unsafe && target[key]) target[key] = src[key];
else defineBuiltIn(target, key, src[key], options);
} return target;
};
var SPECIES$3 = wellKnownSymbol('species');
var setSpecies = function (CONSTRUCTOR_NAME) {
var Constructor = getBuiltIn(CONSTRUCTOR_NAME);
var defineProperty = objectDefineProperty.f;
if (descriptors && Constructor && !Constructor[SPECIES$3]) {
defineProperty(Constructor, SPECIES$3, {
configurable: true,
get: function () { return this; }
});
}
};
var defineProperty$e = objectDefineProperty.f;
var fastKey = internalMetadata.fastKey;
var setInternalState$4 = internalState.set;
var internalStateGetterFor$1 = internalState.getterFor;
var collectionStrong = {
getConstructor: function (wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) {
var Constructor = wrapper(function (that, iterable) {
anInstance(that, Prototype);
setInternalState$4(that, {
type: CONSTRUCTOR_NAME,
index: objectCreate(null),
first: undefined,
last: undefined,
size: 0
});
if (!descriptors) that.size = 0;
if (iterable != undefined) iterate(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP });
});
var Prototype = Constructor.prototype;
var getInternalState = internalStateGetterFor$1(CONSTRUCTOR_NAME);
var define = function (that, key, value) {
var state = getInternalState(that);
var entry = getEntry(that, key);
var previous, index;
// change existing entry
if (entry) {
entry.value = value;
// create new entry
} else {
state.last = entry = {
index: index = fastKey(key, true),
key: key,
value: value,
previous: previous = state.last,
next: undefined,
removed: false
};
if (!state.first) state.first = entry;
if (previous) previous.next = entry;
if (descriptors) state.size++;
else that.size++;
// add to index
if (index !== 'F') state.index[index] = entry;
} return that;
};
var getEntry = function (that, key) {
var state = getInternalState(that);
// fast case
var index = fastKey(key);
var entry;
if (index !== 'F') return state.index[index];
// frozen object case
for (entry = state.first; entry; entry = entry.next) {
if (entry.key == key) return entry;
}
};
defineBuiltIns(Prototype, {
// `{ Map, Set }.prototype.clear()` methods
// https://tc39.es/ecma262/#sec-map.prototype.clear
// https://tc39.es/ecma262/#sec-set.prototype.clear
clear: function clear() {
var that = this;
var state = getInternalState(that);
var data = state.index;
var entry = state.first;
while (entry) {
entry.removed = true;
if (entry.previous) entry.previous = entry.previous.next = undefined;
delete data[entry.index];
entry = entry.next;
}
state.first = state.last = undefined;
if (descriptors) state.size = 0;
else that.size = 0;
},
// `{ Map, Set }.prototype.delete(key)` methods
// https://tc39.es/ecma262/#sec-map.prototype.delete
// https://tc39.es/ecma262/#sec-set.prototype.delete
'delete': function (key) {
var that = this;
var state = getInternalState(that);
var entry = getEntry(that, key);
if (entry) {
var next = entry.next;
var prev = entry.previous;
delete state.index[entry.index];
entry.removed = true;
if (prev) prev.next = next;
if (next) next.previous = prev;
if (state.first == entry) state.first = next;
if (state.last == entry) state.last = prev;
if (descriptors) state.size--;
else that.size--;
} return !!entry;
},
// `{ Map, Set }.prototype.forEach(callbackfn, thisArg = undefined)` methods
// https://tc39.es/ecma262/#sec-map.prototype.foreach
// https://tc39.es/ecma262/#sec-set.prototype.foreach
forEach: function forEach(callbackfn /* , that = undefined */) {
var state = getInternalState(this);
var boundFunction = functionBindContext(callbackfn, arguments.length > 1 ? arguments[1] : undefined);
var entry;
while (entry = entry ? entry.next : state.first) {
boundFunction(entry.value, entry.key, this);
// revert to the last existing entry
while (entry && entry.removed) entry = entry.previous;
}
},
// `{ Map, Set}.prototype.has(key)` methods
// https://tc39.es/ecma262/#sec-map.prototype.has
// https://tc39.es/ecma262/#sec-set.prototype.has
has: function has(key) {
return !!getEntry(this, key);
}
});
defineBuiltIns(Prototype, IS_MAP ? {
// `Map.prototype.get(key)` method
// https://tc39.es/ecma262/#sec-map.prototype.get
get: function get(key) {
var entry = getEntry(this, key);
return entry && entry.value;
},
// `Map.prototype.set(key, value)` method
// https://tc39.es/ecma262/#sec-map.prototype.set
set: function set(key, value) {
return define(this, key === 0 ? 0 : key, value);
}
} : {
// `Set.prototype.add(value)` method
// https://tc39.es/ecma262/#sec-set.prototype.add
add: function add(value) {
return define(this, value = value === 0 ? 0 : value, value);
}
});
if (descriptors) defineProperty$e(Prototype, 'size', {
get: function () {
return getInternalState(this).size;
}
});
return Constructor;
},
setStrong: function (Constructor, CONSTRUCTOR_NAME, IS_MAP) {
var ITERATOR_NAME = CONSTRUCTOR_NAME + ' Iterator';
var getInternalCollectionState = internalStateGetterFor$1(CONSTRUCTOR_NAME);
var getInternalIteratorState = internalStateGetterFor$1(ITERATOR_NAME);
// `{ Map, Set }.prototype.{ keys, values, entries, @@iterator }()` methods
// https://tc39.es/ecma262/#sec-map.prototype.entries
// https://tc39.es/ecma262/#sec-map.prototype.keys
// https://tc39.es/ecma262/#sec-map.prototype.values
// https://tc39.es/ecma262/#sec-map.prototype-@@iterator
// https://tc39.es/ecma262/#sec-set.prototype.entries
// https://tc39.es/ecma262/#sec-set.prototype.keys
// https://tc39.es/ecma262/#sec-set.prototype.values
// https://tc39.es/ecma262/#sec-set.prototype-@@iterator
defineIterator(Constructor, CONSTRUCTOR_NAME, function (iterated, kind) {
setInternalState$4(this, {
type: ITERATOR_NAME,
target: iterated,
state: getInternalCollectionState(iterated),
kind: kind,
last: undefined
});
}, function () {
var state = getInternalIteratorState(this);
var kind = state.kind;
var entry = state.last;
// revert to the last existing entry
while (entry && entry.removed) entry = entry.previous;
// get next entry
if (!state.target || !(state.last = entry = entry ? entry.next : state.state.first)) {
// or finish the iteration
state.target = undefined;
return { value: undefined, done: true };
}
// return step by kind
if (kind == 'keys') return { value: entry.key, done: false };
if (kind == 'values') return { value: entry.value, done: false };
return { value: [entry.key, entry.value], done: false };
}, IS_MAP ? 'entries' : 'values', !IS_MAP, true);
// `{ Map, Set }.prototype[@@species]` accessors
// https://tc39.es/ecma262/#sec-get-map-@@species
// https://tc39.es/ecma262/#sec-get-set-@@species
setSpecies(CONSTRUCTOR_NAME);
}
};
// `Map` constructor
// https://tc39.es/ecma262/#sec-map-objects
collection('Map', function (init) {
return function Map() { return init(this, arguments.length ? arguments[0] : undefined); };
}, collectionStrong);
var map$4 = path.Map;
var map$5 = map$4;
var map$6 = map$5;
// https://tc39.github.io/proposal-setmap-offrom/
var push$4 = [].push;
var collectionFrom = function from(source /* , mapFn, thisArg */) {
var length = arguments.length;
var mapFn = length > 1 ? arguments[1] : undefined;
var mapping, array, n, boundFunction;
aConstructor(this);
mapping = mapFn !== undefined;
if (mapping) aCallable(mapFn);
if (source == undefined) return new this();
array = [];
if (mapping) {
n = 0;
boundFunction = functionBindContext(mapFn, length > 2 ? arguments[2] : undefined);
iterate(source, function (nextItem) {
functionCall(push$4, array, boundFunction(nextItem, n++));
});
} else {
iterate(source, push$4, { that: array });
}
return new this(array);
};
// `Map.from` method
// https://tc39.github.io/proposal-setmap-offrom/#sec-map.from
_export({ target: 'Map', stat: true, forced: true }, {
from: collectionFrom
});
// https://tc39.github.io/proposal-setmap-offrom/
var collectionOf = function of() {
return new this(arraySlice(arguments));
};
// `Map.of` method
// https://tc39.github.io/proposal-setmap-offrom/#sec-map.of
_export({ target: 'Map', stat: true, forced: true }, {
of: collectionOf
});
// https://github.com/tc39/collection-methods
var collectionDeleteAll = function deleteAll(/* ...elements */) {
var collection = anObject(this);
var remover = aCallable(collection['delete']);
var allDeleted = true;
var wasDeleted;
for (var k = 0, len = arguments.length; k < len; k++) {
wasDeleted = functionCall(remover, collection, arguments[k]);
allDeleted = allDeleted && wasDeleted;
}
return !!allDeleted;
};
// `Map.prototype.deleteAll` method
// https://github.com/tc39/proposal-collection-methods
_export({ target: 'Map', proto: true, real: true, forced: true }, {
deleteAll: collectionDeleteAll
});
// `Map.prototype.emplace` method
// https://github.com/thumbsupep/proposal-upsert
var mapEmplace = function emplace(key, handler) {
var map = anObject(this);
var get = aCallable(map.get);
var has = aCallable(map.has);
var set = aCallable(map.set);
var value = (functionCall(has, map, key) && 'update' in handler)
? handler.update(functionCall(get, map, key), key, map)
: handler.insert(key, map);
functionCall(set, map, key, value);
return value;
};
// `Map.prototype.emplace` method
// https://github.com/thumbsupep/proposal-upsert
_export({ target: 'Map', proto: true, real: true, forced: true }, {
emplace: mapEmplace
});
var getMapIterator = getIterator;
// `Map.prototype.every` method
// https://github.com/tc39/proposal-collection-methods
_export({ target: 'Map', proto: true, real: true, forced: true }, {
every: function every(callbackfn /* , thisArg */) {
var map = anObject(this);
var iterator = getMapIterator(map);
var boundFunction = functionBindContext(callbackfn, arguments.length > 1 ? arguments[1] : undefined);
return !iterate(iterator, function (key, value, stop) {
if (!boundFunction(value, key, map)) return stop();
}, { AS_ENTRIES: true, IS_ITERATOR: true, INTERRUPTED: true }).stopped;
}
});
var SPECIES$4 = wellKnownSymbol('species');
// `SpeciesConstructor` abstract operation
// https://tc39.es/ecma262/#sec-speciesconstructor
var speciesConstructor = function (O, defaultConstructor) {
var C = anObject(O).constructor;
var S;
return C === undefined || (S = anObject(C)[SPECIES$4]) == undefined ? defaultConstructor : aConstructor(S);
};
// `Map.prototype.filter` method
// https://github.com/tc39/proposal-collection-methods
_export({ target: 'Map', proto: true, real: true, forced: true }, {
filter: function filter(callbackfn /* , thisArg */) {
var map = anObject(this);
var iterator = getMapIterator(map);
var boundFunction = functionBindContext(callbackfn, arguments.length > 1 ? arguments[1] : undefined);
var newMap = new (speciesConstructor(map, getBuiltIn('Map')))();
var setter = aCallable(newMap.set);
iterate(iterator, function (key, value) {
if (boundFunction(value, key, map)) functionCall(setter, newMap, key, value);
}, { AS_ENTRIES: true, IS_ITERATOR: true });
return newMap;
}
});
// `Map.prototype.find` method
// https://github.com/tc39/proposal-collection-methods
_export({ target: 'Map', proto: true, real: true, forced: true }, {
find: function find(callbackfn /* , thisArg */) {
var map = anObject(this);
var iterator = getMapIterator(map);
var boundFunction = functionBindContext(callbackfn, arguments.length > 1 ? arguments[1] : undefined);
return iterate(iterator, function (key, value, stop) {
if (boundFunction(value, key, map)) return stop(value);
}, { AS_ENTRIES: true, IS_ITERATOR: true, INTERRUPTED: true }).result;
}
});
// `Map.prototype.findKey` method
// https://github.com/tc39/proposal-collection-methods
_export({ target: 'Map', proto: true, real: true, forced: true }, {
findKey: function findKey(callbackfn /* , thisArg */) {
var map = anObject(this);
var iterator = getMapIterator(map);
var boundFunction = functionBindContext(callbackfn, arguments.length > 1 ? arguments[1] : undefined);
return iterate(iterator, function (key, value, stop) {
if (boundFunction(value, key, map)) return stop(key);
}, { AS_ENTRIES: true, IS_ITERATOR: true, INTERRUPTED: true }).result;
}
});
var push$5 = functionUncurryThis([].push);
// `Map.groupBy` method
// https://github.com/tc39/proposal-collection-methods
_export({ target: 'Map', stat: true, forced: true }, {
groupBy: function groupBy(iterable, keyDerivative) {
aCallable(keyDerivative);
var iterator = getIterator(iterable);
var newMap = new this();
var has = aCallable(newMap.has);
var get = aCallable(newMap.get);
var set = aCallable(newMap.set);
iterate(iterator, function (element) {
var derivedKey = keyDerivative(element);
if (!functionCall(has, newMap, derivedKey)) functionCall(set, newMap, derivedKey, [element]);
else push$5(functionCall(get, newMap, derivedKey), element);
}, { IS_ITERATOR: true });
return newMap;
}
});
// `SameValueZero` abstract operation
// https://tc39.es/ecma262/#sec-samevaluezero
var sameValueZero = function (x, y) {
// eslint-disable-next-line no-self-compare -- NaN check
return x === y || x != x && y != y;
};
// `Map.prototype.includes` method
// https://github.com/tc39/proposal-collection-methods
_export({ target: 'Map', proto: true, real: true, forced: true }, {
includes: function includes(searchElement) {
return iterate(getMapIterator(anObject(this)), function (key, value, stop) {
if (sameValueZero(value, searchElement)) return stop();
}, { AS_ENTRIES: true, IS_ITERATOR: true, INTERRUPTED: true }).stopped;
}
});
// `Map.keyBy` method
// https://github.com/tc39/proposal-collection-methods
_export({ target: 'Map', stat: true, forced: true }, {
keyBy: function keyBy(iterable, keyDerivative) {
var newMap = new this();
aCallable(keyDerivative);
var setter = aCallable(newMap.set);
iterate(iterable, function (element) {
functionCall(setter, newMap, keyDerivative(element), element);
});
return newMap;
}
});
// `Map.prototype.keyOf` method
// https://github.com/tc39/proposal-collection-methods
_export({ target: 'Map', proto: true, real: true, forced: true }, {
keyOf: function keyOf(searchElement) {
return iterate(getMapIterator(anObject(this)), function (key, value, stop) {
if (value === searchElement) return stop(key);
}, { AS_ENTRIES: true, IS_ITERATOR: true, INTERRUPTED: true }).result;
}
});
// `Map.prototype.mapKeys` method
// https://github.com/tc39/proposal-collection-methods
_export({ target: 'Map', proto: true, real: true, forced: true }, {
mapKeys: function mapKeys(callbackfn /* , thisArg */) {
var map = anObject(this);
var iterator = getMapIterator(map);
var boundFunction = functionBindContext(callbackfn, arguments.length > 1 ? arguments[1] : undefined);
var newMap = new (speciesConstructor(map, getBuiltIn('Map')))();
var setter = aCallable(newMap.set);
iterate(iterator, function (key, value) {
functionCall(setter, newMap, boundFunction(value, key, map), value);
}, { AS_ENTRIES: true, IS_ITERATOR: true });
return newMap;
}
});
// `Map.prototype.mapValues` method
// https://github.com/tc39/proposal-collection-methods
_export({ target: 'Map', proto: true, real: true, forced: true }, {
mapValues: function mapValues(callbackfn /* , thisArg */) {
var map = anObject(this);
var iterator = getMapIterator(map);
var boundFunction = functionBindContext(callbackfn, arguments.length > 1 ? arguments[1] : undefined);
var newMap = new (speciesConstructor(map, getBuiltIn('Map')))();
var setter = aCallable(newMap.set);
iterate(iterator, function (key, value) {
functionCall(setter, newMap, key, boundFunction(value, key, map));
}, { AS_ENTRIES: true, IS_ITERATOR: true });
return newMap;
}
});
// `Map.prototype.merge` method
// https://github.com/tc39/proposal-collection-methods
_export({ target: 'Map', proto: true, real: true, arity: 1, forced: true }, {
// eslint-disable-next-line no-unused-vars -- required for `.length`
merge: function merge(iterable /* ...iterables */) {
var map = anObject(this);
var setter = aCallable(map.set);
var argumentsLength = arguments.length;
var i = 0;
while (i < argumentsLength) {
iterate(arguments[i++], setter, { that: map, AS_ENTRIES: true });
}
return map;
}
});
var TypeError$i = global_1.TypeError;
// `Map.prototype.reduce` method
// https://github.com/tc39/proposal-collection-methods
_export({ target: 'Map', proto: true, real: true, forced: true }, {
reduce: function reduce(callbackfn /* , initialValue */) {
var map = anObject(this);
var iterator = getMapIterator(map);
var noInitial = arguments.length < 2;
var accumulator = noInitial ? undefined : arguments[1];
aCallable(callbackfn);
iterate(iterator, function (key, value) {
if (noInitial) {
noInitial = false;
accumulator = value;
} else {
accumulator = callbackfn(accumulator, value, key, map);
}
}, { AS_ENTRIES: true, IS_ITERATOR: true });
if (noInitial) throw TypeError$i('Reduce of empty map with no initial value');
return accumulator;
}
});
// `Set.prototype.some` method
// https://github.com/tc39/proposal-collection-methods
_export({ target: 'Map', proto: true, real: true, forced: true }, {
some: function some(callbackfn /* , thisArg */) {
var map = anObject(this);
var iterator = getMapIterator(map);
var boundFunction = functionBindContext(callbackfn, arguments.length > 1 ? arguments[1] : undefined);
return iterate(iterator, function (key, value, stop) {
if (boundFunction(value, key, map)) return stop();
}, { AS_ENTRIES: true, IS_ITERATOR: true, INTERRUPTED: true }).stopped;
}
});
var TypeError$j = global_1.TypeError;
// `Set.prototype.update` method
// https://github.com/tc39/proposal-collection-methods
_export({ target: 'Map', proto: true, real: true, forced: true }, {
update: function update(key, callback /* , thunk */) {
var map = anObject(this);
var get = aCallable(map.get);
var has = aCallable(map.has);
var set = aCallable(map.set);
var length = arguments.length;
aCallable(callback);
var isPresentInMap = functionCall(has, map, key);
if (!isPresentInMap && length < 3) {
throw TypeError$j('Updating absent value');
}
var value = isPresentInMap ? functionCall(get, map, key) : aCallable(length > 2 ? arguments[2] : undefined)(key, map);
functionCall(set, map, key, callback(value, key, map));
return map;
}
});
var TypeError$k = global_1.TypeError;
// `Map.prototype.upsert` method
// https://github.com/thumbsupep/proposal-upsert
var mapUpsert = function upsert(key, updateFn /* , insertFn */) {
var map = anObject(this);
var get = aCallable(map.get);
var has = aCallable(map.has);
var set = aCallable(map.set);
var insertFn = arguments.length > 2 ? arguments[2] : undefined;
var value;
if (!isCallable(updateFn) && !isCallable(insertFn)) {
throw TypeError$k('At least one callback required');
}
if (functionCall(has, map, key)) {
value = functionCall(get, map, key);
if (isCallable(updateFn)) {
value = updateFn(value);
functionCall(set, map, key, value);
}
} else if (isCallable(insertFn)) {
value = insertFn();
functionCall(set, map, key, value);
} return value;
};
// TODO: remove from `core-js@4`
// `Map.prototype.upsert` method (replaced by `Map.prototype.emplace`)
// https://github.com/thumbsupep/proposal-upsert
_export({ target: 'Map', proto: true, real: true, forced: true }, {
upsert: mapUpsert
});
// TODO: remove from `core-js@4`
// `Map.prototype.updateOrInsert` method (replaced by `Map.prototype.emplace`)
// https://github.com/thumbsupep/proposal-upsert
_export({ target: 'Map', proto: true, real: true, name: 'upsert', forced: true }, {
updateOrInsert: mapUpsert
});
// TODO: remove from `core-js@4`
// TODO: remove from `core-js@4`
var map$7 = map$6;
var map$8 = map$7;
var map$9 = map$8;
var isNativeFunction = createCommonjsModule(function (module) {
function _isNativeFunction(fn) {
var _context;
return indexOf$7(_context = Function.toString.call(fn)).call(_context, "[native code]") !== -1;
}
module.exports = _isNativeFunction, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(isNativeFunction);
var construct$5 = construct$3;
var construct$6 = construct$5;
var construct$7 = construct$6;
var construct$8 = construct$7;
var bind$6 = bind$4;
var bind$7 = bind$6;
var bind$8 = bind$7;
var bind$9 = bind$8;
var isNativeReflectConstruct = createCommonjsModule(function (module) {
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !construct$8) return false;
if (construct$8.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(construct$8(Boolean, [], function () {}));
return true;
} catch (e) {
return false;
}
}
module.exports = _isNativeReflectConstruct, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(isNativeReflectConstruct);
var construct$9 = createCommonjsModule(function (module) {
function _construct(Parent, args, Class) {
if (isNativeReflectConstruct()) {
module.exports = _construct = construct$8, module.exports.__esModule = true, module.exports["default"] = module.exports;
} else {
module.exports = _construct = function _construct(Parent, args, Class) {
var a = [null];
a.push.apply(a, args);
var Constructor = bind$9(Function).apply(Parent, a);
var instance = new Constructor();
if (Class) setPrototypeOf$6(instance, Class.prototype);
return instance;
}, module.exports.__esModule = true, module.exports["default"] = module.exports;
}
return _construct.apply(null, arguments);
}
module.exports = _construct, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
var _construct = unwrapExports(construct$9);
var wrapNativeSuper = createCommonjsModule(function (module) {
function _wrapNativeSuper(Class) {
var _cache = typeof map$9 === "function" ? new map$9() : undefined;
module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) {
if (Class === null || !isNativeFunction(Class)) return Class;
if (typeof Class !== "function") {
throw new TypeError("Super expression must either be null or a function");
}
if (typeof _cache !== "undefined") {
if (_cache.has(Class)) return _cache.get(Class);
_cache.set(Class, Wrapper);
}
function Wrapper() {
return construct$9(Class, arguments, getPrototypeOf$6(this).constructor);
}
Wrapper.prototype = create$5(Class.prototype, {
constructor: {
value: Wrapper,
enumerable: false,
writable: true,
configurable: true
}
});
return setPrototypeOf$6(Wrapper, Class);
}, module.exports.__esModule = true, module.exports["default"] = module.exports;
return _wrapNativeSuper(Class);
}
module.exports = _wrapNativeSuper, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
var _wrapNativeSuper = unwrapExports(wrapNativeSuper);
function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* 三个地方的错误异常校验
* 1. markdown 对象参数校验
* 2. editText 用户输入校验执行engine过程以防异常
* 3. 自定义hook校验 对外开发者开发标准校验
*/
var $expectTarget = function $expectTarget(target, Constructor) {
if (!isArray$8(target) && _typeof(target) !== Constructor.name.toLowerCase() || !isArray$8(target) && Constructor.name.toLowerCase() === 'array') {
throw new TypeError("parameter given must be ".concat(Constructor.name));
}
return true;
};
var $expectInherit = function $expectInherit(target, parent) {
if (!(target instanceof parent)) {
throw new Error('the hook does not correctly inherit');
}
return true;
};
var $expectInstance = function $expectInstance(target) {
if (_typeof(target) !== 'object') {
throw new Error('the hook must be a instance, not a class');
}
return true;
}; // ref: https://github.com/mdlavin/nested-error-stacks
var NestedError = /*#__PURE__*/function (_Error) {
_inherits(NestedError, _Error);
var _super = _createSuper$1(NestedError);
function NestedError(message, nested) {
var _this;
_classCallCheck(this, NestedError);
_this = _super.call(this, message);
_this.name = 'Error';
_this.stack = _this.buildStackTrace(nested);
return _this;
}
_createClass(NestedError, [{
key: "buildStackTrace",
value: function buildStackTrace(nested) {
var _context;
var stack = nested && nested.stack ? nested.stack : '';
var newStack = concat$5(_context = "".concat(this.stack, "\nCaused By: ")).call(_context, stack);
return newStack;
}
}]);
return NestedError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
/**
* @typedef {import('~types/cherry').CherryOptions} CherryOptions
* @typedef {import('~types/cherry').CherryEngineOptions} CherryEngineOptions
* @typedef {import('~types/cherry').CustomSyntaxRegConfig} CustomSyntaxRegConfig
* @typedef { (SyntaxBase | ParagraphBase) & { Cherry$$CUSTOM: true } } CustomSyntax
* @typedef { (typeof SyntaxBase | typeof ParagraphBase) & { Cherry$$CUSTOM: true } } CustomSyntaxClass
*/
var WARN_DUPLICATED = -1;
var WARN_NOT_A_VALID_HOOK = -2;
/**
* 处理报错信息在dev模式下才会输出报错信息
* @param {number} type
* @param {any} objClass
* @param {number} index
*/
function processWarning(type, objClass, index) {
if (type === WARN_DUPLICATED) {
var _context, _context2;
Logger.warn(concat$5(_context = concat$5(_context2 = "Duplicate hook name [".concat(objClass.HOOK_NAME, "] found, hook [")).call(_context2, objClass.toString(), "] ")).call(_context, isNaN(index) ? '' : "at index [".concat(index, "] "), "will not take effect."));
} else if (type === WARN_NOT_A_VALID_HOOK) {
var _context3;
Logger.warn(concat$5(_context3 = "Hook [".concat(objClass.toString(), "] ")).call(_context3, isNaN(index) ? '' : "at index [".concat(index, "] "), "is not a valid hook, and will not take effect."));
}
}
/**
* 是否一个合法的 HookClass
* @param {any} HookClass
* @returns { HookClass is (typeof SyntaxBase | typeof ParagraphBase) }
*/
function isHookValid(HookClass) {
return isProtoOfSyntaxBase(HookClass) || isProtoOfParagraphBase(HookClass);
}
/**
* 传入的类是否 SyntaxBase 的子类
* @param {any} value
* @returns { value is typeof SyntaxBase }
*/
function isProtoOfSyntaxBase(value) {
return Object.prototype.isPrototypeOf.call(SyntaxBase, value);
}
/**
* 传入的类是否 ParagraphBase 的子类
* @param {any} value
* @returns { value is typeof ParagraphBase }
*/
function isProtoOfParagraphBase(value) {
return Object.prototype.isPrototypeOf.call(ParagraphBase, value);
}
/**
* 是否一个配置型的自定义语法
* @param {any} value
* @returns { value is CustomSyntaxRegConfig }
*/
function isCustomSyntaxConfig(value) {
var syntaxClass =
/** @type {any} */
/** @type {CustomSyntaxRegConfig} */
value === null || value === void 0 ? void 0 : value.syntaxClass;
return isProtoOfSyntaxBase(syntaxClass) || isProtoOfParagraphBase(syntaxClass);
}
/**
* 是否一个已注册的自定义语法hook类
* @param {any} value
* @returns { value is CustomSyntaxClass }
*/
function isRegisteredCustomSyntaxClass(value) {
return isHookValid(value) &&
/** @type {CustomSyntaxClass} */
(value === null || value === void 0 ? void 0 : value.Cherry$$CUSTOM) === true;
}
/**
* 语法注册中心
*/
var HookCenter = /*#__PURE__*/function () {
/**
*
* @param {(typeof SyntaxBase)[]} hooksConfig
* @param {Partial<CherryOptions>} editorConfig
*/
function HookCenter(hooksConfig, editorConfig, cherry) {
_classCallCheck(this, HookCenter);
this.$locale = cherry.locale;
/**
* @property
* @type {Record<import('./SyntaxBase').HookType, SyntaxBase[]>} hookList hook 名称 -> hook 类型的映射
*/
this.hookList =
/** @type {any} */
{};
/**
* @property
* @type {Record<string, { type: import('./SyntaxBase').HookType }>} hookNameList hook 名称 -> hook 类型的映射
*/
this.hookNameList = {};
$expectTarget(hooksConfig, Array);
this.registerInternalHooks(hooksConfig, editorConfig);
this.registerCustomHooks(editorConfig.engine.customSyntax, editorConfig);
}
/**
* 注册系统默认的语法hook
* @param {any[]} hooksConfig 在hookconfig.js里定义的配置
* @param {Partial<CherryOptions>} editorConfig 编辑器配置
*/
_createClass(HookCenter, [{
key: "registerInternalHooks",
value: function registerInternalHooks(hooksConfig, editorConfig) {
var _this = this;
forEach$3(hooksConfig).call(hooksConfig,
/**
*
* @param {typeof SyntaxBase} HookClass
* @param {number} index
*/
function (HookClass, index) {
var result = _this.register(HookClass, editorConfig);
processWarning(result, HookClass, index);
});
}
/**
* 注册第三方的语法hook
* @param {CherryEngineOptions['customSyntax']} customHooks 用户传入的配置
* @param {Partial<CherryOptions>} editorConfig 编辑器配置
*/
}, {
key: "registerCustomHooks",
value: function registerCustomHooks(customHooks, editorConfig) {
var _this2 = this;
if (!customHooks) {
return;
}
var hookNames = keys$3(customHooks);
forEach$3(hookNames).call(hookNames, function (hookName) {
/** @type {number} */
var result;
/** @type {typeof SyntaxBase} */
var HookClass;
var customHookConfig = {};
var hookClassOrConfig = customHooks[hookName];
if (isProtoOfSyntaxBase(hookClassOrConfig)) {
HookClass = hookClassOrConfig;
} else if (isCustomSyntaxConfig(hookClassOrConfig)) {
HookClass = hookClassOrConfig.syntaxClass;
customHookConfig.force = Boolean(hookClassOrConfig.force);
if (hookClassOrConfig.before) {
customHookConfig.before = hookClassOrConfig.before;
} else if (hookClassOrConfig.after) {
customHookConfig.after = hookClassOrConfig.after;
}
} else {
return;
}
if (isHookValid(HookClass)) {
// 自定义Hook标识
defineProperty$5(HookClass, 'Cherry$$CUSTOM', {
enumerable: false,
configurable: false,
writable: false,
value: true
});
result = _this2.register(HookClass, editorConfig, customHookConfig);
} else {
result = WARN_NOT_A_VALID_HOOK;
}
processWarning(result, HookClass, undefined);
});
}
}, {
key: "getHookList",
value: function getHookList() {
return this.hookList;
}
}, {
key: "getHookNameList",
value: function getHookNameList() {
return this.hookNameList;
}
/**
*
* @param {((...args: any[]) => any) | typeof SyntaxBase} HookClass
* @param {Partial<CherryOptions>} editorConfig
* @param {Omit<CustomSyntaxRegConfig, 'syntaxClass'>} [customHookConfig]
* @returns
*/
}, {
key: "register",
value: function register(HookClass, editorConfig, customHookConfig) {
var _this3 = this;
// filter Configs Here
var externals = editorConfig.externals,
engine = editorConfig.engine;
var syntax = engine.syntax;
/** @type {SyntaxBase | CustomSyntax} */
var instance;
/** @type {string} */
var hookName; // 首先校验Hook是否合法
if (!isHookValid(HookClass)) {
// 可能是一个function hook
if (typeof HookClass === 'function') {
var funcHook = HookClass;
instance = funcHook(editorConfig);
if (!instance || !isHookValid(instance.constructor)) {
return WARN_NOT_A_VALID_HOOK;
}
hookName = instance.getName();
} else {
return WARN_NOT_A_VALID_HOOK;
}
} else {
hookName = HookClass.HOOK_NAME; // TODO: 需要考虑自定义 hook 配置的传入方式
var config = (syntax === null || syntax === void 0 ? void 0 : syntax[hookName]) || {};
instance = new HookClass({
externals: externals,
config: config,
globalConfig: engine.global
});
instance.afterInit(function () {
instance.setLocale(_this3.$locale);
});
} // TODO: 待校验是否需要跳过禁用的自定义 hook
// Skip Disabled Internal Hooks
if (syntax[hookName] === false && !isRegisteredCustomSyntaxClass(HookClass)) {
return;
} // 下面处理的都是 CustomSyntax
var hookType = instance.getType();
if (this.hookNameList[hookName]) {
var _context4;
// 内置 hook 重名
if (!isRegisteredCustomSyntaxClass(HookClass)) {
return WARN_DUPLICATED;
} // 自定义 hook 重名且没有开启覆盖的选项
if (!customHookConfig.force) {
return WARN_DUPLICATED;
} // 强制覆盖以前的Hook所以需要移除
var duplicateHookType = this.hookNameList[hookName].type;
this.hookList[duplicateHookType] = filter$3(_context4 = this.hookList[duplicateHookType]).call(_context4, function (hook) {
return hook.getName() !== hookName;
});
}
this.hookNameList[hookName] = {
type: hookType
};
this.hookList[hookType] = this.hookList[hookType] || []; // 内置Hook直接push到结尾
if (!isRegisteredCustomSyntaxClass(HookClass)) {
this.hookList[hookType].push(instance);
return;
} // 插入自定义Hook
var insertIndex = -1;
if (customHookConfig.before) {
var _context5;
insertIndex = findIndex$3(_context5 = this.hookList[hookType]).call(_context5, function (hook) {
return hook.getName() === customHookConfig.before;
});
if (insertIndex === -1) {
var _context6;
Logger.warn(concat$5(_context6 = "Cannot find hook named [".concat(customHookConfig.before, "],\n custom hook [")).call(_context6, hookName, "] will append to the end of the hooks."));
}
} else if (customHookConfig.after) {
var _context7, _context8;
insertIndex = findIndex$3(_context7 = this.hookList[hookType]).call(_context7, function (hook) {
return hook.getName() === customHookConfig.after;
});
insertIndex === -1 ? Logger.warn(concat$5(_context8 = "Cannot find hook named [".concat(customHookConfig.after, "],\n custom hook [")).call(_context8, hookName, "] will append to the end of the hooks.")) : insertIndex += 1; // 统一处理往前插入的逻辑所以要插入某Hook之后索引需要加一
} // 无需插入或目标索引为数组结尾
if (insertIndex < 0 || insertIndex >= this.hookList[hookType].length) {
this.hookList[hookType].push(instance);
} else {
var _context9;
splice$4(_context9 = this.hookList[hookType]).call(_context9, insertIndex, 0, instance);
} // console.log(this.hookList[hookType]);
}
}]);
return HookCenter;
}();
var arrayWithoutHoles = createCommonjsModule(function (module) {
function _arrayWithoutHoles(arr) {
if (isArray$7(arr)) return arrayLikeToArray(arr);
}
module.exports = _arrayWithoutHoles, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(arrayWithoutHoles);
var iterableToArray = createCommonjsModule(function (module) {
function _iterableToArray(iter) {
if (typeof symbol$5 !== "undefined" && getIteratorMethod$5(iter) != null || iter["@@iterator"] != null) return from_1$6(iter);
}
module.exports = _iterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(iterableToArray);
var nonIterableSpread = createCommonjsModule(function (module) {
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.");
}
module.exports = _nonIterableSpread, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(nonIterableSpread);
var toConsumableArray = createCommonjsModule(function (module) {
function _toConsumableArray(arr) {
return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
}
module.exports = _toConsumableArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
var _toConsumableArray = unwrapExports(toConsumableArray);
var toArray = createCommonjsModule(function (module) {
function _toArray(arr) {
return arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest();
}
module.exports = _toArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
var _toArray = unwrapExports(toArray);
function ownKeys$2(object, enumerableOnly) { var keys = keys$3(object); if (getOwnPropertySymbols$2) { var symbols = getOwnPropertySymbols$2(object); enumerableOnly && (symbols = filter$3(symbols).call(symbols, function (sym) { return getOwnPropertyDescriptor$3(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var _context2, _context3; var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? forEach$3(_context2 = ownKeys$2(Object(source), !0)).call(_context2, function (key) { _defineProperty(target, key, source[key]); }) : getOwnPropertyDescriptors$2 ? defineProperties$2(target, getOwnPropertyDescriptors$2(source)) : forEach$3(_context3 = ownKeys$2(Object(source))).call(_context3, function (key) { defineProperty$5(target, key, getOwnPropertyDescriptor$3(source, key)); }); } return target; }
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
* @param {string} str
* @param {{replacedText:string;begin:number;length:number;}[]} buffer
*/
function replaceStringByBuffer(str, buffer) {
if (!buffer.length) {
return str;
}
var slicedString = [];
var offset = 0;
forEach$3(buffer).call(buffer, function (buf, index) {
slicedString.push(slice$7(str).call(str, offset, buf.begin));
slicedString.push(buf.replacedText);
offset = buf.begin + buf.length;
if (index === buffer.length - 1) {
slicedString.push(slice$7(str).call(str, offset));
}
}); // console.log(slicedString, slicedString.join(''));
return slicedString.join('');
}
/**
* @param {string} str 原始字符串
* @param {RegExp} regex 正则
* @param {(...args: any[])=>string} replacer 字符串替换函数
* @param {boolean} [continuousMatch=false] 是否连续匹配,主要用于需要后向断言的连续语法匹配
* @param {number} [rollbackLength=1] 连续匹配时,每次指针回退的长度,默认为 1
*/
function replaceLookbehind(str, regex, replacer) {
var continuousMatch = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
var rollbackLength = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 1;
if (!regex) {
return str;
} // 从头开始匹配
regex.lastIndex = 0;
var args;
var lastIndex = 0;
var replaceBuffer = [];
while ((args = regex.exec(str)) !== null) {
var replaceInfo = {
begin: args.index,
length: args[0].length
};
if (continuousMatch && args.index === lastIndex - rollbackLength) {
var _context;
var _args = args,
_args2 = _toArray(_args),
match = _args2[0],
restArgs = slice$7(_args2).call(_args2, 2); // 丢弃 leadingChar需要调整begin和length
replaceBuffer.push({
begin: replaceInfo.begin + rollbackLength,
length: replaceInfo.length - rollbackLength,
replacedText: replacer.apply(void 0, concat$5(_context = [slice$7(match).call(match, rollbackLength), '']).call(_context, _toConsumableArray(restArgs)))
});
} else {
replaceBuffer.push(_objectSpread$1(_objectSpread$1({}, replaceInfo), {}, {
replacedText: replacer.apply(void 0, _toConsumableArray(args))
}));
} // console.log(args);
lastIndex = regex.lastIndex;
regex.lastIndex -= rollbackLength;
} // 正则复位,避免影响其他逻辑
regex.lastIndex = 0;
return replaceStringByBuffer(str, replaceBuffer);
}
function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Color = /*#__PURE__*/function (_SyntaxBase) {
_inherits(Color, _SyntaxBase);
var _super = _createSuper$2(Color);
function Color() {
_classCallCheck(this, Color);
return _super.apply(this, arguments);
}
_createClass(Color, [{
key: "toHtml",
value: // constructor() {
// super();
// }
function toHtml(whole, leadingChar, m1, m2) {
var _context, _context2;
return concat$5(_context = concat$5(_context2 = "".concat(leadingChar, "<span style=\"color:")).call(_context2, m1, "\">")).call(_context, m2, "</span>");
}
}, {
key: "makeHtml",
value: function makeHtml(str) {
if (isLookbehindSupported()) {
return str.replace(this.RULE.reg, this.toHtml);
}
return replaceLookbehind(str, this.RULE.reg, this.toHtml, true, 1);
}
}, {
key: "rule",
value: function rule() {
var ret = {
begin: isLookbehindSupported() ? '((?<!\\\\))!!' : '(^|[^\\\\])!!',
end: '!!',
content: '(#[0-9a-zA-Z]{3,6}|[a-z]{3,20})[\\s]([\\w\\W]+?)'
};
ret.reg = new RegExp(ret.begin + ret.content + ret.end, 'g');
return ret;
}
}]);
return Color;
}(SyntaxBase);
_defineProperty(Color, "HOOK_NAME", 'fontColor');
function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var BackgroundColor = /*#__PURE__*/function (_SyntaxBase) {
_inherits(BackgroundColor, _SyntaxBase);
var _super = _createSuper$3(BackgroundColor);
function BackgroundColor() {
_classCallCheck(this, BackgroundColor);
return _super.apply(this, arguments);
}
_createClass(BackgroundColor, [{
key: "toHtml",
value: // constructor() {
// super();
// }
function toHtml(whole, leadingChar, m1, m2) {
var _context, _context2;
return concat$5(_context = concat$5(_context2 = "".concat(leadingChar, "<span style=\"background-color:")).call(_context2, m1, "\">")).call(_context, m2, "</span>");
}
}, {
key: "makeHtml",
value: function makeHtml(str) {
if (isLookbehindSupported()) {
return str.replace(this.RULE.reg, this.toHtml);
}
return replaceLookbehind(str, this.RULE.reg, this.toHtml, true, 1);
}
}, {
key: "rule",
value: function rule() {
var ret = {
begin: isLookbehindSupported() ? '((?<!\\\\))!!!' : '(^|[^\\\\])!!!',
end: '!!!',
content: '(#[0-9a-zA-Z]{3,6}|[a-z]{3,10})[\\s]([\\w\\W]+?)'
};
ret.reg = new RegExp(ret.begin + ret.content + ret.end, 'g');
return ret;
}
}]);
return BackgroundColor;
}(SyntaxBase);
_defineProperty(BackgroundColor, "HOOK_NAME", 'bgColor');
function _createSuper$4(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$4(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$4() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Size = /*#__PURE__*/function (_SyntaxBase) {
_inherits(Size, _SyntaxBase);
var _super = _createSuper$4(Size);
function Size() {
_classCallCheck(this, Size);
return _super.apply(this, arguments);
}
_createClass(Size, [{
key: "toHtml",
value: // constructor() {
// super();
// }
function toHtml(whole, m1, m2, m3) {
var _context, _context2;
return concat$5(_context = concat$5(_context2 = "".concat(m1, "<span style=\"font-size:")).call(_context2, m2, "px;line-height:1em;\">")).call(_context, m3, "</span>");
}
}, {
key: "makeHtml",
value: function makeHtml(str) {
if (!this.test(str)) {
return str;
}
if (isLookbehindSupported()) {
return str.replace(this.RULE.reg, this.toHtml);
}
return replaceLookbehind(str, this.RULE.reg, this.toHtml, true, 1);
}
}, {
key: "rule",
value: function rule() {
var ret = {
begin: isLookbehindSupported() ? '((?<!\\\\))!' : '(^|[^\\\\])!',
end: '!',
content: '([0-9]{1,2})[\\s]([\\w\\W]*?)'
};
ret.reg = new RegExp(ret.begin + ret.content + ret.end, 'g');
return ret;
}
}]);
return Size;
}(SyntaxBase);
_defineProperty(Size, "HOOK_NAME", 'fontSize');
function _createSuper$5(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$5(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$5() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 删除线语法
*/
var Strikethrough = /*#__PURE__*/function (_SyntaxBase) {
_inherits(Strikethrough, _SyntaxBase);
var _super = _createSuper$5(Strikethrough);
function Strikethrough() {
var _this;
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
config: undefined
},
config = _ref.config;
_classCallCheck(this, Strikethrough);
_this = _super.call(this, {
config: config
});
if (!config) {
return _possibleConstructorReturn(_this);
}
_this.needWhitespace = !!config.needWhitespace;
return _this;
}
/**
* 主要逻辑
* @param {string} str markdown源码
* @returns {string} html内容
*/
_createClass(Strikethrough, [{
key: "makeHtml",
value: function makeHtml(str) {
if (!this.test(str)) {
return str;
}
return str.replace(this.RULE.reg, '$1<del>$2</del>');
}
}, {
key: "rule",
value: function rule() {
var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
config: undefined
},
config = _ref2.config;
/** @type {Partial<import('~types/syntax').BasicHookRegexpRule>} */
var ret = {};
if (!!config.needWhitespace) {
ret = {
begin: '(^|[\\s])\\~T\\~T',
end: '\\~T\\~T(?=\\s|$)',
content: '([\\w\\W]+?)'
};
} else {
ret = {
begin: '(^|[^\\\\])\\~T\\~T',
end: '\\~T\\~T',
content: '([\\w\\W]+?)'
};
}
ret.reg = new RegExp(ret.begin + ret.content + ret.end, 'g');
return ret;
}
}]);
return Strikethrough;
}(SyntaxBase);
_defineProperty(Strikethrough, "HOOK_NAME", 'strikethrough');
function _createSuper$6(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$6(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$6() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Sup = /*#__PURE__*/function (_SyntaxBase) {
_inherits(Sup, _SyntaxBase);
var _super = _createSuper$6(Sup);
function Sup() {
_classCallCheck(this, Sup);
return _super.apply(this, arguments);
}
_createClass(Sup, [{
key: "toHtml",
value: // constructor() {
// super();
// }
function toHtml(whole, leadingChar, m1) {
var _context;
return concat$5(_context = "".concat(leadingChar, "<sup>")).call(_context, m1, "</sup>");
}
}, {
key: "makeHtml",
value: function makeHtml(str) {
if (isLookbehindSupported()) {
return str.replace(this.RULE.reg, this.toHtml);
}
return replaceLookbehind(str, this.RULE.reg, this.toHtml, true, 1);
}
}, {
key: "rule",
value: function rule() {
var ret = {
begin: isLookbehindSupported() ? '((?<!\\\\))\\^' : '(^|[^\\\\])\\^',
end: '\\^',
content: '([\\w\\W]+?)'
};
ret.reg = new RegExp(ret.begin + ret.content + ret.end, 'g');
return ret;
}
}]);
return Sup;
}(SyntaxBase);
_defineProperty(Sup, "HOOK_NAME", 'sup');
function _createSuper$7(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$7(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$7() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Sub = /*#__PURE__*/function (_SyntaxBase) {
_inherits(Sub, _SyntaxBase);
var _super = _createSuper$7(Sub);
function Sub() {
_classCallCheck(this, Sub);
return _super.apply(this, arguments);
}
_createClass(Sub, [{
key: "toHtml",
value: // constructor() {
// super();
// }
function toHtml(whole, leadingChar, m1) {
var _context;
return concat$5(_context = "".concat(leadingChar, "<sub>")).call(_context, m1, "</sub>");
}
}, {
key: "makeHtml",
value: function makeHtml(str) {
if (isLookbehindSupported()) {
return str.replace(this.RULE.reg, this.toHtml);
}
return replaceLookbehind(str, this.RULE.reg, this.toHtml, true, 1);
}
}, {
key: "rule",
value: function rule() {
var ret = {
begin: isLookbehindSupported() ? '((?<!\\\\))\\^\\^' : '(^|[^\\\\])\\^\\^',
end: '\\^\\^',
content: '([\\w\\W]+?)'
};
ret.reg = new RegExp(ret.begin + ret.content + ret.end, 'g');
return ret;
}
}]);
return Sub;
}(SyntaxBase);
_defineProperty(Sub, "HOOK_NAME", 'sub');
var prismCore = createCommonjsModule(function (module) {
/// <reference lib="WebWorker"/>
var _self = (typeof window !== 'undefined')
? window // if in browser
: (
(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope)
? self // if in worker
: {} // if in node js
);
/**
* Prism: Lightweight, robust, elegant syntax highlighting
*
* @license MIT <https://opensource.org/licenses/MIT>
* @author Lea Verou <https://lea.verou.me>
* @namespace
* @public
*/
var Prism = (function (_self) {
// Private helper vars
var lang = /(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i;
var uniqueId = 0;
// The grammar object for plaintext
var plainTextGrammar = {};
var _ = {
/**
* By default, Prism will attempt to highlight all code elements (by calling {@link Prism.highlightAll}) on the
* current page after the page finished loading. This might be a problem if e.g. you wanted to asynchronously load
* additional languages or plugins yourself.
*
* By setting this value to `true`, Prism will not automatically highlight all code elements on the page.
*
* You obviously have to change this value before the automatic highlighting started. To do this, you can add an
* empty Prism object into the global scope before loading the Prism script like this:
*
* ```js
* window.Prism = window.Prism || {};
* Prism.manual = true;
* // add a new <script> to load Prism's script
* ```
*
* @default false
* @type {boolean}
* @memberof Prism
* @public
*/
manual: _self.Prism && _self.Prism.manual,
/**
* By default, if Prism is in a web worker, it assumes that it is in a worker it created itself, so it uses
* `addEventListener` to communicate with its parent instance. However, if you're using Prism manually in your
* own worker, you don't want it to do this.
*
* By setting this value to `true`, Prism will not add its own listeners to the worker.
*
* You obviously have to change this value before Prism executes. To do this, you can add an
* empty Prism object into the global scope before loading the Prism script like this:
*
* ```js
* window.Prism = window.Prism || {};
* Prism.disableWorkerMessageHandler = true;
* // Load Prism's script
* ```
*
* @default false
* @type {boolean}
* @memberof Prism
* @public
*/
disableWorkerMessageHandler: _self.Prism && _self.Prism.disableWorkerMessageHandler,
/**
* A namespace for utility methods.
*
* All function in this namespace that are not explicitly marked as _public_ are for __internal use only__ and may
* change or disappear at any time.
*
* @namespace
* @memberof Prism
*/
util: {
encode: function encode(tokens) {
if (tokens instanceof Token) {
return new Token(tokens.type, encode(tokens.content), tokens.alias);
} else if (Array.isArray(tokens)) {
return tokens.map(encode);
} else {
return tokens.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\u00a0/g, ' ');
}
},
/**
* Returns the name of the type of the given value.
*
* @param {any} o
* @returns {string}
* @example
* type(null) === 'Null'
* type(undefined) === 'Undefined'
* type(123) === 'Number'
* type('foo') === 'String'
* type(true) === 'Boolean'
* type([1, 2]) === 'Array'
* type({}) === 'Object'
* type(String) === 'Function'
* type(/abc+/) === 'RegExp'
*/
type: function (o) {
return Object.prototype.toString.call(o).slice(8, -1);
},
/**
* Returns a unique number for the given object. Later calls will still return the same number.
*
* @param {Object} obj
* @returns {number}
*/
objId: function (obj) {
if (!obj['__id']) {
Object.defineProperty(obj, '__id', { value: ++uniqueId });
}
return obj['__id'];
},
/**
* Creates a deep clone of the given object.
*
* The main intended use of this function is to clone language definitions.
*
* @param {T} o
* @param {Record<number, any>} [visited]
* @returns {T}
* @template T
*/
clone: function deepClone(o, visited) {
visited = visited || {};
var clone; var id;
switch (_.util.type(o)) {
case 'Object':
id = _.util.objId(o);
if (visited[id]) {
return visited[id];
}
clone = /** @type {Record<string, any>} */ ({});
visited[id] = clone;
for (var key in o) {
if (o.hasOwnProperty(key)) {
clone[key] = deepClone(o[key], visited);
}
}
return /** @type {any} */ (clone);
case 'Array':
id = _.util.objId(o);
if (visited[id]) {
return visited[id];
}
clone = [];
visited[id] = clone;
(/** @type {Array} */(/** @type {any} */(o))).forEach(function (v, i) {
clone[i] = deepClone(v, visited);
});
return /** @type {any} */ (clone);
default:
return o;
}
},
/**
* Returns the Prism language of the given element set by a `language-xxxx` or `lang-xxxx` class.
*
* If no language is set for the element or the element is `null` or `undefined`, `none` will be returned.
*
* @param {Element} element
* @returns {string}
*/
getLanguage: function (element) {
while (element) {
var m = lang.exec(element.className);
if (m) {
return m[1].toLowerCase();
}
element = element.parentElement;
}
return 'none';
},
/**
* Sets the Prism `language-xxxx` class of the given element.
*
* @param {Element} element
* @param {string} language
* @returns {void}
*/
setLanguage: function (element, language) {
// remove all `language-xxxx` classes
// (this might leave behind a leading space)
element.className = element.className.replace(RegExp(lang, 'gi'), '');
// add the new `language-xxxx` class
// (using `classList` will automatically clean up spaces for us)
element.classList.add('language-' + language);
},
/**
* Returns the script element that is currently executing.
*
* This does __not__ work for line script element.
*
* @returns {HTMLScriptElement | null}
*/
currentScript: function () {
if (typeof document === 'undefined') {
return null;
}
if ('currentScript' in document && 1 < 2 /* hack to trip TS' flow analysis */) {
return /** @type {any} */ (document.currentScript);
}
// IE11 workaround
// we'll get the src of the current script by parsing IE11's error stack trace
// this will not work for inline scripts
try {
throw new Error();
} catch (err) {
// Get file src url from stack. Specifically works with the format of stack traces in IE.
// A stack will look like this:
//
// Error
// at _.util.currentScript (http://localhost/components/prism-core.js:119:5)
// at Global code (http://localhost/components/prism-core.js:606:1)
var src = (/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(err.stack) || [])[1];
if (src) {
var scripts = document.getElementsByTagName('script');
for (var i in scripts) {
if (scripts[i].src == src) {
return scripts[i];
}
}
}
return null;
}
},
/**
* Returns whether a given class is active for `element`.
*
* The class can be activated if `element` or one of its ancestors has the given class and it can be deactivated
* if `element` or one of its ancestors has the negated version of the given class. The _negated version_ of the
* given class is just the given class with a `no-` prefix.
*
* Whether the class is active is determined by the closest ancestor of `element` (where `element` itself is
* closest ancestor) that has the given class or the negated version of it. If neither `element` nor any of its
* ancestors have the given class or the negated version of it, then the default activation will be returned.
*
* In the paradoxical situation where the closest ancestor contains __both__ the given class and the negated
* version of it, the class is considered active.
*
* @param {Element} element
* @param {string} className
* @param {boolean} [defaultActivation=false]
* @returns {boolean}
*/
isActive: function (element, className, defaultActivation) {
var no = 'no-' + className;
while (element) {
var classList = element.classList;
if (classList.contains(className)) {
return true;
}
if (classList.contains(no)) {
return false;
}
element = element.parentElement;
}
return !!defaultActivation;
}
},
/**
* This namespace contains all currently loaded languages and the some helper functions to create and modify languages.
*
* @namespace
* @memberof Prism
* @public
*/
languages: {
/**
* The grammar for plain, unformatted text.
*/
plain: plainTextGrammar,
plaintext: plainTextGrammar,
text: plainTextGrammar,
txt: plainTextGrammar,
/**
* Creates a deep copy of the language with the given id and appends the given tokens.
*
* If a token in `redef` also appears in the copied language, then the existing token in the copied language
* will be overwritten at its original position.
*
* ## Best practices
*
* Since the position of overwriting tokens (token in `redef` that overwrite tokens in the copied language)
* doesn't matter, they can technically be in any order. However, this can be confusing to others that trying to
* understand the language definition because, normally, the order of tokens matters in Prism grammars.
*
* Therefore, it is encouraged to order overwriting tokens according to the positions of the overwritten tokens.
* Furthermore, all non-overwriting tokens should be placed after the overwriting ones.
*
* @param {string} id The id of the language to extend. This has to be a key in `Prism.languages`.
* @param {Grammar} redef The new tokens to append.
* @returns {Grammar} The new language created.
* @public
* @example
* Prism.languages['css-with-colors'] = Prism.languages.extend('css', {
* // Prism.languages.css already has a 'comment' token, so this token will overwrite CSS' 'comment' token
* // at its original position
* 'comment': { ... },
* // CSS doesn't have a 'color' token, so this token will be appended
* 'color': /\b(?:red|green|blue)\b/
* });
*/
extend: function (id, redef) {
var lang = _.util.clone(_.languages[id]);
for (var key in redef) {
lang[key] = redef[key];
}
return lang;
},
/**
* Inserts tokens _before_ another token in a language definition or any other grammar.
*
* ## Usage
*
* This helper method makes it easy to modify existing languages. For example, the CSS language definition
* not only defines CSS highlighting for CSS documents, but also needs to define highlighting for CSS embedded
* in HTML through `<style>` elements. To do this, it needs to modify `Prism.languages.markup` and add the
* appropriate tokens. However, `Prism.languages.markup` is a regular JavaScript object literal, so if you do
* this:
*
* ```js
* Prism.languages.markup.style = {
* // token
* };
* ```
*
* then the `style` token will be added (and processed) at the end. `insertBefore` allows you to insert tokens
* before existing tokens. For the CSS example above, you would use it like this:
*
* ```js
* Prism.languages.insertBefore('markup', 'cdata', {
* 'style': {
* // token
* }
* });
* ```
*
* ## Special cases
*
* If the grammars of `inside` and `insert` have tokens with the same name, the tokens in `inside`'s grammar
* will be ignored.
*
* This behavior can be used to insert tokens after `before`:
*
* ```js
* Prism.languages.insertBefore('markup', 'comment', {
* 'comment': Prism.languages.markup.comment,
* // tokens after 'comment'
* });
* ```
*
* ## Limitations
*
* The main problem `insertBefore` has to solve is iteration order. Since ES2015, the iteration order for object
* properties is guaranteed to be the insertion order (except for integer keys) but some browsers behave
* differently when keys are deleted and re-inserted. So `insertBefore` can't be implemented by temporarily
* deleting properties which is necessary to insert at arbitrary positions.
*
* To solve this problem, `insertBefore` doesn't actually insert the given tokens into the target object.
* Instead, it will create a new object and replace all references to the target object with the new one. This
* can be done without temporarily deleting properties, so the iteration order is well-defined.
*
* However, only references that can be reached from `Prism.languages` or `insert` will be replaced. I.e. if
* you hold the target object in a variable, then the value of the variable will not change.
*
* ```js
* var oldMarkup = Prism.languages.markup;
* var newMarkup = Prism.languages.insertBefore('markup', 'comment', { ... });
*
* assert(oldMarkup !== Prism.languages.markup);
* assert(newMarkup === Prism.languages.markup);
* ```
*
* @param {string} inside The property of `root` (e.g. a language id in `Prism.languages`) that contains the
* object to be modified.
* @param {string} before The key to insert before.
* @param {Grammar} insert An object containing the key-value pairs to be inserted.
* @param {Object<string, any>} [root] The object containing `inside`, i.e. the object that contains the
* object to be modified.
*
* Defaults to `Prism.languages`.
* @returns {Grammar} The new grammar object.
* @public
*/
insertBefore: function (inside, before, insert, root) {
root = root || /** @type {any} */ (_.languages);
var grammar = root[inside];
/** @type {Grammar} */
var ret = {};
for (var token in grammar) {
if (grammar.hasOwnProperty(token)) {
if (token == before) {
for (var newToken in insert) {
if (insert.hasOwnProperty(newToken)) {
ret[newToken] = insert[newToken];
}
}
}
// Do not insert token which also occur in insert. See #1525
if (!insert.hasOwnProperty(token)) {
ret[token] = grammar[token];
}
}
}
var old = root[inside];
root[inside] = ret;
// Update references in other language definitions
_.languages.DFS(_.languages, function (key, value) {
if (value === old && key != inside) {
this[key] = ret;
}
});
return ret;
},
// Traverse a language definition with Depth First Search
DFS: function DFS(o, callback, type, visited) {
visited = visited || {};
var objId = _.util.objId;
for (var i in o) {
if (o.hasOwnProperty(i)) {
callback.call(o, i, o[i], type || i);
var property = o[i];
var propertyType = _.util.type(property);
if (propertyType === 'Object' && !visited[objId(property)]) {
visited[objId(property)] = true;
DFS(property, callback, null, visited);
} else if (propertyType === 'Array' && !visited[objId(property)]) {
visited[objId(property)] = true;
DFS(property, callback, i, visited);
}
}
}
}
},
plugins: {},
/**
* This is the most high-level function in Prisms API.
* It fetches all the elements that have a `.language-xxxx` class and then calls {@link Prism.highlightElement} on
* each one of them.
*
* This is equivalent to `Prism.highlightAllUnder(document, async, callback)`.
*
* @param {boolean} [async=false] Same as in {@link Prism.highlightAllUnder}.
* @param {HighlightCallback} [callback] Same as in {@link Prism.highlightAllUnder}.
* @memberof Prism
* @public
*/
highlightAll: function (async, callback) {
_.highlightAllUnder(document, async, callback);
},
/**
* Fetches all the descendants of `container` that have a `.language-xxxx` class and then calls
* {@link Prism.highlightElement} on each one of them.
*
* The following hooks will be run:
* 1. `before-highlightall`
* 2. `before-all-elements-highlight`
* 3. All hooks of {@link Prism.highlightElement} for each element.
*
* @param {ParentNode} container The root element, whose descendants that have a `.language-xxxx` class will be highlighted.
* @param {boolean} [async=false] Whether each element is to be highlighted asynchronously using Web Workers.
* @param {HighlightCallback} [callback] An optional callback to be invoked on each element after its highlighting is done.
* @memberof Prism
* @public
*/
highlightAllUnder: function (container, async, callback) {
var env = {
callback: callback,
container: container,
selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'
};
_.hooks.run('before-highlightall', env);
env.elements = Array.prototype.slice.apply(env.container.querySelectorAll(env.selector));
_.hooks.run('before-all-elements-highlight', env);
for (var i = 0, element; (element = env.elements[i++]);) {
_.highlightElement(element, async === true, env.callback);
}
},
/**
* Highlights the code inside a single element.
*
* The following hooks will be run:
* 1. `before-sanity-check`
* 2. `before-highlight`
* 3. All hooks of {@link Prism.highlight}. These hooks will be run by an asynchronous worker if `async` is `true`.
* 4. `before-insert`
* 5. `after-highlight`
* 6. `complete`
*
* Some the above hooks will be skipped if the element doesn't contain any text or there is no grammar loaded for
* the element's language.
*
* @param {Element} element The element containing the code.
* It must have a class of `language-xxxx` to be processed, where `xxxx` is a valid language identifier.
* @param {boolean} [async=false] Whether the element is to be highlighted asynchronously using Web Workers
* to improve performance and avoid blocking the UI when highlighting very large chunks of code. This option is
* [disabled by default](https://prismjs.com/faq.html#why-is-asynchronous-highlighting-disabled-by-default).
*
* Note: All language definitions required to highlight the code must be included in the main `prism.js` file for
* asynchronous highlighting to work. You can build your own bundle on the
* [Download page](https://prismjs.com/download.html).
* @param {HighlightCallback} [callback] An optional callback to be invoked after the highlighting is done.
* Mostly useful when `async` is `true`, since in that case, the highlighting is done asynchronously.
* @memberof Prism
* @public
*/
highlightElement: function (element, async, callback) {
// Find language
var language = _.util.getLanguage(element);
var grammar = _.languages[language];
// Set language on the element, if not present
_.util.setLanguage(element, language);
// Set language on the parent, for styling
var parent = element.parentElement;
if (parent && parent.nodeName.toLowerCase() === 'pre') {
_.util.setLanguage(parent, language);
}
var code = element.textContent;
var env = {
element: element,
language: language,
grammar: grammar,
code: code
};
function insertHighlightedCode(highlightedCode) {
env.highlightedCode = highlightedCode;
_.hooks.run('before-insert', env);
env.element.innerHTML = env.highlightedCode;
_.hooks.run('after-highlight', env);
_.hooks.run('complete', env);
callback && callback.call(env.element);
}
_.hooks.run('before-sanity-check', env);
// plugins may change/add the parent/element
parent = env.element.parentElement;
if (parent && parent.nodeName.toLowerCase() === 'pre' && !parent.hasAttribute('tabindex')) {
parent.setAttribute('tabindex', '0');
}
if (!env.code) {
_.hooks.run('complete', env);
callback && callback.call(env.element);
return;
}
_.hooks.run('before-highlight', env);
if (!env.grammar) {
insertHighlightedCode(_.util.encode(env.code));
return;
}
if (async && _self.Worker) {
var worker = new Worker(_.filename);
worker.onmessage = function (evt) {
insertHighlightedCode(evt.data);
};
worker.postMessage(JSON.stringify({
language: env.language,
code: env.code,
immediateClose: true
}));
} else {
insertHighlightedCode(_.highlight(env.code, env.grammar, env.language));
}
},
/**
* Low-level function, only use if you know what youre doing. It accepts a string of text as input
* and the language definitions to use, and returns a string with the HTML produced.
*
* The following hooks will be run:
* 1. `before-tokenize`
* 2. `after-tokenize`
* 3. `wrap`: On each {@link Token}.
*
* @param {string} text A string with the code to be highlighted.
* @param {Grammar} grammar An object containing the tokens to use.
*
* Usually a language definition like `Prism.languages.markup`.
* @param {string} language The name of the language definition passed to `grammar`.
* @returns {string} The highlighted HTML.
* @memberof Prism
* @public
* @example
* Prism.highlight('var foo = true;', Prism.languages.javascript, 'javascript');
*/
highlight: function (text, grammar, language) {
var env = {
code: text,
grammar: grammar,
language: language
};
_.hooks.run('before-tokenize', env);
if (!env.grammar) {
throw new Error('The language "' + env.language + '" has no grammar.');
}
env.tokens = _.tokenize(env.code, env.grammar);
_.hooks.run('after-tokenize', env);
return Token.stringify(_.util.encode(env.tokens), env.language);
},
/**
* This is the heart of Prism, and the most low-level function you can use. It accepts a string of text as input
* and the language definitions to use, and returns an array with the tokenized code.
*
* When the language definition includes nested tokens, the function is called recursively on each of these tokens.
*
* This method could be useful in other contexts as well, as a very crude parser.
*
* @param {string} text A string with the code to be highlighted.
* @param {Grammar} grammar An object containing the tokens to use.
*
* Usually a language definition like `Prism.languages.markup`.
* @returns {TokenStream} An array of strings and tokens, a token stream.
* @memberof Prism
* @public
* @example
* let code = `var foo = 0;`;
* let tokens = Prism.tokenize(code, Prism.languages.javascript);
* tokens.forEach(token => {
* if (token instanceof Prism.Token && token.type === 'number') {
* console.log(`Found numeric literal: ${token.content}`);
* }
* });
*/
tokenize: function (text, grammar) {
var rest = grammar.rest;
if (rest) {
for (var token in rest) {
grammar[token] = rest[token];
}
delete grammar.rest;
}
var tokenList = new LinkedList();
addAfter(tokenList, tokenList.head, text);
matchGrammar(text, tokenList, grammar, tokenList.head, 0);
return toArray(tokenList);
},
/**
* @namespace
* @memberof Prism
* @public
*/
hooks: {
all: {},
/**
* Adds the given callback to the list of callbacks for the given hook.
*
* The callback will be invoked when the hook it is registered for is run.
* Hooks are usually directly run by a highlight function but you can also run hooks yourself.
*
* One callback function can be registered to multiple hooks and the same hook multiple times.
*
* @param {string} name The name of the hook.
* @param {HookCallback} callback The callback function which is given environment variables.
* @public
*/
add: function (name, callback) {
var hooks = _.hooks.all;
hooks[name] = hooks[name] || [];
hooks[name].push(callback);
},
/**
* Runs a hook invoking all registered callbacks with the given environment variables.
*
* Callbacks will be invoked synchronously and in the order in which they were registered.
*
* @param {string} name The name of the hook.
* @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
* @public
*/
run: function (name, env) {
var callbacks = _.hooks.all[name];
if (!callbacks || !callbacks.length) {
return;
}
for (var i = 0, callback; (callback = callbacks[i++]);) {
callback(env);
}
}
},
Token: Token
};
_self.Prism = _;
// Typescript note:
// The following can be used to import the Token type in JSDoc:
//
// @typedef {InstanceType<import("./prism-core")["Token"]>} Token
/**
* Creates a new token.
*
* @param {string} type See {@link Token#type type}
* @param {string | TokenStream} content See {@link Token#content content}
* @param {string|string[]} [alias] The alias(es) of the token.
* @param {string} [matchedStr=""] A copy of the full string this token was created from.
* @class
* @global
* @public
*/
function Token(type, content, alias, matchedStr) {
/**
* The type of the token.
*
* This is usually the key of a pattern in a {@link Grammar}.
*
* @type {string}
* @see GrammarToken
* @public
*/
this.type = type;
/**
* The strings or tokens contained by this token.
*
* This will be a token stream if the pattern matched also defined an `inside` grammar.
*
* @type {string | TokenStream}
* @public
*/
this.content = content;
/**
* The alias(es) of the token.
*
* @type {string|string[]}
* @see GrammarToken
* @public
*/
this.alias = alias;
// Copy of the full string this token was created from
this.length = (matchedStr || '').length | 0;
}
/**
* A token stream is an array of strings and {@link Token Token} objects.
*
* Token streams have to fulfill a few properties that are assumed by most functions (mostly internal ones) that process
* them.
*
* 1. No adjacent strings.
* 2. No empty strings.
*
* The only exception here is the token stream that only contains the empty string and nothing else.
*
* @typedef {Array<string | Token>} TokenStream
* @global
* @public
*/
/**
* Converts the given token or token stream to an HTML representation.
*
* The following hooks will be run:
* 1. `wrap`: On each {@link Token}.
*
* @param {string | Token | TokenStream} o The token or token stream to be converted.
* @param {string} language The name of current language.
* @returns {string} The HTML representation of the token or token stream.
* @memberof Token
* @static
*/
Token.stringify = function stringify(o, language) {
if (typeof o == 'string') {
return o;
}
if (Array.isArray(o)) {
var s = '';
o.forEach(function (e) {
s += stringify(e, language);
});
return s;
}
var env = {
type: o.type,
content: stringify(o.content, language),
tag: 'span',
classes: ['token', o.type],
attributes: {},
language: language
};
var aliases = o.alias;
if (aliases) {
if (Array.isArray(aliases)) {
Array.prototype.push.apply(env.classes, aliases);
} else {
env.classes.push(aliases);
}
}
_.hooks.run('wrap', env);
var attributes = '';
for (var name in env.attributes) {
attributes += ' ' + name + '="' + (env.attributes[name] || '').replace(/"/g, '&quot;') + '"';
}
return '<' + env.tag + ' class="' + env.classes.join(' ') + '"' + attributes + '>' + env.content + '</' + env.tag + '>';
};
/**
* @param {RegExp} pattern
* @param {number} pos
* @param {string} text
* @param {boolean} lookbehind
* @returns {RegExpExecArray | null}
*/
function matchPattern(pattern, pos, text, lookbehind) {
pattern.lastIndex = pos;
var match = pattern.exec(text);
if (match && lookbehind && match[1]) {
// change the match to remove the text matched by the Prism lookbehind group
var lookbehindLength = match[1].length;
match.index += lookbehindLength;
match[0] = match[0].slice(lookbehindLength);
}
return match;
}
/**
* @param {string} text
* @param {LinkedList<string | Token>} tokenList
* @param {any} grammar
* @param {LinkedListNode<string | Token>} startNode
* @param {number} startPos
* @param {RematchOptions} [rematch]
* @returns {void}
* @private
*
* @typedef RematchOptions
* @property {string} cause
* @property {number} reach
*/
function matchGrammar(text, tokenList, grammar, startNode, startPos, rematch) {
for (var token in grammar) {
if (!grammar.hasOwnProperty(token) || !grammar[token]) {
continue;
}
var patterns = grammar[token];
patterns = Array.isArray(patterns) ? patterns : [patterns];
for (var j = 0; j < patterns.length; ++j) {
if (rematch && rematch.cause == token + ',' + j) {
return;
}
var patternObj = patterns[j];
var inside = patternObj.inside;
var lookbehind = !!patternObj.lookbehind;
var greedy = !!patternObj.greedy;
var alias = patternObj.alias;
if (greedy && !patternObj.pattern.global) {
// Without the global flag, lastIndex won't work
var flags = patternObj.pattern.toString().match(/[imsuy]*$/)[0];
patternObj.pattern = RegExp(patternObj.pattern.source, flags + 'g');
}
/** @type {RegExp} */
var pattern = patternObj.pattern || patternObj;
for ( // iterate the token list and keep track of the current token/string position
var currentNode = startNode.next, pos = startPos;
currentNode !== tokenList.tail;
pos += currentNode.value.length, currentNode = currentNode.next
) {
if (rematch && pos >= rematch.reach) {
break;
}
var str = currentNode.value;
if (tokenList.length > text.length) {
// Something went terribly wrong, ABORT, ABORT!
return;
}
if (str instanceof Token) {
continue;
}
var removeCount = 1; // this is the to parameter of removeBetween
var match;
if (greedy) {
match = matchPattern(pattern, pos, text, lookbehind);
if (!match || match.index >= text.length) {
break;
}
var from = match.index;
var to = match.index + match[0].length;
var p = pos;
// find the node that contains the match
p += currentNode.value.length;
while (from >= p) {
currentNode = currentNode.next;
p += currentNode.value.length;
}
// adjust pos (and p)
p -= currentNode.value.length;
pos = p;
// the current node is a Token, then the match starts inside another Token, which is invalid
if (currentNode.value instanceof Token) {
continue;
}
// find the last node which is affected by this match
for (
var k = currentNode;
k !== tokenList.tail && (p < to || typeof k.value === 'string');
k = k.next
) {
removeCount++;
p += k.value.length;
}
removeCount--;
// replace with the new match
str = text.slice(pos, p);
match.index -= pos;
} else {
match = matchPattern(pattern, 0, str, lookbehind);
if (!match) {
continue;
}
}
// eslint-disable-next-line no-redeclare
var from = match.index;
var matchStr = match[0];
var before = str.slice(0, from);
var after = str.slice(from + matchStr.length);
var reach = pos + str.length;
if (rematch && reach > rematch.reach) {
rematch.reach = reach;
}
var removeFrom = currentNode.prev;
if (before) {
removeFrom = addAfter(tokenList, removeFrom, before);
pos += before.length;
}
removeRange(tokenList, removeFrom, removeCount);
var wrapped = new Token(token, inside ? _.tokenize(matchStr, inside) : matchStr, alias, matchStr);
currentNode = addAfter(tokenList, removeFrom, wrapped);
if (after) {
addAfter(tokenList, currentNode, after);
}
if (removeCount > 1) {
// at least one Token object was removed, so we have to do some rematching
// this can only happen if the current pattern is greedy
/** @type {RematchOptions} */
var nestedRematch = {
cause: token + ',' + j,
reach: reach
};
matchGrammar(text, tokenList, grammar, currentNode.prev, pos, nestedRematch);
// the reach might have been extended because of the rematching
if (rematch && nestedRematch.reach > rematch.reach) {
rematch.reach = nestedRematch.reach;
}
}
}
}
}
}
/**
* @typedef LinkedListNode
* @property {T} value
* @property {LinkedListNode<T> | null} prev The previous node.
* @property {LinkedListNode<T> | null} next The next node.
* @template T
* @private
*/
/**
* @template T
* @private
*/
function LinkedList() {
/** @type {LinkedListNode<T>} */
var head = { value: null, prev: null, next: null };
/** @type {LinkedListNode<T>} */
var tail = { value: null, prev: head, next: null };
head.next = tail;
/** @type {LinkedListNode<T>} */
this.head = head;
/** @type {LinkedListNode<T>} */
this.tail = tail;
this.length = 0;
}
/**
* Adds a new node with the given value to the list.
*
* @param {LinkedList<T>} list
* @param {LinkedListNode<T>} node
* @param {T} value
* @returns {LinkedListNode<T>} The added node.
* @template T
*/
function addAfter(list, node, value) {
// assumes that node != list.tail && values.length >= 0
var next = node.next;
var newNode = { value: value, prev: node, next: next };
node.next = newNode;
next.prev = newNode;
list.length++;
return newNode;
}
/**
* Removes `count` nodes after the given node. The given node will not be removed.
*
* @param {LinkedList<T>} list
* @param {LinkedListNode<T>} node
* @param {number} count
* @template T
*/
function removeRange(list, node, count) {
var next = node.next;
for (var i = 0; i < count && next !== list.tail; i++) {
next = next.next;
}
node.next = next;
next.prev = node;
list.length -= i;
}
/**
* @param {LinkedList<T>} list
* @returns {T[]}
* @template T
*/
function toArray(list) {
var array = [];
var node = list.head.next;
while (node !== list.tail) {
array.push(node.value);
node = node.next;
}
return array;
}
if (!_self.document) {
if (!_self.addEventListener) {
// in Node.js
return _;
}
if (!_.disableWorkerMessageHandler) {
// In worker
_self.addEventListener('message', function (evt) {
var message = JSON.parse(evt.data);
var lang = message.language;
var code = message.code;
var immediateClose = message.immediateClose;
_self.postMessage(_.highlight(code, _.languages[lang], lang));
if (immediateClose) {
_self.close();
}
}, false);
}
return _;
}
// Get current script and highlight
var script = _.util.currentScript();
if (script) {
_.filename = script.src;
if (script.hasAttribute('data-manual')) {
_.manual = true;
}
}
function highlightAutomaticallyCallback() {
if (!_.manual) {
_.highlightAll();
}
}
if (!_.manual) {
// If the document state is "loading", then we'll use DOMContentLoaded.
// If the document state is "interactive" and the prism.js script is deferred, then we'll also use the
// DOMContentLoaded event because there might be some plugins or languages which have also been deferred and they
// might take longer one animation frame to execute which can create a race condition where only some plugins have
// been loaded when Prism.highlightAll() is executed, depending on how fast resources are loaded.
// See https://github.com/PrismJS/prism/issues/2102
var readyState = document.readyState;
if (readyState === 'loading' || readyState === 'interactive' && script && script.defer) {
document.addEventListener('DOMContentLoaded', highlightAutomaticallyCallback);
} else {
if (window.requestAnimationFrame) {
window.requestAnimationFrame(highlightAutomaticallyCallback);
} else {
window.setTimeout(highlightAutomaticallyCallback, 16);
}
}
}
return _;
}(_self));
if ( module.exports) {
module.exports = Prism;
}
// hack for components to work correctly in node.js
if (typeof commonjsGlobal !== 'undefined') {
commonjsGlobal.Prism = Prism;
}
// some additional documentation/types
/**
* The expansion of a simple `RegExp` literal to support additional properties.
*
* @typedef GrammarToken
* @property {RegExp} pattern The regular expression of the token.
* @property {boolean} [lookbehind=false] If `true`, then the first capturing group of `pattern` will (effectively)
* behave as a lookbehind group meaning that the captured text will not be part of the matched text of the new token.
* @property {boolean} [greedy=false] Whether the token is greedy.
* @property {string|string[]} [alias] An optional alias or list of aliases.
* @property {Grammar} [inside] The nested grammar of this token.
*
* The `inside` grammar will be used to tokenize the text value of each token of this kind.
*
* This can be used to make nested and even recursive language definitions.
*
* Note: This can cause infinite recursion. Be careful when you embed different languages or even the same language into
* each another.
* @global
* @public
*/
/**
* @typedef Grammar
* @type {Object<string, RegExp | GrammarToken | Array<RegExp | GrammarToken>>}
* @property {Grammar} [rest] An optional grammar object that will be appended to this grammar.
* @global
* @public
*/
/**
* A function which will invoked after an element was successfully highlighted.
*
* @callback HighlightCallback
* @param {Element} element The element successfully highlighted.
* @returns {void}
* @global
* @public
*/
/**
* @callback HookCallback
* @param {Object<string, any>} env The environment variables of the hook.
* @returns {void}
* @global
* @public
*/
});
Prism.languages.clike = {
'comment': [
{
pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,
lookbehind: true,
greedy: true
},
{
pattern: /(^|[^\\:])\/\/.*/,
lookbehind: true,
greedy: true
}
],
'string': {
pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
greedy: true
},
'class-name': {
pattern: /(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,
lookbehind: true,
inside: {
'punctuation': /[.\\]/
}
},
'keyword': /\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,
'boolean': /\b(?:false|true)\b/,
'function': /\b\w+(?=\()/,
'number': /\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,
'operator': /[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,
'punctuation': /[{}[\];(),.:]/
};
Prism.languages.c = Prism.languages.extend('clike', {
'comment': {
pattern: /\/\/(?:[^\r\n\\]|\\(?:\r\n?|\n|(?![\r\n])))*|\/\*[\s\S]*?(?:\*\/|$)/,
greedy: true
},
'string': {
// https://en.cppreference.com/w/c/language/string_literal
pattern: /"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"/,
greedy: true
},
'class-name': {
pattern: /(\b(?:enum|struct)\s+(?:__attribute__\s*\(\([\s\S]*?\)\)\s*)?)\w+|\b[a-z]\w*_t\b/,
lookbehind: true
},
'keyword': /\b(?:_Alignas|_Alignof|_Atomic|_Bool|_Complex|_Generic|_Imaginary|_Noreturn|_Static_assert|_Thread_local|__attribute__|asm|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|inline|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|typeof|union|unsigned|void|volatile|while)\b/,
'function': /\b[a-z_]\w*(?=\s*\()/i,
'number': /(?:\b0x(?:[\da-f]+(?:\.[\da-f]*)?|\.[\da-f]+)(?:p[+-]?\d+)?|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?)[ful]{0,4}/i,
'operator': />>=?|<<=?|->|([-+&|:])\1|[?:~]|[-+*/%&|^!=<>]=?/
});
Prism.languages.insertBefore('c', 'string', {
'char': {
// https://en.cppreference.com/w/c/language/character_constant
pattern: /'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n]){0,32}'/,
greedy: true
}
});
Prism.languages.insertBefore('c', 'string', {
'macro': {
// allow for multiline macro definitions
// spaces after the # character compile fine with gcc
pattern: /(^[\t ]*)#\s*[a-z](?:[^\r\n\\/]|\/(?!\*)|\/\*(?:[^*]|\*(?!\/))*\*\/|\\(?:\r\n|[\s\S]))*/im,
lookbehind: true,
greedy: true,
alias: 'property',
inside: {
'string': [
{
// highlight the path of the include statement as a string
pattern: /^(#\s*include\s*)<[^>]+>/,
lookbehind: true
},
Prism.languages.c['string']
],
'char': Prism.languages.c['char'],
'comment': Prism.languages.c['comment'],
'macro-name': [
{
pattern: /(^#\s*define\s+)\w+\b(?!\()/i,
lookbehind: true
},
{
pattern: /(^#\s*define\s+)\w+\b(?=\()/i,
lookbehind: true,
alias: 'function'
}
],
// highlight macro directives as keywords
'directive': {
pattern: /^(#\s*)[a-z]+/,
lookbehind: true,
alias: 'keyword'
},
'directive-hash': /^#/,
'punctuation': /##|\\(?=[\r\n])/,
'expression': {
pattern: /\S[\s\S]*/,
inside: Prism.languages.c
}
}
}
});
Prism.languages.insertBefore('c', 'function', {
// highlight predefined macros as constants
'constant': /\b(?:EOF|NULL|SEEK_CUR|SEEK_END|SEEK_SET|__DATE__|__FILE__|__LINE__|__TIMESTAMP__|__TIME__|__func__|stderr|stdin|stdout)\b/
});
delete Prism.languages.c['boolean'];
(function (Prism) {
/**
* Replaces all placeholders "<<n>>" of given pattern with the n-th replacement (zero based).
*
* Note: This is a simple text based replacement. Be careful when using backreferences!
*
* @param {string} pattern the given pattern.
* @param {string[]} replacements a list of replacement which can be inserted into the given pattern.
* @returns {string} the pattern with all placeholders replaced with their corresponding replacements.
* @example replace(/a<<0>>a/.source, [/b+/.source]) === /a(?:b+)a/.source
*/
function replace(pattern, replacements) {
return pattern.replace(/<<(\d+)>>/g, function (m, index) {
return '(?:' + replacements[+index] + ')';
});
}
/**
* @param {string} pattern
* @param {string[]} replacements
* @param {string} [flags]
* @returns {RegExp}
*/
function re(pattern, replacements, flags) {
return RegExp(replace(pattern, replacements), flags || '');
}
/**
* Creates a nested pattern where all occurrences of the string `<<self>>` are replaced with the pattern itself.
*
* @param {string} pattern
* @param {number} depthLog2
* @returns {string}
*/
function nested(pattern, depthLog2) {
for (var i = 0; i < depthLog2; i++) {
pattern = pattern.replace(/<<self>>/g, function () { return '(?:' + pattern + ')'; });
}
return pattern.replace(/<<self>>/g, '[^\\s\\S]');
}
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/
var keywordKinds = {
// keywords which represent a return or variable type
type: 'bool byte char decimal double dynamic float int long object sbyte short string uint ulong ushort var void',
// keywords which are used to declare a type
typeDeclaration: 'class enum interface record struct',
// contextual keywords
// ("var" and "dynamic" are missing because they are used like types)
contextual: 'add alias and ascending async await by descending from(?=\\s*(?:\\w|$)) get global group into init(?=\\s*;) join let nameof not notnull on or orderby partial remove select set unmanaged value when where with(?=\\s*{)',
// all other keywords
other: 'abstract as base break case catch checked const continue default delegate do else event explicit extern finally fixed for foreach goto if implicit in internal is lock namespace new null operator out override params private protected public readonly ref return sealed sizeof stackalloc static switch this throw try typeof unchecked unsafe using virtual volatile while yield'
};
// keywords
function keywordsToPattern(words) {
return '\\b(?:' + words.trim().replace(/ /g, '|') + ')\\b';
}
var typeDeclarationKeywords = keywordsToPattern(keywordKinds.typeDeclaration);
var keywords = RegExp(keywordsToPattern(keywordKinds.type + ' ' + keywordKinds.typeDeclaration + ' ' + keywordKinds.contextual + ' ' + keywordKinds.other));
var nonTypeKeywords = keywordsToPattern(keywordKinds.typeDeclaration + ' ' + keywordKinds.contextual + ' ' + keywordKinds.other);
var nonContextualKeywords = keywordsToPattern(keywordKinds.type + ' ' + keywordKinds.typeDeclaration + ' ' + keywordKinds.other);
// types
var generic = nested(/<(?:[^<>;=+\-*/%&|^]|<<self>>)*>/.source, 2); // the idea behind the other forbidden characters is to prevent false positives. Same for tupleElement.
var nestedRound = nested(/\((?:[^()]|<<self>>)*\)/.source, 2);
var name = /@?\b[A-Za-z_]\w*\b/.source;
var genericName = replace(/<<0>>(?:\s*<<1>>)?/.source, [name, generic]);
var identifier = replace(/(?!<<0>>)<<1>>(?:\s*\.\s*<<1>>)*/.source, [nonTypeKeywords, genericName]);
var array = /\[\s*(?:,\s*)*\]/.source;
var typeExpressionWithoutTuple = replace(/<<0>>(?:\s*(?:\?\s*)?<<1>>)*(?:\s*\?)?/.source, [identifier, array]);
var tupleElement = replace(/[^,()<>[\];=+\-*/%&|^]|<<0>>|<<1>>|<<2>>/.source, [generic, nestedRound, array]);
var tuple = replace(/\(<<0>>+(?:,<<0>>+)+\)/.source, [tupleElement]);
var typeExpression = replace(/(?:<<0>>|<<1>>)(?:\s*(?:\?\s*)?<<2>>)*(?:\s*\?)?/.source, [tuple, identifier, array]);
var typeInside = {
'keyword': keywords,
'punctuation': /[<>()?,.:[\]]/
};
// strings & characters
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure#character-literals
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure#string-literals
var character = /'(?:[^\r\n'\\]|\\.|\\[Uux][\da-fA-F]{1,8})'/.source; // simplified pattern
var regularString = /"(?:\\.|[^\\"\r\n])*"/.source;
var verbatimString = /@"(?:""|\\[\s\S]|[^\\"])*"(?!")/.source;
Prism.languages.csharp = Prism.languages.extend('clike', {
'string': [
{
pattern: re(/(^|[^$\\])<<0>>/.source, [verbatimString]),
lookbehind: true,
greedy: true
},
{
pattern: re(/(^|[^@$\\])<<0>>/.source, [regularString]),
lookbehind: true,
greedy: true
}
],
'class-name': [
{
// Using static
// using static System.Math;
pattern: re(/(\busing\s+static\s+)<<0>>(?=\s*;)/.source, [identifier]),
lookbehind: true,
inside: typeInside
},
{
// Using alias (type)
// using Project = PC.MyCompany.Project;
pattern: re(/(\busing\s+<<0>>\s*=\s*)<<1>>(?=\s*;)/.source, [name, typeExpression]),
lookbehind: true,
inside: typeInside
},
{
// Using alias (alias)
// using Project = PC.MyCompany.Project;
pattern: re(/(\busing\s+)<<0>>(?=\s*=)/.source, [name]),
lookbehind: true
},
{
// Type declarations
// class Foo<A, B>
// interface Foo<out A, B>
pattern: re(/(\b<<0>>\s+)<<1>>/.source, [typeDeclarationKeywords, genericName]),
lookbehind: true,
inside: typeInside
},
{
// Single catch exception declaration
// catch(Foo)
// (things like catch(Foo e) is covered by variable declaration)
pattern: re(/(\bcatch\s*\(\s*)<<0>>/.source, [identifier]),
lookbehind: true,
inside: typeInside
},
{
// Name of the type parameter of generic constraints
// where Foo : class
pattern: re(/(\bwhere\s+)<<0>>/.source, [name]),
lookbehind: true
},
{
// Casts and checks via as and is.
// as Foo<A>, is Bar<B>
// (things like if(a is Foo b) is covered by variable declaration)
pattern: re(/(\b(?:is(?:\s+not)?|as)\s+)<<0>>/.source, [typeExpressionWithoutTuple]),
lookbehind: true,
inside: typeInside
},
{
// Variable, field and parameter declaration
// (Foo bar, Bar baz, Foo[,,] bay, Foo<Bar, FooBar<Bar>> bax)
pattern: re(/\b<<0>>(?=\s+(?!<<1>>|with\s*\{)<<2>>(?:\s*[=,;:{)\]]|\s+(?:in|when)\b))/.source, [typeExpression, nonContextualKeywords, name]),
inside: typeInside
}
],
'keyword': keywords,
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure#literals
'number': /(?:\b0(?:x[\da-f_]*[\da-f]|b[01_]*[01])|(?:\B\.\d+(?:_+\d+)*|\b\d+(?:_+\d+)*(?:\.\d+(?:_+\d+)*)?)(?:e[-+]?\d+(?:_+\d+)*)?)(?:[dflmu]|lu|ul)?\b/i,
'operator': />>=?|<<=?|[-=]>|([-+&|])\1|~|\?\?=?|[-+*/%&|^!=<>]=?/,
'punctuation': /\?\.?|::|[{}[\];(),.:]/
});
Prism.languages.insertBefore('csharp', 'number', {
'range': {
pattern: /\.\./,
alias: 'operator'
}
});
Prism.languages.insertBefore('csharp', 'punctuation', {
'named-parameter': {
pattern: re(/([(,]\s*)<<0>>(?=\s*:)/.source, [name]),
lookbehind: true,
alias: 'punctuation'
}
});
Prism.languages.insertBefore('csharp', 'class-name', {
'namespace': {
// namespace Foo.Bar {}
// using Foo.Bar;
pattern: re(/(\b(?:namespace|using)\s+)<<0>>(?:\s*\.\s*<<0>>)*(?=\s*[;{])/.source, [name]),
lookbehind: true,
inside: {
'punctuation': /\./
}
},
'type-expression': {
// default(Foo), typeof(Foo<Bar>), sizeof(int)
pattern: re(/(\b(?:default|sizeof|typeof)\s*\(\s*(?!\s))(?:[^()\s]|\s(?!\s)|<<0>>)*(?=\s*\))/.source, [nestedRound]),
lookbehind: true,
alias: 'class-name',
inside: typeInside
},
'return-type': {
// Foo<Bar> ForBar(); Foo IFoo.Bar() => 0
// int this[int index] => 0; T IReadOnlyList<T>.this[int index] => this[index];
// int Foo => 0; int Foo { get; set } = 0;
pattern: re(/<<0>>(?=\s+(?:<<1>>\s*(?:=>|[({]|\.\s*this\s*\[)|this\s*\[))/.source, [typeExpression, identifier]),
inside: typeInside,
alias: 'class-name'
},
'constructor-invocation': {
// new List<Foo<Bar[]>> { }
pattern: re(/(\bnew\s+)<<0>>(?=\s*[[({])/.source, [typeExpression]),
lookbehind: true,
inside: typeInside,
alias: 'class-name'
},
/*'explicit-implementation': {
// int IFoo<Foo>.Bar => 0; void IFoo<Foo<Foo>>.Foo<T>();
pattern: replace(/\b<<0>>(?=\.<<1>>)/, className, methodOrPropertyDeclaration),
inside: classNameInside,
alias: 'class-name'
},*/
'generic-method': {
// foo<Bar>()
pattern: re(/<<0>>\s*<<1>>(?=\s*\()/.source, [name, generic]),
inside: {
'function': re(/^<<0>>/.source, [name]),
'generic': {
pattern: RegExp(generic),
alias: 'class-name',
inside: typeInside
}
}
},
'type-list': {
// The list of types inherited or of generic constraints
// class Foo<F> : Bar, IList<FooBar>
// where F : Bar, IList<int>
pattern: re(
/\b((?:<<0>>\s+<<1>>|record\s+<<1>>\s*<<5>>|where\s+<<2>>)\s*:\s*)(?:<<3>>|<<4>>|<<1>>\s*<<5>>|<<6>>)(?:\s*,\s*(?:<<3>>|<<4>>|<<6>>))*(?=\s*(?:where|[{;]|=>|$))/.source,
[typeDeclarationKeywords, genericName, name, typeExpression, keywords.source, nestedRound, /\bnew\s*\(\s*\)/.source]
),
lookbehind: true,
inside: {
'record-arguments': {
pattern: re(/(^(?!new\s*\()<<0>>\s*)<<1>>/.source, [genericName, nestedRound]),
lookbehind: true,
greedy: true,
inside: Prism.languages.csharp
},
'keyword': keywords,
'class-name': {
pattern: RegExp(typeExpression),
greedy: true,
inside: typeInside
},
'punctuation': /[,()]/
}
},
'preprocessor': {
pattern: /(^[\t ]*)#.*/m,
lookbehind: true,
alias: 'property',
inside: {
// highlight preprocessor directives as keywords
'directive': {
pattern: /(#)\b(?:define|elif|else|endif|endregion|error|if|line|nullable|pragma|region|undef|warning)\b/,
lookbehind: true,
alias: 'keyword'
}
}
}
});
// attributes
var regularStringOrCharacter = regularString + '|' + character;
var regularStringCharacterOrComment = replace(/\/(?![*/])|\/\/[^\r\n]*[\r\n]|\/\*(?:[^*]|\*(?!\/))*\*\/|<<0>>/.source, [regularStringOrCharacter]);
var roundExpression = nested(replace(/[^"'/()]|<<0>>|\(<<self>>*\)/.source, [regularStringCharacterOrComment]), 2);
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/#attribute-targets
var attrTarget = /\b(?:assembly|event|field|method|module|param|property|return|type)\b/.source;
var attr = replace(/<<0>>(?:\s*\(<<1>>*\))?/.source, [identifier, roundExpression]);
Prism.languages.insertBefore('csharp', 'class-name', {
'attribute': {
// Attributes
// [Foo], [Foo(1), Bar(2, Prop = "foo")], [return: Foo(1), Bar(2)], [assembly: Foo(Bar)]
pattern: re(/((?:^|[^\s\w>)?])\s*\[\s*)(?:<<0>>\s*:\s*)?<<1>>(?:\s*,\s*<<1>>)*(?=\s*\])/.source, [attrTarget, attr]),
lookbehind: true,
greedy: true,
inside: {
'target': {
pattern: re(/^<<0>>(?=\s*:)/.source, [attrTarget]),
alias: 'keyword'
},
'attribute-arguments': {
pattern: re(/\(<<0>>*\)/.source, [roundExpression]),
inside: Prism.languages.csharp
},
'class-name': {
pattern: RegExp(identifier),
inside: {
'punctuation': /\./
}
},
'punctuation': /[:,]/
}
}
});
// string interpolation
var formatString = /:[^}\r\n]+/.source;
// multi line
var mInterpolationRound = nested(replace(/[^"'/()]|<<0>>|\(<<self>>*\)/.source, [regularStringCharacterOrComment]), 2);
var mInterpolation = replace(/\{(?!\{)(?:(?![}:])<<0>>)*<<1>>?\}/.source, [mInterpolationRound, formatString]);
// single line
var sInterpolationRound = nested(replace(/[^"'/()]|\/(?!\*)|\/\*(?:[^*]|\*(?!\/))*\*\/|<<0>>|\(<<self>>*\)/.source, [regularStringOrCharacter]), 2);
var sInterpolation = replace(/\{(?!\{)(?:(?![}:])<<0>>)*<<1>>?\}/.source, [sInterpolationRound, formatString]);
function createInterpolationInside(interpolation, interpolationRound) {
return {
'interpolation': {
pattern: re(/((?:^|[^{])(?:\{\{)*)<<0>>/.source, [interpolation]),
lookbehind: true,
inside: {
'format-string': {
pattern: re(/(^\{(?:(?![}:])<<0>>)*)<<1>>(?=\}$)/.source, [interpolationRound, formatString]),
lookbehind: true,
inside: {
'punctuation': /^:/
}
},
'punctuation': /^\{|\}$/,
'expression': {
pattern: /[\s\S]+/,
alias: 'language-csharp',
inside: Prism.languages.csharp
}
}
},
'string': /[\s\S]+/
};
}
Prism.languages.insertBefore('csharp', 'string', {
'interpolation-string': [
{
pattern: re(/(^|[^\\])(?:\$@|@\$)"(?:""|\\[\s\S]|\{\{|<<0>>|[^\\{"])*"/.source, [mInterpolation]),
lookbehind: true,
greedy: true,
inside: createInterpolationInside(mInterpolation, mInterpolationRound),
},
{
pattern: re(/(^|[^@\\])\$"(?:\\.|\{\{|<<0>>|[^\\"{])*"/.source, [sInterpolation]),
lookbehind: true,
greedy: true,
inside: createInterpolationInside(sInterpolation, sInterpolationRound),
}
],
'char': {
pattern: RegExp(character),
greedy: true
}
});
Prism.languages.dotnet = Prism.languages.cs = Prism.languages.csharp;
}(Prism));
(function (Prism) {
var keyword = /\b(?:alignas|alignof|asm|auto|bool|break|case|catch|char|char16_t|char32_t|char8_t|class|co_await|co_return|co_yield|compl|concept|const|const_cast|consteval|constexpr|constinit|continue|decltype|default|delete|do|double|dynamic_cast|else|enum|explicit|export|extern|final|float|for|friend|goto|if|import|inline|int|int16_t|int32_t|int64_t|int8_t|long|module|mutable|namespace|new|noexcept|nullptr|operator|override|private|protected|public|register|reinterpret_cast|requires|return|short|signed|sizeof|static|static_assert|static_cast|struct|switch|template|this|thread_local|throw|try|typedef|typeid|typename|uint16_t|uint32_t|uint64_t|uint8_t|union|unsigned|using|virtual|void|volatile|wchar_t|while)\b/;
var modName = /\b(?!<keyword>)\w+(?:\s*\.\s*\w+)*\b/.source.replace(/<keyword>/g, function () { return keyword.source; });
Prism.languages.cpp = Prism.languages.extend('c', {
'class-name': [
{
pattern: RegExp(/(\b(?:class|concept|enum|struct|typename)\s+)(?!<keyword>)\w+/.source
.replace(/<keyword>/g, function () { return keyword.source; })),
lookbehind: true
},
// This is intended to capture the class name of method implementations like:
// void foo::bar() const {}
// However! The `foo` in the above example could also be a namespace, so we only capture the class name if
// it starts with an uppercase letter. This approximation should give decent results.
/\b[A-Z]\w*(?=\s*::\s*\w+\s*\()/,
// This will capture the class name before destructors like:
// Foo::~Foo() {}
/\b[A-Z_]\w*(?=\s*::\s*~\w+\s*\()/i,
// This also intends to capture the class name of method implementations but here the class has template
// parameters, so it can't be a namespace (until C++ adds generic namespaces).
/\b\w+(?=\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>\s*::\s*\w+\s*\()/
],
'keyword': keyword,
'number': {
pattern: /(?:\b0b[01']+|\b0x(?:[\da-f']+(?:\.[\da-f']*)?|\.[\da-f']+)(?:p[+-]?[\d']+)?|(?:\b[\d']+(?:\.[\d']*)?|\B\.[\d']+)(?:e[+-]?[\d']+)?)[ful]{0,4}/i,
greedy: true
},
'operator': />>=?|<<=?|->|--|\+\+|&&|\|\||[?:~]|<=>|[-+*/%&|^!=<>]=?|\b(?:and|and_eq|bitand|bitor|not|not_eq|or|or_eq|xor|xor_eq)\b/,
'boolean': /\b(?:false|true)\b/
});
Prism.languages.insertBefore('cpp', 'string', {
'module': {
// https://en.cppreference.com/w/cpp/language/modules
pattern: RegExp(
/(\b(?:import|module)\s+)/.source +
'(?:' +
// header-name
/"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|<[^<>\r\n]*>/.source +
'|' +
// module name or partition or both
/<mod-name>(?:\s*:\s*<mod-name>)?|:\s*<mod-name>/.source.replace(/<mod-name>/g, function () { return modName; }) +
')'
),
lookbehind: true,
greedy: true,
inside: {
'string': /^[<"][\s\S]+/,
'operator': /:/,
'punctuation': /\./
}
},
'raw-string': {
pattern: /R"([^()\\ ]{0,16})\([\s\S]*?\)\1"/,
alias: 'string',
greedy: true
}
});
Prism.languages.insertBefore('cpp', 'keyword', {
'generic-function': {
pattern: /\b(?!operator\b)[a-z_]\w*\s*<(?:[^<>]|<[^<>]*>)*>(?=\s*\()/i,
inside: {
'function': /^\w+/,
'generic': {
pattern: /<[\s\S]+/,
alias: 'class-name',
inside: Prism.languages.cpp
}
}
}
});
Prism.languages.insertBefore('cpp', 'operator', {
'double-colon': {
pattern: /::/,
alias: 'punctuation'
}
});
Prism.languages.insertBefore('cpp', 'class-name', {
// the base clause is an optional list of parent classes
// https://en.cppreference.com/w/cpp/language/class
'base-clause': {
pattern: /(\b(?:class|struct)\s+\w+\s*:\s*)[^;{}"'\s]+(?:\s+[^;{}"'\s]+)*(?=\s*[;{])/,
lookbehind: true,
greedy: true,
inside: Prism.languages.extend('cpp', {})
}
});
Prism.languages.insertBefore('inside', 'double-colon', {
// All untokenized words that are not namespaces should be class names
'class-name': /\b[a-z_]\w*\b(?!\s*::)/i
}, Prism.languages.cpp['base-clause']);
}(Prism));
Prism.languages.markup = {
'comment': {
pattern: /<!--(?:(?!<!--)[\s\S])*?-->/,
greedy: true
},
'prolog': {
pattern: /<\?[\s\S]+?\?>/,
greedy: true
},
'doctype': {
// https://www.w3.org/TR/xml/#NT-doctypedecl
pattern: /<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,
greedy: true,
inside: {
'internal-subset': {
pattern: /(^[^\[]*\[)[\s\S]+(?=\]>$)/,
lookbehind: true,
greedy: true,
inside: null // see below
},
'string': {
pattern: /"[^"]*"|'[^']*'/,
greedy: true
},
'punctuation': /^<!|>$|[[\]]/,
'doctype-tag': /^DOCTYPE/i,
'name': /[^\s<>'"]+/
}
},
'cdata': {
pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
greedy: true
},
'tag': {
pattern: /<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,
greedy: true,
inside: {
'tag': {
pattern: /^<\/?[^\s>\/]+/,
inside: {
'punctuation': /^<\/?/,
'namespace': /^[^\s>\/:]+:/
}
},
'special-attr': [],
'attr-value': {
pattern: /=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,
inside: {
'punctuation': [
{
pattern: /^=/,
alias: 'attr-equals'
},
/"|'/
]
}
},
'punctuation': /\/?>/,
'attr-name': {
pattern: /[^\s>\/]+/,
inside: {
'namespace': /^[^\s>\/:]+:/
}
}
}
},
'entity': [
{
pattern: /&[\da-z]{1,8};/i,
alias: 'named-entity'
},
/&#x?[\da-f]{1,8};/i
]
};
Prism.languages.markup['tag'].inside['attr-value'].inside['entity'] =
Prism.languages.markup['entity'];
Prism.languages.markup['doctype'].inside['internal-subset'].inside = Prism.languages.markup;
// Plugin to make entity title show the real entity, idea by Roman Komarov
Prism.hooks.add('wrap', function (env) {
if (env.type === 'entity') {
env.attributes['title'] = env.content.replace(/&amp;/, '&');
}
});
Object.defineProperty(Prism.languages.markup.tag, 'addInlined', {
/**
* Adds an inlined language to markup.
*
* An example of an inlined language is CSS with `<style>` tags.
*
* @param {string} tagName The name of the tag that contains the inlined language. This name will be treated as
* case insensitive.
* @param {string} lang The language key.
* @example
* addInlined('style', 'css');
*/
value: function addInlined(tagName, lang) {
var includedCdataInside = {};
includedCdataInside['language-' + lang] = {
pattern: /(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,
lookbehind: true,
inside: Prism.languages[lang]
};
includedCdataInside['cdata'] = /^<!\[CDATA\[|\]\]>$/i;
var inside = {
'included-cdata': {
pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
inside: includedCdataInside
}
};
inside['language-' + lang] = {
pattern: /[\s\S]+/,
inside: Prism.languages[lang]
};
var def = {};
def[tagName] = {
pattern: RegExp(/(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g, function () { return tagName; }), 'i'),
lookbehind: true,
greedy: true,
inside: inside
};
Prism.languages.insertBefore('markup', 'cdata', def);
}
});
Object.defineProperty(Prism.languages.markup.tag, 'addAttribute', {
/**
* Adds an pattern to highlight languages embedded in HTML attributes.
*
* An example of an inlined language is CSS with `style` attributes.
*
* @param {string} attrName The name of the tag that contains the inlined language. This name will be treated as
* case insensitive.
* @param {string} lang The language key.
* @example
* addAttribute('style', 'css');
*/
value: function (attrName, lang) {
Prism.languages.markup.tag.inside['special-attr'].push({
pattern: RegExp(
/(^|["'\s])/.source + '(?:' + attrName + ')' + /\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source,
'i'
),
lookbehind: true,
inside: {
'attr-name': /^[^\s=]+/,
'attr-value': {
pattern: /=[\s\S]+/,
inside: {
'value': {
pattern: /(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,
lookbehind: true,
alias: [lang, 'language-' + lang],
inside: Prism.languages[lang]
},
'punctuation': [
{
pattern: /^=/,
alias: 'attr-equals'
},
/"|'/
]
}
}
}
});
}
});
Prism.languages.html = Prism.languages.markup;
Prism.languages.mathml = Prism.languages.markup;
Prism.languages.svg = Prism.languages.markup;
Prism.languages.xml = Prism.languages.extend('markup', {});
Prism.languages.ssml = Prism.languages.xml;
Prism.languages.atom = Prism.languages.xml;
Prism.languages.rss = Prism.languages.xml;
(function (Prism) {
var string = /(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;
Prism.languages.css = {
'comment': /\/\*[\s\S]*?\*\//,
'atrule': {
pattern: /@[\w-](?:[^;{\s]|\s+(?![\s{]))*(?:;|(?=\s*\{))/,
inside: {
'rule': /^@[\w-]+/,
'selector-function-argument': {
pattern: /(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,
lookbehind: true,
alias: 'selector'
},
'keyword': {
pattern: /(^|[^\w-])(?:and|not|only|or)(?![\w-])/,
lookbehind: true
}
// See rest below
}
},
'url': {
// https://drafts.csswg.org/css-values-3/#urls
pattern: RegExp('\\burl\\((?:' + string.source + '|' + /(?:[^\\\r\n()"']|\\[\s\S])*/.source + ')\\)', 'i'),
greedy: true,
inside: {
'function': /^url/i,
'punctuation': /^\(|\)$/,
'string': {
pattern: RegExp('^' + string.source + '$'),
alias: 'url'
}
}
},
'selector': {
pattern: RegExp('(^|[{}\\s])[^{}\\s](?:[^{};"\'\\s]|\\s+(?![\\s{])|' + string.source + ')*(?=\\s*\\{)'),
lookbehind: true
},
'string': {
pattern: string,
greedy: true
},
'property': {
pattern: /(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,
lookbehind: true
},
'important': /!important\b/i,
'function': {
pattern: /(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,
lookbehind: true
},
'punctuation': /[(){};:,]/
};
Prism.languages.css['atrule'].inside.rest = Prism.languages.css;
var markup = Prism.languages.markup;
if (markup) {
markup.tag.addInlined('style', 'css');
markup.tag.addAttribute('style', 'css');
}
}(Prism));
(function (Prism) {
var keywords = [
/\b(?:async|sync|yield)\*/,
/\b(?:abstract|assert|async|await|break|case|catch|class|const|continue|covariant|default|deferred|do|dynamic|else|enum|export|extends|extension|external|factory|final|finally|for|get|hide|if|implements|import|in|interface|library|mixin|new|null|on|operator|part|rethrow|return|set|show|static|super|switch|sync|this|throw|try|typedef|var|void|while|with|yield)\b/
];
// Handles named imports, such as http.Client
var packagePrefix = /(^|[^\w.])(?:[a-z]\w*\s*\.\s*)*(?:[A-Z]\w*\s*\.\s*)*/.source;
// based on the dart naming conventions
var className = {
pattern: RegExp(packagePrefix + /[A-Z](?:[\d_A-Z]*[a-z]\w*)?\b/.source),
lookbehind: true,
inside: {
'namespace': {
pattern: /^[a-z]\w*(?:\s*\.\s*[a-z]\w*)*(?:\s*\.)?/,
inside: {
'punctuation': /\./
}
},
}
};
Prism.languages.dart = Prism.languages.extend('clike', {
'class-name': [
className,
{
// variables and parameters
// this to support class names (or generic parameters) which do not contain a lower case letter (also works for methods)
pattern: RegExp(packagePrefix + /[A-Z]\w*(?=\s+\w+\s*[;,=()])/.source),
lookbehind: true,
inside: className.inside
}
],
'keyword': keywords,
'operator': /\bis!|\b(?:as|is)\b|\+\+|--|&&|\|\||<<=?|>>=?|~(?:\/=?)?|[+\-*\/%&^|=!<>]=?|\?/
});
Prism.languages.insertBefore('dart', 'string', {
'string-literal': {
pattern: /r?(?:("""|''')[\s\S]*?\1|(["'])(?:\\.|(?!\2)[^\\\r\n])*\2(?!\2))/,
greedy: true,
inside: {
'interpolation': {
pattern: /((?:^|[^\\])(?:\\{2})*)\$(?:\w+|\{(?:[^{}]|\{[^{}]*\})*\})/,
lookbehind: true,
inside: {
'punctuation': /^\$\{?|\}$/,
'expression': {
pattern: /[\s\S]+/,
inside: Prism.languages.dart
}
}
},
'string': /[\s\S]+/
}
},
'string': undefined
});
Prism.languages.insertBefore('dart', 'class-name', {
'metadata': {
pattern: /@\w+/,
alias: 'function'
}
});
Prism.languages.insertBefore('dart', 'class-name', {
'generics': {
pattern: /<(?:[\w\s,.&?]|<(?:[\w\s,.&?]|<(?:[\w\s,.&?]|<[\w\s,.&?]*>)*>)*>)*>/,
inside: {
'class-name': className,
'keyword': keywords,
'punctuation': /[<>(),.:]/,
'operator': /[?&|]/
}
},
});
}(Prism));
(function (Prism) {
Prism.languages.diff = {
'coord': [
// Match all kinds of coord lines (prefixed by "+++", "---" or "***").
/^(?:\*{3}|-{3}|\+{3}).*$/m,
// Match "@@ ... @@" coord lines in unified diff.
/^@@.*@@$/m,
// Match coord lines in normal diff (starts with a number).
/^\d.*$/m
]
// deleted, inserted, unchanged, diff
};
/**
* A map from the name of a block to its line prefix.
*
* @type {Object<string, string>}
*/
var PREFIXES = {
'deleted-sign': '-',
'deleted-arrow': '<',
'inserted-sign': '+',
'inserted-arrow': '>',
'unchanged': ' ',
'diff': '!',
};
// add a token for each prefix
Object.keys(PREFIXES).forEach(function (name) {
var prefix = PREFIXES[name];
var alias = [];
if (!/^\w+$/.test(name)) { // "deleted-sign" -> "deleted"
alias.push(/\w+/.exec(name)[0]);
}
if (name === 'diff') {
alias.push('bold');
}
Prism.languages.diff[name] = {
pattern: RegExp('^(?:[' + prefix + '].*(?:\r\n?|\n|(?![\\s\\S])))+', 'm'),
alias: alias,
inside: {
'line': {
pattern: /(.)(?=[\s\S]).*(?:\r\n?|\n)?/,
lookbehind: true
},
'prefix': {
pattern: /[\s\S]/,
alias: /\w+/.exec(name)[0]
}
}
};
});
// make prefixes available to Diff plugin
Object.defineProperty(Prism.languages.diff, 'PREFIXES', {
value: PREFIXES
});
}(Prism));
(function (Prism) {
// Many of the following regexes will contain negated lookaheads like `[ \t]+(?![ \t])`. This is a trick to ensure
// that quantifiers behave *atomically*. Atomic quantifiers are necessary to prevent exponential backtracking.
var spaceAfterBackSlash = /\\[\r\n](?:\s|\\[\r\n]|#.*(?!.))*(?![\s#]|\\[\r\n])/.source;
// At least one space, comment, or line break
var space = /(?:[ \t]+(?![ \t])(?:<SP_BS>)?|<SP_BS>)/.source
.replace(/<SP_BS>/g, function () { return spaceAfterBackSlash; });
var string = /"(?:[^"\\\r\n]|\\(?:\r\n|[\s\S]))*"|'(?:[^'\\\r\n]|\\(?:\r\n|[\s\S]))*'/.source;
var option = /--[\w-]+=(?:<STR>|(?!["'])(?:[^\s\\]|\\.)+)/.source.replace(/<STR>/g, function () { return string; });
var stringRule = {
pattern: RegExp(string),
greedy: true
};
var commentRule = {
pattern: /(^[ \t]*)#.*/m,
lookbehind: true,
greedy: true
};
/**
* @param {string} source
* @param {string} flags
* @returns {RegExp}
*/
function re(source, flags) {
source = source
.replace(/<OPT>/g, function () { return option; })
.replace(/<SP>/g, function () { return space; });
return RegExp(source, flags);
}
Prism.languages.docker = {
'instruction': {
pattern: /(^[ \t]*)(?:ADD|ARG|CMD|COPY|ENTRYPOINT|ENV|EXPOSE|FROM|HEALTHCHECK|LABEL|MAINTAINER|ONBUILD|RUN|SHELL|STOPSIGNAL|USER|VOLUME|WORKDIR)(?=\s)(?:\\.|[^\r\n\\])*(?:\\$(?:\s|#.*$)*(?![\s#])(?:\\.|[^\r\n\\])*)*/im,
lookbehind: true,
greedy: true,
inside: {
'options': {
pattern: re(/(^(?:ONBUILD<SP>)?\w+<SP>)<OPT>(?:<SP><OPT>)*/.source, 'i'),
lookbehind: true,
greedy: true,
inside: {
'property': {
pattern: /(^|\s)--[\w-]+/,
lookbehind: true
},
'string': [
stringRule,
{
pattern: /(=)(?!["'])(?:[^\s\\]|\\.)+/,
lookbehind: true
}
],
'operator': /\\$/m,
'punctuation': /=/
}
},
'keyword': [
{
// https://docs.docker.com/engine/reference/builder/#healthcheck
pattern: re(/(^(?:ONBUILD<SP>)?HEALTHCHECK<SP>(?:<OPT><SP>)*)(?:CMD|NONE)\b/.source, 'i'),
lookbehind: true,
greedy: true
},
{
// https://docs.docker.com/engine/reference/builder/#from
pattern: re(/(^(?:ONBUILD<SP>)?FROM<SP>(?:<OPT><SP>)*(?!--)[^ \t\\]+<SP>)AS/.source, 'i'),
lookbehind: true,
greedy: true
},
{
// https://docs.docker.com/engine/reference/builder/#onbuild
pattern: re(/(^ONBUILD<SP>)\w+/.source, 'i'),
lookbehind: true,
greedy: true
},
{
pattern: /^\w+/,
greedy: true
}
],
'comment': commentRule,
'string': stringRule,
'variable': /\$(?:\w+|\{[^{}"'\\]*\})/,
'operator': /\\$/m
}
},
'comment': commentRule
};
Prism.languages.dockerfile = Prism.languages.docker;
}(Prism));
Prism.languages.git = {
/*
* A simple one line comment like in a git status command
* For instance:
* $ git status
* # On branch infinite-scroll
* # Your branch and 'origin/sharedBranches/frontendTeam/infinite-scroll' have diverged,
* # and have 1 and 2 different commits each, respectively.
* nothing to commit (working directory clean)
*/
'comment': /^#.*/m,
/*
* Regexp to match the changed lines in a git diff output. Check the example below.
*/
'deleted': /^[-].*/m,
'inserted': /^\+.*/m,
/*
* a string (double and simple quote)
*/
'string': /("|')(?:\\.|(?!\1)[^\\\r\n])*\1/,
/*
* a git command. It starts with a random prompt finishing by a $, then "git" then some other parameters
* For instance:
* $ git add file.txt
*/
'command': {
pattern: /^.*\$ git .*$/m,
inside: {
/*
* A git command can contain a parameter starting by a single or a double dash followed by a string
* For instance:
* $ git diff --cached
* $ git log -p
*/
'parameter': /\s--?\w+/
}
},
/*
* Coordinates displayed in a git diff command
* For instance:
* $ git diff
* diff --git file.txt file.txt
* index 6214953..1d54a52 100644
* --- file.txt
* +++ file.txt
* @@ -1 +1,2 @@
* -Here's my tetx file
* +Here's my text file
* +And this is the second line
*/
'coord': /^@@.*@@$/m,
/*
* Match a "commit [SHA1]" line in a git log output.
* For instance:
* $ git log
* commit a11a14ef7e26f2ca62d4b35eac455ce636d0dc09
* Author: lgiraudel
* Date: Mon Feb 17 11:18:34 2014 +0100
*
* Add of a new line
*/
'commit-sha1': /^commit \w{40}$/m
};
Prism.languages.glsl = Prism.languages.extend('c', {
'keyword': /\b(?:active|asm|atomic_uint|attribute|[ibdu]?vec[234]|bool|break|buffer|case|cast|centroid|class|coherent|common|const|continue|d?mat[234](?:x[234])?|default|discard|do|double|else|enum|extern|external|false|filter|fixed|flat|float|for|fvec[234]|goto|half|highp|hvec[234]|[iu]?sampler2DMS(?:Array)?|[iu]?sampler2DRect|[iu]?samplerBuffer|[iu]?samplerCube|[iu]?samplerCubeArray|[iu]?sampler[123]D|[iu]?sampler[12]DArray|[iu]?image2DMS(?:Array)?|[iu]?image2DRect|[iu]?imageBuffer|[iu]?imageCube|[iu]?imageCubeArray|[iu]?image[123]D|[iu]?image[12]DArray|if|in|inline|inout|input|int|interface|invariant|layout|long|lowp|mediump|namespace|noinline|noperspective|out|output|partition|patch|precise|precision|public|readonly|resource|restrict|return|sample|sampler[12]DArrayShadow|sampler[12]DShadow|sampler2DRectShadow|sampler3DRect|samplerCubeArrayShadow|samplerCubeShadow|shared|short|sizeof|smooth|static|struct|subroutine|superp|switch|template|this|true|typedef|uint|uniform|union|unsigned|using|varying|void|volatile|while|writeonly)\b/
});
Prism.languages.go = Prism.languages.extend('clike', {
'string': {
pattern: /(^|[^\\])"(?:\\.|[^"\\\r\n])*"|`[^`]*`/,
lookbehind: true,
greedy: true
},
'keyword': /\b(?:break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go(?:to)?|if|import|interface|map|package|range|return|select|struct|switch|type|var)\b/,
'boolean': /\b(?:_|false|iota|nil|true)\b/,
'number': [
// binary and octal integers
/\b0(?:b[01_]+|o[0-7_]+)i?\b/i,
// hexadecimal integers and floats
/\b0x(?:[a-f\d_]+(?:\.[a-f\d_]*)?|\.[a-f\d_]+)(?:p[+-]?\d+(?:_\d+)*)?i?(?!\w)/i,
// decimal integers and floats
/(?:\b\d[\d_]*(?:\.[\d_]*)?|\B\.\d[\d_]*)(?:e[+-]?[\d_]+)?i?(?!\w)/i
],
'operator': /[*\/%^!=]=?|\+[=+]?|-[=-]?|\|[=|]?|&(?:=|&|\^=?)?|>(?:>=?|=)?|<(?:<=?|=|-)?|:=|\.\.\./,
'builtin': /\b(?:append|bool|byte|cap|close|complex|complex(?:64|128)|copy|delete|error|float(?:32|64)|u?int(?:8|16|32|64)?|imag|len|make|new|panic|print(?:ln)?|real|recover|rune|string|uintptr)\b/
});
Prism.languages.insertBefore('go', 'string', {
'char': {
pattern: /'(?:\\.|[^'\\\r\n]){0,10}'/,
greedy: true
}
});
delete Prism.languages.go['class-name'];
// https://go.dev/ref/mod#go-mod-file-module
Prism.languages['go-mod'] = Prism.languages['go-module'] = {
'comment': {
pattern: /\/\/.*/,
greedy: true
},
'version': {
pattern: /(^|[\s()[\],])v\d+\.\d+\.\d+(?:[+-][-+.\w]*)?(?![^\s()[\],])/,
lookbehind: true,
alias: 'number'
},
'go-version': {
pattern: /((?:^|\s)go\s+)\d+(?:\.\d+){1,2}/,
lookbehind: true,
alias: 'number'
},
'keyword': {
pattern: /^([ \t]*)(?:exclude|go|module|replace|require|retract)\b/m,
lookbehind: true
},
'operator': /=>/,
'punctuation': /[()[\],]/
};
(function (Prism) {
// https://yaml.org/spec/1.2/spec.html#c-ns-anchor-property
// https://yaml.org/spec/1.2/spec.html#c-ns-alias-node
var anchorOrAlias = /[*&][^\s[\]{},]+/;
// https://yaml.org/spec/1.2/spec.html#c-ns-tag-property
var tag = /!(?:<[\w\-%#;/?:@&=+$,.!~*'()[\]]+>|(?:[a-zA-Z\d-]*!)?[\w\-%#;/?:@&=+$.~*'()]+)?/;
// https://yaml.org/spec/1.2/spec.html#c-ns-properties(n,c)
var properties = '(?:' + tag.source + '(?:[ \t]+' + anchorOrAlias.source + ')?|'
+ anchorOrAlias.source + '(?:[ \t]+' + tag.source + ')?)';
// https://yaml.org/spec/1.2/spec.html#ns-plain(n,c)
// This is a simplified version that doesn't support "#" and multiline keys
// All these long scarry character classes are simplified versions of YAML's characters
var plainKey = /(?:[^\s\x00-\x08\x0e-\x1f!"#%&'*,\-:>?@[\]`{|}\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]|[?:-]<PLAIN>)(?:[ \t]*(?:(?![#:])<PLAIN>|:<PLAIN>))*/.source
.replace(/<PLAIN>/g, function () { return /[^\s\x00-\x08\x0e-\x1f,[\]{}\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]/.source; });
var string = /"(?:[^"\\\r\n]|\\.)*"|'(?:[^'\\\r\n]|\\.)*'/.source;
/**
*
* @param {string} value
* @param {string} [flags]
* @returns {RegExp}
*/
function createValuePattern(value, flags) {
flags = (flags || '').replace(/m/g, '') + 'm'; // add m flag
var pattern = /([:\-,[{]\s*(?:\s<<prop>>[ \t]+)?)(?:<<value>>)(?=[ \t]*(?:$|,|\]|\}|(?:[\r\n]\s*)?#))/.source
.replace(/<<prop>>/g, function () { return properties; }).replace(/<<value>>/g, function () { return value; });
return RegExp(pattern, flags);
}
Prism.languages.yaml = {
'scalar': {
pattern: RegExp(/([\-:]\s*(?:\s<<prop>>[ \t]+)?[|>])[ \t]*(?:((?:\r?\n|\r)[ \t]+)\S[^\r\n]*(?:\2[^\r\n]+)*)/.source
.replace(/<<prop>>/g, function () { return properties; })),
lookbehind: true,
alias: 'string'
},
'comment': /#.*/,
'key': {
pattern: RegExp(/((?:^|[:\-,[{\r\n?])[ \t]*(?:<<prop>>[ \t]+)?)<<key>>(?=\s*:\s)/.source
.replace(/<<prop>>/g, function () { return properties; })
.replace(/<<key>>/g, function () { return '(?:' + plainKey + '|' + string + ')'; })),
lookbehind: true,
greedy: true,
alias: 'atrule'
},
'directive': {
pattern: /(^[ \t]*)%.+/m,
lookbehind: true,
alias: 'important'
},
'datetime': {
pattern: createValuePattern(/\d{4}-\d\d?-\d\d?(?:[tT]|[ \t]+)\d\d?:\d{2}:\d{2}(?:\.\d*)?(?:[ \t]*(?:Z|[-+]\d\d?(?::\d{2})?))?|\d{4}-\d{2}-\d{2}|\d\d?:\d{2}(?::\d{2}(?:\.\d*)?)?/.source),
lookbehind: true,
alias: 'number'
},
'boolean': {
pattern: createValuePattern(/false|true/.source, 'i'),
lookbehind: true,
alias: 'important'
},
'null': {
pattern: createValuePattern(/null|~/.source, 'i'),
lookbehind: true,
alias: 'important'
},
'string': {
pattern: createValuePattern(string),
lookbehind: true,
greedy: true
},
'number': {
pattern: createValuePattern(/[+-]?(?:0x[\da-f]+|0o[0-7]+|(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?|\.inf|\.nan)/.source, 'i'),
lookbehind: true
},
'tag': tag,
'important': anchorOrAlias,
'punctuation': /---|[:[\]{}\-,|>?]|\.\.\./
};
Prism.languages.yml = Prism.languages.yaml;
}(Prism));
(function (Prism) {
// Allow only one line break
var inner = /(?:\\.|[^\\\n\r]|(?:\n|\r\n?)(?![\r\n]))/.source;
/**
* This function is intended for the creation of the bold or italic pattern.
*
* This also adds a lookbehind group to the given pattern to ensure that the pattern is not backslash-escaped.
*
* _Note:_ Keep in mind that this adds a capturing group.
*
* @param {string} pattern
* @returns {RegExp}
*/
function createInline(pattern) {
pattern = pattern.replace(/<inner>/g, function () { return inner; });
return RegExp(/((?:^|[^\\])(?:\\{2})*)/.source + '(?:' + pattern + ')');
}
var tableCell = /(?:\\.|``(?:[^`\r\n]|`(?!`))+``|`[^`\r\n]+`|[^\\|\r\n`])+/.source;
var tableRow = /\|?__(?:\|__)+\|?(?:(?:\n|\r\n?)|(?![\s\S]))/.source.replace(/__/g, function () { return tableCell; });
var tableLine = /\|?[ \t]*:?-{3,}:?[ \t]*(?:\|[ \t]*:?-{3,}:?[ \t]*)+\|?(?:\n|\r\n?)/.source;
Prism.languages.markdown = Prism.languages.extend('markup', {});
Prism.languages.insertBefore('markdown', 'prolog', {
'front-matter-block': {
pattern: /(^(?:\s*[\r\n])?)---(?!.)[\s\S]*?[\r\n]---(?!.)/,
lookbehind: true,
greedy: true,
inside: {
'punctuation': /^---|---$/,
'front-matter': {
pattern: /\S+(?:\s+\S+)*/,
alias: ['yaml', 'language-yaml'],
inside: Prism.languages.yaml
}
}
},
'blockquote': {
// > ...
pattern: /^>(?:[\t ]*>)*/m,
alias: 'punctuation'
},
'table': {
pattern: RegExp('^' + tableRow + tableLine + '(?:' + tableRow + ')*', 'm'),
inside: {
'table-data-rows': {
pattern: RegExp('^(' + tableRow + tableLine + ')(?:' + tableRow + ')*$'),
lookbehind: true,
inside: {
'table-data': {
pattern: RegExp(tableCell),
inside: Prism.languages.markdown
},
'punctuation': /\|/
}
},
'table-line': {
pattern: RegExp('^(' + tableRow + ')' + tableLine + '$'),
lookbehind: true,
inside: {
'punctuation': /\||:?-{3,}:?/
}
},
'table-header-row': {
pattern: RegExp('^' + tableRow + '$'),
inside: {
'table-header': {
pattern: RegExp(tableCell),
alias: 'important',
inside: Prism.languages.markdown
},
'punctuation': /\|/
}
}
}
},
'code': [
{
// Prefixed by 4 spaces or 1 tab and preceded by an empty line
pattern: /((?:^|\n)[ \t]*\n|(?:^|\r\n?)[ \t]*\r\n?)(?: {4}|\t).+(?:(?:\n|\r\n?)(?: {4}|\t).+)*/,
lookbehind: true,
alias: 'keyword'
},
{
// ```optional language
// code block
// ```
pattern: /^```[\s\S]*?^```$/m,
greedy: true,
inside: {
'code-block': {
pattern: /^(```.*(?:\n|\r\n?))[\s\S]+?(?=(?:\n|\r\n?)^```$)/m,
lookbehind: true
},
'code-language': {
pattern: /^(```).+/,
lookbehind: true
},
'punctuation': /```/
}
}
],
'title': [
{
// title 1
// =======
// title 2
// -------
pattern: /\S.*(?:\n|\r\n?)(?:==+|--+)(?=[ \t]*$)/m,
alias: 'important',
inside: {
punctuation: /==+$|--+$/
}
},
{
// # title 1
// ###### title 6
pattern: /(^\s*)#.+/m,
lookbehind: true,
alias: 'important',
inside: {
punctuation: /^#+|#+$/
}
}
],
'hr': {
// ***
// ---
// * * *
// -----------
pattern: /(^\s*)([*-])(?:[\t ]*\2){2,}(?=\s*$)/m,
lookbehind: true,
alias: 'punctuation'
},
'list': {
// * item
// + item
// - item
// 1. item
pattern: /(^\s*)(?:[*+-]|\d+\.)(?=[\t ].)/m,
lookbehind: true,
alias: 'punctuation'
},
'url-reference': {
// [id]: http://example.com "Optional title"
// [id]: http://example.com 'Optional title'
// [id]: http://example.com (Optional title)
// [id]: <http://example.com> "Optional title"
pattern: /!?\[[^\]]+\]:[\t ]+(?:\S+|<(?:\\.|[^>\\])+>)(?:[\t ]+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\)))?/,
inside: {
'variable': {
pattern: /^(!?\[)[^\]]+/,
lookbehind: true
},
'string': /(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\))$/,
'punctuation': /^[\[\]!:]|[<>]/
},
alias: 'url'
},
'bold': {
// **strong**
// __strong__
// allow one nested instance of italic text using the same delimiter
pattern: createInline(/\b__(?:(?!_)<inner>|_(?:(?!_)<inner>)+_)+__\b|\*\*(?:(?!\*)<inner>|\*(?:(?!\*)<inner>)+\*)+\*\*/.source),
lookbehind: true,
greedy: true,
inside: {
'content': {
pattern: /(^..)[\s\S]+(?=..$)/,
lookbehind: true,
inside: {} // see below
},
'punctuation': /\*\*|__/
}
},
'italic': {
// *em*
// _em_
// allow one nested instance of bold text using the same delimiter
pattern: createInline(/\b_(?:(?!_)<inner>|__(?:(?!_)<inner>)+__)+_\b|\*(?:(?!\*)<inner>|\*\*(?:(?!\*)<inner>)+\*\*)+\*/.source),
lookbehind: true,
greedy: true,
inside: {
'content': {
pattern: /(^.)[\s\S]+(?=.$)/,
lookbehind: true,
inside: {} // see below
},
'punctuation': /[*_]/
}
},
'strike': {
// ~~strike through~~
// ~strike~
// eslint-disable-next-line regexp/strict
pattern: createInline(/(~~?)(?:(?!~)<inner>)+\2/.source),
lookbehind: true,
greedy: true,
inside: {
'content': {
pattern: /(^~~?)[\s\S]+(?=\1$)/,
lookbehind: true,
inside: {} // see below
},
'punctuation': /~~?/
}
},
'code-snippet': {
// `code`
// ``code``
pattern: /(^|[^\\`])(?:``[^`\r\n]+(?:`[^`\r\n]+)*``(?!`)|`[^`\r\n]+`(?!`))/,
lookbehind: true,
greedy: true,
alias: ['code', 'keyword']
},
'url': {
// [example](http://example.com "Optional title")
// [example][id]
// [example] [id]
pattern: createInline(/!?\[(?:(?!\])<inner>)+\](?:\([^\s)]+(?:[\t ]+"(?:\\.|[^"\\])*")?\)|[ \t]?\[(?:(?!\])<inner>)+\])/.source),
lookbehind: true,
greedy: true,
inside: {
'operator': /^!/,
'content': {
pattern: /(^\[)[^\]]+(?=\])/,
lookbehind: true,
inside: {} // see below
},
'variable': {
pattern: /(^\][ \t]?\[)[^\]]+(?=\]$)/,
lookbehind: true
},
'url': {
pattern: /(^\]\()[^\s)]+/,
lookbehind: true
},
'string': {
pattern: /(^[ \t]+)"(?:\\.|[^"\\])*"(?=\)$)/,
lookbehind: true
}
}
}
});
['url', 'bold', 'italic', 'strike'].forEach(function (token) {
['url', 'bold', 'italic', 'strike', 'code-snippet'].forEach(function (inside) {
if (token !== inside) {
Prism.languages.markdown[token].inside.content.inside[inside] = Prism.languages.markdown[inside];
}
});
});
Prism.hooks.add('after-tokenize', function (env) {
if (env.language !== 'markdown' && env.language !== 'md') {
return;
}
function walkTokens(tokens) {
if (!tokens || typeof tokens === 'string') {
return;
}
for (var i = 0, l = tokens.length; i < l; i++) {
var token = tokens[i];
if (token.type !== 'code') {
walkTokens(token.content);
continue;
}
/*
* Add the correct `language-xxxx` class to this code block. Keep in mind that the `code-language` token
* is optional. But the grammar is defined so that there is only one case we have to handle:
*
* token.content = [
* <span class="punctuation">```</span>,
* <span class="code-language">xxxx</span>,
* '\n', // exactly one new lines (\r or \n or \r\n)
* <span class="code-block">...</span>,
* '\n', // exactly one new lines again
* <span class="punctuation">```</span>
* ];
*/
var codeLang = token.content[1];
var codeBlock = token.content[3];
if (codeLang && codeBlock &&
codeLang.type === 'code-language' && codeBlock.type === 'code-block' &&
typeof codeLang.content === 'string') {
// this might be a language that Prism does not support
// do some replacements to support C++, C#, and F#
var lang = codeLang.content.replace(/\b#/g, 'sharp').replace(/\b\+\+/g, 'pp');
// only use the first word
lang = (/[a-z][\w-]*/i.exec(lang) || [''])[0].toLowerCase();
var alias = 'language-' + lang;
// add alias
if (!codeBlock.alias) {
codeBlock.alias = [alias];
} else if (typeof codeBlock.alias === 'string') {
codeBlock.alias = [codeBlock.alias, alias];
} else {
codeBlock.alias.push(alias);
}
}
}
}
walkTokens(env.tokens);
});
Prism.hooks.add('wrap', function (env) {
if (env.type !== 'code-block') {
return;
}
var codeLang = '';
for (var i = 0, l = env.classes.length; i < l; i++) {
var cls = env.classes[i];
var match = /language-(.+)/.exec(cls);
if (match) {
codeLang = match[1];
break;
}
}
var grammar = Prism.languages[codeLang];
if (!grammar) {
if (codeLang && codeLang !== 'none' && Prism.plugins.autoloader) {
var id = 'md-' + new Date().valueOf() + '-' + Math.floor(Math.random() * 1e16);
env.attributes['id'] = id;
Prism.plugins.autoloader.loadLanguages(codeLang, function () {
var ele = document.getElementById(id);
if (ele) {
ele.innerHTML = Prism.highlight(ele.textContent, Prism.languages[codeLang], codeLang);
}
});
}
} else {
env.content = Prism.highlight(textContent(env.content), grammar, codeLang);
}
});
var tagPattern = RegExp(Prism.languages.markup.tag.pattern.source, 'gi');
/**
* A list of known entity names.
*
* This will always be incomplete to save space. The current list is the one used by lowdash's unescape function.
*
* @see {@link https://github.com/lodash/lodash/blob/2da024c3b4f9947a48517639de7560457cd4ec6c/unescape.js#L2}
*/
var KNOWN_ENTITY_NAMES = {
'amp': '&',
'lt': '<',
'gt': '>',
'quot': '"',
};
// IE 11 doesn't support `String.fromCodePoint`
var fromCodePoint = String.fromCodePoint || String.fromCharCode;
/**
* Returns the text content of a given HTML source code string.
*
* @param {string} html
* @returns {string}
*/
function textContent(html) {
// remove all tags
var text = html.replace(tagPattern, '');
// decode known entities
text = text.replace(/&(\w{1,8}|#x?[\da-f]{1,8});/gi, function (m, code) {
code = code.toLowerCase();
if (code[0] === '#') {
var value;
if (code[1] === 'x') {
value = parseInt(code.slice(2), 16);
} else {
value = Number(code.slice(1));
}
return fromCodePoint(value);
} else {
var known = KNOWN_ENTITY_NAMES[code];
if (known) {
return known;
}
// unable to decode
return m;
}
});
return text;
}
Prism.languages.md = Prism.languages.markdown;
}(Prism));
Prism.languages.graphql = {
'comment': /#.*/,
'description': {
pattern: /(?:"""(?:[^"]|(?!""")")*"""|"(?:\\.|[^\\"\r\n])*")(?=\s*[a-z_])/i,
greedy: true,
alias: 'string',
inside: {
'language-markdown': {
pattern: /(^"(?:"")?)(?!\1)[\s\S]+(?=\1$)/,
lookbehind: true,
inside: Prism.languages.markdown
}
}
},
'string': {
pattern: /"""(?:[^"]|(?!""")")*"""|"(?:\\.|[^\\"\r\n])*"/,
greedy: true
},
'number': /(?:\B-|\b)\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,
'boolean': /\b(?:false|true)\b/,
'variable': /\$[a-z_]\w*/i,
'directive': {
pattern: /@[a-z_]\w*/i,
alias: 'function'
},
'attr-name': {
pattern: /\b[a-z_]\w*(?=\s*(?:\((?:[^()"]|"(?:\\.|[^\\"\r\n])*")*\))?:)/i,
greedy: true
},
'atom-input': {
pattern: /\b[A-Z]\w*Input\b/,
alias: 'class-name'
},
'scalar': /\b(?:Boolean|Float|ID|Int|String)\b/,
'constant': /\b[A-Z][A-Z_\d]*\b/,
'class-name': {
pattern: /(\b(?:enum|implements|interface|on|scalar|type|union)\s+|&\s*|:\s*|\[)[A-Z_]\w*/,
lookbehind: true
},
'fragment': {
pattern: /(\bfragment\s+|\.{3}\s*(?!on\b))[a-zA-Z_]\w*/,
lookbehind: true,
alias: 'function'
},
'definition-mutation': {
pattern: /(\bmutation\s+)[a-zA-Z_]\w*/,
lookbehind: true,
alias: 'function'
},
'definition-query': {
pattern: /(\bquery\s+)[a-zA-Z_]\w*/,
lookbehind: true,
alias: 'function'
},
'keyword': /\b(?:directive|enum|extend|fragment|implements|input|interface|mutation|on|query|repeatable|scalar|schema|subscription|type|union)\b/,
'operator': /[!=|&]|\.{3}/,
'property-query': /\w+(?=\s*\()/,
'object': /\w+(?=\s*\{)/,
'punctuation': /[!(){}\[\]:=,]/,
'property': /\w+/
};
Prism.hooks.add('after-tokenize', function afterTokenizeGraphql(env) {
if (env.language !== 'graphql') {
return;
}
/**
* get the graphql token stream that we want to customize
*
* @typedef {InstanceType<import("./prism-core")["Token"]>} Token
* @type {Token[]}
*/
var validTokens = env.tokens.filter(function (token) {
return typeof token !== 'string' && token.type !== 'comment' && token.type !== 'scalar';
});
var currentIndex = 0;
/**
* Returns whether the token relative to the current index has the given type.
*
* @param {number} offset
* @returns {Token | undefined}
*/
function getToken(offset) {
return validTokens[currentIndex + offset];
}
/**
* Returns whether the token relative to the current index has the given type.
*
* @param {readonly string[]} types
* @param {number} [offset=0]
* @returns {boolean}
*/
function isTokenType(types, offset) {
offset = offset || 0;
for (var i = 0; i < types.length; i++) {
var token = getToken(i + offset);
if (!token || token.type !== types[i]) {
return false;
}
}
return true;
}
/**
* Returns the index of the closing bracket to an opening bracket.
*
* It is assumed that `token[currentIndex - 1]` is an opening bracket.
*
* If no closing bracket could be found, `-1` will be returned.
*
* @param {RegExp} open
* @param {RegExp} close
* @returns {number}
*/
function findClosingBracket(open, close) {
var stackHeight = 1;
for (var i = currentIndex; i < validTokens.length; i++) {
var token = validTokens[i];
var content = token.content;
if (token.type === 'punctuation' && typeof content === 'string') {
if (open.test(content)) {
stackHeight++;
} else if (close.test(content)) {
stackHeight--;
if (stackHeight === 0) {
return i;
}
}
}
}
return -1;
}
/**
* Adds an alias to the given token.
*
* @param {Token} token
* @param {string} alias
* @returns {void}
*/
function addAlias(token, alias) {
var aliases = token.alias;
if (!aliases) {
token.alias = aliases = [];
} else if (!Array.isArray(aliases)) {
token.alias = aliases = [aliases];
}
aliases.push(alias);
}
for (; currentIndex < validTokens.length;) {
var startToken = validTokens[currentIndex++];
// add special aliases for mutation tokens
if (startToken.type === 'keyword' && startToken.content === 'mutation') {
// any array of the names of all input variables (if any)
var inputVariables = [];
if (isTokenType(['definition-mutation', 'punctuation']) && getToken(1).content === '(') {
// definition
currentIndex += 2; // skip 'definition-mutation' and 'punctuation'
var definitionEnd = findClosingBracket(/^\($/, /^\)$/);
if (definitionEnd === -1) {
continue;
}
// find all input variables
for (; currentIndex < definitionEnd; currentIndex++) {
var t = getToken(0);
if (t.type === 'variable') {
addAlias(t, 'variable-input');
inputVariables.push(t.content);
}
}
currentIndex = definitionEnd + 1;
}
if (isTokenType(['punctuation', 'property-query']) && getToken(0).content === '{') {
currentIndex++; // skip opening bracket
addAlias(getToken(0), 'property-mutation');
if (inputVariables.length > 0) {
var mutationEnd = findClosingBracket(/^\{$/, /^\}$/);
if (mutationEnd === -1) {
continue;
}
// give references to input variables a special alias
for (var i = currentIndex; i < mutationEnd; i++) {
var varToken = validTokens[i];
if (varToken.type === 'variable' && inputVariables.indexOf(varToken.content) >= 0) {
addAlias(varToken, 'variable-input');
}
}
}
}
}
}
});
/**
* Original by Samuel Flores
*
* Adds the following new token classes:
* constant, builtin, variable, symbol, regex
*/
(function (Prism) {
Prism.languages.ruby = Prism.languages.extend('clike', {
'comment': {
pattern: /#.*|^=begin\s[\s\S]*?^=end/m,
greedy: true
},
'class-name': {
pattern: /(\b(?:class|module)\s+|\bcatch\s+\()[\w.\\]+|\b[A-Z_]\w*(?=\s*\.\s*new\b)/,
lookbehind: true,
inside: {
'punctuation': /[.\\]/
}
},
'keyword': /\b(?:BEGIN|END|alias|and|begin|break|case|class|def|define_method|defined|do|each|else|elsif|end|ensure|extend|for|if|in|include|module|new|next|nil|not|or|prepend|private|protected|public|raise|redo|require|rescue|retry|return|self|super|then|throw|undef|unless|until|when|while|yield)\b/,
'operator': /\.{2,3}|&\.|===|<?=>|[!=]?~|(?:&&|\|\||<<|>>|\*\*|[+\-*/%<>!^&|=])=?|[?:]/,
'punctuation': /[(){}[\].,;]/,
});
Prism.languages.insertBefore('ruby', 'operator', {
'double-colon': {
pattern: /::/,
alias: 'punctuation'
},
});
var interpolation = {
pattern: /((?:^|[^\\])(?:\\{2})*)#\{(?:[^{}]|\{[^{}]*\})*\}/,
lookbehind: true,
inside: {
'content': {
pattern: /^(#\{)[\s\S]+(?=\}$)/,
lookbehind: true,
inside: Prism.languages.ruby
},
'delimiter': {
pattern: /^#\{|\}$/,
alias: 'punctuation'
}
}
};
delete Prism.languages.ruby.function;
var percentExpression = '(?:' + [
/([^a-zA-Z0-9\s{(\[<=])(?:(?!\1)[^\\]|\\[\s\S])*\1/.source,
/\((?:[^()\\]|\\[\s\S]|\((?:[^()\\]|\\[\s\S])*\))*\)/.source,
/\{(?:[^{}\\]|\\[\s\S]|\{(?:[^{}\\]|\\[\s\S])*\})*\}/.source,
/\[(?:[^\[\]\\]|\\[\s\S]|\[(?:[^\[\]\\]|\\[\s\S])*\])*\]/.source,
/<(?:[^<>\\]|\\[\s\S]|<(?:[^<>\\]|\\[\s\S])*>)*>/.source
].join('|') + ')';
var symbolName = /(?:"(?:\\.|[^"\\\r\n])*"|(?:\b[a-zA-Z_]\w*|[^\s\0-\x7F]+)[?!]?|\$.)/.source;
Prism.languages.insertBefore('ruby', 'keyword', {
'regex-literal': [
{
pattern: RegExp(/%r/.source + percentExpression + /[egimnosux]{0,6}/.source),
greedy: true,
inside: {
'interpolation': interpolation,
'regex': /[\s\S]+/
}
},
{
pattern: /(^|[^/])\/(?!\/)(?:\[[^\r\n\]]+\]|\\.|[^[/\\\r\n])+\/[egimnosux]{0,6}(?=\s*(?:$|[\r\n,.;})#]))/,
lookbehind: true,
greedy: true,
inside: {
'interpolation': interpolation,
'regex': /[\s\S]+/
}
}
],
'variable': /[@$]+[a-zA-Z_]\w*(?:[?!]|\b)/,
'symbol': [
{
pattern: RegExp(/(^|[^:]):/.source + symbolName),
lookbehind: true,
greedy: true
},
{
pattern: RegExp(/([\r\n{(,][ \t]*)/.source + symbolName + /(?=:(?!:))/.source),
lookbehind: true,
greedy: true
},
],
'method-definition': {
pattern: /(\bdef\s+)\w+(?:\s*\.\s*\w+)?/,
lookbehind: true,
inside: {
'function': /\b\w+$/,
'keyword': /^self\b/,
'class-name': /^\w+/,
'punctuation': /\./
}
}
});
Prism.languages.insertBefore('ruby', 'string', {
'string-literal': [
{
pattern: RegExp(/%[qQiIwWs]?/.source + percentExpression),
greedy: true,
inside: {
'interpolation': interpolation,
'string': /[\s\S]+/
}
},
{
pattern: /("|')(?:#\{[^}]+\}|#(?!\{)|\\(?:\r\n|[\s\S])|(?!\1)[^\\#\r\n])*\1/,
greedy: true,
inside: {
'interpolation': interpolation,
'string': /[\s\S]+/
}
},
{
pattern: /<<[-~]?([a-z_]\w*)[\r\n](?:.*[\r\n])*?[\t ]*\1/i,
alias: 'heredoc-string',
greedy: true,
inside: {
'delimiter': {
pattern: /^<<[-~]?[a-z_]\w*|\b[a-z_]\w*$/i,
inside: {
'symbol': /\b\w+/,
'punctuation': /^<<[-~]?/
}
},
'interpolation': interpolation,
'string': /[\s\S]+/
}
},
{
pattern: /<<[-~]?'([a-z_]\w*)'[\r\n](?:.*[\r\n])*?[\t ]*\1/i,
alias: 'heredoc-string',
greedy: true,
inside: {
'delimiter': {
pattern: /^<<[-~]?'[a-z_]\w*'|\b[a-z_]\w*$/i,
inside: {
'symbol': /\b\w+/,
'punctuation': /^<<[-~]?'|'$/,
}
},
'string': /[\s\S]+/
}
}
],
'command-literal': [
{
pattern: RegExp(/%x/.source + percentExpression),
greedy: true,
inside: {
'interpolation': interpolation,
'command': {
pattern: /[\s\S]+/,
alias: 'string'
}
}
},
{
pattern: /`(?:#\{[^}]+\}|#(?!\{)|\\(?:\r\n|[\s\S])|[^\\`#\r\n])*`/,
greedy: true,
inside: {
'interpolation': interpolation,
'command': {
pattern: /[\s\S]+/,
alias: 'string'
}
}
}
]
});
delete Prism.languages.ruby.string;
Prism.languages.insertBefore('ruby', 'number', {
'builtin': /\b(?:Array|Bignum|Binding|Class|Continuation|Dir|Exception|FalseClass|File|Fixnum|Float|Hash|IO|Integer|MatchData|Method|Module|NilClass|Numeric|Object|Proc|Range|Regexp|Stat|String|Struct|Symbol|TMS|Thread|ThreadGroup|Time|TrueClass)\b/,
'constant': /\b[A-Z][A-Z0-9_]*(?:[?!]|\b)/
});
Prism.languages.rb = Prism.languages.ruby;
}(Prism));
(function (Prism) {
var specialEscape = {
pattern: /\\[\\(){}[\]^$+*?|.]/,
alias: 'escape'
};
var escape = /\\(?:x[\da-fA-F]{2}|u[\da-fA-F]{4}|u\{[\da-fA-F]+\}|0[0-7]{0,2}|[123][0-7]{2}|c[a-zA-Z]|.)/;
var charSet = {
pattern: /\.|\\[wsd]|\\p\{[^{}]+\}/i,
alias: 'class-name'
};
var charSetWithoutDot = {
pattern: /\\[wsd]|\\p\{[^{}]+\}/i,
alias: 'class-name'
};
var rangeChar = '(?:[^\\\\-]|' + escape.source + ')';
var range = RegExp(rangeChar + '-' + rangeChar);
// the name of a capturing group
var groupName = {
pattern: /(<|')[^<>']+(?=[>']$)/,
lookbehind: true,
alias: 'variable'
};
Prism.languages.regex = {
'char-class': {
pattern: /((?:^|[^\\])(?:\\\\)*)\[(?:[^\\\]]|\\[\s\S])*\]/,
lookbehind: true,
inside: {
'char-class-negation': {
pattern: /(^\[)\^/,
lookbehind: true,
alias: 'operator'
},
'char-class-punctuation': {
pattern: /^\[|\]$/,
alias: 'punctuation'
},
'range': {
pattern: range,
inside: {
'escape': escape,
'range-punctuation': {
pattern: /-/,
alias: 'operator'
}
}
},
'special-escape': specialEscape,
'char-set': charSetWithoutDot,
'escape': escape
}
},
'special-escape': specialEscape,
'char-set': charSet,
'backreference': [
{
// a backreference which is not an octal escape
pattern: /\\(?![123][0-7]{2})[1-9]/,
alias: 'keyword'
},
{
pattern: /\\k<[^<>']+>/,
alias: 'keyword',
inside: {
'group-name': groupName
}
}
],
'anchor': {
pattern: /[$^]|\\[ABbGZz]/,
alias: 'function'
},
'escape': escape,
'group': [
{
// https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html
// https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference?view=netframework-4.7.2#grouping-constructs
// (), (?<name>), (?'name'), (?>), (?:), (?=), (?!), (?<=), (?<!), (?is-m), (?i-m:)
pattern: /\((?:\?(?:<[^<>']+>|'[^<>']+'|[>:]|<?[=!]|[idmnsuxU]+(?:-[idmnsuxU]+)?:?))?/,
alias: 'punctuation',
inside: {
'group-name': groupName
}
},
{
pattern: /\)/,
alias: 'punctuation'
}
],
'quantifier': {
pattern: /(?:[+*?]|\{\d+(?:,\d*)?\})[?+]?/,
alias: 'number'
},
'alternation': {
pattern: /\|/,
alias: 'keyword'
}
};
}(Prism));
Prism.languages.javascript = Prism.languages.extend('clike', {
'class-name': [
Prism.languages.clike['class-name'],
{
pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,
lookbehind: true
}
],
'keyword': [
{
pattern: /((?:^|\})\s*)catch\b/,
lookbehind: true
},
{
pattern: /(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,
lookbehind: true
},
],
// Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444)
'function': /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,
'number': {
pattern: RegExp(
/(^|[^\w$])/.source +
'(?:' +
(
// constant
/NaN|Infinity/.source +
'|' +
// binary integer
/0[bB][01]+(?:_[01]+)*n?/.source +
'|' +
// octal integer
/0[oO][0-7]+(?:_[0-7]+)*n?/.source +
'|' +
// hexadecimal integer
/0[xX][\dA-Fa-f]+(?:_[\dA-Fa-f]+)*n?/.source +
'|' +
// decimal bigint
/\d+(?:_\d+)*n/.source +
'|' +
// decimal number (integer or float) but no bigint
/(?:\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[Ee][+-]?\d+(?:_\d+)*)?/.source
) +
')' +
/(?![\w$])/.source
),
lookbehind: true
},
'operator': /--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/
});
Prism.languages.javascript['class-name'][0].pattern = /(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/;
Prism.languages.insertBefore('javascript', 'keyword', {
'regex': {
pattern: RegExp(
// lookbehind
// eslint-disable-next-line regexp/no-dupe-characters-character-class
/((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)/.source +
// Regex pattern:
// There are 2 regex patterns here. The RegExp set notation proposal added support for nested character
// classes if the `v` flag is present. Unfortunately, nested CCs are both context-free and incompatible
// with the only syntax, so we have to define 2 different regex patterns.
/\//.source +
'(?:' +
/(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}/.source +
'|' +
// `v` flag syntax. This supports 3 levels of nested character classes.
/(?:\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.)*\])*\])*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}v[dgimyus]{0,7}/.source +
')' +
// lookahead
/(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/.source
),
lookbehind: true,
greedy: true,
inside: {
'regex-source': {
pattern: /^(\/)[\s\S]+(?=\/[a-z]*$)/,
lookbehind: true,
alias: 'language-regex',
inside: Prism.languages.regex
},
'regex-delimiter': /^\/|\/$/,
'regex-flags': /^[a-z]+$/,
}
},
// This must be declared before keyword because we use "function" inside the look-forward
'function-variable': {
pattern: /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,
alias: 'function'
},
'parameter': [
{
pattern: /(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,
lookbehind: true,
inside: Prism.languages.javascript
},
{
pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,
lookbehind: true,
inside: Prism.languages.javascript
},
{
pattern: /(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,
lookbehind: true,
inside: Prism.languages.javascript
},
{
pattern: /((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,
lookbehind: true,
inside: Prism.languages.javascript
}
],
'constant': /\b[A-Z](?:[A-Z_]|\dx?)*\b/
});
Prism.languages.insertBefore('javascript', 'string', {
'hashbang': {
pattern: /^#!.*/,
greedy: true,
alias: 'comment'
},
'template-string': {
pattern: /`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,
greedy: true,
inside: {
'template-punctuation': {
pattern: /^`|`$/,
alias: 'string'
},
'interpolation': {
pattern: /((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,
lookbehind: true,
inside: {
'interpolation-punctuation': {
pattern: /^\$\{|\}$/,
alias: 'punctuation'
},
rest: Prism.languages.javascript
}
},
'string': /[\s\S]+/
}
},
'string-property': {
pattern: /((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,
lookbehind: true,
greedy: true,
alias: 'property'
}
});
Prism.languages.insertBefore('javascript', 'operator', {
'literal-property': {
pattern: /((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,
lookbehind: true,
alias: 'property'
},
});
if (Prism.languages.markup) {
Prism.languages.markup.tag.addInlined('script', 'javascript');
// add attribute support for all DOM events.
// https://developer.mozilla.org/en-US/docs/Web/Events#Standard_events
Prism.languages.markup.tag.addAttribute(
/on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)/.source,
'javascript'
);
}
Prism.languages.js = Prism.languages.javascript;
(function (Prism) {
/**
* Returns the placeholder for the given language id and index.
*
* @param {string} language
* @param {string|number} index
* @returns {string}
*/
function getPlaceholder(language, index) {
return '___' + language.toUpperCase() + index + '___';
}
Object.defineProperties(Prism.languages['markup-templating'] = {}, {
buildPlaceholders: {
/**
* Tokenize all inline templating expressions matching `placeholderPattern`.
*
* If `replaceFilter` is provided, only matches of `placeholderPattern` for which `replaceFilter` returns
* `true` will be replaced.
*
* @param {object} env The environment of the `before-tokenize` hook.
* @param {string} language The language id.
* @param {RegExp} placeholderPattern The matches of this pattern will be replaced by placeholders.
* @param {(match: string) => boolean} [replaceFilter]
*/
value: function (env, language, placeholderPattern, replaceFilter) {
if (env.language !== language) {
return;
}
var tokenStack = env.tokenStack = [];
env.code = env.code.replace(placeholderPattern, function (match) {
if (typeof replaceFilter === 'function' && !replaceFilter(match)) {
return match;
}
var i = tokenStack.length;
var placeholder;
// Check for existing strings
while (env.code.indexOf(placeholder = getPlaceholder(language, i)) !== -1) {
++i;
}
// Create a sparse array
tokenStack[i] = match;
return placeholder;
});
// Switch the grammar to markup
env.grammar = Prism.languages.markup;
}
},
tokenizePlaceholders: {
/**
* Replace placeholders with proper tokens after tokenizing.
*
* @param {object} env The environment of the `after-tokenize` hook.
* @param {string} language The language id.
*/
value: function (env, language) {
if (env.language !== language || !env.tokenStack) {
return;
}
// Switch the grammar back
env.grammar = Prism.languages[language];
var j = 0;
var keys = Object.keys(env.tokenStack);
function walkTokens(tokens) {
for (var i = 0; i < tokens.length; i++) {
// all placeholders are replaced already
if (j >= keys.length) {
break;
}
var token = tokens[i];
if (typeof token === 'string' || (token.content && typeof token.content === 'string')) {
var k = keys[j];
var t = env.tokenStack[k];
var s = typeof token === 'string' ? token : token.content;
var placeholder = getPlaceholder(language, k);
var index = s.indexOf(placeholder);
if (index > -1) {
++j;
var before = s.substring(0, index);
var middle = new Prism.Token(language, Prism.tokenize(t, env.grammar), 'language-' + language, t);
var after = s.substring(index + placeholder.length);
var replacement = [];
if (before) {
replacement.push.apply(replacement, walkTokens([before]));
}
replacement.push(middle);
if (after) {
replacement.push.apply(replacement, walkTokens([after]));
}
if (typeof token === 'string') {
tokens.splice.apply(tokens, [i, 1].concat(replacement));
} else {
token.content = replacement;
}
}
} else if (token.content /* && typeof token.content !== 'string' */) {
walkTokens(token.content);
}
}
return tokens;
}
walkTokens(env.tokens);
}
}
});
}(Prism));
/* FIXME :
:extend() is not handled specifically : its highlighting is buggy.
Mixin usage must be inside a ruleset to be highlighted.
At-rules (e.g. import) containing interpolations are buggy.
Detached rulesets are highlighted as at-rules.
A comment before a mixin usage prevents the latter to be properly highlighted.
*/
Prism.languages.less = Prism.languages.extend('css', {
'comment': [
/\/\*[\s\S]*?\*\//,
{
pattern: /(^|[^\\])\/\/.*/,
lookbehind: true
}
],
'atrule': {
pattern: /@[\w-](?:\((?:[^(){}]|\([^(){}]*\))*\)|[^(){};\s]|\s+(?!\s))*?(?=\s*\{)/,
inside: {
'punctuation': /[:()]/
}
},
// selectors and mixins are considered the same
'selector': {
pattern: /(?:@\{[\w-]+\}|[^{};\s@])(?:@\{[\w-]+\}|\((?:[^(){}]|\([^(){}]*\))*\)|[^(){};@\s]|\s+(?!\s))*?(?=\s*\{)/,
inside: {
// mixin parameters
'variable': /@+[\w-]+/
}
},
'property': /(?:@\{[\w-]+\}|[\w-])+(?:\+_?)?(?=\s*:)/,
'operator': /[+\-*\/]/
});
Prism.languages.insertBefore('less', 'property', {
'variable': [
// Variable declaration (the colon must be consumed!)
{
pattern: /@[\w-]+\s*:/,
inside: {
'punctuation': /:/
}
},
// Variable usage
/@@?[\w-]+/
],
'mixin-usage': {
pattern: /([{;]\s*)[.#](?!\d)[\w-].*?(?=[(;])/,
lookbehind: true,
alias: 'function'
}
});
Prism.languages.scss = Prism.languages.extend('css', {
'comment': {
pattern: /(^|[^\\])(?:\/\*[\s\S]*?\*\/|\/\/.*)/,
lookbehind: true
},
'atrule': {
pattern: /@[\w-](?:\([^()]+\)|[^()\s]|\s+(?!\s))*?(?=\s+[{;])/,
inside: {
'rule': /@[\w-]+/
// See rest below
}
},
// url, compassified
'url': /(?:[-a-z]+-)?url(?=\()/i,
// CSS selector regex is not appropriate for Sass
// since there can be lot more things (var, @ directive, nesting..)
// a selector must start at the end of a property or after a brace (end of other rules or nesting)
// it can contain some characters that aren't used for defining rules or end of selector, & (parent selector), or interpolated variable
// the end of a selector is found when there is no rules in it ( {} or {\s}) or if there is a property (because an interpolated var
// can "pass" as a selector- e.g: proper#{$erty})
// this one was hard to do, so please be careful if you edit this one :)
'selector': {
// Initial look-ahead is used to prevent matching of blank selectors
pattern: /(?=\S)[^@;{}()]?(?:[^@;{}()\s]|\s+(?!\s)|#\{\$[-\w]+\})+(?=\s*\{(?:\}|\s|[^}][^:{}]*[:{][^}]))/,
inside: {
'parent': {
pattern: /&/,
alias: 'important'
},
'placeholder': /%[-\w]+/,
'variable': /\$[-\w]+|#\{\$[-\w]+\}/
}
},
'property': {
pattern: /(?:[-\w]|\$[-\w]|#\{\$[-\w]+\})+(?=\s*:)/,
inside: {
'variable': /\$[-\w]+|#\{\$[-\w]+\}/
}
}
});
Prism.languages.insertBefore('scss', 'atrule', {
'keyword': [
/@(?:content|debug|each|else(?: if)?|extend|for|forward|function|if|import|include|mixin|return|use|warn|while)\b/i,
{
pattern: /( )(?:from|through)(?= )/,
lookbehind: true
}
]
});
Prism.languages.insertBefore('scss', 'important', {
// var and interpolated vars
'variable': /\$[-\w]+|#\{\$[-\w]+\}/
});
Prism.languages.insertBefore('scss', 'function', {
'module-modifier': {
pattern: /\b(?:as|hide|show|with)\b/i,
alias: 'keyword'
},
'placeholder': {
pattern: /%[-\w]+/,
alias: 'selector'
},
'statement': {
pattern: /\B!(?:default|optional)\b/i,
alias: 'keyword'
},
'boolean': /\b(?:false|true)\b/,
'null': {
pattern: /\bnull\b/,
alias: 'keyword'
},
'operator': {
pattern: /(\s)(?:[-+*\/%]|[=!]=|<=?|>=?|and|not|or)(?=\s)/,
lookbehind: true
}
});
Prism.languages.scss['atrule'].inside.rest = Prism.languages.scss;
/* TODO
Handle multiline code after tag
%foo= some |
multiline |
code |
*/
(function (Prism) {
Prism.languages.haml = {
// Multiline stuff should appear before the rest
'multiline-comment': {
pattern: /((?:^|\r?\n|\r)([\t ]*))(?:\/|-#).*(?:(?:\r?\n|\r)\2[\t ].+)*/,
lookbehind: true,
alias: 'comment'
},
'multiline-code': [
{
pattern: /((?:^|\r?\n|\r)([\t ]*)(?:[~-]|[&!]?=)).*,[\t ]*(?:(?:\r?\n|\r)\2[\t ].*,[\t ]*)*(?:(?:\r?\n|\r)\2[\t ].+)/,
lookbehind: true,
inside: Prism.languages.ruby
},
{
pattern: /((?:^|\r?\n|\r)([\t ]*)(?:[~-]|[&!]?=)).*\|[\t ]*(?:(?:\r?\n|\r)\2[\t ].*\|[\t ]*)*/,
lookbehind: true,
inside: Prism.languages.ruby
}
],
// See at the end of the file for known filters
'filter': {
pattern: /((?:^|\r?\n|\r)([\t ]*)):[\w-]+(?:(?:\r?\n|\r)(?:\2[\t ].+|\s*?(?=\r?\n|\r)))+/,
lookbehind: true,
inside: {
'filter-name': {
pattern: /^:[\w-]+/,
alias: 'symbol'
}
}
},
'markup': {
pattern: /((?:^|\r?\n|\r)[\t ]*)<.+/,
lookbehind: true,
inside: Prism.languages.markup
},
'doctype': {
pattern: /((?:^|\r?\n|\r)[\t ]*)!!!(?: .+)?/,
lookbehind: true
},
'tag': {
// Allows for one nested group of braces
pattern: /((?:^|\r?\n|\r)[\t ]*)[%.#][\w\-#.]*[\w\-](?:\([^)]+\)|\{(?:\{[^}]+\}|[^{}])+\}|\[[^\]]+\])*[\/<>]*/,
lookbehind: true,
inside: {
'attributes': [
{
// Lookbehind tries to prevent interpolations from breaking it all
// Allows for one nested group of braces
pattern: /(^|[^#])\{(?:\{[^}]+\}|[^{}])+\}/,
lookbehind: true,
inside: Prism.languages.ruby
},
{
pattern: /\([^)]+\)/,
inside: {
'attr-value': {
pattern: /(=\s*)(?:"(?:\\.|[^\\"\r\n])*"|[^)\s]+)/,
lookbehind: true
},
'attr-name': /[\w:-]+(?=\s*!?=|\s*[,)])/,
'punctuation': /[=(),]/
}
},
{
pattern: /\[[^\]]+\]/,
inside: Prism.languages.ruby
}
],
'punctuation': /[<>]/
}
},
'code': {
pattern: /((?:^|\r?\n|\r)[\t ]*(?:[~-]|[&!]?=)).+/,
lookbehind: true,
inside: Prism.languages.ruby
},
// Interpolations in plain text
'interpolation': {
pattern: /#\{[^}]+\}/,
inside: {
'delimiter': {
pattern: /^#\{|\}$/,
alias: 'punctuation'
},
'ruby': {
pattern: /[\s\S]+/,
inside: Prism.languages.ruby
}
}
},
'punctuation': {
pattern: /((?:^|\r?\n|\r)[\t ]*)[~=\-&!]+/,
lookbehind: true
}
};
var filter_pattern = '((?:^|\\r?\\n|\\r)([\\t ]*)):{{filter_name}}(?:(?:\\r?\\n|\\r)(?:\\2[\\t ].+|\\s*?(?=\\r?\\n|\\r)))+';
// Non exhaustive list of available filters and associated languages
var filters = [
'css',
{ filter: 'coffee', language: 'coffeescript' },
'erb',
'javascript',
'less',
'markdown',
'ruby',
'scss',
'textile'
];
var all_filters = {};
for (var i = 0, l = filters.length; i < l; i++) {
var filter = filters[i];
filter = typeof filter === 'string' ? { filter: filter, language: filter } : filter;
if (Prism.languages[filter.language]) {
all_filters['filter-' + filter.filter] = {
pattern: RegExp(filter_pattern.replace('{{filter_name}}', function () { return filter.filter; })),
lookbehind: true,
inside: {
'filter-name': {
pattern: /^:[\w-]+/,
alias: 'symbol'
},
'text': {
pattern: /[\s\S]+/,
alias: [filter.language, 'language-' + filter.language],
inside: Prism.languages[filter.language]
}
}
};
}
}
Prism.languages.insertBefore('haml', 'filter', all_filters);
}(Prism));
Prism.languages.ini = {
/**
* The component mimics the behavior of the Win32 API parser.
*
* @see {@link https://github.com/PrismJS/prism/issues/2775#issuecomment-787477723}
*/
'comment': {
pattern: /(^[ \f\t\v]*)[#;][^\n\r]*/m,
lookbehind: true
},
'section': {
pattern: /(^[ \f\t\v]*)\[[^\n\r\]]*\]?/m,
lookbehind: true,
inside: {
'section-name': {
pattern: /(^\[[ \f\t\v]*)[^ \f\t\v\]]+(?:[ \f\t\v]+[^ \f\t\v\]]+)*/,
lookbehind: true,
alias: 'selector'
},
'punctuation': /\[|\]/
}
},
'key': {
pattern: /(^[ \f\t\v]*)[^ \f\n\r\t\v=]+(?:[ \f\t\v]+[^ \f\n\r\t\v=]+)*(?=[ \f\t\v]*=)/m,
lookbehind: true,
alias: 'attr-name'
},
'value': {
pattern: /(=[ \f\t\v]*)[^ \f\n\r\t\v]+(?:[ \f\t\v]+[^ \f\n\r\t\v]+)*/,
lookbehind: true,
alias: 'attr-value',
inside: {
'inner-value': {
pattern: /^("|').+(?=\1$)/,
lookbehind: true
}
}
},
'punctuation': /=/
};
(function (Prism) {
var keywords = /\b(?:abstract|assert|boolean|break|byte|case|catch|char|class|const|continue|default|do|double|else|enum|exports|extends|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|module|native|new|non-sealed|null|open|opens|package|permits|private|protected|provides|public|record(?!\s*[(){}[\]<>=%~.:,;?+\-*/&|^])|requires|return|sealed|short|static|strictfp|super|switch|synchronized|this|throw|throws|to|transient|transitive|try|uses|var|void|volatile|while|with|yield)\b/;
// full package (optional) + parent classes (optional)
var classNamePrefix = /(?:[a-z]\w*\s*\.\s*)*(?:[A-Z]\w*\s*\.\s*)*/.source;
// based on the java naming conventions
var className = {
pattern: RegExp(/(^|[^\w.])/.source + classNamePrefix + /[A-Z](?:[\d_A-Z]*[a-z]\w*)?\b/.source),
lookbehind: true,
inside: {
'namespace': {
pattern: /^[a-z]\w*(?:\s*\.\s*[a-z]\w*)*(?:\s*\.)?/,
inside: {
'punctuation': /\./
}
},
'punctuation': /\./
}
};
Prism.languages.java = Prism.languages.extend('clike', {
'string': {
pattern: /(^|[^\\])"(?:\\.|[^"\\\r\n])*"/,
lookbehind: true,
greedy: true
},
'class-name': [
className,
{
// variables, parameters, and constructor references
// this to support class names (or generic parameters) which do not contain a lower case letter (also works for methods)
pattern: RegExp(/(^|[^\w.])/.source + classNamePrefix + /[A-Z]\w*(?=\s+\w+\s*[;,=()]|\s*(?:\[[\s,]*\]\s*)?::\s*new\b)/.source),
lookbehind: true,
inside: className.inside
},
{
// class names based on keyword
// this to support class names (or generic parameters) which do not contain a lower case letter (also works for methods)
pattern: RegExp(/(\b(?:class|enum|extends|implements|instanceof|interface|new|record|throws)\s+)/.source + classNamePrefix + /[A-Z]\w*\b/.source),
lookbehind: true,
inside: className.inside
}
],
'keyword': keywords,
'function': [
Prism.languages.clike.function,
{
pattern: /(::\s*)[a-z_]\w*/,
lookbehind: true
}
],
'number': /\b0b[01][01_]*L?\b|\b0x(?:\.[\da-f_p+-]+|[\da-f_]+(?:\.[\da-f_p+-]+)?)\b|(?:\b\d[\d_]*(?:\.[\d_]*)?|\B\.\d[\d_]*)(?:e[+-]?\d[\d_]*)?[dfl]?/i,
'operator': {
pattern: /(^|[^.])(?:<<=?|>>>?=?|->|--|\+\+|&&|\|\||::|[?:~]|[-+*/%&|^!=<>]=?)/m,
lookbehind: true
}
});
Prism.languages.insertBefore('java', 'string', {
'triple-quoted-string': {
// http://openjdk.java.net/jeps/355#Description
pattern: /"""[ \t]*[\r\n](?:(?:"|"")?(?:\\.|[^"\\]))*"""/,
greedy: true,
alias: 'string'
},
'char': {
pattern: /'(?:\\.|[^'\\\r\n]){1,6}'/,
greedy: true
}
});
Prism.languages.insertBefore('java', 'class-name', {
'annotation': {
pattern: /(^|[^.])@\w+(?:\s*\.\s*\w+)*/,
lookbehind: true,
alias: 'punctuation'
},
'generics': {
pattern: /<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&))*>)*>)*>)*>/,
inside: {
'class-name': className,
'keyword': keywords,
'punctuation': /[<>(),.:]/,
'operator': /[?&|]/
}
},
'import': [
{
pattern: RegExp(/(\bimport\s+)/.source + classNamePrefix + /(?:[A-Z]\w*|\*)(?=\s*;)/.source),
lookbehind: true,
inside: {
'namespace': className.inside.namespace,
'punctuation': /\./,
'operator': /\*/,
'class-name': /\w+/
}
},
{
pattern: RegExp(/(\bimport\s+static\s+)/.source + classNamePrefix + /(?:\w+|\*)(?=\s*;)/.source),
lookbehind: true,
alias: 'static',
inside: {
'namespace': className.inside.namespace,
'static': /\b\w+$/,
'punctuation': /\./,
'operator': /\*/,
'class-name': /\w+/
}
}
],
'namespace': {
pattern: RegExp(
/(\b(?:exports|import(?:\s+static)?|module|open|opens|package|provides|requires|to|transitive|uses|with)\s+)(?!<keyword>)[a-z]\w*(?:\.[a-z]\w*)*\.?/
.source.replace(/<keyword>/g, function () { return keywords.source; })),
lookbehind: true,
inside: {
'punctuation': /\./,
}
}
});
}(Prism));
// https://www.json.org/json-en.html
Prism.languages.json = {
'property': {
pattern: /(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/,
lookbehind: true,
greedy: true
},
'string': {
pattern: /(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,
lookbehind: true,
greedy: true
},
'comment': {
pattern: /\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/,
greedy: true
},
'number': /-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,
'punctuation': /[{}[\],]/,
'operator': /:/,
'boolean': /\b(?:false|true)\b/,
'null': {
pattern: /\bnull\b/,
alias: 'keyword'
}
};
Prism.languages.webmanifest = Prism.languages.json;
(function (Prism) {
var string = /("|')(?:\\(?:\r\n?|\n|.)|(?!\1)[^\\\r\n])*\1/;
Prism.languages.json5 = Prism.languages.extend('json', {
'property': [
{
pattern: RegExp(string.source + '(?=\\s*:)'),
greedy: true
},
{
pattern: /(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/,
alias: 'unquoted'
}
],
'string': {
pattern: string,
greedy: true
},
'number': /[+-]?\b(?:NaN|Infinity|0x[a-fA-F\d]+)\b|[+-]?(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[eE][+-]?\d+\b)?/
});
}(Prism));
Prism.languages.lua = {
'comment': /^#!.+|--(?:\[(=*)\[[\s\S]*?\]\1\]|.*)/m,
// \z may be used to skip the following space
'string': {
pattern: /(["'])(?:(?!\1)[^\\\r\n]|\\z(?:\r\n|\s)|\\(?:\r\n|[^z]))*\1|\[(=*)\[[\s\S]*?\]\2\]/,
greedy: true
},
'number': /\b0x[a-f\d]+(?:\.[a-f\d]*)?(?:p[+-]?\d+)?\b|\b\d+(?:\.\B|(?:\.\d*)?(?:e[+-]?\d+)?\b)|\B\.\d+(?:e[+-]?\d+)?\b/i,
'keyword': /\b(?:and|break|do|else|elseif|end|false|for|function|goto|if|in|local|nil|not|or|repeat|return|then|true|until|while)\b/,
'function': /(?!\d)\w+(?=\s*(?:[({]))/,
'operator': [
/[-+*%^&|#]|\/\/?|<[<=]?|>[>=]?|[=~]=?/,
{
// Match ".." but don't break "..."
pattern: /(^|[^.])\.\.(?!\.)/,
lookbehind: true
}
],
'punctuation': /[\[\](){},;]|\.+|:+/
};
Prism.languages.matlab = {
'comment': [
/%\{[\s\S]*?\}%/,
/%.+/
],
'string': {
pattern: /\B'(?:''|[^'\r\n])*'/,
greedy: true
},
// FIXME We could handle imaginary numbers as a whole
'number': /(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[eE][+-]?\d+)?(?:[ij])?|\b[ij]\b/,
'keyword': /\b(?:NaN|break|case|catch|continue|else|elseif|end|for|function|if|inf|otherwise|parfor|pause|pi|return|switch|try|while)\b/,
'function': /\b(?!\d)\w+(?=\s*\()/,
'operator': /\.?[*^\/\\']|[+\-:@]|[<>=~]=?|&&?|\|\|?/,
'punctuation': /\.{3}|[.,;\[\](){}!]/
};
(function (Prism) {
var operators = [
// query and projection
'$eq', '$gt', '$gte', '$in', '$lt', '$lte', '$ne', '$nin', '$and', '$not', '$nor', '$or',
'$exists', '$type', '$expr', '$jsonSchema', '$mod', '$regex', '$text', '$where', '$geoIntersects',
'$geoWithin', '$near', '$nearSphere', '$all', '$elemMatch', '$size', '$bitsAllClear', '$bitsAllSet',
'$bitsAnyClear', '$bitsAnySet', '$comment', '$elemMatch', '$meta', '$slice',
// update
'$currentDate', '$inc', '$min', '$max', '$mul', '$rename', '$set', '$setOnInsert', '$unset',
'$addToSet', '$pop', '$pull', '$push', '$pullAll', '$each', '$position', '$slice', '$sort', '$bit',
// aggregation pipeline stages
'$addFields', '$bucket', '$bucketAuto', '$collStats', '$count', '$currentOp', '$facet', '$geoNear',
'$graphLookup', '$group', '$indexStats', '$limit', '$listLocalSessions', '$listSessions', '$lookup',
'$match', '$merge', '$out', '$planCacheStats', '$project', '$redact', '$replaceRoot', '$replaceWith',
'$sample', '$set', '$skip', '$sort', '$sortByCount', '$unionWith', '$unset', '$unwind', '$setWindowFields',
// aggregation pipeline operators
'$abs', '$accumulator', '$acos', '$acosh', '$add', '$addToSet', '$allElementsTrue', '$and',
'$anyElementTrue', '$arrayElemAt', '$arrayToObject', '$asin', '$asinh', '$atan', '$atan2',
'$atanh', '$avg', '$binarySize', '$bsonSize', '$ceil', '$cmp', '$concat', '$concatArrays', '$cond',
'$convert', '$cos', '$dateFromParts', '$dateToParts', '$dateFromString', '$dateToString', '$dayOfMonth',
'$dayOfWeek', '$dayOfYear', '$degreesToRadians', '$divide', '$eq', '$exp', '$filter', '$first',
'$floor', '$function', '$gt', '$gte', '$hour', '$ifNull', '$in', '$indexOfArray', '$indexOfBytes',
'$indexOfCP', '$isArray', '$isNumber', '$isoDayOfWeek', '$isoWeek', '$isoWeekYear', '$last',
'$last', '$let', '$literal', '$ln', '$log', '$log10', '$lt', '$lte', '$ltrim', '$map', '$max',
'$mergeObjects', '$meta', '$min', '$millisecond', '$minute', '$mod', '$month', '$multiply', '$ne',
'$not', '$objectToArray', '$or', '$pow', '$push', '$radiansToDegrees', '$range', '$reduce',
'$regexFind', '$regexFindAll', '$regexMatch', '$replaceOne', '$replaceAll', '$reverseArray', '$round',
'$rtrim', '$second', '$setDifference', '$setEquals', '$setIntersection', '$setIsSubset', '$setUnion',
'$size', '$sin', '$slice', '$split', '$sqrt', '$stdDevPop', '$stdDevSamp', '$strcasecmp', '$strLenBytes',
'$strLenCP', '$substr', '$substrBytes', '$substrCP', '$subtract', '$sum', '$switch', '$tan',
'$toBool', '$toDate', '$toDecimal', '$toDouble', '$toInt', '$toLong', '$toObjectId', '$toString',
'$toLower', '$toUpper', '$trim', '$trunc', '$type', '$week', '$year', '$zip', '$count', '$dateAdd',
'$dateDiff', '$dateSubtract', '$dateTrunc', '$getField', '$rand', '$sampleRate', '$setField', '$unsetField',
// aggregation pipeline query modifiers
'$comment', '$explain', '$hint', '$max', '$maxTimeMS', '$min', '$orderby', '$query',
'$returnKey', '$showDiskLoc', '$natural',
];
var builtinFunctions = [
'ObjectId',
'Code',
'BinData',
'DBRef',
'Timestamp',
'NumberLong',
'NumberDecimal',
'MaxKey',
'MinKey',
'RegExp',
'ISODate',
'UUID',
];
operators = operators.map(function (operator) {
return operator.replace('$', '\\$');
});
var operatorsSource = '(?:' + operators.join('|') + ')\\b';
Prism.languages.mongodb = Prism.languages.extend('javascript', {});
Prism.languages.insertBefore('mongodb', 'string', {
'property': {
pattern: /(?:(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)(?=\s*:)/,
greedy: true,
inside: {
'keyword': RegExp('^([\'"])?' + operatorsSource + '(?:\\1)?$')
}
}
});
Prism.languages.mongodb.string.inside = {
url: {
// url pattern
pattern: /https?:\/\/[-\w@:%.+~#=]{1,256}\.[a-z0-9()]{1,6}\b[-\w()@:%+.~#?&/=]*/i,
greedy: true
},
entity: {
// ipv4
pattern: /\b(?:(?:[01]?\d\d?|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d\d?|2[0-4]\d|25[0-5])\b/,
greedy: true
}
};
Prism.languages.insertBefore('mongodb', 'constant', {
'builtin': {
pattern: RegExp('\\b(?:' + builtinFunctions.join('|') + ')\\b'),
alias: 'keyword'
}
});
}(Prism));
(function (Prism) {
var variable = /\$(?:\w[a-z\d]*(?:_[^\x00-\x1F\s"'\\()$]*)?|\{[^}\s"'\\]+\})/i;
Prism.languages.nginx = {
'comment': {
pattern: /(^|[\s{};])#.*/,
lookbehind: true,
greedy: true
},
'directive': {
pattern: /(^|\s)\w(?:[^;{}"'\\\s]|\\.|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\s+(?:#.*(?!.)|(?![#\s])))*?(?=\s*[;{])/,
lookbehind: true,
greedy: true,
inside: {
'string': {
pattern: /((?:^|[^\\])(?:\\\\)*)(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/,
lookbehind: true,
greedy: true,
inside: {
'escape': {
pattern: /\\["'\\nrt]/,
alias: 'entity'
},
'variable': variable
}
},
'comment': {
pattern: /(\s)#.*/,
lookbehind: true,
greedy: true
},
'keyword': {
pattern: /^\S+/,
greedy: true
},
// other patterns
'boolean': {
pattern: /(\s)(?:off|on)(?!\S)/,
lookbehind: true
},
'number': {
pattern: /(\s)\d+[a-z]*(?!\S)/i,
lookbehind: true
},
'variable': variable
}
},
'punctuation': /[{};]/
};
}(Prism));
Prism.languages.objectivec = Prism.languages.extend('c', {
'string': {
pattern: /@?"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"/,
greedy: true
},
'keyword': /\b(?:asm|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|in|inline|int|long|register|return|self|short|signed|sizeof|static|struct|super|switch|typedef|typeof|union|unsigned|void|volatile|while)\b|(?:@interface|@end|@implementation|@protocol|@class|@public|@protected|@private|@property|@try|@catch|@finally|@throw|@synthesize|@dynamic|@selector)\b/,
'operator': /-[->]?|\+\+?|!=?|<<?=?|>>?=?|==?|&&?|\|\|?|[~^%?*\/@]/
});
delete Prism.languages.objectivec['class-name'];
Prism.languages.objc = Prism.languages.objectivec;
// Based on Free Pascal
/* TODO
Support inline asm ?
*/
Prism.languages.pascal = {
'directive': {
pattern: /\{\$[\s\S]*?\}/,
greedy: true,
alias: ['marco', 'property']
},
'comment': {
pattern: /\(\*[\s\S]*?\*\)|\{[\s\S]*?\}|\/\/.*/,
greedy: true
},
'string': {
pattern: /(?:'(?:''|[^'\r\n])*'(?!')|#[&$%]?[a-f\d]+)+|\^[a-z]/i,
greedy: true
},
'asm': {
pattern: /(\basm\b)[\s\S]+?(?=\bend\s*[;[])/i,
lookbehind: true,
greedy: true,
inside: null // see below
},
'keyword': [
{
// Turbo Pascal
pattern: /(^|[^&])\b(?:absolute|array|asm|begin|case|const|constructor|destructor|do|downto|else|end|file|for|function|goto|if|implementation|inherited|inline|interface|label|nil|object|of|operator|packed|procedure|program|record|reintroduce|repeat|self|set|string|then|to|type|unit|until|uses|var|while|with)\b/i,
lookbehind: true
},
{
// Free Pascal
pattern: /(^|[^&])\b(?:dispose|exit|false|new|true)\b/i,
lookbehind: true
},
{
// Object Pascal
pattern: /(^|[^&])\b(?:class|dispinterface|except|exports|finalization|finally|initialization|inline|library|on|out|packed|property|raise|resourcestring|threadvar|try)\b/i,
lookbehind: true
},
{
// Modifiers
pattern: /(^|[^&])\b(?:absolute|abstract|alias|assembler|bitpacked|break|cdecl|continue|cppdecl|cvar|default|deprecated|dynamic|enumerator|experimental|export|external|far|far16|forward|generic|helper|implements|index|interrupt|iochecks|local|message|name|near|nodefault|noreturn|nostackframe|oldfpccall|otherwise|overload|override|pascal|platform|private|protected|public|published|read|register|reintroduce|result|safecall|saveregisters|softfloat|specialize|static|stdcall|stored|strict|unaligned|unimplemented|varargs|virtual|write)\b/i,
lookbehind: true
}
],
'number': [
// Hexadecimal, octal and binary
/(?:[&%]\d+|\$[a-f\d]+)/i,
// Decimal
/\b\d+(?:\.\d+)?(?:e[+-]?\d+)?/i
],
'operator': [
/\.\.|\*\*|:=|<[<=>]?|>[>=]?|[+\-*\/]=?|[@^=]/,
{
pattern: /(^|[^&])\b(?:and|as|div|exclude|in|include|is|mod|not|or|shl|shr|xor)\b/,
lookbehind: true
}
],
'punctuation': /\(\.|\.\)|[()\[\]:;,.]/
};
Prism.languages.pascal.asm.inside = Prism.languages.extend('pascal', {
'asm': undefined,
'keyword': undefined,
'operator': undefined
});
Prism.languages.objectpascal = Prism.languages.pascal;
/**
* Original by Aaron Harun: http://aahacreative.com/2012/07/31/php-syntax-highlighting-prism/
* Modified by Miles Johnson: http://milesj.me
* Rewritten by Tom Pavelec
*
* Supports PHP 5.3 - 8.0
*/
(function (Prism) {
var comment = /\/\*[\s\S]*?\*\/|\/\/.*|#(?!\[).*/;
var constant = [
{
pattern: /\b(?:false|true)\b/i,
alias: 'boolean'
},
{
pattern: /(::\s*)\b[a-z_]\w*\b(?!\s*\()/i,
greedy: true,
lookbehind: true,
},
{
pattern: /(\b(?:case|const)\s+)\b[a-z_]\w*(?=\s*[;=])/i,
greedy: true,
lookbehind: true,
},
/\b(?:null)\b/i,
/\b[A-Z_][A-Z0-9_]*\b(?!\s*\()/,
];
var number = /\b0b[01]+(?:_[01]+)*\b|\b0o[0-7]+(?:_[0-7]+)*\b|\b0x[\da-f]+(?:_[\da-f]+)*\b|(?:\b\d+(?:_\d+)*\.?(?:\d+(?:_\d+)*)?|\B\.\d+)(?:e[+-]?\d+)?/i;
var operator = /<?=>|\?\?=?|\.{3}|\??->|[!=]=?=?|::|\*\*=?|--|\+\+|&&|\|\||<<|>>|[?~]|[/^|%*&<>.+-]=?/;
var punctuation = /[{}\[\](),:;]/;
Prism.languages.php = {
'delimiter': {
pattern: /\?>$|^<\?(?:php(?=\s)|=)?/i,
alias: 'important'
},
'comment': comment,
'variable': /\$+(?:\w+\b|(?=\{))/,
'package': {
pattern: /(namespace\s+|use\s+(?:function\s+)?)(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,
lookbehind: true,
inside: {
'punctuation': /\\/
}
},
'class-name-definition': {
pattern: /(\b(?:class|enum|interface|trait)\s+)\b[a-z_]\w*(?!\\)\b/i,
lookbehind: true,
alias: 'class-name'
},
'function-definition': {
pattern: /(\bfunction\s+)[a-z_]\w*(?=\s*\()/i,
lookbehind: true,
alias: 'function'
},
'keyword': [
{
pattern: /(\(\s*)\b(?:array|bool|boolean|float|int|integer|object|string)\b(?=\s*\))/i,
alias: 'type-casting',
greedy: true,
lookbehind: true
},
{
pattern: /([(,?]\s*)\b(?:array(?!\s*\()|bool|callable|(?:false|null)(?=\s*\|)|float|int|iterable|mixed|object|self|static|string)\b(?=\s*\$)/i,
alias: 'type-hint',
greedy: true,
lookbehind: true
},
{
pattern: /(\)\s*:\s*(?:\?\s*)?)\b(?:array(?!\s*\()|bool|callable|(?:false|null)(?=\s*\|)|float|int|iterable|mixed|never|object|self|static|string|void)\b/i,
alias: 'return-type',
greedy: true,
lookbehind: true
},
{
pattern: /\b(?:array(?!\s*\()|bool|float|int|iterable|mixed|object|string|void)\b/i,
alias: 'type-declaration',
greedy: true
},
{
pattern: /(\|\s*)(?:false|null)\b|\b(?:false|null)(?=\s*\|)/i,
alias: 'type-declaration',
greedy: true,
lookbehind: true
},
{
pattern: /\b(?:parent|self|static)(?=\s*::)/i,
alias: 'static-context',
greedy: true
},
{
// yield from
pattern: /(\byield\s+)from\b/i,
lookbehind: true
},
// `class` is always a keyword unlike other keywords
/\bclass\b/i,
{
// https://www.php.net/manual/en/reserved.keywords.php
//
// keywords cannot be preceded by "->"
// the complex lookbehind means `(?<!(?:->|::)\s*)`
pattern: /((?:^|[^\s>:]|(?:^|[^-])>|(?:^|[^:]):)\s*)\b(?:abstract|and|array|as|break|callable|case|catch|clone|const|continue|declare|default|die|do|echo|else|elseif|empty|enddeclare|endfor|endforeach|endif|endswitch|endwhile|enum|eval|exit|extends|final|finally|fn|for|foreach|function|global|goto|if|implements|include|include_once|instanceof|insteadof|interface|isset|list|match|namespace|never|new|or|parent|print|private|protected|public|readonly|require|require_once|return|self|static|switch|throw|trait|try|unset|use|var|while|xor|yield|__halt_compiler)\b/i,
lookbehind: true
}
],
'argument-name': {
pattern: /([(,]\s*)\b[a-z_]\w*(?=\s*:(?!:))/i,
lookbehind: true
},
'class-name': [
{
pattern: /(\b(?:extends|implements|instanceof|new(?!\s+self|\s+static))\s+|\bcatch\s*\()\b[a-z_]\w*(?!\\)\b/i,
greedy: true,
lookbehind: true
},
{
pattern: /(\|\s*)\b[a-z_]\w*(?!\\)\b/i,
greedy: true,
lookbehind: true
},
{
pattern: /\b[a-z_]\w*(?!\\)\b(?=\s*\|)/i,
greedy: true
},
{
pattern: /(\|\s*)(?:\\?\b[a-z_]\w*)+\b/i,
alias: 'class-name-fully-qualified',
greedy: true,
lookbehind: true,
inside: {
'punctuation': /\\/
}
},
{
pattern: /(?:\\?\b[a-z_]\w*)+\b(?=\s*\|)/i,
alias: 'class-name-fully-qualified',
greedy: true,
inside: {
'punctuation': /\\/
}
},
{
pattern: /(\b(?:extends|implements|instanceof|new(?!\s+self\b|\s+static\b))\s+|\bcatch\s*\()(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,
alias: 'class-name-fully-qualified',
greedy: true,
lookbehind: true,
inside: {
'punctuation': /\\/
}
},
{
pattern: /\b[a-z_]\w*(?=\s*\$)/i,
alias: 'type-declaration',
greedy: true
},
{
pattern: /(?:\\?\b[a-z_]\w*)+(?=\s*\$)/i,
alias: ['class-name-fully-qualified', 'type-declaration'],
greedy: true,
inside: {
'punctuation': /\\/
}
},
{
pattern: /\b[a-z_]\w*(?=\s*::)/i,
alias: 'static-context',
greedy: true
},
{
pattern: /(?:\\?\b[a-z_]\w*)+(?=\s*::)/i,
alias: ['class-name-fully-qualified', 'static-context'],
greedy: true,
inside: {
'punctuation': /\\/
}
},
{
pattern: /([(,?]\s*)[a-z_]\w*(?=\s*\$)/i,
alias: 'type-hint',
greedy: true,
lookbehind: true
},
{
pattern: /([(,?]\s*)(?:\\?\b[a-z_]\w*)+(?=\s*\$)/i,
alias: ['class-name-fully-qualified', 'type-hint'],
greedy: true,
lookbehind: true,
inside: {
'punctuation': /\\/
}
},
{
pattern: /(\)\s*:\s*(?:\?\s*)?)\b[a-z_]\w*(?!\\)\b/i,
alias: 'return-type',
greedy: true,
lookbehind: true
},
{
pattern: /(\)\s*:\s*(?:\?\s*)?)(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,
alias: ['class-name-fully-qualified', 'return-type'],
greedy: true,
lookbehind: true,
inside: {
'punctuation': /\\/
}
}
],
'constant': constant,
'function': {
pattern: /(^|[^\\\w])\\?[a-z_](?:[\w\\]*\w)?(?=\s*\()/i,
lookbehind: true,
inside: {
'punctuation': /\\/
}
},
'property': {
pattern: /(->\s*)\w+/,
lookbehind: true
},
'number': number,
'operator': operator,
'punctuation': punctuation
};
var string_interpolation = {
pattern: /\{\$(?:\{(?:\{[^{}]+\}|[^{}]+)\}|[^{}])+\}|(^|[^\\{])\$+(?:\w+(?:\[[^\r\n\[\]]+\]|->\w+)?)/,
lookbehind: true,
inside: Prism.languages.php
};
var string = [
{
pattern: /<<<'([^']+)'[\r\n](?:.*[\r\n])*?\1;/,
alias: 'nowdoc-string',
greedy: true,
inside: {
'delimiter': {
pattern: /^<<<'[^']+'|[a-z_]\w*;$/i,
alias: 'symbol',
inside: {
'punctuation': /^<<<'?|[';]$/
}
}
}
},
{
pattern: /<<<(?:"([^"]+)"[\r\n](?:.*[\r\n])*?\1;|([a-z_]\w*)[\r\n](?:.*[\r\n])*?\2;)/i,
alias: 'heredoc-string',
greedy: true,
inside: {
'delimiter': {
pattern: /^<<<(?:"[^"]+"|[a-z_]\w*)|[a-z_]\w*;$/i,
alias: 'symbol',
inside: {
'punctuation': /^<<<"?|[";]$/
}
},
'interpolation': string_interpolation
}
},
{
pattern: /`(?:\\[\s\S]|[^\\`])*`/,
alias: 'backtick-quoted-string',
greedy: true
},
{
pattern: /'(?:\\[\s\S]|[^\\'])*'/,
alias: 'single-quoted-string',
greedy: true
},
{
pattern: /"(?:\\[\s\S]|[^\\"])*"/,
alias: 'double-quoted-string',
greedy: true,
inside: {
'interpolation': string_interpolation
}
}
];
Prism.languages.insertBefore('php', 'variable', {
'string': string,
'attribute': {
pattern: /#\[(?:[^"'\/#]|\/(?![*/])|\/\/.*$|#(?!\[).*$|\/\*(?:[^*]|\*(?!\/))*\*\/|"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*')+\](?=\s*[a-z$#])/im,
greedy: true,
inside: {
'attribute-content': {
pattern: /^(#\[)[\s\S]+(?=\]$)/,
lookbehind: true,
// inside can appear subset of php
inside: {
'comment': comment,
'string': string,
'attribute-class-name': [
{
pattern: /([^:]|^)\b[a-z_]\w*(?!\\)\b/i,
alias: 'class-name',
greedy: true,
lookbehind: true
},
{
pattern: /([^:]|^)(?:\\?\b[a-z_]\w*)+/i,
alias: [
'class-name',
'class-name-fully-qualified'
],
greedy: true,
lookbehind: true,
inside: {
'punctuation': /\\/
}
}
],
'constant': constant,
'number': number,
'operator': operator,
'punctuation': punctuation
}
},
'delimiter': {
pattern: /^#\[|\]$/,
alias: 'punctuation'
}
}
},
});
Prism.hooks.add('before-tokenize', function (env) {
if (!/<\?/.test(env.code)) {
return;
}
var phpPattern = /<\?(?:[^"'/#]|\/(?![*/])|("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|(?:\/\/|#(?!\[))(?:[^?\n\r]|\?(?!>))*(?=$|\?>|[\r\n])|#\[|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$))*?(?:\?>|$)/g;
Prism.languages['markup-templating'].buildPlaceholders(env, 'php', phpPattern);
});
Prism.hooks.add('after-tokenize', function (env) {
Prism.languages['markup-templating'].tokenizePlaceholders(env, 'php');
});
}(Prism));
(function (Prism) {
var builtinTypes = /\b(?:bool|bytes|double|s?fixed(?:32|64)|float|[su]?int(?:32|64)|string)\b/;
Prism.languages.protobuf = Prism.languages.extend('clike', {
'class-name': [
{
pattern: /(\b(?:enum|extend|message|service)\s+)[A-Za-z_]\w*(?=\s*\{)/,
lookbehind: true
},
{
pattern: /(\b(?:rpc\s+\w+|returns)\s*\(\s*(?:stream\s+)?)\.?[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*(?=\s*\))/,
lookbehind: true
}
],
'keyword': /\b(?:enum|extend|extensions|import|message|oneof|option|optional|package|public|repeated|required|reserved|returns|rpc(?=\s+\w)|service|stream|syntax|to)\b(?!\s*=\s*\d)/,
'function': /\b[a-z_]\w*(?=\s*\()/i
});
Prism.languages.insertBefore('protobuf', 'operator', {
'map': {
pattern: /\bmap<\s*[\w.]+\s*,\s*[\w.]+\s*>(?=\s+[a-z_]\w*\s*[=;])/i,
alias: 'class-name',
inside: {
'punctuation': /[<>.,]/,
'builtin': builtinTypes
}
},
'builtin': builtinTypes,
'positional-class-name': {
pattern: /(?:\b|\B\.)[a-z_]\w*(?:\.[a-z_]\w*)*(?=\s+[a-z_]\w*\s*[=;])/i,
alias: 'class-name',
inside: {
'punctuation': /\./
}
},
'annotation': {
pattern: /(\[\s*)[a-z_]\w*(?=\s*=)/i,
lookbehind: true
}
});
}(Prism));
Prism.languages.python = {
'comment': {
pattern: /(^|[^\\])#.*/,
lookbehind: true,
greedy: true
},
'string-interpolation': {
pattern: /(?:f|fr|rf)(?:("""|''')[\s\S]*?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,
greedy: true,
inside: {
'interpolation': {
// "{" <expression> <optional "!s", "!r", or "!a"> <optional ":" format specifier> "}"
pattern: /((?:^|[^{])(?:\{\{)*)\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}])+\})+\})+\}/,
lookbehind: true,
inside: {
'format-spec': {
pattern: /(:)[^:(){}]+(?=\}$)/,
lookbehind: true
},
'conversion-option': {
pattern: /![sra](?=[:}]$)/,
alias: 'punctuation'
},
rest: null
}
},
'string': /[\s\S]+/
}
},
'triple-quoted-string': {
pattern: /(?:[rub]|br|rb)?("""|''')[\s\S]*?\1/i,
greedy: true,
alias: 'string'
},
'string': {
pattern: /(?:[rub]|br|rb)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,
greedy: true
},
'function': {
pattern: /((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,
lookbehind: true
},
'class-name': {
pattern: /(\bclass\s+)\w+/i,
lookbehind: true
},
'decorator': {
pattern: /(^[\t ]*)@\w+(?:\.\w+)*/m,
lookbehind: true,
alias: ['annotation', 'punctuation'],
inside: {
'punctuation': /\./
}
},
'keyword': /\b(?:_(?=\s*:)|and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,
'builtin': /\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,
'boolean': /\b(?:False|None|True)\b/,
'number': /\b0(?:b(?:_?[01])+|o(?:_?[0-7])+|x(?:_?[a-f0-9])+)\b|(?:\b\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\B\.\d+(?:_\d+)*)(?:e[+-]?\d+(?:_\d+)*)?j?(?!\w)/i,
'operator': /[-+%=]=?|!=|:=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,
'punctuation': /[{}[\];(),.:]/
};
Prism.languages.python['string-interpolation'].inside['interpolation'].inside.rest = Prism.languages.python;
Prism.languages.py = Prism.languages.python;
Prism.languages.r = {
'comment': /#.*/,
'string': {
pattern: /(['"])(?:\\.|(?!\1)[^\\\r\n])*\1/,
greedy: true
},
'percent-operator': {
// Includes user-defined operators
// and %%, %*%, %/%, %in%, %o%, %x%
pattern: /%[^%\s]*%/,
alias: 'operator'
},
'boolean': /\b(?:FALSE|TRUE)\b/,
'ellipsis': /\.\.(?:\.|\d+)/,
'number': [
/\b(?:Inf|NaN)\b/,
/(?:\b0x[\dA-Fa-f]+(?:\.\d*)?|\b\d+(?:\.\d*)?|\B\.\d+)(?:[EePp][+-]?\d+)?[iL]?/
],
'keyword': /\b(?:NA|NA_character_|NA_complex_|NA_integer_|NA_real_|NULL|break|else|for|function|if|in|next|repeat|while)\b/,
'operator': /->?>?|<(?:=|<?-)?|[>=!]=?|::?|&&?|\|\|?|[+*\/^$@~]/,
'punctuation': /[(){}\[\],;]/
};
(function (Prism) {
var multilineComment = /\/\*(?:[^*/]|\*(?!\/)|\/(?!\*)|<self>)*\*\//.source;
for (var i = 0; i < 2; i++) {
// support 4 levels of nested comments
multilineComment = multilineComment.replace(/<self>/g, function () { return multilineComment; });
}
multilineComment = multilineComment.replace(/<self>/g, function () { return /[^\s\S]/.source; });
Prism.languages.rust = {
'comment': [
{
pattern: RegExp(/(^|[^\\])/.source + multilineComment),
lookbehind: true,
greedy: true
},
{
pattern: /(^|[^\\:])\/\/.*/,
lookbehind: true,
greedy: true
}
],
'string': {
pattern: /b?"(?:\\[\s\S]|[^\\"])*"|b?r(#*)"(?:[^"]|"(?!\1))*"\1/,
greedy: true
},
'char': {
pattern: /b?'(?:\\(?:x[0-7][\da-fA-F]|u\{(?:[\da-fA-F]_*){1,6}\}|.)|[^\\\r\n\t'])'/,
greedy: true
},
'attribute': {
pattern: /#!?\[(?:[^\[\]"]|"(?:\\[\s\S]|[^\\"])*")*\]/,
greedy: true,
alias: 'attr-name',
inside: {
'string': null // see below
}
},
// Closure params should not be confused with bitwise OR |
'closure-params': {
pattern: /([=(,:]\s*|\bmove\s*)\|[^|]*\||\|[^|]*\|(?=\s*(?:\{|->))/,
lookbehind: true,
greedy: true,
inside: {
'closure-punctuation': {
pattern: /^\||\|$/,
alias: 'punctuation'
},
rest: null // see below
}
},
'lifetime-annotation': {
pattern: /'\w+/,
alias: 'symbol'
},
'fragment-specifier': {
pattern: /(\$\w+:)[a-z]+/,
lookbehind: true,
alias: 'punctuation'
},
'variable': /\$\w+/,
'function-definition': {
pattern: /(\bfn\s+)\w+/,
lookbehind: true,
alias: 'function'
},
'type-definition': {
pattern: /(\b(?:enum|struct|trait|type|union)\s+)\w+/,
lookbehind: true,
alias: 'class-name'
},
'module-declaration': [
{
pattern: /(\b(?:crate|mod)\s+)[a-z][a-z_\d]*/,
lookbehind: true,
alias: 'namespace'
},
{
pattern: /(\b(?:crate|self|super)\s*)::\s*[a-z][a-z_\d]*\b(?:\s*::(?:\s*[a-z][a-z_\d]*\s*::)*)?/,
lookbehind: true,
alias: 'namespace',
inside: {
'punctuation': /::/
}
}
],
'keyword': [
// https://github.com/rust-lang/reference/blob/master/src/keywords.md
/\b(?:Self|abstract|as|async|await|become|box|break|const|continue|crate|do|dyn|else|enum|extern|final|fn|for|if|impl|in|let|loop|macro|match|mod|move|mut|override|priv|pub|ref|return|self|static|struct|super|trait|try|type|typeof|union|unsafe|unsized|use|virtual|where|while|yield)\b/,
// primitives and str
// https://doc.rust-lang.org/stable/rust-by-example/primitives.html
/\b(?:bool|char|f(?:32|64)|[ui](?:8|16|32|64|128|size)|str)\b/
],
// functions can technically start with an upper-case letter, but this will introduce a lot of false positives
// and Rust's naming conventions recommend snake_case anyway.
// https://doc.rust-lang.org/1.0.0/style/style/naming/README.html
'function': /\b[a-z_]\w*(?=\s*(?:::\s*<|\())/,
'macro': {
pattern: /\b\w+!/,
alias: 'property'
},
'constant': /\b[A-Z_][A-Z_\d]+\b/,
'class-name': /\b[A-Z]\w*\b/,
'namespace': {
pattern: /(?:\b[a-z][a-z_\d]*\s*::\s*)*\b[a-z][a-z_\d]*\s*::(?!\s*<)/,
inside: {
'punctuation': /::/
}
},
// Hex, oct, bin, dec numbers with visual separators and type suffix
'number': /\b(?:0x[\dA-Fa-f](?:_?[\dA-Fa-f])*|0o[0-7](?:_?[0-7])*|0b[01](?:_?[01])*|(?:(?:\d(?:_?\d)*)?\.)?\d(?:_?\d)*(?:[Ee][+-]?\d+)?)(?:_?(?:f32|f64|[iu](?:8|16|32|64|size)?))?\b/,
'boolean': /\b(?:false|true)\b/,
'punctuation': /->|\.\.=|\.{1,3}|::|[{}[\];(),:]/,
'operator': /[-+*\/%!^]=?|=[=>]?|&[&=]?|\|[|=]?|<<?=?|>>?=?|[@?]/
};
Prism.languages.rust['closure-params'].inside.rest = Prism.languages.rust;
Prism.languages.rust['attribute'].inside['string'] = Prism.languages.rust['string'];
}(Prism));
Prism.languages.sql = {
'comment': {
pattern: /(^|[^\\])(?:\/\*[\s\S]*?\*\/|(?:--|\/\/|#).*)/,
lookbehind: true
},
'variable': [
{
pattern: /@(["'`])(?:\\[\s\S]|(?!\1)[^\\])+\1/,
greedy: true
},
/@[\w.$]+/
],
'string': {
pattern: /(^|[^@\\])("|')(?:\\[\s\S]|(?!\2)[^\\]|\2\2)*\2/,
greedy: true,
lookbehind: true
},
'identifier': {
pattern: /(^|[^@\\])`(?:\\[\s\S]|[^`\\]|``)*`/,
greedy: true,
lookbehind: true,
inside: {
'punctuation': /^`|`$/
}
},
'function': /\b(?:AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/i, // Should we highlight user defined functions too?
'keyword': /\b(?:ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:COL|_INSERT)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|KEYS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURN(?:ING|S)?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/i,
'boolean': /\b(?:FALSE|NULL|TRUE)\b/i,
'number': /\b0x[\da-f]+\b|\b\d+(?:\.\d*)?|\B\.\d+\b/i,
'operator': /[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|DIV|ILIKE|IN|IS|LIKE|NOT|OR|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/i,
'punctuation': /[;[\]()`,.]/
};
(function (Prism) {
Prism.languages.typescript = Prism.languages.extend('javascript', {
'class-name': {
pattern: /(\b(?:class|extends|implements|instanceof|interface|new|type)\s+)(?!keyof\b)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?:\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>)?/,
lookbehind: true,
greedy: true,
inside: null // see below
},
'builtin': /\b(?:Array|Function|Promise|any|boolean|console|never|number|string|symbol|unknown)\b/,
});
// The keywords TypeScript adds to JavaScript
Prism.languages.typescript.keyword.push(
/\b(?:abstract|declare|is|keyof|readonly|require)\b/,
// keywords that have to be followed by an identifier
/\b(?:asserts|infer|interface|module|namespace|type)\b(?=\s*(?:[{_$a-zA-Z\xA0-\uFFFF]|$))/,
// This is for `import type *, {}`
/\btype\b(?=\s*(?:[\{*]|$))/
);
// doesn't work with TS because TS is too complex
delete Prism.languages.typescript['parameter'];
delete Prism.languages.typescript['literal-property'];
// a version of typescript specifically for highlighting types
var typeInside = Prism.languages.extend('typescript', {});
delete typeInside['class-name'];
Prism.languages.typescript['class-name'].inside = typeInside;
Prism.languages.insertBefore('typescript', 'function', {
'decorator': {
pattern: /@[$\w\xA0-\uFFFF]+/,
inside: {
'at': {
pattern: /^@/,
alias: 'operator'
},
'function': /^[\s\S]+/
}
},
'generic-function': {
// e.g. foo<T extends "bar" | "baz">( ...
pattern: /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>(?=\s*\()/,
greedy: true,
inside: {
'function': /^#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*/,
'generic': {
pattern: /<[\s\S]+/, // everything after the first <
alias: 'class-name',
inside: typeInside
}
}
}
});
Prism.languages.ts = Prism.languages.typescript;
}(Prism));
(function (Prism) {
var javascript = Prism.util.clone(Prism.languages.javascript);
var space = /(?:\s|\/\/.*(?!.)|\/\*(?:[^*]|\*(?!\/))\*\/)/.source;
var braces = /(?:\{(?:\{(?:\{[^{}]*\}|[^{}])*\}|[^{}])*\})/.source;
var spread = /(?:\{<S>*\.{3}(?:[^{}]|<BRACES>)*\})/.source;
/**
* @param {string} source
* @param {string} [flags]
*/
function re(source, flags) {
source = source
.replace(/<S>/g, function () { return space; })
.replace(/<BRACES>/g, function () { return braces; })
.replace(/<SPREAD>/g, function () { return spread; });
return RegExp(source, flags);
}
spread = re(spread).source;
Prism.languages.jsx = Prism.languages.extend('markup', javascript);
Prism.languages.jsx.tag.pattern = re(
/<\/?(?:[\w.:-]+(?:<S>+(?:[\w.:$-]+(?:=(?:"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*'|[^\s{'"/>=]+|<BRACES>))?|<SPREAD>))*<S>*\/?)?>/.source
);
Prism.languages.jsx.tag.inside['tag'].pattern = /^<\/?[^\s>\/]*/;
Prism.languages.jsx.tag.inside['attr-value'].pattern = /=(?!\{)(?:"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*'|[^\s'">]+)/;
Prism.languages.jsx.tag.inside['tag'].inside['class-name'] = /^[A-Z]\w*(?:\.[A-Z]\w*)*$/;
Prism.languages.jsx.tag.inside['comment'] = javascript['comment'];
Prism.languages.insertBefore('inside', 'attr-name', {
'spread': {
pattern: re(/<SPREAD>/.source),
inside: Prism.languages.jsx
}
}, Prism.languages.jsx.tag);
Prism.languages.insertBefore('inside', 'special-attr', {
'script': {
// Allow for two levels of nesting
pattern: re(/=<BRACES>/.source),
alias: 'language-javascript',
inside: {
'script-punctuation': {
pattern: /^=(?=\{)/,
alias: 'punctuation'
},
rest: Prism.languages.jsx
},
}
}, Prism.languages.jsx.tag);
// The following will handle plain text inside tags
var stringifyToken = function (token) {
if (!token) {
return '';
}
if (typeof token === 'string') {
return token;
}
if (typeof token.content === 'string') {
return token.content;
}
return token.content.map(stringifyToken).join('');
};
var walkTokens = function (tokens) {
var openedTags = [];
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
var notTagNorBrace = false;
if (typeof token !== 'string') {
if (token.type === 'tag' && token.content[0] && token.content[0].type === 'tag') {
// We found a tag, now find its kind
if (token.content[0].content[0].content === '</') {
// Closing tag
if (openedTags.length > 0 && openedTags[openedTags.length - 1].tagName === stringifyToken(token.content[0].content[1])) {
// Pop matching opening tag
openedTags.pop();
}
} else {
if (token.content[token.content.length - 1].content === '/>') ; else {
// Opening tag
openedTags.push({
tagName: stringifyToken(token.content[0].content[1]),
openedBraces: 0
});
}
}
} else if (openedTags.length > 0 && token.type === 'punctuation' && token.content === '{') {
// Here we might have entered a JSX context inside a tag
openedTags[openedTags.length - 1].openedBraces++;
} else if (openedTags.length > 0 && openedTags[openedTags.length - 1].openedBraces > 0 && token.type === 'punctuation' && token.content === '}') {
// Here we might have left a JSX context inside a tag
openedTags[openedTags.length - 1].openedBraces--;
} else {
notTagNorBrace = true;
}
}
if (notTagNorBrace || typeof token === 'string') {
if (openedTags.length > 0 && openedTags[openedTags.length - 1].openedBraces === 0) {
// Here we are inside a tag, and not inside a JSX context.
// That's plain text: drop any tokens matched.
var plainText = stringifyToken(token);
// And merge text with adjacent text
if (i < tokens.length - 1 && (typeof tokens[i + 1] === 'string' || tokens[i + 1].type === 'plain-text')) {
plainText += stringifyToken(tokens[i + 1]);
tokens.splice(i + 1, 1);
}
if (i > 0 && (typeof tokens[i - 1] === 'string' || tokens[i - 1].type === 'plain-text')) {
plainText = stringifyToken(tokens[i - 1]) + plainText;
tokens.splice(i - 1, 1);
i--;
}
tokens[i] = new Prism.Token('plain-text', plainText, null, plainText);
}
}
if (token.content && typeof token.content !== 'string') {
walkTokens(token.content);
}
}
};
Prism.hooks.add('after-tokenize', function (env) {
if (env.language !== 'jsx' && env.language !== 'tsx') {
return;
}
walkTokens(env.tokens);
});
}(Prism));
(function (Prism) {
var typescript = Prism.util.clone(Prism.languages.typescript);
Prism.languages.tsx = Prism.languages.extend('jsx', typescript);
// doesn't work with TS because TS is too complex
delete Prism.languages.tsx['parameter'];
delete Prism.languages.tsx['literal-property'];
// This will prevent collisions between TSX tags and TS generic types.
// Idea by https://github.com/karlhorky
// Discussion: https://github.com/PrismJS/prism/issues/2594#issuecomment-710666928
var tag = Prism.languages.tsx.tag;
tag.pattern = RegExp(/(^|[^\w$]|(?=<\/))/.source + '(?:' + tag.pattern.source + ')', tag.pattern.flags);
tag.lookbehind = true;
}(Prism));
(function (Prism) {
Prism.languages.sass = Prism.languages.extend('css', {
// Sass comments don't need to be closed, only indented
'comment': {
pattern: /^([ \t]*)\/[\/*].*(?:(?:\r?\n|\r)\1[ \t].+)*/m,
lookbehind: true,
greedy: true
}
});
Prism.languages.insertBefore('sass', 'atrule', {
// We want to consume the whole line
'atrule-line': {
// Includes support for = and + shortcuts
pattern: /^(?:[ \t]*)[@+=].+/m,
greedy: true,
inside: {
'atrule': /(?:@[\w-]+|[+=])/
}
}
});
delete Prism.languages.sass.atrule;
var variable = /\$[-\w]+|#\{\$[-\w]+\}/;
var operator = [
/[+*\/%]|[=!]=|<=?|>=?|\b(?:and|not|or)\b/,
{
pattern: /(\s)-(?=\s)/,
lookbehind: true
}
];
Prism.languages.insertBefore('sass', 'property', {
// We want to consume the whole line
'variable-line': {
pattern: /^[ \t]*\$.+/m,
greedy: true,
inside: {
'punctuation': /:/,
'variable': variable,
'operator': operator
}
},
// We want to consume the whole line
'property-line': {
pattern: /^[ \t]*(?:[^:\s]+ *:.*|:[^:\s].*)/m,
greedy: true,
inside: {
'property': [
/[^:\s]+(?=\s*:)/,
{
pattern: /(:)[^:\s]+/,
lookbehind: true
}
],
'punctuation': /:/,
'variable': variable,
'operator': operator,
'important': Prism.languages.sass.important
}
}
});
delete Prism.languages.sass.property;
delete Prism.languages.sass.important;
// Now that whole lines for other patterns are consumed,
// what's left should be selectors
Prism.languages.insertBefore('sass', 'punctuation', {
'selector': {
pattern: /^([ \t]*)\S(?:,[^,\r\n]+|[^,\r\n]*)(?:,[^,\r\n]+)*(?:,(?:\r?\n|\r)\1[ \t]+\S(?:,[^,\r\n]+|[^,\r\n]*)(?:,[^,\r\n]+)*)*/m,
lookbehind: true,
greedy: true
}
});
}(Prism));
(function (Prism) {
// $ set | grep '^[A-Z][^[:space:]]*=' | cut -d= -f1 | tr '\n' '|'
// + LC_ALL, RANDOM, REPLY, SECONDS.
// + make sure PS1..4 are here as they are not always set,
// - some useless things.
var envVars = '\\b(?:BASH|BASHOPTS|BASH_ALIASES|BASH_ARGC|BASH_ARGV|BASH_CMDS|BASH_COMPLETION_COMPAT_DIR|BASH_LINENO|BASH_REMATCH|BASH_SOURCE|BASH_VERSINFO|BASH_VERSION|COLORTERM|COLUMNS|COMP_WORDBREAKS|DBUS_SESSION_BUS_ADDRESS|DEFAULTS_PATH|DESKTOP_SESSION|DIRSTACK|DISPLAY|EUID|GDMSESSION|GDM_LANG|GNOME_KEYRING_CONTROL|GNOME_KEYRING_PID|GPG_AGENT_INFO|GROUPS|HISTCONTROL|HISTFILE|HISTFILESIZE|HISTSIZE|HOME|HOSTNAME|HOSTTYPE|IFS|INSTANCE|JOB|LANG|LANGUAGE|LC_ADDRESS|LC_ALL|LC_IDENTIFICATION|LC_MEASUREMENT|LC_MONETARY|LC_NAME|LC_NUMERIC|LC_PAPER|LC_TELEPHONE|LC_TIME|LESSCLOSE|LESSOPEN|LINES|LOGNAME|LS_COLORS|MACHTYPE|MAILCHECK|MANDATORY_PATH|NO_AT_BRIDGE|OLDPWD|OPTERR|OPTIND|ORBIT_SOCKETDIR|OSTYPE|PAPERSIZE|PATH|PIPESTATUS|PPID|PS1|PS2|PS3|PS4|PWD|RANDOM|REPLY|SECONDS|SELINUX_INIT|SESSION|SESSIONTYPE|SESSION_MANAGER|SHELL|SHELLOPTS|SHLVL|SSH_AUTH_SOCK|TERM|UID|UPSTART_EVENTS|UPSTART_INSTANCE|UPSTART_JOB|UPSTART_SESSION|USER|WINDOWID|XAUTHORITY|XDG_CONFIG_DIRS|XDG_CURRENT_DESKTOP|XDG_DATA_DIRS|XDG_GREETER_DATA_DIR|XDG_MENU_PREFIX|XDG_RUNTIME_DIR|XDG_SEAT|XDG_SEAT_PATH|XDG_SESSION_DESKTOP|XDG_SESSION_ID|XDG_SESSION_PATH|XDG_SESSION_TYPE|XDG_VTNR|XMODIFIERS)\\b';
var commandAfterHeredoc = {
pattern: /(^(["']?)\w+\2)[ \t]+\S.*/,
lookbehind: true,
alias: 'punctuation', // this looks reasonably well in all themes
inside: null // see below
};
var insideString = {
'bash': commandAfterHeredoc,
'environment': {
pattern: RegExp('\\$' + envVars),
alias: 'constant'
},
'variable': [
// [0]: Arithmetic Environment
{
pattern: /\$?\(\([\s\S]+?\)\)/,
greedy: true,
inside: {
// If there is a $ sign at the beginning highlight $(( and )) as variable
'variable': [
{
pattern: /(^\$\(\([\s\S]+)\)\)/,
lookbehind: true
},
/^\$\(\(/
],
'number': /\b0x[\dA-Fa-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[Ee]-?\d+)?/,
// Operators according to https://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic
'operator': /--|\+\+|\*\*=?|<<=?|>>=?|&&|\|\||[=!+\-*/%<>^&|]=?|[?~:]/,
// If there is no $ sign at the beginning highlight (( and )) as punctuation
'punctuation': /\(\(?|\)\)?|,|;/
}
},
// [1]: Command Substitution
{
pattern: /\$\((?:\([^)]+\)|[^()])+\)|`[^`]+`/,
greedy: true,
inside: {
'variable': /^\$\(|^`|\)$|`$/
}
},
// [2]: Brace expansion
{
pattern: /\$\{[^}]+\}/,
greedy: true,
inside: {
'operator': /:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,
'punctuation': /[\[\]]/,
'environment': {
pattern: RegExp('(\\{)' + envVars),
lookbehind: true,
alias: 'constant'
}
}
},
/\$(?:\w+|[#?*!@$])/
],
// Escape sequences from echo and printf's manuals, and escaped quotes.
'entity': /\\(?:[abceEfnrtv\\"]|O?[0-7]{1,3}|U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{1,2})/
};
Prism.languages.bash = {
'shebang': {
pattern: /^#!\s*\/.*/,
alias: 'important'
},
'comment': {
pattern: /(^|[^"{\\$])#.*/,
lookbehind: true
},
'function-name': [
// a) function foo {
// b) foo() {
// c) function foo() {
// but not “foo {”
{
// a) and c)
pattern: /(\bfunction\s+)[\w-]+(?=(?:\s*\(?:\s*\))?\s*\{)/,
lookbehind: true,
alias: 'function'
},
{
// b)
pattern: /\b[\w-]+(?=\s*\(\s*\)\s*\{)/,
alias: 'function'
}
],
// Highlight variable names as variables in for and select beginnings.
'for-or-select': {
pattern: /(\b(?:for|select)\s+)\w+(?=\s+in\s)/,
alias: 'variable',
lookbehind: true
},
// Highlight variable names as variables in the left-hand part
// of assignments (“=” and “+=”).
'assign-left': {
pattern: /(^|[\s;|&]|[<>]\()\w+(?=\+?=)/,
inside: {
'environment': {
pattern: RegExp('(^|[\\s;|&]|[<>]\\()' + envVars),
lookbehind: true,
alias: 'constant'
}
},
alias: 'variable',
lookbehind: true
},
'string': [
// Support for Here-documents https://en.wikipedia.org/wiki/Here_document
{
pattern: /((?:^|[^<])<<-?\s*)(\w+)\s[\s\S]*?(?:\r?\n|\r)\2/,
lookbehind: true,
greedy: true,
inside: insideString
},
// Here-document with quotes around the tag
// → No expansion (so no “inside”).
{
pattern: /((?:^|[^<])<<-?\s*)(["'])(\w+)\2\s[\s\S]*?(?:\r?\n|\r)\3/,
lookbehind: true,
greedy: true,
inside: {
'bash': commandAfterHeredoc
}
},
// “Normal” string
{
// https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html
pattern: /(^|[^\\](?:\\\\)*)"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/,
lookbehind: true,
greedy: true,
inside: insideString
},
{
// https://www.gnu.org/software/bash/manual/html_node/Single-Quotes.html
pattern: /(^|[^$\\])'[^']*'/,
lookbehind: true,
greedy: true
},
{
// https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html
pattern: /\$'(?:[^'\\]|\\[\s\S])*'/,
greedy: true,
inside: {
'entity': insideString.entity
}
}
],
'environment': {
pattern: RegExp('\\$?' + envVars),
alias: 'constant'
},
'variable': insideString.variable,
'function': {
pattern: /(^|[\s;|&]|[<>]\()(?:add|apropos|apt|apt-cache|apt-get|aptitude|aspell|automysqlbackup|awk|basename|bash|bc|bconsole|bg|bzip2|cal|cat|cfdisk|chgrp|chkconfig|chmod|chown|chroot|cksum|clear|cmp|column|comm|composer|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|debootstrap|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|docker|docker-compose|du|egrep|eject|env|ethtool|expand|expect|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|git|gparted|grep|groupadd|groupdel|groupmod|groups|grub-mkconfig|gzip|halt|head|hg|history|host|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|ip|jobs|join|kill|killall|less|link|ln|locate|logname|logrotate|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|lynx|make|man|mc|mdadm|mkconfig|mkdir|mke2fs|mkfifo|mkfs|mkisofs|mknod|mkswap|mmv|more|most|mount|mtools|mtr|mutt|mv|nano|nc|netstat|nice|nl|node|nohup|notify-send|npm|nslookup|op|open|parted|passwd|paste|pathchk|ping|pkill|pnpm|podman|podman-compose|popd|pr|printcap|printenv|ps|pushd|pv|quota|quotacheck|quotactl|ram|rar|rcp|reboot|remsync|rename|renice|rev|rm|rmdir|rpm|rsync|scp|screen|sdiff|sed|sendmail|seq|service|sftp|sh|shellcheck|shuf|shutdown|sleep|slocate|sort|split|ssh|stat|strace|su|sudo|sum|suspend|swapon|sync|tac|tail|tar|tee|time|timeout|top|touch|tr|traceroute|tsort|tty|umount|uname|unexpand|uniq|units|unrar|unshar|unzip|update-grub|uptime|useradd|userdel|usermod|users|uudecode|uuencode|v|vcpkg|vdir|vi|vim|virsh|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yarn|yes|zenity|zip|zsh|zypper)(?=$|[)\s;|&])/,
lookbehind: true
},
'keyword': {
pattern: /(^|[\s;|&]|[<>]\()(?:case|do|done|elif|else|esac|fi|for|function|if|in|select|then|until|while)(?=$|[)\s;|&])/,
lookbehind: true
},
// https://www.gnu.org/software/bash/manual/html_node/Shell-Builtin-Commands.html
'builtin': {
pattern: /(^|[\s;|&]|[<>]\()(?:\.|:|alias|bind|break|builtin|caller|cd|command|continue|declare|echo|enable|eval|exec|exit|export|getopts|hash|help|let|local|logout|mapfile|printf|pwd|read|readarray|readonly|return|set|shift|shopt|source|test|times|trap|type|typeset|ulimit|umask|unalias|unset)(?=$|[)\s;|&])/,
lookbehind: true,
// Alias added to make those easier to distinguish from strings.
alias: 'class-name'
},
'boolean': {
pattern: /(^|[\s;|&]|[<>]\()(?:false|true)(?=$|[)\s;|&])/,
lookbehind: true
},
'file-descriptor': {
pattern: /\B&\d\b/,
alias: 'important'
},
'operator': {
// Lots of redirections here, but not just that.
pattern: /\d?<>|>\||\+=|=[=~]?|!=?|<<[<-]?|[&\d]?>>|\d[<>]&?|[<>][&=]?|&[>&]?|\|[&|]?/,
inside: {
'file-descriptor': {
pattern: /^\d/,
alias: 'important'
}
}
},
'punctuation': /\$?\(\(?|\)\)?|\.\.|[{}[\];\\]/,
'number': {
pattern: /(^|\s)(?:[1-9]\d*|0)(?:[.,]\d+)?\b/,
lookbehind: true
}
};
commandAfterHeredoc.inside = Prism.languages.bash;
/* Patterns in command substitution. */
var toBeCopied = [
'comment',
'function-name',
'for-or-select',
'assign-left',
'string',
'environment',
'function',
'keyword',
'builtin',
'boolean',
'file-descriptor',
'operator',
'punctuation',
'number'
];
var inside = insideString.variable[1].inside;
for (var i = 0; i < toBeCopied.length; i++) {
inside[toBeCopied[i]] = Prism.languages.bash[toBeCopied[i]];
}
Prism.languages.shell = Prism.languages.bash;
}(Prism));
Prism.languages.swift = {
'comment': {
// Nested comments are supported up to 2 levels
pattern: /(^|[^\\:])(?:\/\/.*|\/\*(?:[^/*]|\/(?!\*)|\*(?!\/)|\/\*(?:[^*]|\*(?!\/))*\*\/)*\*\/)/,
lookbehind: true,
greedy: true
},
'string-literal': [
// https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html
{
pattern: RegExp(
/(^|[^"#])/.source
+ '(?:'
// single-line string
+ /"(?:\\(?:\((?:[^()]|\([^()]*\))*\)|\r\n|[^(])|[^\\\r\n"])*"/.source
+ '|'
// multi-line string
+ /"""(?:\\(?:\((?:[^()]|\([^()]*\))*\)|[^(])|[^\\"]|"(?!""))*"""/.source
+ ')'
+ /(?!["#])/.source
),
lookbehind: true,
greedy: true,
inside: {
'interpolation': {
pattern: /(\\\()(?:[^()]|\([^()]*\))*(?=\))/,
lookbehind: true,
inside: null // see below
},
'interpolation-punctuation': {
pattern: /^\)|\\\($/,
alias: 'punctuation'
},
'punctuation': /\\(?=[\r\n])/,
'string': /[\s\S]+/
}
},
{
pattern: RegExp(
/(^|[^"#])(#+)/.source
+ '(?:'
// single-line string
+ /"(?:\\(?:#+\((?:[^()]|\([^()]*\))*\)|\r\n|[^#])|[^\\\r\n])*?"/.source
+ '|'
// multi-line string
+ /"""(?:\\(?:#+\((?:[^()]|\([^()]*\))*\)|[^#])|[^\\])*?"""/.source
+ ')'
+ '\\2'
),
lookbehind: true,
greedy: true,
inside: {
'interpolation': {
pattern: /(\\#+\()(?:[^()]|\([^()]*\))*(?=\))/,
lookbehind: true,
inside: null // see below
},
'interpolation-punctuation': {
pattern: /^\)|\\#+\($/,
alias: 'punctuation'
},
'string': /[\s\S]+/
}
},
],
'directive': {
// directives with conditions
pattern: RegExp(
/#/.source
+ '(?:'
+ (
/(?:elseif|if)\b/.source
+ '(?:[ \t]*'
// This regex is a little complex. It's equivalent to this:
// (?:![ \t]*)?(?:\b\w+\b(?:[ \t]*<round>)?|<round>)(?:[ \t]*(?:&&|\|\|))?
// where <round> is a general parentheses expression.
+ /(?:![ \t]*)?(?:\b\w+\b(?:[ \t]*\((?:[^()]|\([^()]*\))*\))?|\((?:[^()]|\([^()]*\))*\))(?:[ \t]*(?:&&|\|\|))?/.source
+ ')+'
)
+ '|'
+ /(?:else|endif)\b/.source
+ ')'
),
alias: 'property',
inside: {
'directive-name': /^#\w+/,
'boolean': /\b(?:false|true)\b/,
'number': /\b\d+(?:\.\d+)*\b/,
'operator': /!|&&|\|\||[<>]=?/,
'punctuation': /[(),]/
}
},
'literal': {
pattern: /#(?:colorLiteral|column|dsohandle|file(?:ID|Literal|Path)?|function|imageLiteral|line)\b/,
alias: 'constant'
},
'other-directive': {
pattern: /#\w+\b/,
alias: 'property'
},
'attribute': {
pattern: /@\w+/,
alias: 'atrule'
},
'function-definition': {
pattern: /(\bfunc\s+)\w+/,
lookbehind: true,
alias: 'function'
},
'label': {
// https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html#ID141
pattern: /\b(break|continue)\s+\w+|\b[a-zA-Z_]\w*(?=\s*:\s*(?:for|repeat|while)\b)/,
lookbehind: true,
alias: 'important'
},
'keyword': /\b(?:Any|Protocol|Self|Type|actor|as|assignment|associatedtype|associativity|async|await|break|case|catch|class|continue|convenience|default|defer|deinit|didSet|do|dynamic|else|enum|extension|fallthrough|fileprivate|final|for|func|get|guard|higherThan|if|import|in|indirect|infix|init|inout|internal|is|isolated|lazy|left|let|lowerThan|mutating|none|nonisolated|nonmutating|open|operator|optional|override|postfix|precedencegroup|prefix|private|protocol|public|repeat|required|rethrows|return|right|safe|self|set|some|static|struct|subscript|super|switch|throw|throws|try|typealias|unowned|unsafe|var|weak|where|while|willSet)\b/,
'boolean': /\b(?:false|true)\b/,
'nil': {
pattern: /\bnil\b/,
alias: 'constant'
},
'short-argument': /\$\d+\b/,
'omit': {
pattern: /\b_\b/,
alias: 'keyword'
},
'number': /\b(?:[\d_]+(?:\.[\de_]+)?|0x[a-f0-9_]+(?:\.[a-f0-9p_]+)?|0b[01_]+|0o[0-7_]+)\b/i,
// A class name must start with an upper-case letter and be either 1 letter long or contain a lower-case letter.
'class-name': /\b[A-Z](?:[A-Z_\d]*[a-z]\w*)?\b/,
'function': /\b[a-z_]\w*(?=\s*\()/i,
'constant': /\b(?:[A-Z_]{2,}|k[A-Z][A-Za-z_]+)\b/,
// Operators are generic in Swift. Developers can even create new operators (e.g. +++).
// https://docs.swift.org/swift-book/ReferenceManual/zzSummaryOfTheGrammar.html#ID481
// This regex only supports ASCII operators.
'operator': /[-+*/%=!<>&|^~?]+|\.[.\-+*/%=!<>&|^~?]+/,
'punctuation': /[{}[\]();,.:\\]/
};
Prism.languages.swift['string-literal'].forEach(function (rule) {
rule.inside['interpolation'].inside = Prism.languages.swift;
});
Prism.languages['visual-basic'] = {
'comment': {
pattern: /(?:[']|REM\b)(?:[^\r\n_]|_(?:\r\n?|\n)?)*/i,
inside: {
'keyword': /^REM/i
}
},
'directive': {
pattern: /#(?:Const|Else|ElseIf|End|ExternalChecksum|ExternalSource|If|Region)(?:\b_[ \t]*(?:\r\n?|\n)|.)+/i,
alias: 'property',
greedy: true
},
'string': {
pattern: /\$?["“”](?:["“”]{2}|[^"“”])*["“”]C?/i,
greedy: true
},
'date': {
pattern: /#[ \t]*(?:\d+([/-])\d+\1\d+(?:[ \t]+(?:\d+[ \t]*(?:AM|PM)|\d+:\d+(?::\d+)?(?:[ \t]*(?:AM|PM))?))?|\d+[ \t]*(?:AM|PM)|\d+:\d+(?::\d+)?(?:[ \t]*(?:AM|PM))?)[ \t]*#/i,
alias: 'number'
},
'number': /(?:(?:\b\d+(?:\.\d+)?|\.\d+)(?:E[+-]?\d+)?|&[HO][\dA-F]+)(?:[FRD]|U?[ILS])?/i,
'boolean': /\b(?:False|Nothing|True)\b/i,
'keyword': /\b(?:AddHandler|AddressOf|Alias|And(?:Also)?|As|Boolean|ByRef|Byte|ByVal|Call|Case|Catch|C(?:Bool|Byte|Char|Date|Dbl|Dec|Int|Lng|Obj|SByte|Short|Sng|Str|Type|UInt|ULng|UShort)|Char|Class|Const|Continue|Currency|Date|Decimal|Declare|Default|Delegate|Dim|DirectCast|Do|Double|Each|Else(?:If)?|End(?:If)?|Enum|Erase|Error|Event|Exit|Finally|For|Friend|Function|Get(?:Type|XMLNamespace)?|Global|GoSub|GoTo|Handles|If|Implements|Imports|In|Inherits|Integer|Interface|Is|IsNot|Let|Lib|Like|Long|Loop|Me|Mod|Module|Must(?:Inherit|Override)|My(?:Base|Class)|Namespace|Narrowing|New|Next|Not(?:Inheritable|Overridable)?|Object|Of|On|Operator|Option(?:al)?|Or(?:Else)?|Out|Overloads|Overridable|Overrides|ParamArray|Partial|Private|Property|Protected|Public|RaiseEvent|ReadOnly|ReDim|RemoveHandler|Resume|Return|SByte|Select|Set|Shadows|Shared|short|Single|Static|Step|Stop|String|Structure|Sub|SyncLock|Then|Throw|To|Try|TryCast|Type|TypeOf|U(?:Integer|Long|Short)|Until|Using|Variant|Wend|When|While|Widening|With(?:Events)?|WriteOnly|Xor)\b/i,
'operator': /[+\-*/\\^<=>&#@$%!]|\b_(?=[ \t]*[\r\n])/,
'punctuation': /[{}().,:?]/
};
Prism.languages.vb = Prism.languages['visual-basic'];
Prism.languages.vba = Prism.languages['visual-basic'];
Prism.languages.wasm = {
'comment': [
/\(;[\s\S]*?;\)/,
{
pattern: /;;.*/,
greedy: true
}
],
'string': {
pattern: /"(?:\\[\s\S]|[^"\\])*"/,
greedy: true
},
'keyword': [
{
pattern: /\b(?:align|offset)=/,
inside: {
'operator': /=/
}
},
{
pattern: /\b(?:(?:f32|f64|i32|i64)(?:\.(?:abs|add|and|ceil|clz|const|convert_[su]\/i(?:32|64)|copysign|ctz|demote\/f64|div(?:_[su])?|eqz?|extend_[su]\/i32|floor|ge(?:_[su])?|gt(?:_[su])?|le(?:_[su])?|load(?:(?:8|16|32)_[su])?|lt(?:_[su])?|max|min|mul|neg?|nearest|or|popcnt|promote\/f32|reinterpret\/[fi](?:32|64)|rem_[su]|rot[lr]|shl|shr_[su]|sqrt|store(?:8|16|32)?|sub|trunc(?:_[su]\/f(?:32|64))?|wrap\/i64|xor))?|memory\.(?:grow|size))\b/,
inside: {
'punctuation': /\./
}
},
/\b(?:anyfunc|block|br(?:_if|_table)?|call(?:_indirect)?|data|drop|elem|else|end|export|func|get_(?:global|local)|global|if|import|local|loop|memory|module|mut|nop|offset|param|result|return|select|set_(?:global|local)|start|table|tee_local|then|type|unreachable)\b/
],
'variable': /\$[\w!#$%&'*+\-./:<=>?@\\^`|~]+/,
'number': /[+-]?\b(?:\d(?:_?\d)*(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?|0x[\da-fA-F](?:_?[\da-fA-F])*(?:\.[\da-fA-F](?:_?[\da-fA-D])*)?(?:[pP][+-]?\d(?:_?\d)*)?)\b|\binf\b|\bnan(?::0x[\da-fA-F](?:_?[\da-fA-D])*)?\b/,
'punctuation': /[()]/
};
// 预览区域代码块可切换语言功能: https://github.com/Tencent/cherry-markdown/issues/433;
var CODE_PREVIEWER_LANG_SELECT_CLASS_NAME = 'cherry-code-preview-lang-select';
/**
* 生成preview区域的代码语言设置区域
*/
var getCodePreviewLangSelectElement = function getCodePreviewLangSelectElement(lang) {
var optionsElement = map$3(codePreviewLangSelectList).call(codePreviewLangSelectList, function (item) {
var _context2;
if (lang === item) {
var _context;
return concat$5(_context = "<option value=\"".concat(item, "\" selected=\"selected\">")).call(_context, item, "</option>");
}
return concat$5(_context2 = "<option value=\"".concat(item, "\">")).call(_context2, item, "</option>");
});
return "<select id=\"code-preview-lang-select\" style=\"display:none;\" class=\"".concat(CODE_PREVIEWER_LANG_SELECT_CLASS_NAME, "\">\n <option value=\"\" selected disabled hidden>Choose here</option>\n ").concat(optionsElement.join(''), "\n </select>");
}; // program language list:
var codePreviewLangSelectList = ['javascript', 'typescript', 'html', 'css', 'shell', 'python', 'golang', 'java', 'c', 'c++', 'c#', 'php', 'ruby', 'swift', 'kotlin', 'scala', 'rust', 'dart', 'elixir', 'haskell', 'lua', 'perl', 'r', 'sql'];
function ownKeys$3(object, enumerableOnly) { var keys = keys$3(object); if (getOwnPropertySymbols$2) { var symbols = getOwnPropertySymbols$2(object); enumerableOnly && (symbols = filter$3(symbols).call(symbols, function (sym) { return getOwnPropertyDescriptor$3(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var _context22, _context23; var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? forEach$3(_context22 = ownKeys$3(Object(source), !0)).call(_context22, function (key) { _defineProperty(target, key, source[key]); }) : getOwnPropertyDescriptors$2 ? defineProperties$2(target, getOwnPropertyDescriptors$2(source)) : forEach$3(_context23 = ownKeys$3(Object(source))).call(_context23, function (key) { defineProperty$5(target, key, getOwnPropertyDescriptor$3(source, key)); }); } return target; }
function _createSuper$8(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$8(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$8() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
prismCore.manual = true;
var CUSTOM_WRAPPER = {
figure: 'figure'
};
var CodeBlock = /*#__PURE__*/function (_ParagraphBase) {
_inherits(CodeBlock, _ParagraphBase);
var _super = _createSuper$8(CodeBlock);
function CodeBlock(_ref) {
var _this;
var externals = _ref.externals,
config = _ref.config;
_classCallCheck(this, CodeBlock);
_this = _super.call(this, {
needCache: true
});
CodeBlock.inlineCodeCache = {};
_this.codeCache = {};
_this.customLang = [];
_this.customParser = {};
_this.wrap = config.wrap; // 超出是否换行
_this.lineNumber = config.lineNumber; // 是否显示行号
_this.copyCode = config.copyCode; // 是否显示“复制”按钮
_this.mermaid = config.mermaid; // mermaid的配置目前仅支持格式设置svg2img=true 展示成图片false 展示成svg
_this.indentedCodeBlock = typeof config.indentedCodeBlock === 'undefined' ? true : config.indentedCodeBlock; // 是否支持缩进代码块
_this.INLINE_CODE_REGEX = /(`+)(.+?(?:\n.+?)*?)\1/g;
if (config && config.customRenderer) {
var _context;
_this.customLang = map$3(_context = keys$3(config.customRenderer)).call(_context, function (lang) {
return lang.toLowerCase();
});
_this.customParser = _objectSpread$2({}, config.customRenderer);
}
_this.customHighlighter = config.highlighter;
return _this;
}
_createClass(CodeBlock, [{
key: "$codeCache",
value: function $codeCache(sign, str) {
if (sign && str) {
this.codeCache[sign] = str;
}
if (this.codeCache[sign]) {
return this.codeCache[sign];
}
if (this.codeCache.length > 40) {
this.codeCache.length = 0;
}
return false;
} // 渲染特定语言代码块
}, {
key: "parseCustomLanguage",
value: function parseCustomLanguage(lang, codeSrc, props) {
var _context2, _context3, _context4, _context5, _context6;
var engine = this.customParser[lang];
if (!engine || typeof engine.render !== 'function') {
return false;
}
var html = engine.render(codeSrc, props.sign, this.$engine, this.mermaid);
if (!html) {
return false;
}
var tag = CUSTOM_WRAPPER[engine.constructor.TYPE] || 'div';
return concat$5(_context2 = concat$5(_context3 = concat$5(_context4 = concat$5(_context5 = concat$5(_context6 = "<".concat(tag, " data-sign=\"")).call(_context6, props.sign, "\" data-type=\"")).call(_context5, lang, "\" data-lines=\"")).call(_context4, props.lines, "\">")).call(_context3, html, "</")).call(_context2, tag, ">");
} // 修复渲染行号时打散的标签
}, {
key: "fillTag",
value: function fillTag(lines) {
var tagStack = []; // 存储未闭合标签
return map$3(lines).call(lines, function (rawLine) {
if (!rawLine) return '';
var line = rawLine; // 补全上一行未闭合标签
while (tagStack.length) {
var _context7;
var tag = tagStack.pop();
line = concat$5(_context7 = "".concat(tag)).call(_context7, line);
} // 计算未闭合标签
var tags = line.match(/<span class="(.+?)">|<\/span>/g);
var close = 0;
if (!tags) return line;
while (tags.length) {
var _tag = tags.pop();
if (/<\/span>/.test(_tag)) close += 1;else if (!close) {
tagStack.unshift(_tag.match(/<span class="(.+?)">/)[0]);
} else {
close -= 1;
}
} // 补全未闭合标签
for (var i = 0; i < tagStack.length; i++) {
line = "".concat(line, "</span>");
}
return line;
});
} // 渲染行号
}, {
key: "renderLineNumber",
value: function renderLineNumber(code) {
if (!this.lineNumber) return code;
var codeLines = code.split('\n');
codeLines.pop(); // 末尾回车不增加行号
codeLines = this.fillTag(codeLines);
return "<span class=\"code-line\">".concat(codeLines.join('</span>\n<span class="code-line">'), "</span>");
}
/**
* 判断内置转换语法是否被覆盖
* @param {string} lang
*/
}, {
key: "isInternalCustomLangCovered",
value: function isInternalCustomLangCovered(lang) {
var _context8;
return indexOf$8(_context8 = this.customLang).call(_context8, lang) !== -1;
}
/**
* 预处理代码块
* @param {string} match
* @param {string} leadingContent
* @param {string} code
*/
}, {
key: "computeLines",
value: function computeLines(match, leadingContent, code) {
var leadingSpaces = leadingContent;
var lines = this.getLineCount(match, leadingSpaces);
var sign = this.$engine.md5(match.replace(/^\n+/, '') + lines);
return {
sign: sign,
lines: lines
};
}
/**
* 补齐用codeBlock承载的mermaid
* @param {string} $code
* @param {string} $lang
*/
}, {
key: "appendMermaid",
value: function appendMermaid($code, $lang) {
var code = $code,
lang = $lang; // 临时实现流程图、时序图缩略写法
if (/^flow([ ](TD|LR))?$/i.test(lang) && !this.isInternalCustomLangCovered(lang)) {
var _context9;
var suffix = lang.match(/^flow(?:[ ](TD|LR))?$/i) || [];
code = concat$5(_context9 = "graph ".concat(suffix[1] || 'TD', "\n")).call(_context9, code);
lang = 'mermaid';
}
if (/^seq$/i.test(lang) && !this.isInternalCustomLangCovered(lang)) {
code = "sequenceDiagram\n".concat(code);
lang = 'mermaid';
}
if (lang === 'mermaid') {
// 8.4.8版本兼容8.5.2版本的语法
code = code.replace(/(^[\s]*)stateDiagram-v2\n/, '$1stateDiagram\n'); // code = code.replace(/(^[\s]*)sequenceDiagram[ \t]*\n[\s]*autonumber[ \t]*\n/, '$1sequenceDiagram\n');
}
return [code, lang];
}
/**
* 包裹代码块,解决单行代码超出长度
* @param {string} $code
* @param {string} lang
*/
}, {
key: "wrapCode",
value: function wrapCode($code, lang) {
var _context10, _context11;
return concat$5(_context10 = concat$5(_context11 = "<code class=\"language-".concat(lang)).call(_context11, this.wrap ? ' wrap' : '', "\">")).call(_context10, $code, "</code>");
}
/**
* 使用渲染引擎处理代码块
* @param {string} $code
* @param {string} $lang
* @param {string} sign
* @param {number} lines
*/
}, {
key: "renderCodeBlock",
value: function renderCodeBlock($code, $lang, sign, lines) {
var _context12, _context13, _context14, _context15, _context16;
var cacheCode = $code;
var lang = $lang;
if (this.customHighlighter) {
// 平台自定义代码块样式
cacheCode = this.customHighlighter(cacheCode, lang);
} else {
// 默认使用prism渲染代码块
if (!lang || !prismCore.languages[lang]) lang = 'javascript'; // 如果没有写语言默认用js样式渲染
cacheCode = prismCore.highlight(cacheCode, prismCore.languages[lang], lang);
cacheCode = this.renderLineNumber(cacheCode);
}
cacheCode = concat$5(_context12 = concat$5(_context13 = concat$5(_context14 = concat$5(_context15 = concat$5(_context16 = "<div data-sign=\"".concat(sign, "\" data-type=\"codeBlock\" data-lines=\"")).call(_context16, lines, "\">\n ")).call(_context15, getCodePreviewLangSelectElement($lang), "\n ")).call(_context14, this.copyCode ? '<div class="cherry-copy-code-block" style="display:none;"><i class="ch-icon ch-icon-copy" title="copy"></i></div>' : '', "\n <pre class=\"language-")).call(_context13, lang, "\">")).call(_context12, this.wrapCode(cacheCode, lang), "</pre>\n </div>");
return cacheCode;
}
/**
* 获取缩进代码块语法的正则
* 缩进代码块必须要以连续两个以上的换行符开头
*/
}, {
key: "$getIndentedCodeReg",
value: function $getIndentedCodeReg() {
var ret = {
begin: '(?:^|\\n\\s*\\n)(?: {4}|\\t)',
end: '(?=$|\\n( {0,3}[^ \\t\\n]|\\n[^ \\t\\n]))',
content: '([\\s\\S]+?)'
};
return new RegExp(ret.begin + ret.content + ret.end, 'g');
}
/**
* 生成缩进代码块(没有行号、没有代码高亮)
*/
}, {
key: "$getIndentCodeBlock",
value: function $getIndentCodeBlock(str) {
var _this2 = this;
if (!this.indentedCodeBlock) {
return str;
}
return this.$recoverCodeInIndent(str).replace(this.$getIndentedCodeReg(), function (match, code) {
var _context17, _context18;
var lineCount = (match.match(/\n/g) || []).length;
var sign = _this2.$engine.md5(match);
var html = concat$5(_context17 = concat$5(_context18 = "<pre data-sign=\"".concat(sign, "\" data-lines=\"")).call(_context18, lineCount, "\"><code>")).call(_context17, escapeHTMLSpecialChar(code.replace(/\n( {4}|\t)/g, '\n')), "</code></pre>"); // return this.getCacheWithSpace(this.pushCache(html), match, true);
return prependLineFeedForParagraph(match, _this2.pushCache(html, sign, lineCount));
});
}
/**
* 预处理缩进代码块,将缩进代码块里的高亮代码块和行内代码进行占位处理
*/
}, {
key: "$replaceCodeInIndent",
value: function $replaceCodeInIndent(str) {
if (!this.indentedCodeBlock) {
return str;
}
return str.replace(this.$getIndentedCodeReg(), function (match) {
return match.replace(/`/g, '~~~IndentCode');
});
}
/**
* 恢复预处理的内容
*/
}, {
key: "$recoverCodeInIndent",
value: function $recoverCodeInIndent(str) {
if (!this.indentedCodeBlock) {
return str;
}
return str.replace(this.$getIndentedCodeReg(), function (match) {
return match.replace(/~~~IndentCode/g, '`');
});
}
}, {
key: "beforeMakeHtml",
value: function beforeMakeHtml(str, sentenceMakeFunc, markdownParams) {
var _this3 = this;
var $str = str; // 预处理缩进代码块
$str = this.$replaceCodeInIndent($str);
$str = $str.replace(this.RULE.reg, function (match, leadingContent, leadingContentBlockQuote, begin, lang, code) {
var _leadingContent$match, _leadingContent$match2, _context20;
function addBlockQuoteSignToResult(result) {
if (leadingContentBlockQuote) {
var regex = new RegExp("^\n*", '');
var leadingNewline = result.match(regex)[0]; // eslint-disable-next-line no-param-reassign
result = leadingNewline + leadingContentBlockQuote + result.replace(regex, function (_) {
return '';
});
}
return result;
}
var $code = code;
var _this3$computeLines = _this3.computeLines(match, leadingContent, code),
sign = _this3$computeLines.sign,
lines = _this3$computeLines.lines; // 从缓存中获取html
var cacheCode = _this3.$codeCache(sign);
if (cacheCode && cacheCode !== '') {
// 别忘了把 ">"(引用块)加回来
var _result = _this3.getCacheWithSpace(_this3.pushCache(cacheCode, sign, lines), match);
return addBlockQuoteSignToResult(_result);
}
$code = _this3.$recoverCodeInIndent($code);
$code = $code.replace(/~D/g, '$');
$code = $code.replace(/~T/g, '~');
/** 处理缩进 - start: 当首行反引号前存在多个空格缩进时,代码内容要相应去除相同数量的空格 */
var indentSpaces = (_leadingContent$match = leadingContent === null || leadingContent === void 0 ? void 0 : (_leadingContent$match2 = leadingContent.match(/[ ]/g)) === null || _leadingContent$match2 === void 0 ? void 0 : _leadingContent$match2.length) !== null && _leadingContent$match !== void 0 ? _leadingContent$match : 0;
if (indentSpaces > 0) {
var regex = new RegExp("(^|\\n)[ ]{1,".concat(indentSpaces, "}"), 'g');
$code = $code.replace(regex, '$1');
}
/** 处理缩进 - end */
// 如果本代码块处于一个引用块(形如 "> " 或 "> > ")中,那么需要从代码中每一行去掉引用块的符号
if (leadingContentBlockQuote) {
var _regex = new RegExp("(^|\\n)".concat(leadingContentBlockQuote), 'g');
$code = $code.replace(_regex, '$1');
} // 未命中缓存,执行渲染
var $lang = trim$3(lang).call(lang); // 如果是公式关键字,则直接返回
if (/^(math|katex|latex)$/i.test($lang) && !_this3.isInternalCustomLangCovered($lang)) {
var _context19;
var prefix = match.match(/^\s*/g); // ~D为经编辑器中间转义后的$code结尾包含结束```前的所有换行符,所以不需要补换行
return concat$5(_context19 = "".concat(prefix, "~D~D\n")).call(_context19, $code, "~D~D"); // 提供公式语法供公式钩子解析
}
var _this3$appendMermaid = _this3.appendMermaid($code, $lang);
var _this3$appendMermaid2 = _slicedToArray(_this3$appendMermaid, 2);
$code = _this3$appendMermaid2[0];
$lang = _this3$appendMermaid2[1];
// 自定义语言渲染,可覆盖内置的自定义语言逻辑
if (indexOf$8(_context20 = _this3.customLang).call(_context20, $lang.toLowerCase()) !== -1) {
cacheCode = _this3.parseCustomLanguage($lang, $code, {
lines: lines,
sign: sign
});
if (cacheCode && cacheCode !== '') {
_this3.$codeCache(sign, cacheCode);
return _this3.getCacheWithSpace(_this3.pushCache(cacheCode, sign, lines), match);
} // 渲染出错则按正常code进行渲染
} // $code = this.$replaceSpecialChar($code);
$code = $code.replace(/~X/g, '\\`');
cacheCode = _this3.renderCodeBlock($code, $lang, sign, lines);
cacheCode = cacheCode.replace(/\\/g, '\\\\');
cacheCode = _this3.$codeCache(sign, cacheCode);
var result = _this3.getCacheWithSpace(_this3.pushCache(cacheCode, sign, lines), match);
return addBlockQuoteSignToResult(result);
}); // 表格里处理行内代码让一个td里的行内代码语法生效让跨td的行内代码语法失效
$str = $str.replace(getTableRule(true), function (whole) {
var _context21;
return map$3(_context21 = whole.split('|')).call(_context21, function (oneTd) {
return _this3.makeInlineCode(oneTd);
}).join('|').replace(/`/g, '\\`');
}); // 为了避免InlineCode被HtmlBlock转义需要在这里提前缓存
// InlineBlock只需要在afterMakeHtml还原即可
$str = this.makeInlineCode($str); // 处理缩进代码块
$str = this.$getIndentCodeBlock($str);
return $str;
}
}, {
key: "makeInlineCode",
value: function makeInlineCode(str) {
var _this4 = this;
var $str = str;
if (this.INLINE_CODE_REGEX.test($str)) {
$str = $str.replace(/\\`/g, '~~not~inlineCode');
$str = $str.replace(this.INLINE_CODE_REGEX, function (match, syntax, code) {
if (trim$3(code).call(code) === '`') {
return match;
}
var $code = code.replace(/~~not~inlineCode/g, '\\`');
$code = _this4.$replaceSpecialChar($code);
$code = $code.replace(/\\/g, '\\\\');
var html = "<code>".concat(escapeHTMLSpecialChar($code), "</code>");
var sign = _this4.$engine.md5(html);
CodeBlock.inlineCodeCache[sign] = html;
return "~~CODE".concat(sign, "$");
});
$str = $str.replace(/~~not~inlineCode/g, '\\`');
}
return $str;
}
}, {
key: "makeHtml",
value: function makeHtml(str) {
return str;
}
}, {
key: "$replaceSpecialChar",
value: function $replaceSpecialChar(str) {
var $str = str.replace(/~Q/g, '\\~');
$str = $str.replace(/~Y/g, '\\!');
$str = $str.replace(/~Z/g, '\\#');
$str = $str.replace(/~&/g, '\\&');
$str = $str.replace(/~K/g, '\\/'); // $str = $str.replace(/~D/g, '$');
// $str = $str.replace(/~T/g, '~');
return $str;
}
}, {
key: "rule",
value: function rule() {
return getCodeBlockRule();
}
}, {
key: "mounted",
value: function mounted(dom) {// prettyPrint.prettyPrint();
}
}]);
return CodeBlock;
}(ParagraphBase);
_defineProperty(CodeBlock, "HOOK_NAME", 'codeBlock');
_defineProperty(CodeBlock, "inlineCodeCache", {});
function _createSuper$9(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$9(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$9() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var InlineCode = /*#__PURE__*/function (_ParagraphBase) {
_inherits(InlineCode, _ParagraphBase);
var _super = _createSuper$9(InlineCode);
function InlineCode() {
_classCallCheck(this, InlineCode);
return _super.apply(this, arguments);
}
_createClass(InlineCode, [{
key: "makeHtml",
value: // constructor() {
// super();
// }
function makeHtml(str) {
return str;
}
}, {
key: "afterMakeHtml",
value: function afterMakeHtml(str) {
var $str = str;
if (keys$3(CodeBlock.inlineCodeCache).length > 0) {
$str = $str.replace(/~~CODE([0-9a-zA-Z]+)\$/g, function (match, sign) {
return CodeBlock.inlineCodeCache[sign];
});
CodeBlock.inlineCodeCache = {};
}
return $str;
}
}, {
key: "rule",
value: function rule() {
var ret = {
begin: '(`+)[ ]*',
end: '[ ]*\\1',
content: '(.+?(?:\\n.+?)*?)'
};
ret.reg = compileRegExp(ret, 'g');
return ret;
}
}]);
return InlineCode;
}(ParagraphBase);
_defineProperty(InlineCode, "HOOK_NAME", 'inlineCode');
var crypt = createCommonjsModule(function (module) {
(function() {
var base64map
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
crypt = {
// Bit-wise rotation left
rotl: function(n, b) {
return (n << b) | (n >>> (32 - b));
},
// Bit-wise rotation right
rotr: function(n, b) {
return (n << (32 - b)) | (n >>> b);
},
// Swap big-endian to little-endian and vice versa
endian: function(n) {
// If number given, swap endian
if (n.constructor == Number) {
return crypt.rotl(n, 8) & 0x00FF00FF | crypt.rotl(n, 24) & 0xFF00FF00;
}
// Else, assume array and swap all items
for (var i = 0; i < n.length; i++)
n[i] = crypt.endian(n[i]);
return n;
},
// Generate an array of any length of random bytes
randomBytes: function(n) {
for (var bytes = []; n > 0; n--)
bytes.push(Math.floor(Math.random() * 256));
return bytes;
},
// Convert a byte array to big-endian 32-bit words
bytesToWords: function(bytes) {
for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8)
words[b >>> 5] |= bytes[i] << (24 - b % 32);
return words;
},
// Convert big-endian 32-bit words to a byte array
wordsToBytes: function(words) {
for (var bytes = [], b = 0; b < words.length * 32; b += 8)
bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);
return bytes;
},
// Convert a byte array to a hex string
bytesToHex: function(bytes) {
for (var hex = [], i = 0; i < bytes.length; i++) {
hex.push((bytes[i] >>> 4).toString(16));
hex.push((bytes[i] & 0xF).toString(16));
}
return hex.join('');
},
// Convert a hex string to a byte array
hexToBytes: function(hex) {
for (var bytes = [], c = 0; c < hex.length; c += 2)
bytes.push(parseInt(hex.substr(c, 2), 16));
return bytes;
},
// Convert a byte array to a base-64 string
bytesToBase64: function(bytes) {
for (var base64 = [], i = 0; i < bytes.length; i += 3) {
var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
for (var j = 0; j < 4; j++)
if (i * 8 + j * 6 <= bytes.length * 8)
base64.push(base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F));
else
base64.push('=');
}
return base64.join('');
},
// Convert a base-64 string to a byte array
base64ToBytes: function(base64) {
// Remove non-base-64 characters
base64 = base64.replace(/[^A-Z0-9+\/]/ig, '');
for (var bytes = [], i = 0, imod4 = 0; i < base64.length;
imod4 = ++i % 4) {
if (imod4 == 0) continue;
bytes.push(((base64map.indexOf(base64.charAt(i - 1))
& (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2))
| (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2)));
}
return bytes;
}
};
module.exports = crypt;
})();
});
var charenc = {
// UTF-8 encoding
utf8: {
// Convert a string to a byte array
stringToBytes: function(str) {
return charenc.bin.stringToBytes(unescape(encodeURIComponent(str)));
},
// Convert a byte array to a string
bytesToString: function(bytes) {
return decodeURIComponent(escape(charenc.bin.bytesToString(bytes)));
}
},
// Binary encoding
bin: {
// Convert a string to a byte array
stringToBytes: function(str) {
for (var bytes = [], i = 0; i < str.length; i++)
bytes.push(str.charCodeAt(i) & 0xFF);
return bytes;
},
// Convert a byte array to a string
bytesToString: function(bytes) {
for (var str = [], i = 0; i < bytes.length; i++)
str.push(String.fromCharCode(bytes[i]));
return str.join('');
}
}
};
var charenc_1 = charenc;
/*!
* Determine if an object is a Buffer
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
// The _isBuffer check is for Safari 5-7 support, because it's missing
// Object.prototype.constructor. Remove this eventually
var isBuffer_1$1 = function (obj) {
return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
};
function isBuffer (obj) {
return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
}
// For Node v0.10 support. Remove this eventually.
function isSlowBuffer (obj) {
return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
}
var md5 = createCommonjsModule(function (module) {
(function(){
var crypt$1 = crypt,
utf8 = charenc_1.utf8,
isBuffer = isBuffer_1$1,
bin = charenc_1.bin,
// The core
md5 = function (message, options) {
// Convert to byte array
if (message.constructor == String)
if (options && options.encoding === 'binary')
message = bin.stringToBytes(message);
else
message = utf8.stringToBytes(message);
else if (isBuffer(message))
message = Array.prototype.slice.call(message, 0);
else if (!Array.isArray(message) && message.constructor !== Uint8Array)
message = message.toString();
// else, assume byte array already
var m = crypt$1.bytesToWords(message),
l = message.length * 8,
a = 1732584193,
b = -271733879,
c = -1732584194,
d = 271733878;
// Swap endian
for (var i = 0; i < m.length; i++) {
m[i] = ((m[i] << 8) | (m[i] >>> 24)) & 0x00FF00FF |
((m[i] << 24) | (m[i] >>> 8)) & 0xFF00FF00;
}
// Padding
m[l >>> 5] |= 0x80 << (l % 32);
m[(((l + 64) >>> 9) << 4) + 14] = l;
// Method shortcuts
var FF = md5._ff,
GG = md5._gg,
HH = md5._hh,
II = md5._ii;
for (var i = 0; i < m.length; i += 16) {
var aa = a,
bb = b,
cc = c,
dd = d;
a = FF(a, b, c, d, m[i+ 0], 7, -680876936);
d = FF(d, a, b, c, m[i+ 1], 12, -389564586);
c = FF(c, d, a, b, m[i+ 2], 17, 606105819);
b = FF(b, c, d, a, m[i+ 3], 22, -1044525330);
a = FF(a, b, c, d, m[i+ 4], 7, -176418897);
d = FF(d, a, b, c, m[i+ 5], 12, 1200080426);
c = FF(c, d, a, b, m[i+ 6], 17, -1473231341);
b = FF(b, c, d, a, m[i+ 7], 22, -45705983);
a = FF(a, b, c, d, m[i+ 8], 7, 1770035416);
d = FF(d, a, b, c, m[i+ 9], 12, -1958414417);
c = FF(c, d, a, b, m[i+10], 17, -42063);
b = FF(b, c, d, a, m[i+11], 22, -1990404162);
a = FF(a, b, c, d, m[i+12], 7, 1804603682);
d = FF(d, a, b, c, m[i+13], 12, -40341101);
c = FF(c, d, a, b, m[i+14], 17, -1502002290);
b = FF(b, c, d, a, m[i+15], 22, 1236535329);
a = GG(a, b, c, d, m[i+ 1], 5, -165796510);
d = GG(d, a, b, c, m[i+ 6], 9, -1069501632);
c = GG(c, d, a, b, m[i+11], 14, 643717713);
b = GG(b, c, d, a, m[i+ 0], 20, -373897302);
a = GG(a, b, c, d, m[i+ 5], 5, -701558691);
d = GG(d, a, b, c, m[i+10], 9, 38016083);
c = GG(c, d, a, b, m[i+15], 14, -660478335);
b = GG(b, c, d, a, m[i+ 4], 20, -405537848);
a = GG(a, b, c, d, m[i+ 9], 5, 568446438);
d = GG(d, a, b, c, m[i+14], 9, -1019803690);
c = GG(c, d, a, b, m[i+ 3], 14, -187363961);
b = GG(b, c, d, a, m[i+ 8], 20, 1163531501);
a = GG(a, b, c, d, m[i+13], 5, -1444681467);
d = GG(d, a, b, c, m[i+ 2], 9, -51403784);
c = GG(c, d, a, b, m[i+ 7], 14, 1735328473);
b = GG(b, c, d, a, m[i+12], 20, -1926607734);
a = HH(a, b, c, d, m[i+ 5], 4, -378558);
d = HH(d, a, b, c, m[i+ 8], 11, -2022574463);
c = HH(c, d, a, b, m[i+11], 16, 1839030562);
b = HH(b, c, d, a, m[i+14], 23, -35309556);
a = HH(a, b, c, d, m[i+ 1], 4, -1530992060);
d = HH(d, a, b, c, m[i+ 4], 11, 1272893353);
c = HH(c, d, a, b, m[i+ 7], 16, -155497632);
b = HH(b, c, d, a, m[i+10], 23, -1094730640);
a = HH(a, b, c, d, m[i+13], 4, 681279174);
d = HH(d, a, b, c, m[i+ 0], 11, -358537222);
c = HH(c, d, a, b, m[i+ 3], 16, -722521979);
b = HH(b, c, d, a, m[i+ 6], 23, 76029189);
a = HH(a, b, c, d, m[i+ 9], 4, -640364487);
d = HH(d, a, b, c, m[i+12], 11, -421815835);
c = HH(c, d, a, b, m[i+15], 16, 530742520);
b = HH(b, c, d, a, m[i+ 2], 23, -995338651);
a = II(a, b, c, d, m[i+ 0], 6, -198630844);
d = II(d, a, b, c, m[i+ 7], 10, 1126891415);
c = II(c, d, a, b, m[i+14], 15, -1416354905);
b = II(b, c, d, a, m[i+ 5], 21, -57434055);
a = II(a, b, c, d, m[i+12], 6, 1700485571);
d = II(d, a, b, c, m[i+ 3], 10, -1894986606);
c = II(c, d, a, b, m[i+10], 15, -1051523);
b = II(b, c, d, a, m[i+ 1], 21, -2054922799);
a = II(a, b, c, d, m[i+ 8], 6, 1873313359);
d = II(d, a, b, c, m[i+15], 10, -30611744);
c = II(c, d, a, b, m[i+ 6], 15, -1560198380);
b = II(b, c, d, a, m[i+13], 21, 1309151649);
a = II(a, b, c, d, m[i+ 4], 6, -145523070);
d = II(d, a, b, c, m[i+11], 10, -1120210379);
c = II(c, d, a, b, m[i+ 2], 15, 718787259);
b = II(b, c, d, a, m[i+ 9], 21, -343485551);
a = (a + aa) >>> 0;
b = (b + bb) >>> 0;
c = (c + cc) >>> 0;
d = (d + dd) >>> 0;
}
return crypt$1.endian([a, b, c, d]);
};
// Auxiliary functions
md5._ff = function (a, b, c, d, x, s, t) {
var n = a + (b & c | ~b & d) + (x >>> 0) + t;
return ((n << s) | (n >>> (32 - s))) + b;
};
md5._gg = function (a, b, c, d, x, s, t) {
var n = a + (b & d | c & ~d) + (x >>> 0) + t;
return ((n << s) | (n >>> (32 - s))) + b;
};
md5._hh = function (a, b, c, d, x, s, t) {
var n = a + (b ^ c ^ d) + (x >>> 0) + t;
return ((n << s) | (n >>> (32 - s))) + b;
};
md5._ii = function (a, b, c, d, x, s, t) {
var n = a + (c ^ (b | ~d)) + (x >>> 0) + t;
return ((n << s) | (n >>> (32 - s))) + b;
};
// Package private blocksize
md5._blocksize = 16;
md5._digestsize = 16;
module.exports = function (message, options) {
if (message === undefined || message === null)
throw new Error('Illegal argument ' + message);
var digestbytes = crypt$1.wordsToBytes(md5(message, options));
return options && options.asBytes ? digestbytes :
options && options.asString ? bin.bytesToString(digestbytes) :
crypt$1.bytesToHex(digestbytes);
};
})();
});
var urlCache = {};
var cherryInnerLinkRegex = /^cherry-inner:\/\/([0-9a-f]+)$/i;
function urlProcessorProxy(urlProcessor) {
return function (url, srcType) {
if (UrlCache.isInnerLink(url)) {
var newUrl = urlProcessor(UrlCache.get(url), srcType);
return UrlCache.replace(url, newUrl);
}
return urlProcessor(url, srcType);
};
}
var UrlCache = /*#__PURE__*/function () {
function UrlCache() {
_classCallCheck(this, UrlCache);
}
_createClass(UrlCache, null, [{
key: "isInnerLink",
value:
/**
* 判断url是否Cherry的内部链接
* @param {string} url 要检测的URL
* @returns
*/
function isInnerLink(url) {
return cherryInnerLinkRegex.test(url);
}
/**
* 缓存url为内部链接主要用于缩短超长链接避免正则超时
* @param {string} url 要转换为内部链接的URL
* @returns
*/
}, {
key: "set",
value: function set(url) {
var urlSign = md5(url);
urlCache[urlSign] = url;
return "cherry-inner://".concat(urlSign);
}
/**
* 获取原始链接
* @param {string} innerUrl 内部链接
* @returns
*/
}, {
key: "get",
value: function get(innerUrl) {
var _innerUrl$match;
var _ref = (_innerUrl$match = innerUrl.match(cherryInnerLinkRegex)) !== null && _innerUrl$match !== void 0 ? _innerUrl$match : [],
_ref2 = _slicedToArray(_ref, 2),
urlSign = _ref2[1];
if (!urlSign) {
return;
}
return urlCache[urlSign];
}
/**
* 替换指定内部链接的真实地址
* @param {string} innerUrl 原始内部链接
* @param {string} newUrl 需要替换的链接
*/
}, {
key: "replace",
value: function replace(innerUrl, newUrl) {
var _innerUrl$match2;
var _ref3 = (_innerUrl$match2 = innerUrl.match(cherryInnerLinkRegex)) !== null && _innerUrl$match2 !== void 0 ? _innerUrl$match2 : [],
_ref4 = _slicedToArray(_ref3, 2),
urlSign = _ref4[1];
if (!urlSign) {
return;
}
urlCache[urlSign] = newUrl;
return innerUrl;
}
/**
* 替换所有内部链接为原始的真实地址
* @param {string} html 包含 cherry-inner 协议地址的 html 文本
*/
}, {
key: "restoreAll",
value: function restoreAll(html) {
var cherryInnerLinkRegex = /cherry-inner:\/\/([0-9a-f]+)/gi;
var $html = html.replace(cherryInnerLinkRegex, function (match) {
var originalUrl = UrlCache.get(match);
return originalUrl || match;
});
return $html;
}
/**
* 清空缓存
*/
}, {
key: "clear",
value: function clear() {
urlCache = {};
}
}]);
return UrlCache;
}();
function _createSuper$a(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$a(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$a() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Link = /*#__PURE__*/function (_SyntaxBase) {
_inherits(Link, _SyntaxBase);
var _super = _createSuper$a(Link);
function Link(_ref) {
var _this;
var config = _ref.config,
globalConfig = _ref.globalConfig;
_classCallCheck(this, Link);
_this = _super.call(this, {
config: config
});
_this.urlProcessor = globalConfig.urlProcessor; // eslint-disable-next-line no-nested-ternary
_this.target = config.target ? "target=\"".concat(config.target, "\"") : !!config.openNewPage ? 'target="_blank"' : '';
_this.rel = config.rel ? "rel=\"".concat(config.rel, "\"") : '';
return _this;
}
/**
* 校验link中text的方括号是否符合规则
* @param {string} rawText
*/
_createClass(Link, [{
key: "checkBrackets",
value: function checkBrackets(rawText) {
var stack = [];
var text = "[".concat(rawText, "]"); // 前方有奇数个\当前字符被转义
var checkEscape = function checkEscape(place) {
return slice$7(text).call(text, 0, place).match(/\\*$/)[0].length & 1;
};
for (var i = text.length - 1; text[i]; i--) {
if (i === text.length - 1 && checkEscape(i)) break;
if (text[i] === ']' && !checkEscape(i)) stack.push(']');
if (text[i] === '[' && !checkEscape(i)) {
stack.pop();
if (!stack.length) {
return {
isValid: true,
coreText: slice$7(text).call(text, i + 1, text.length - 1),
extraLeadingChar: slice$7(text).call(text, 0, i)
};
}
}
}
return {
isValid: false,
// 方括号匹配不上
coreText: rawText,
extraLeadingChar: ''
};
}
/**
*
* @param {string} match 匹配的完整字符串
* @param {string} leadingChar 正则分组一:前置字符
* @param {string} text 正则分组二:链接文字
* @param {string|undefined} link 正则分组三链接URL
* @param {string|undefined} title 正则分组四链接title
* @param {string|undefined} ref 正则分组五:链接引用
* @param {string|undefined} target 正则分组六:新窗口打开
* @returns
*/
}, {
key: "toHtml",
value: function toHtml(match, leadingChar, text, link, title, ref, target) {
var refType = typeof link === 'undefined' ? 'ref' : 'url';
var attrs = '';
if (refType === 'ref') {
// 全局引用理应在CommentReference中被替换没有被替换说明没有定义引用项
return match;
}
if (refType === 'url') {
var _context5;
var _this$checkBrackets = this.checkBrackets(text),
isValid = _this$checkBrackets.isValid,
coreText = _this$checkBrackets.coreText,
extraLeadingChar = _this$checkBrackets.extraLeadingChar;
if (!isValid) return match;
attrs = title && trim$3(title).call(title) !== '' ? " title=\"".concat(escapeHTMLSpecialChar(title.replace(/["']/g, '')), "\"") : '';
if (target) {
attrs += " target=\"".concat(target.replace(/{target\s*=\s*(.*?)}/, '$1'), "\"");
} else if (this.target) {
attrs += " ".concat(this.target);
}
var processedURL = trim$3(link).call(link).replace(/~1D/g, '~D'); // 还原替换的$符号
var processedText = coreText.replace(/~1D/g, '~D'); // 还原替换的$符号
// text可能是html标签依赖htmlBlock进行处理
if (isValidScheme(processedURL)) {
var _context, _context2, _context3, _context4;
processedURL = this.urlProcessor(processedURL, 'link');
processedURL = encodeURIOnce(processedURL);
return concat$5(_context = concat$5(_context2 = concat$5(_context3 = concat$5(_context4 = "".concat(leadingChar + extraLeadingChar, "<a href=\"")).call(_context4, UrlCache.set(processedURL), "\" ")).call(_context3, this.rel, " ")).call(_context2, attrs, ">")).call(_context, processedText, "</a>");
}
return concat$5(_context5 = "".concat(leadingChar + extraLeadingChar, "<span>")).call(_context5, text, "</span>");
} // should never happen
return match;
}
}, {
key: "toStdMarkdown",
value: function toStdMarkdown(match) {
return match;
}
}, {
key: "makeHtml",
value: function makeHtml(str) {
var $str = str.replace(this.RULE.reg, function (match) {
return match.replace(/~D/g, '~1D');
});
if (isLookbehindSupported()) {
var _context6;
$str = $str.replace(this.RULE.reg, bind$5(_context6 = this.toHtml).call(_context6, this));
} else {
var _context7;
$str = replaceLookbehind($str, this.RULE.reg, bind$5(_context7 = this.toHtml).call(_context7, this), true, 1);
}
$str = $str.replace(this.RULE.reg, function (match) {
return match.replace(/~1D/g, '~D');
});
return $str;
}
}, {
key: "rule",
value: function rule() {
// (?<protocol>\\w+:)\\/\\/
var ret = {
// lookbehind启用分组是为了和不兼容lookbehind的场景共用一个回调
begin: isLookbehindSupported() ? '((?<!\\\\))' : '(^|[^\\\\])',
content: ['\\[([^\\n]+?)\\]', // ?<text>
'[ \\t]*', // any spaces
"".concat('(?:' + '\\(' +
/**
* allow double quotes
* e.g.
* [link](") ⭕️ valid
* [link]("") ⭕️ valid
* [link](" ") ❌ invalid
*/
'([^\\s)]+)' + // ?<link> url
'(?:[ \\t]((?:".*?")|(?:\'.*?\')))?' + // ?<title> optional
'\\)' + '|' + // or
'\\[(').concat(NOT_ALL_WHITE_SPACES_INLINE, ")\\]") + // ?<ref> global ref
')', '(\\{target\\s*=\\s*(_blank|_parent|_self|_top)\\})?'].join(''),
end: ''
}; // let ret = {begin:'((^|[^\\\\])\\*\\*|([\\s]|^)__)',
// end:'(\\*\\*([\\s\\S]|$)|__([\\s]|$))', content:'([^\\n]+?)'};
ret.reg = compileRegExp(ret, 'g');
return ret;
}
}]);
return Link;
}(SyntaxBase);
_defineProperty(Link, "HOOK_NAME", 'link');
var RangeError$2 = global_1.RangeError;
// `String.prototype.repeat` method implementation
// https://tc39.es/ecma262/#sec-string.prototype.repeat
var stringRepeat = function repeat(count) {
var str = toString_1(requireObjectCoercible(this));
var result = '';
var n = toIntegerOrInfinity(count);
if (n < 0 || n == Infinity) throw RangeError$2('Wrong number of repetitions');
for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) result += str;
return result;
};
// `String.prototype.repeat` method
// https://tc39.es/ecma262/#sec-string.prototype.repeat
_export({ target: 'String', proto: true }, {
repeat: stringRepeat
});
var repeat = entryVirtual('String').repeat;
var StringPrototype$2 = String.prototype;
var repeat$1 = function (it) {
var own = it.repeat;
return typeof it == 'string' || it === StringPrototype$2
|| (objectIsPrototypeOf(StringPrototype$2, it) && own === StringPrototype$2.repeat) ? repeat : own;
};
var repeat$2 = repeat$1;
var repeat$3 = repeat$2;
function _createSuper$b(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$b(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$b() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Emphasis = /*#__PURE__*/function (_SyntaxBase) {
_inherits(Emphasis, _SyntaxBase);
var _super = _createSuper$b(Emphasis);
function Emphasis() {
var _this;
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
config: undefined
},
config = _ref.config;
_classCallCheck(this, Emphasis);
_this = _super.call(this, {
config: config
});
if (!config) {
return _possibleConstructorReturn(_this);
}
_this.allowWhitespace = !!config.allowWhitespace;
return _this;
}
_createClass(Emphasis, [{
key: "makeHtml",
value: function makeHtml(str, sentenceMakeFunc) {
var converAsterisk = function converAsterisk(match, leading, symbol, text) {
var _context, _context2, _context3, _context4, _context5;
var tagType = symbol.length % 2 === 1 ? 'em' : 'strong';
var repeat = Math.floor(symbol.length / 2);
var prefix = repeat$3(_context = '<strong>').call(_context, repeat);
var suffix = repeat$3(_context2 = '</strong>').call(_context2, repeat);
if (tagType === 'em') {
prefix += '<em>';
suffix = "</em>".concat(suffix);
} // 这里转义_是为了避免跨标签识别
var result = concat$5(_context3 = concat$5(_context4 = concat$5(_context5 = "".concat(leading)).call(_context5, prefix)).call(_context4, sentenceMakeFunc(text).html.replace(/_/g, '~U'))).call(_context3, suffix);
return result;
};
var $str = str;
if (this.allowWhitespace) {
$str = $str.replace(/(^|\n[\s]*)(\*)([^\s*](?:.*?)(?:(?:\n.*?)*?))\*/g, converAsterisk);
$str = $str.replace(/(^|\n[\s]*)(\*{2,})((?:.*?)(?:(?:\n.*?)*?))\2/g, converAsterisk);
$str = $str.replace(/([^\n*\\\s][ ]*)(\*+)((?:.*?)(?:(?:\n.*?)*?))\2/g, converAsterisk);
} else {
$str = $str.replace(this.RULE.asterisk.reg, converAsterisk);
}
$str = $str.replace(this.RULE.underscore.reg, function (match, leading, symbol, text, index, string) {
var _context6, _context7, _context8, _context9, _context10;
if (trim$3(text).call(text) === '') {
return match;
}
var tagType = symbol.length % 2 === 1 ? 'em' : 'strong';
var repeat = Math.floor(symbol.length / 2);
var prefix = repeat$3(_context6 = '<strong>').call(_context6, repeat);
var suffix = repeat$3(_context7 = '</strong>').call(_context7, repeat);
var innerText = sentenceMakeFunc(text).html;
if (tagType === 'em') {
// if(/<em>.*?<\/em>/.test(innerText)) {
// prefix += symbol;
// suffix = symbol + suffix;
// } else {
prefix += '<em>';
suffix = "</em>".concat(suffix); // }
}
var result = concat$5(_context8 = concat$5(_context9 = concat$5(_context10 = "".concat(leading)).call(_context10, prefix)).call(_context9, innerText)).call(_context8, suffix);
return result;
});
return $str.replace(/~U/g, '_');
}
}, {
key: "test",
value: function test(str, flavor) {
return this.RULE[flavor].reg && this.RULE[flavor].reg.test(str);
}
}, {
key: "rule",
value: function rule() {
var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
config: undefined
},
config = _ref2.config;
var allowWhitespace = config ? !!config.allowWhitespace : false;
var REGEX = allowWhitespace ? ALLOW_WHITESPACE_MULTILINE : DO_NOT_STARTS_AND_END_WITH_SPACES_MULTILINE_ALLOW_EMPTY;
var asterisk = {
begin: '(^|[^\\\\])(\\*+)',
// ?<leading>, ?<symbol>
content: "(".concat(REGEX, ")"),
// ?<text>
end: '\\2'
}; // UNDERSCORE_EMPHASIS_BORDER允许除下划线以外的「标点符号」和空格出现使用[^\w\S \t]或[\W\s]会有性能问题
var underscore = {
begin: "(^|".concat(UNDERSCORE_EMPHASIS_BOUNDARY, ")(_+)"),
// ?<leading>, ?<symbol>
content: "(".concat(REGEX, ")"),
// ?<text>
end: "\\2(?=".concat(UNDERSCORE_EMPHASIS_BOUNDARY, "|$)")
};
asterisk.reg = compileRegExp(asterisk, 'g');
underscore.reg = compileRegExp(underscore, 'g');
return {
asterisk: asterisk,
underscore: underscore
};
}
}]);
return Emphasis;
}(SyntaxBase);
_defineProperty(Emphasis, "HOOK_NAME", 'fontEmphasis');
function _createSuper$c(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$c(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$c() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 段落级语法
* 段落级语法可以具备以下特性:
* 1、排他性可以排除将当前语法之后的所有段落语法
* 2、可排序在../HooksConfig.js里设置排序顺序在前面的段落语法先渲染
* 3、可嵌套行内语法
*
* 段落级语法有以下义务:
* 1、维护签名签名用来实现预览区域的局部更新功能
* 2、维护行号行号用来实现编辑区和预览区同步滚动
* 每个段落语法负责计算上文的行号上文行号不是0就是1大于1会由BR语法计算行号
*/
var Paragraph = /*#__PURE__*/function (_ParagraphBase) {
_inherits(Paragraph, _ParagraphBase);
var _super = _createSuper$c(Paragraph);
function Paragraph(options) {
var _this;
_classCallCheck(this, Paragraph);
_this = _super.call(this);
_this.initBrReg(options.globalConfig.classicBr);
return _this;
}
/**
* 段落语法的核心渲染函数
* @param {string} str markdown源码
* @param {Function} sentenceMakeFunc 行内语法渲染器
* @returns {string} html内容
*/
_createClass(Paragraph, [{
key: "makeHtml",
value: function makeHtml(str, sentenceMakeFunc) {
var _this2 = this;
if (!this.test(str)) {
return str;
}
return str.replace(this.RULE.reg, function (match, preLines, content) {
var _context8;
if (_this2.isContainsCache(match, true)) {
return match;
} // 判断当前内容里是否包含段落渲染引擎暂存缓存关键字
var cacheMixedInMatches = _this2.isContainsCache(content);
var processor = function processor(p) {
var _context, _context2, _context3, _context4, _context5, _context6;
if (trim$3(p).call(p) === '') {
return '';
} // 调用行内语法获得段落的签名和对应html内容
var _sentenceMakeFunc = sentenceMakeFunc(p),
sign = _sentenceMakeFunc.sign,
html = _sentenceMakeFunc.html;
var domName = 'p'; // 如果包含html块级标签比如div、blockquote等则当前段落外层用div包裹反之用p包裹
var isContainBlockTest = new RegExp("<(".concat(blockNames, ")[^>]*>"), 'i');
if (isContainBlockTest.test(html)) {
domName = 'div';
} // 计算行号
var lines = _this2.getLineCount(p, p);
return concat$5(_context = concat$5(_context2 = concat$5(_context3 = concat$5(_context4 = concat$5(_context5 = concat$5(_context6 = "<".concat(domName, " data-sign=\"")).call(_context6, sign)).call(_context5, lines, "\" data-type=\"")).call(_context4, domName, "\" data-lines=\"")).call(_context3, lines, "\">")).call(_context2, _this2.$cleanParagraph(html), "</")).call(_context, domName, ">");
};
if (cacheMixedInMatches) {
var _context7;
return _this2.makeExcludingCached(concat$5(_context7 = "".concat(preLines)).call(_context7, content), processor);
}
return processor(concat$5(_context8 = "".concat(preLines)).call(_context8, content));
});
}
}, {
key: "rule",
value: function rule() {
var ret = {
begin: '(?:^|\\n)(\\n*)',
end: '(?=\\s*$|\\n\\n)',
content: '([\\s\\S]+?)'
};
ret.reg = new RegExp(ret.begin + ret.content + ret.end, 'g');
return ret;
}
}]);
return Paragraph;
}(ParagraphBase);
_defineProperty(Paragraph, "HOOK_NAME", 'normalParagraph');
var isDataDescriptor = function (descriptor) {
return descriptor !== undefined && (hasOwnProperty_1(descriptor, 'value') || hasOwnProperty_1(descriptor, 'writable'));
};
// `Reflect.get` method
// https://tc39.es/ecma262/#sec-reflect.get
function get$1(target, propertyKey /* , receiver */) {
var receiver = arguments.length < 3 ? target : arguments[2];
var descriptor, prototype;
if (anObject(target) === receiver) return target[propertyKey];
descriptor = objectGetOwnPropertyDescriptor.f(target, propertyKey);
if (descriptor) return isDataDescriptor(descriptor)
? descriptor.value
: descriptor.get === undefined ? undefined : functionCall(descriptor.get, receiver);
if (isObject(prototype = objectGetPrototypeOf(target))) return get$1(prototype, propertyKey, receiver);
}
_export({ target: 'Reflect', stat: true }, {
get: get$1
});
var get$2 = path.Reflect.get;
var get$3 = get$2;
var get$4 = get$3;
var get$5 = get$4;
var get$6 = get$5;
var get$7 = get$6;
var getOwnPropertyDescriptor$4 = getOwnPropertyDescriptor$2;
var getOwnPropertyDescriptor$5 = getOwnPropertyDescriptor$4;
var getOwnPropertyDescriptor$6 = getOwnPropertyDescriptor$5;
var getOwnPropertyDescriptor$7 = getOwnPropertyDescriptor$6;
var superPropBase = createCommonjsModule(function (module) {
function _superPropBase(object, property) {
while (!Object.prototype.hasOwnProperty.call(object, property)) {
object = getPrototypeOf$6(object);
if (object === null) break;
}
return object;
}
module.exports = _superPropBase, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(superPropBase);
var get$8 = createCommonjsModule(function (module) {
function _get() {
if (typeof Reflect !== "undefined" && get$7) {
module.exports = _get = get$7, module.exports.__esModule = true, module.exports["default"] = module.exports;
} else {
module.exports = _get = function _get(target, property, receiver) {
var base = superPropBase(target, property);
if (!base) return;
var desc = getOwnPropertyDescriptor$7(base, property);
if (desc.get) {
return desc.get.call(arguments.length < 3 ? target : receiver);
}
return desc.value;
}, module.exports.__esModule = true, module.exports["default"] = module.exports;
}
return _get.apply(this, arguments);
}
module.exports = _get, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
var _get = unwrapExports(get$8);
function _createSuper$d(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$d(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$d() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var ATX_HEADER = 'atx';
var SETEXT_HEADER = 'setext';
var toDashChars = /[\s\-_]/;
var alphabetic = /[A-Za-z]/;
var numeric = /[0-9]/;
var Header = /*#__PURE__*/function (_ParagraphBase) {
_inherits(Header, _ParagraphBase);
var _super = _createSuper$d(Header);
function Header() {
var _this;
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
config: undefined,
externals: undefined
},
externals = _ref.externals,
config = _ref.config;
_classCallCheck(this, Header);
_this = _super.call(this, {
needCache: true
});
_this.strict = config ? !!config.strict : true;
_this.RULE = _this.rule();
_this.headerIDCache = [];
_this.headerIDCounter = {};
_this.config = config || {}; // TODO: AllowCustomID
return _this;
}
_createClass(Header, [{
key: "$parseTitleText",
value: function $parseTitleText() {
var html = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
if (typeof html !== 'string') {
return '';
}
return html.replace(/<.*?>/g, '').replace(/&#60;/g, '<').replace(/&#62;/g, '>');
}
/**
* refer:
* @see https://github.com/vsch/flexmark-java/blob/8bf621924158dfed8b84120479c82704020a6927/flexmark
* /src/main/java/com/vladsch/flexmark/html/renderer/HeaderIdGenerator.java#L90-L113
*
* @param {string} headerText
* @param {boolean} [toLowerCase]
* @returns
*/
}, {
key: "$generateId",
value: function $generateId(headerText) {
var toLowerCase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var len = headerText.length;
var id = '';
for (var i = 0; i < len; i++) {
var c = headerText.charAt(i);
if (alphabetic.test(c)) {
id += toLowerCase ? c.toLowerCase() : c;
} else if (numeric.test(c)) {
id += c;
} else if (toDashChars.test(c)) {
id += id.length < 1 || id.charAt(id.length - 1) !== '-' ? '-' : '';
} else if (c.charCodeAt(0) > 255) {
// unicode
try {
id += encodeURIComponent(c);
} catch (error) {// empty
}
}
}
return id;
}
}, {
key: "generateIDNoDup",
value: function generateIDNoDup(headerText) {
var _context;
// 处理被引擎转换过的实体字符
var unescapedHeaderText = headerText.replace(/&#60;/g, '<').replace(/&#62;/g, '>');
var newId = this.$generateId(unescapedHeaderText, true);
var idIndex = indexOf$8(_context = this.headerIDCache).call(_context, newId);
if (idIndex !== -1) {
this.headerIDCounter[idIndex] += 1;
newId += "-".concat(this.headerIDCounter[idIndex] + 1);
} else {
var newIndex = this.headerIDCache.push(newId);
this.headerIDCounter[newIndex - 1] = 1;
}
return newId;
}
}, {
key: "$wrapHeader",
value: function $wrapHeader(text, level, dataLines, sentenceMakeFunc) {
var _context2, _context3, _context4, _context5, _context6, _context7;
// 需要经过一次escape
var processedText = sentenceMakeFunc(trim$3(text).call(text));
var html = processedText.html; // TODO: allowCustomID开关
// let htmlAttr = this.getAttributes(html);
// html = htmlAttr.str;
// let attrs = htmlAttr.attrs;
// console.log(attrs);
var customIDRegex = /\s+\{#([A-Za-z0-9-]+)\}$/; // ?<id>
var idMatch = html.match(customIDRegex);
var anchorID;
if (idMatch !== null) {
html = html.substring(0, idMatch.index);
var _idMatch = _slicedToArray(idMatch, 2);
anchorID = _idMatch[1];
}
var headerTextRaw = this.$parseTitleText(html);
if (!anchorID) {
var replaceFootNote = /~fn#([0-9]+)#/g;
anchorID = this.generateIDNoDup(headerTextRaw.replace(replaceFootNote, ''));
}
var safeAnchorID = "safe_".concat(anchorID); // transform header id to avoid being sanitized
var sign = this.$engine.md5(concat$5(_context2 = concat$5(_context3 = concat$5(_context4 = "".concat(level, "-")).call(_context4, processedText.sign, "-")).call(_context3, anchorID, "-")).call(_context2, dataLines));
var result = [concat$5(_context5 = concat$5(_context6 = concat$5(_context7 = "<h".concat(level, " id=\"")).call(_context7, safeAnchorID, "\" data-sign=\"")).call(_context6, sign, "\" data-lines=\"")).call(_context5, dataLines, "\">"), this.$getAnchor(anchorID), "".concat(html), "</h".concat(level, ">")].join('');
return {
html: result,
sign: "".concat(sign)
};
}
}, {
key: "$getAnchor",
value: function $getAnchor(anchorID) {
var anchorStyle = this.config.anchorStyle || 'default';
if (anchorStyle === 'none') {
return '';
}
return "<a class=\"anchor\" href=\"#".concat(anchorID, "\"></a>");
}
}, {
key: "beforeMakeHtml",
value: function beforeMakeHtml(str) {
var _this2 = this;
var $str = str; // atx 优先
if (this.test($str, ATX_HEADER)) {
$str = $str.replace(this.RULE[ATX_HEADER].reg, function (match, lines, level, text) {
if (trim$3(text).call(text) === '') {
return match;
}
return _this2.getCacheWithSpace(_this2.pushCache(match), match, true);
});
} // 按照目前的引擎每个hook只会执行一次所以需要并行执行替换
if (this.test($str, SETEXT_HEADER)) {
$str = $str.replace(this.RULE[SETEXT_HEADER].reg, function (match, lines, text) {
if (trim$3(text).call(text) === '' || _this2.isContainsCache(text)) {
return match;
}
return _this2.getCacheWithSpace(_this2.pushCache(match), match, true);
});
}
return $str;
}
}, {
key: "makeHtml",
value: function makeHtml(str, sentenceMakeFunc) {
var _this3 = this;
// 先还原
var $str = this.restoreCache(str); // atx 优先
if (this.test($str, ATX_HEADER)) {
$str = $str.replace(this.RULE[ATX_HEADER].reg, function (match, lines, level, text) {
// 其中有两行是beforeMake加上的
var lineCount = calculateLinesOfParagraph(lines, _this3.getLineCount(match.replace(/^\n+/, '')));
var $text = text.replace(/\s+#+\s*$/, ''); // close tag
var _this3$$wrapHeader = _this3.$wrapHeader($text, level.length, lineCount, sentenceMakeFunc),
result = _this3$$wrapHeader.html,
sign = _this3$$wrapHeader.sign; // 文章的开头不加换行
return _this3.getCacheWithSpace(_this3.pushCache(result, sign, lineCount), match, true);
});
} // 按照目前的引擎每个hook只会执行一次所以需要并行执行替换
if (this.test($str, SETEXT_HEADER)) {
$str = $str.replace(this.RULE[SETEXT_HEADER].reg, function (match, lines, text, level) {
if (_this3.isContainsCache(text)) {
return match;
} // 其中有两行是beforeMake加上的
var lineCount = calculateLinesOfParagraph(lines, _this3.getLineCount(match.replace(/^\n+/, '')));
var headerLevel = level[0] === '-' ? 2 : 1; // =: H1, -: H2
var _this3$$wrapHeader2 = _this3.$wrapHeader(text, headerLevel, lineCount, sentenceMakeFunc),
result = _this3$$wrapHeader2.html,
sign = _this3$$wrapHeader2.sign; // 文章的开头不加换行
return _this3.getCacheWithSpace(_this3.pushCache(result, sign, lineCount), match, true);
});
}
return $str;
}
}, {
key: "afterMakeHtml",
value: function afterMakeHtml(html) {
var $html = _get(_getPrototypeOf(Header.prototype), "afterMakeHtml", this).call(this, html);
this.headerIDCache = [];
this.headerIDCounter = {};
return $html;
}
}, {
key: "test",
value: function test(str, flavor) {
return this.RULE[flavor].reg && this.RULE[flavor].reg.test(str);
}
}, {
key: "rule",
value: function rule() {
// setext Header
// TODO: 支持多行标题
var setext = {
begin: '(?:^|\\n)(\\n*)',
// (?<lines>\\n*)
content: ['(?:\\h*', '(.+)', // (?<text>.+)
')\\n', '(?:\\h*', '([=]+|[-]+)', // (?<level>[=]+|[-]+)
')'].join(''),
end: '(?=$|\\n)'
};
setext.reg = compileRegExp(setext, 'g', true); // atx header
var atx = {
begin: '(?:^|\\n)(\\n*)(?:\\h*(#{1,6}))',
// (?<lines>\\n*), (?<level>#{1,6})
content: '(.+?)',
// '(?<text>.+?)'
end: '(?=$|\\n)'
};
this.strict && (atx.begin += '(?=\\h+)'); // (?=\\s+) for strict mode
atx.reg = compileRegExp(atx, 'g', true);
return {
setext: setext,
atx: atx
};
}
}]);
return Header;
}(ParagraphBase);
_defineProperty(Header, "HOOK_NAME", 'header');
function _createSuper$e(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$e(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$e() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Transfer = /*#__PURE__*/function (_SyntaxBase) {
_inherits(Transfer, _SyntaxBase);
var _super = _createSuper$e(Transfer);
function Transfer() {
_classCallCheck(this, Transfer);
return _super.apply(this, arguments);
}
_createClass(Transfer, [{
key: "rule",
value: // constructor() {
// super();
// }
function rule() {
var ret = {};
ret.reg = new RegExp('');
return ret;
}
}, {
key: "beforeMakeHtml",
value: function beforeMakeHtml(str) {
return str.replace(/\\\n/g, '\\ \n');
}
}, {
key: "afterMakeHtml",
value: function afterMakeHtml(str) {
var $str = str.replace(/~Q/g, '~');
$str = $str.replace(/~X/g, '`');
$str = $str.replace(/~Y/g, '!');
$str = $str.replace(/~Z/g, '#');
$str = $str.replace(/~&/g, '&');
$str = $str.replace(/~K/g, '/');
return $str;
}
}]);
return Transfer;
}(SyntaxBase);
_defineProperty(Transfer, "HOOK_NAME", 'transfer');
var TypeError$l = global_1.TypeError;
// `Array.prototype.{ reduce, reduceRight }` methods implementation
var createMethod$4 = function (IS_RIGHT) {
return function (that, callbackfn, argumentsLength, memo) {
aCallable(callbackfn);
var O = toObject(that);
var self = indexedObject(O);
var length = lengthOfArrayLike(O);
var index = IS_RIGHT ? length - 1 : 0;
var i = IS_RIGHT ? -1 : 1;
if (argumentsLength < 2) while (true) {
if (index in self) {
memo = self[index];
index += i;
break;
}
index += i;
if (IS_RIGHT ? index < 0 : length <= index) {
throw TypeError$l('Reduce of empty array with no initial value');
}
}
for (;IS_RIGHT ? index >= 0 : length > index; index += i) if (index in self) {
memo = callbackfn(memo, self[index], index, O);
}
return memo;
};
};
var arrayReduce = {
// `Array.prototype.reduce` method
// https://tc39.es/ecma262/#sec-array.prototype.reduce
left: createMethod$4(false),
// `Array.prototype.reduceRight` method
// https://tc39.es/ecma262/#sec-array.prototype.reduceright
right: createMethod$4(true)
};
var engineIsNode = classofRaw(global_1.process) == 'process';
var $reduce = arrayReduce.left;
var STRICT_METHOD$2 = arrayMethodIsStrict('reduce');
// Chrome 80-82 has a critical bug
// https://bugs.chromium.org/p/chromium/issues/detail?id=1049982
var CHROME_BUG = !engineIsNode && engineV8Version > 79 && engineV8Version < 83;
// `Array.prototype.reduce` method
// https://tc39.es/ecma262/#sec-array.prototype.reduce
_export({ target: 'Array', proto: true, forced: !STRICT_METHOD$2 || CHROME_BUG }, {
reduce: function reduce(callbackfn /* , initialValue */) {
var length = arguments.length;
return $reduce(this, callbackfn, length, length > 1 ? arguments[1] : undefined);
}
});
var reduce = entryVirtual('Array').reduce;
var ArrayPrototype$a = Array.prototype;
var reduce$1 = function (it) {
var own = it.reduce;
return it === ArrayPrototype$a || (objectIsPrototypeOf(ArrayPrototype$a, it) && own === ArrayPrototype$a.reduce) ? reduce : own;
};
var reduce$2 = reduce$1;
var reduce$3 = reduce$2;
function ownKeys$4(object, enumerableOnly) { var keys = keys$3(object); if (getOwnPropertySymbols$2) { var symbols = getOwnPropertySymbols$2(object); enumerableOnly && (symbols = filter$3(symbols).call(symbols, function (sym) { return getOwnPropertyDescriptor$3(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var _context21, _context22; var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? forEach$3(_context21 = ownKeys$4(Object(source), !0)).call(_context21, function (key) { _defineProperty(target, key, source[key]); }) : getOwnPropertyDescriptors$2 ? defineProperties$2(target, getOwnPropertyDescriptors$2(source)) : forEach$3(_context22 = ownKeys$4(Object(source))).call(_context22, function (key) { defineProperty$5(target, key, getOwnPropertyDescriptor$3(source, key)); }); } return target; }
function _createSuper$f(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$f(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$f() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var TABLE_LOOSE = 'loose';
var TABLE_STRICT = 'strict';
var Table = /*#__PURE__*/function (_ParagraphBase) {
_inherits(Table, _ParagraphBase);
var _super = _createSuper$f(Table);
function Table(_ref) {
var _this;
var externals = _ref.externals,
config = _ref.config;
_classCallCheck(this, Table);
_this = _super.call(this, {
needCache: true
});
var enableChart = config.enableChart,
ChartRenderEngine = config.chartRenderEngine,
requiredPackages = config.externals,
_config$chartEngineOp = config.chartEngineOptions,
chartEngineOptions = _config$chartEngineOp === void 0 ? {} : _config$chartEngineOp;
_this.chartRenderEngine = null;
if (enableChart === true) {
try {
_this.chartRenderEngine = new ChartRenderEngine(_objectSpread$3(_objectSpread$3({}, externals && requiredPackages instanceof Array && reduce$3(requiredPackages).call(requiredPackages, function (acc, pkg) {
delete chartEngineOptions[pkg]; // 过滤第三方包选项
return _objectSpread$3(_objectSpread$3({}, acc), {}, _defineProperty({}, pkg, externals[pkg]));
}, {})), {}, {
renderer: 'svg',
width: 500,
height: 300
}, chartEngineOptions));
} catch (error) {
console.warn(error);
}
}
return _this;
} // 保持每列长度一致
_createClass(Table, [{
key: "$extendColumns",
value: function $extendColumns(row, colCount) {
var _context;
var delta = colCount - row.length;
if (delta < 1) {
return row;
}
return concat$5(row).call(row, repeat$3(_context = '&nbsp;|').call(_context, delta).split('|', delta));
}
}, {
key: "$parseChartOptions",
value: function $parseChartOptions(cell) {
// 初始化失败
if (!this.chartRenderEngine) {
return null;
}
var CHART_REGEX = /^[ ]*:(\w+):(?:[ ]*{(.*?)}[ ]*)?$/;
if (!CHART_REGEX.test(cell)) {
return null;
}
var match = cell.match(CHART_REGEX);
var _match = _slicedToArray(match, 3),
chartType = _match[1],
axisOptions = _match[2];
var DEFAULT_AXIS_OPTIONS = ['x', 'y'];
return {
type: chartType,
options: axisOptions ? axisOptions.split(/\s*,\s*/) : DEFAULT_AXIS_OPTIONS
};
}
}, {
key: "$parseColumnAlignRules",
value: function $parseColumnAlignRules(row) {
var COLUMN_ALIGN_MAP = {
L: 'left',
R: 'right',
C: 'center'
};
var COLUMN_ALIGN_CACHE_SIGN = ['U', 'L', 'R', 'C']; // U for undefined
var textAlignRules = map$3(row).call(row, function (rule) {
var $rule = trim$3(rule).call(rule);
var index = 0;
if (/^:/.test($rule)) {
index += 1;
}
if (/:$/.test($rule)) {
index += 2;
}
return COLUMN_ALIGN_CACHE_SIGN[index];
});
return {
textAlignRules: textAlignRules,
COLUMN_ALIGN_MAP: COLUMN_ALIGN_MAP
};
}
}, {
key: "$parseTable",
value: function $parseTable(lines, sentenceMakeFunc, dataLines) {
var _context2,
_this2 = this,
_context8,
_context9,
_context10,
_context11,
_context12;
var maxCol = 0;
var rows = map$3(lines).call(lines, function (line, index) {
var cols = line.replace(/\\\|/g, '~CS').split('|');
if (cols[0] === '') {
cols.shift();
}
if (cols[cols.length - 1] === '') {
cols.pop();
} // 文本对齐相关列,不作为最多列数的参考依据
index !== 1 && (maxCol = Math.max(maxCol, cols.length));
return cols;
});
var _this$$parseColumnAli = this.$parseColumnAlignRules(rows[1]),
textAlignRules = _this$$parseColumnAli.textAlignRules,
COLUMN_ALIGN_MAP = _this$$parseColumnAli.COLUMN_ALIGN_MAP;
var tableObject = {
header: [],
rows: [],
colLength: maxCol,
rowLength: rows.length - 2 // 去除表头和控制行
};
var chartOptions = this.$parseChartOptions(rows[0][0]);
var chartOptionsSign = this.$engine.md5(rows[0][0]); // 如果需要生成图表,
if (chartOptions) {
rows[0][0] = '';
}
/**
* ~CTHD: <thead>
* ~CTHD$: </thead>
* ~CTBD: <tbody>
* ~CTBD$: </tbody>
* ~CTR: <tr>
* ~CTR$: </tr>
* ~CTH(L|R|C|U): <th>
* ~CTH$: </th>
* ~CTD(L|R|C|U): <td>
* ~CTD$: </td>
*/
var tableHeader = map$3(_context2 = this.$extendColumns(rows[0], maxCol)).call(_context2, function (cell, col) {
var _context3, _context4;
tableObject.header.push(cell.replace(/~CS/g, '\\|'));
var _sentenceMakeFunc = sentenceMakeFunc(trim$3(_context3 = cell.replace(/~CS/g, '\\|')).call(_context3)),
cellHtml = _sentenceMakeFunc.html; // 前后补一个空格,否则自动链接会将缓存的内容全部收入链接内部
return concat$5(_context4 = "~CTH".concat(textAlignRules[col] || 'U', " ")).call(_context4, cellHtml, " ~CTH$");
}).join('');
var tableRows = reduce$3(rows).call(rows, function (table, row, line) {
var _context5;
if (line <= 1) {
return table;
}
var currentRowCountWithoutHeader = line - 2;
tableObject.rows[currentRowCountWithoutHeader] = [];
var $extendedColumns = map$3(_context5 = _this2.$extendColumns(row, maxCol)).call(_context5, function (cell, col) {
var _context6, _context7;
tableObject.rows[currentRowCountWithoutHeader].push(cell.replace(/~CS/g, '\\|'));
var _sentenceMakeFunc2 = sentenceMakeFunc(trim$3(_context6 = cell.replace(/~CS/g, '\\|')).call(_context6)),
cellHtml = _sentenceMakeFunc2.html; // 前后补一个空格,否则自动链接会将缓存的内容全部收入链接内部
return concat$5(_context7 = "~CTD".concat(textAlignRules[col] || 'U', " ")).call(_context7, cellHtml, " ~CTD$");
});
table.push("~CTR".concat($extendedColumns.join(''), "~CTR$"));
return table;
}, []).join(''); // console.log('obj', tableObject);
var tableResult = this.$renderTable(COLUMN_ALIGN_MAP, tableHeader, tableRows, dataLines);
if (!chartOptions) {
return tableResult;
}
var chart = this.chartRenderEngine.render(chartOptions.type, chartOptions.options, tableObject);
var chartHtml = concat$5(_context8 = concat$5(_context9 = concat$5(_context10 = concat$5(_context11 = "<figure id=\"table_chart_".concat(chartOptionsSign, "_")).call(_context11, tableResult.sign, "\"\n data-sign=\"table_chart_")).call(_context10, chartOptionsSign, "_")).call(_context9, tableResult.sign, "\" data-lines=\"0\">")).call(_context8, chart, "</figure>");
return {
html: concat$5(_context12 = "".concat(chartHtml)).call(_context12, tableResult.html),
sign: chartOptionsSign + tableResult.sign
};
}
/**
* 如果table.head是空的就不渲染<thead>了
* @param {String} str
* @returns {Boolean}
*/
}, {
key: "$testHeadEmpty",
value: function $testHeadEmpty(str) {
var test = str.replace(/&nbsp;/g, '').replace(/\s/g, '').replace(/(~CTH\$|~CTHU|~CTHL|~CTHR|~CTHC)/g, '');
return (test === null || test === void 0 ? void 0 : test.length) > 0;
}
}, {
key: "$renderTable",
value: function $renderTable(COLUMN_ALIGN_MAP, tableHeader, tableRows, dataLines) {
var _context13, _context14, _context15, _context16;
var cacheSrc = this.$testHeadEmpty(tableHeader) ? concat$5(_context13 = "~CTHD".concat(tableHeader, "~CTHD$~CTBD")).call(_context13, tableRows, "~CTBD$") : "~CTBD".concat(tableRows, "~CTBD$");
var html = cacheSrc;
var sign = this.$engine.md5(html);
var renderHtml = html.replace(/~CTHD\$/g, '</thead>').replace(/~CTHD/g, '<thead>').replace(/~CTBD\$/g, '</tbody>').replace(/~CTBD/g, '</tbody>').replace(/~CTR\$/g, '</tr>').replace(/~CTR/g, '<tr>').replace(/[ ]?~CTH\$/g, '</th>').replace(/[ ]?~CTD\$/g, '</td>') // 在这里将加上的空格还原回来
.replace(/~CT(D|H)(L|R|C|U)[ ]?/g, function (match, type, align) {
var tag = "<t".concat(type);
if (align === 'U') {
tag += '>';
} else {
tag += " align=\"".concat(COLUMN_ALIGN_MAP[align], "\">");
}
return tag;
}).replace(/\\\|/g, '|'); // escape \|
return {
html: concat$5(_context14 = concat$5(_context15 = concat$5(_context16 = "<div class=\"cherry-table-container\" data-sign=\"".concat(sign)).call(_context16, dataLines, "\" data-lines=\"")).call(_context15, dataLines, "\">\n <table class=\"cherry-table\">")).call(_context14, renderHtml, "</table></div>"),
sign: sign
};
}
}, {
key: "makeHtml",
value: function makeHtml(str, sentenceMakeFunc) {
var _this3 = this;
var $str = str; // strict fenced mode
if (this.test($str, TABLE_STRICT)) {
$str = $str.replace(this.RULE[TABLE_STRICT].reg, function (match, leading) {
var _context17;
var dataLines = _this3.getLineCount(match, leading); // 必须先trim否则分割出来的结果不对
// 将fenced mode转换为loose mode
var lines = map$3(_context17 = trim$3(match).call(match).split(/\n/)).call(_context17, function (line) {
var _context18;
return trim$3(_context18 = String(line)).call(_context18);
});
var _this3$$parseTable = _this3.$parseTable(lines, sentenceMakeFunc, dataLines),
table = _this3$$parseTable.html,
sign = _this3$$parseTable.sign;
return _this3.getCacheWithSpace(_this3.pushCache(table, sign, dataLines), match);
});
} // loose mode
if (this.test($str, TABLE_LOOSE)) {
// console.log(TABLE_LOOSE);
$str = $str.replace(this.RULE[TABLE_LOOSE].reg, function (match, leading) {
var _context19;
var dataLines = _this3.getLineCount(match, leading); // 必须先trim否则分割出来的结果不对
var lines = map$3(_context19 = trim$3(match).call(match).split(/\n/)).call(_context19, function (line) {
var _context20;
return trim$3(_context20 = String(line)).call(_context20);
});
var _this3$$parseTable2 = _this3.$parseTable(lines, sentenceMakeFunc, dataLines),
table = _this3$$parseTable2.html,
sign = _this3$$parseTable2.sign;
return _this3.getCacheWithSpace(_this3.pushCache(table, sign, dataLines), match);
});
}
return $str;
}
}, {
key: "test",
value: function test(str, flavor) {
return this.RULE[flavor].reg && this.RULE[flavor].reg.test(str);
}
}, {
key: "rule",
value: function rule() {
return getTableRule();
}
}]);
return Table;
}(ParagraphBase);
_defineProperty(Table, "HOOK_NAME", 'table');
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* 判断当前是否浏览器环境
* @returns
*/
function isBrowser() {
return (typeof window === "undefined" ? "undefined" : _typeof(window)) === 'object';
}
function _createSuper$g(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$g(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$g() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Br = /*#__PURE__*/function (_ParagraphBase) {
_inherits(Br, _ParagraphBase);
var _super = _createSuper$g(Br);
function Br(options) {
var _this;
_classCallCheck(this, Br);
_this = _super.call(this, {
needCache: true
});
_this.classicBr = testKeyInLocal('classicBr') ? getIsClassicBrFromLocal() : options.globalConfig.classicBr;
return _this;
}
_createClass(Br, [{
key: "beforeMakeHtml",
value: function beforeMakeHtml(str) {
var _this2 = this;
if (!this.test(str)) {
return str;
}
return str.replace(this.RULE.reg, function (match, lines, index) {
var _lines$match$length, _lines$match;
// 不处理全文开头的连续空行
if (index === 0) {
return match;
}
var lineCount = (_lines$match$length = (_lines$match = lines.match(/\n/g)) === null || _lines$match === void 0 ? void 0 : _lines$match.length) !== null && _lines$match$length !== void 0 ? _lines$match$length : 0;
var sign = "br".concat(lineCount);
var html = '';
if (isBrowser()) {
// 为了同步滚动
if (_this2.classicBr) {
var _context;
html = concat$5(_context = "<span data-sign=\"".concat(sign, "\" data-type=\"br\" data-lines=\"")).call(_context, lineCount, "\"></span>");
} else {
var _context2;
html = concat$5(_context2 = "<p data-sign=\"".concat(sign, "\" data-type=\"br\" data-lines=\"")).call(_context2, lineCount, "\">&nbsp;</p>");
}
} else {
// node环境下直接输出br
html = _this2.classicBr ? '' : '<br/>';
}
var placeHolder = _this2.pushCache(html, sign, lineCount); // 结尾只补充一个\n是因为Br将下一个段落中间的所有换行都替换掉了而两个换行符会导致下一个区块行数计算错误
return "\n\n".concat(placeHolder, "\n");
});
}
}, {
key: "makeHtml",
value: function makeHtml(str, sentenceMakeFunc) {
return str;
} // afterMakeHtml(str) {
// return str.replace(/~~B/g, (match) => {
// let lines = that.brCache.shift() - 1;
// return '<p data-sign="br' + lines + '" data-type="br" data-lines="' + lines + '">&nbsp;</p>';
// });
// }
// default: this.restoreCache();
}, {
key: "rule",
value: function rule() {
/**
* 样例:
* block1\n
* \n
* \n
* block2
*
* 匹配逻辑:
* 开头必为一个换行符所以后续只需要匹配至少两个空行即可生成一个换行行数即content匹配到的换行符个数
*/
var ret = {
begin: '(?:\\n)',
end: '',
content: '((?:\\h*\\n){2,})'
};
ret.reg = compileRegExp(ret, 'g', true);
return ret;
}
}]);
return Br;
}(ParagraphBase);
_defineProperty(Br, "HOOK_NAME", 'br');
function _createSuper$h(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$h(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$h() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 分割线语法
*/
var Hr = /*#__PURE__*/function (_ParagraphBase) {
_inherits(Hr, _ParagraphBase);
var _super = _createSuper$h(Hr);
function Hr() {
_classCallCheck(this, Hr);
return _super.call(this, {
needCache: true
});
}
_createClass(Hr, [{
key: "beforeMakeHtml",
value: function beforeMakeHtml(str) {
var _this = this;
return str.replace(this.RULE.reg, function (match, preLines) {
var _context;
var lineCount = (preLines.match(/\n/g) || []).length + 1; // 计算签名,签名可能会重复,符合预期
var sign = "hr".concat(lineCount);
var placeHolder = _this.pushCache(concat$5(_context = "<hr data-sign=\"".concat(sign, "\" data-lines=\"")).call(_context, lineCount, "\" />"), sign);
return prependLineFeedForParagraph(match, placeHolder);
});
}
}, {
key: "makeHtml",
value: function makeHtml(str, sentenceMakeFunc) {
return str;
}
}, {
key: "rule",
value: function rule() {
// 分割线必须有从新行开始,比如以换行结束
var ret = {
begin: '(?:^|\\n)(\\n*)[ ]*',
end: '(?=$|\\n)',
content: '((?:-[ \\t]*){3,}|(?:\\*[ \\t]*){3,}|(?:_[ \\t]*){3,})'
};
ret.reg = new RegExp(ret.begin + ret.content + ret.end, 'g');
return ret;
}
}]);
return Hr;
}(ParagraphBase);
_defineProperty(Hr, "HOOK_NAME", 'hr');
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var imgAltHelper = {
/**
* 提取alt部分的扩展属性
* @param {string} alt 图片引用中的alt部分
* @returns
*/
processExtendAttributesInAlt: function processExtendAttributesInAlt(alt) {
var attrRegex = /#([0-9]+(px|em|pt|pc|in|mm|cm|ex|%)|auto)/g;
var info = alt.match(attrRegex);
if (!info) {
return '';
}
var extendAttrs = '';
var _info = _slicedToArray(info, 2),
width = _info[0],
height = _info[1];
if (width) {
extendAttrs = " width=\"".concat(width.replace(/[ #]*/g, ''), "\"");
}
if (height) {
extendAttrs += " height=\"".concat(height.replace(/[ #]*/g, ''), "\"");
}
return extendAttrs;
},
/**
* 提取alt部分的扩展样式
* @param {string} alt 图片引用中的alt部分
* @returns {{extendStyles:string, extendClasses:string}}
*/
processExtendStyleInAlt: function processExtendStyleInAlt(alt) {
var extendStyles = this.$getAlignment(alt);
var extendClasses = '';
var info = alt.match(/#(border|shadow|radius|B|S|R)/g);
if (info) {
for (var i = 0; i < info.length; i++) {
switch (info[i]) {
case '#border':
case '#B':
extendStyles += 'border:1px solid #888888;padding: 2px;box-sizing: border-box;';
extendClasses += ' cherry-img-border';
break;
case '#shadow':
case '#S':
extendStyles += 'box-shadow:0 2px 15px -5px rgb(0 0 0 / 50%);';
extendClasses += ' cherry-img-shadow';
break;
case '#radius':
case '#R':
extendStyles += 'border-radius: 15px;';
extendClasses += ' cherry-img-radius';
break;
}
}
}
return {
extendStyles: extendStyles,
extendClasses: extendClasses
};
},
/**
* 从alt中提取对齐方式信息
* @param {string} alt
* @returns {string}
*/
$getAlignment: function $getAlignment(alt) {
var styleRegex = /#(center|right|left|float-right|float-left)/i;
var info = alt.match(styleRegex);
if (!info) {
return '';
}
var _info2 = _slicedToArray(info, 2),
alignment = _info2[1];
switch (alignment) {
case 'center':
return 'transform:translateX(-50%);margin-left:50%;display:block;';
case 'right':
return 'transform:translateX(-100%);margin-left:100%;margin-right:-100%;display:block;';
case 'left':
return 'transform:translateX(0);margin-left:0;display:block;';
case 'float-right':
return 'float:right;transform:translateX(0);margin-left:0;display:block;';
case 'float-left':
return 'float:left;transform:translateX(0);margin-left:0;display:block;';
}
}
};
function ownKeys$5(object, enumerableOnly) { var keys = keys$3(object); if (getOwnPropertySymbols$2) { var symbols = getOwnPropertySymbols$2(object); enumerableOnly && (symbols = filter$3(symbols).call(symbols, function (sym) { return getOwnPropertyDescriptor$3(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var _context22, _context23; var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? forEach$3(_context22 = ownKeys$5(Object(source), !0)).call(_context22, function (key) { _defineProperty(target, key, source[key]); }) : getOwnPropertyDescriptors$2 ? defineProperties$2(target, getOwnPropertyDescriptors$2(source)) : forEach$3(_context23 = ownKeys$5(Object(source))).call(_context23, function (key) { defineProperty$5(target, key, getOwnPropertyDescriptor$3(source, key)); }); } return target; }
function _createSuper$i(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$i(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$i() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var replacerFactory = function replacerFactory(type, match, leadingChar, alt, link, title, posterContent, config, globalConfig) {
var refType = typeof link === 'undefined' ? 'ref' : 'url';
var attrs = '';
if (refType === 'ref') {
// TODO: 全局引用
return match;
}
if (refType === 'url') {
var _context, _context2, _context3, _context4, _context5, _context6, _context7, _context8;
var extent = imgAltHelper.processExtendAttributesInAlt(alt);
var _imgAltHelper$process = imgAltHelper.processExtendStyleInAlt(alt),
style = _imgAltHelper$process.extendStyles,
classes = _imgAltHelper$process.extendClasses;
if (style) {
style = " style=\"".concat(style, "\" ");
}
if (classes) {
classes = " class=\"".concat(classes, "\" ");
}
attrs = title && trim$3(title).call(title) !== '' ? " title=\"".concat(escapeHTMLSpecialCharOnce(title), "\"") : '';
if (posterContent) {
attrs += " poster=".concat(encodeURIOnce(posterContent));
}
var processedURL = globalConfig.urlProcessor(link, type);
var defaultWrapper = concat$5(_context = concat$5(_context2 = concat$5(_context3 = concat$5(_context4 = concat$5(_context5 = concat$5(_context6 = concat$5(_context7 = "<".concat(type, " src=\"")).call(_context7, UrlCache.set(encodeURIOnce(processedURL)), "\"")).call(_context6, attrs, " ")).call(_context5, extent, " ")).call(_context4, style, " ")).call(_context3, classes, " controls=\"controls\">")).call(_context2, escapeHTMLSpecialCharOnce(alt || ''), "</")).call(_context, type, ">");
return concat$5(_context8 = "".concat(leadingChar)).call(_context8, config.videoWrapper ? config.videoWrapper(link) : defaultWrapper);
} // should never happen
return match;
};
var Image$1 = /*#__PURE__*/function (_SyntaxBase) {
_inherits(Image, _SyntaxBase);
var _super = _createSuper$i(Image);
function Image(_ref) {
var _this;
var config = _ref.config,
globalConfig = _ref.globalConfig;
_classCallCheck(this, Image);
_this = _super.call(this, null);
_this.urlProcessor = globalConfig.urlProcessor; // TODO: URL Validator
_this.extendMedia = {
tag: ['video', 'audio'],
replacer: {
video: function video(match, leadingChar, alt, link, title, poster) {
return replacerFactory('video', match, leadingChar, alt, link, title, poster, config, globalConfig);
},
audio: function audio(match, leadingChar, alt, link, title, poster) {
return replacerFactory('audio', match, leadingChar, alt, link, title, poster, config, globalConfig);
}
}
};
_this.RULE = _this.rule(_this.extendMedia);
return _this;
}
_createClass(Image, [{
key: "toHtml",
value: function toHtml(match, leadingChar, alt, link, title, ref, extendAttrs) {
// console.log(match, alt, link, ref, title);
var refType = typeof link === 'undefined' ? 'ref' : 'url';
var attrs = '';
if (refType === 'ref') {
// 全局引用理应在CommentReference中被替换没有被替换说明没有定义引用项
return match;
}
if (refType === 'url') {
var _context9, _context10, _context11, _context12, _context13, _context14, _context15, _context16;
var extent = imgAltHelper.processExtendAttributesInAlt(alt);
var _imgAltHelper$process2 = imgAltHelper.processExtendStyleInAlt(alt),
style = _imgAltHelper$process2.extendStyles,
classes = _imgAltHelper$process2.extendClasses;
if (style) {
style = " style=\"".concat(style, "\" ");
}
if (classes) {
classes = " class=\"".concat(classes, "\" ");
}
attrs = title && trim$3(title).call(title) !== '' ? " title=\"".concat(escapeHTMLSpecialCharOnce(title.replace(/["']/g, '')), "\"") : '';
var srcProp = 'src';
var srcValue;
var cherryOptions = this.$engine.$cherry.options;
if (cherryOptions.callback && cherryOptions.callback.beforeImageMounted) {
var imgAttrs = cherryOptions.callback.beforeImageMounted(srcProp, link);
srcProp = imgAttrs.srcProp || srcProp;
srcValue = imgAttrs.src || link;
}
var extendAttrStr = extendAttrs ? extendAttrs.replace(/[{}]/g, '').replace(/([^=\s]+)=([^\s]+)/g, '$1="$2"').replace(/&/g, '&amp;') // 对&多做一次转义cherry现有的机制会自动把&amp;转成&只有多做一次转义才能抵消cherry的机制
: '';
return concat$5(_context9 = concat$5(_context10 = concat$5(_context11 = concat$5(_context12 = concat$5(_context13 = concat$5(_context14 = concat$5(_context15 = concat$5(_context16 = "".concat(leadingChar, "<img ")).call(_context16, srcProp, "=\"")).call(_context15, UrlCache.set(encodeURIOnce(this.urlProcessor(srcValue, 'image'))), "\" ")).call(_context14, extent, " ")).call(_context13, style, " ")).call(_context12, classes, " alt=\"")).call(_context11, escapeHTMLSpecialCharOnce(alt || ''), "\"")).call(_context10, attrs, " ")).call(_context9, extendAttrStr, "/>");
} // should never happen
return match;
}
}, {
key: "toMediaHtml",
value: function toMediaHtml(match, leadingChar, mediaType, alt, link, title, ref, posterWrap, poster) {
var _this$extendMedia$rep, _context17;
if (!this.extendMedia.replacer[mediaType]) {
return match;
}
for (var _len = arguments.length, args = new Array(_len > 9 ? _len - 9 : 0), _key = 9; _key < _len; _key++) {
args[_key - 9] = arguments[_key];
}
return (_this$extendMedia$rep = this.extendMedia.replacer[mediaType]).call.apply(_this$extendMedia$rep, concat$5(_context17 = [this, match, leadingChar, alt, link, title, poster]).call(_context17, args));
}
}, {
key: "makeHtml",
value: function makeHtml(str) {
var $str = str;
if (this.test($str)) {
if (isLookbehindSupported()) {
var _context18;
$str = $str.replace(this.RULE.reg, bind$5(_context18 = this.toHtml).call(_context18, this));
} else {
var _context19;
$str = replaceLookbehind($str, this.RULE.reg, bind$5(_context19 = this.toHtml).call(_context19, this), true, 1);
}
}
if (this.testMedia($str)) {
if (isLookbehindSupported()) {
var _context20;
$str = $str.replace(this.RULE.regExtend, bind$5(_context20 = this.toMediaHtml).call(_context20, this));
} else {
var _context21;
$str = replaceLookbehind($str, this.RULE.regExtend, bind$5(_context21 = this.toMediaHtml).call(_context21, this), true, 1);
}
}
return $str;
} // afterMakeHtml(str) {
// return UrlCache.restoreAll(str);
// }
}, {
key: "testMedia",
value: function testMedia(str) {
return this.RULE.regExtend && this.RULE.regExtend.test(str);
}
}, {
key: "rule",
value: function rule(extendMedia) {
var ret = {
// lookbehind启用分组是为了和不兼容lookbehind的场景共用一个回调
begin: isLookbehindSupported() ? '((?<!\\\\))!' : '(^|[^\\\\])!',
content: ['\\[([^\\n]*?)\\]', // ?<alt>
'[ \\t]*', // any spaces
"".concat('(?:' + '\\(' + '([^"][^\\s]+?)' + // ?<link> url
'(?:[ \\t]((?:".*?")|(?:\'.*?\')))?' + // ?<title> optional
'\\)' + '|' + // or
'\\[(').concat(NOT_ALL_WHITE_SPACES_INLINE, ")\\]") + // ?<ref> global ref
')'].join(''),
end: '({[^{}]+?})?' // extend attrs e.g. {width=50 height=60}
};
if (extendMedia) {
var extend = _objectSpread$4({}, ret); // TODO: 支持Lookbehind
extend.begin = isLookbehindSupported() ? "((?<!\\\\))!(".concat(extendMedia.tag.join('|'), ")") : "(^|[^\\\\])!(".concat(extendMedia.tag.join('|'), ")");
extend.end = '({poster=(.*)})?';
ret.regExtend = compileRegExp(extend, 'g');
}
ret.reg = compileRegExp(ret, 'g');
return ret;
}
}]);
return Image;
}(SyntaxBase);
_defineProperty(Image$1, "HOOK_NAME", 'image');
function ownKeys$6(object, enumerableOnly) { var keys = keys$3(object); if (getOwnPropertySymbols$2) { var symbols = getOwnPropertySymbols$2(object); enumerableOnly && (symbols = filter$3(symbols).call(symbols, function (sym) { return getOwnPropertyDescriptor$3(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$5(target) { for (var i = 1; i < arguments.length; i++) { var _context10, _context11; var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? forEach$3(_context10 = ownKeys$6(Object(source), !0)).call(_context10, function (key) { _defineProperty(target, key, source[key]); }) : getOwnPropertyDescriptors$2 ? defineProperties$2(target, getOwnPropertyDescriptors$2(source)) : forEach$3(_context11 = ownKeys$6(Object(source))).call(_context11, function (key) { defineProperty$5(target, key, getOwnPropertyDescriptor$3(source, key)); }); } return target; }
function _createSuper$j(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$j(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$j() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var INDENT_SPACE_NUM = 4; // commonmark default use 1~4 spaces for indent
var TAB_SPACE_NUM = 4; // 1 tab === 4 space
function attrsToAttributeString(object) {
var _context;
if (_typeof(object) !== 'object' && keys$3(object).length < 1) {
return '';
}
var attrs = ['']; // 为了join一步到位
forEach$3(_context = keys$3(object)).call(_context, function (key) {
var _context2;
attrs.push(concat$5(_context2 = "".concat(key, "=\"")).call(_context2, object[key], "\""));
});
return attrs.join(' ');
}
function makeChecklist(text) {
return text.replace(/^((?:|[\t ]+)[*+-]\s+)\[(\s|x)\]/gm, function (whole, pre, test) {
var _context3;
var checkHtml = /\s/.test(test) ? '<span class="ch-icon ch-icon-square"></span>' : '<span class="ch-icon ch-icon-check"></span>';
return concat$5(_context3 = "".concat(pre)).call(_context3, checkHtml);
});
} // 缩进处理
function handleIndent(str, node) {
var indentRegex = /^(\t|[ ])/;
var $str = str;
while (indentRegex.test($str)) {
node.space += $str[0] === '\t' ? TAB_SPACE_NUM : 1;
$str = $str.replace(indentRegex, '');
}
return $str;
} // 序号样式处理
function getListStyle(m2) {
if (/^[a-z]/.test(m2)) {
return 'lower-greek';
}
if (/^[一二三四五六七八九十]/.test(m2)) {
return 'cjk-ideographic';
}
if (/^I/.test(m2)) {
return 'upper-roman';
}
if (/^\+/.test(m2)) {
return 'circle';
}
if (/^\*/.test(m2)) {
return 'square';
}
return 'default';
} // 标识符处理
function handleMark(str, node) {
var listRegex = /^((([*+-]|\d+[.]|[a-z]\.|[I一二三四五六七八九十]+\.)[ \t]+)([^\r]*?)($|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.]|[a-z]\.|[I一二三四五六七八九十]+\.)[ \t]+)))/;
if (!listRegex.test(str)) {
node.type = 'blank';
return str;
}
return str.replace(listRegex, function (wholeMatch, m1, m2, m3, m4) {
node.type = m2.search(/[*+-]/g) > -1 ? 'ul' : 'ol';
node.listStyle = getListStyle(m2);
node.start = Number(m2.replace('.', '')) ? Number(m2.replace('.', '')) : 1;
return m4;
});
}
var Node$1 = /*#__PURE__*/_createClass( // 列表树节点
function Node() {
_classCallCheck(this, Node);
this.index = 0;
this.space = 0;
this.type = '';
this.start = 1;
this.listStyle = '';
this.strs = [];
this.children = [];
this.lines = 0;
});
var List = /*#__PURE__*/function (_ParagraphBase) {
_inherits(List, _ParagraphBase);
var _super = _createSuper$j(List);
function List(_ref) {
var _this;
var config = _ref.config;
_classCallCheck(this, List);
_this = _super.call(this, {
needCache: true
});
_this.config = config || {};
_this.tree = [];
_this.emptyLines = 0;
_this.indentSpace = Math.max(_this.config.indentSpace, 2);
return _this;
}
_createClass(List, [{
key: "addNode",
value: function addNode(node, current, parent, last) {
if (node.type === 'blank') {
this.tree[last].strs.push(node.strs[0]);
} else {
this.tree[parent].children.push(current);
this.tree[current] = _objectSpread$5(_objectSpread$5({}, node), {}, {
parent: parent
});
}
}
}, {
key: "buildTree",
value: function buildTree(html, sentenceMakeFunc) {
var items = html.split('\n');
this.tree = [];
items.unshift(''); // 列表结尾换行符个数
var endLineFlagLength = html.match(/\n*$/g)[0].length;
for (var i = 0; i < items.length - endLineFlagLength; i++) {
var node = new Node$1();
items[i] = handleIndent(items[i], node);
items[i] = handleMark(items[i], node);
node.strs.push(sentenceMakeFunc(items[i]).html);
node.index = i;
if (i === 0) {
// 根节点
node.space = -2;
this.tree.push(node);
continue;
}
var last = i - 1;
while (!this.tree[last]) {
last -= 1;
}
if (node.type === 'blank') {
this.addNode(node, i, this.tree[last].parent, last);
} else {
while (!this.tree[last] || this.tree[last].space > node.space) {
last -= 1;
}
var space = node.space;
var lastSpace = this.tree[last].space;
if (space < lastSpace + this.indentSpace) {
// 成为同级节点
if (this.config.listNested && this.tree[last].type !== node.type) {
this.addNode(node, i, last);
} else {
this.addNode(node, i, this.tree[last].parent);
}
} else if (space < lastSpace + this.indentSpace + INDENT_SPACE_NUM) {
// 成为子节点
this.addNode(node, i, last);
} else {
// 纯文本
node.type = 'blank';
this.addNode(node, i, this.tree[last].parent, last);
}
}
}
}
}, {
key: "renderSubTree",
value: function renderSubTree(node, children, type) {
var _this2 = this,
_context7,
_context8,
_context9;
var lines = 0;
var attr = {};
var content = reduce$3(children).call(children, function (html, item) {
var _context4, _context5, _context6;
var child = _this2.tree[item];
var itemAttr = {};
var str = "<p>".concat(child.strs.join('<br>'), "</p>");
child.lines += _this2.getLineCount(child.strs.join('\n'));
var children = child.children.length ? _this2.renderTree(item) : '';
node.lines += child.lines;
lines += child.lines; // checklist 样式适配
var checklistRegex = /<span class="ch-icon ch-icon-(square|check)"><\/span>/;
if (checklistRegex.test(str)) {
itemAttr["class"] = 'check-list-item';
}
return concat$5(_context4 = concat$5(_context5 = concat$5(_context6 = "".concat(html, "<li")).call(_context6, attrsToAttributeString(itemAttr), ">")).call(_context5, str)).call(_context4, children, "</li>");
}, '');
if (node.parent === undefined) {
// 根节点增加属性
attr['data-lines'] = node.index === 0 ? lines + this.emptyLines : lines;
attr['data-sign'] = this.sign;
}
if (children[0] && type === 'ol') {
attr.start = this.tree[children[0]].start;
}
attr["class"] = "cherry-list__".concat(this.tree[children[0]].listStyle);
return concat$5(_context7 = concat$5(_context8 = concat$5(_context9 = "<".concat(type)).call(_context9, attrsToAttributeString(attr), ">")).call(_context8, content, "</")).call(_context7, type, ">");
}
}, {
key: "renderTree",
value: function renderTree(current) {
var _this3 = this;
var from = 0;
var node = this.tree[current];
var children = node.children;
var html = reduce$3(children).call(children, function (html, item, index) {
if (index === 0) return html;
if (_this3.tree[children[index]].type === _this3.tree[children[index - 1]].type) {
return html;
}
var subTree = _this3.renderSubTree(node, slice$7(children).call(children, from, index), _this3.tree[children[index - 1]].type);
from = index;
return html + subTree;
}, '');
var childrenHtml = children.length ? this.renderSubTree(node, slice$7(children).call(children, from, children.length), this.tree[children[children.length - 1]].type) : '';
return html + childrenHtml;
}
}, {
key: "toHtml",
value: function toHtml(wholeMatch, sentenceMakeFunc) {
var _wholeMatch$match$len, _wholeMatch$match;
// 行数计算吸收的空行
this.emptyLines = (_wholeMatch$match$len = (_wholeMatch$match = wholeMatch.match(/^\n\n/)) === null || _wholeMatch$match === void 0 ? void 0 : _wholeMatch$match.length) !== null && _wholeMatch$match$len !== void 0 ? _wholeMatch$match$len : 0;
var text = wholeMatch.replace(/~0$/g, '').replace(/^\n+/, '');
this.buildTree(makeChecklist(text), sentenceMakeFunc);
var result = this.renderTree(0);
return this.pushCache(result, this.sign, this.$getLineNum(wholeMatch));
}
}, {
key: "$getLineNum",
value: function $getLineNum(str) {
var _str$match$length, _str$match, _$str$match$length, _$str$match;
var beginLine = (_str$match$length = (_str$match = str.match(/^\n\n/)) === null || _str$match === void 0 ? void 0 : _str$match.length) !== null && _str$match$length !== void 0 ? _str$match$length : 0;
var $str = str.replace(/^\n+/, '').replace(/\n+$/, '\n');
return (_$str$match$length = (_$str$match = $str.match(/\n/g)) === null || _$str$match === void 0 ? void 0 : _$str$match.length) !== null && _$str$match$length !== void 0 ? _$str$match$length : 0 + beginLine;
}
}, {
key: "makeHtml",
value: function makeHtml(str, sentenceMakeFunc) {
var _this4 = this;
var $str = "".concat(str, "~0");
if (this.test($str)) {
$str = $str.replace(this.RULE.reg, function (wholeMatch) {
return _this4.getCacheWithSpace(_this4.checkCache(wholeMatch, sentenceMakeFunc, _this4.$getLineNum(wholeMatch)), wholeMatch);
});
}
$str = $str.replace(/~0$/g, '');
return $str;
}
}, {
key: "rule",
value: function rule() {
var ret = {
begin: '(?:^|\n)(\n*)(([ ]{0,3}([*+-]|\\d+[.]|[a-z]\\.|[I一二三四五六七八九十]+\\.)[ \\t]+)',
content: '([^\\r]+?)',
end: '(~0|\\n{2,}(?=\\S)(?![ \\t]*(?:[*+-]|\\d+[.]|[a-z]\\.|[I一二三四五六七八九十]+\\.)[ \\t]+)))'
};
ret.reg = new RegExp(ret.begin + ret.content + ret.end, 'gm');
return ret;
}
}]);
return List;
}(ParagraphBase);
_defineProperty(List, "HOOK_NAME", 'list');
function _createSuper$k(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$k(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$k() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function computeLeadingSpaces(leadingChars) {
var indentRegex = /^(\t|[ ]{1,4})/;
var leadingCharsTemp = leadingChars;
var indent = 0;
while (indentRegex.test(leadingCharsTemp)) {
leadingCharsTemp = leadingCharsTemp.replace(/^(\t|[ ]{1,4})/g, '');
indent += 1;
}
return indent;
}
var Blockquote = /*#__PURE__*/function (_ParagraphBase) {
_inherits(Blockquote, _ParagraphBase);
var _super = _createSuper$k(Blockquote);
function Blockquote() {
_classCallCheck(this, Blockquote);
return _super.call(this, {
needCache: true
}); // TODO: String.prototype.repeat polyfill
}
_createClass(Blockquote, [{
key: "handleMatch",
value: function handleMatch(str, sentenceMakeFunc) {
var _this = this;
return str.replace(this.RULE.reg, function (match, lines, content) {
var _context, _context2, _context4;
var _sentenceMakeFunc = sentenceMakeFunc(content),
contentSign = _sentenceMakeFunc.sign,
parsedHtml = _sentenceMakeFunc.html;
var sign = _this.signWithCache(parsedHtml) || contentSign;
var lineCount = _this.getLineCount(match, lines); // 段落所占行数
var listRegex = /^(([ \t]{0,3}([*+-]|\d+[.]|[a-z]\.|[I一二三四五六七八九十]+\.)[ \t]+)([^\r]+?)($|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.]|[a-z]\.|[I一二三四五六七八九十]+\.)[ \t]+)))/;
var lastIndent = computeLeadingSpaces(lines); // 逐行处理
var contentLines = parsedHtml.split('\n');
var replaceReg = /^[>\s]+/;
var countReg = />/g;
var lastLevel = 1;
var level = 0;
var handledHtml = concat$5(_context = concat$5(_context2 = "<blockquote data-sign=\"".concat(sign, "_")).call(_context2, lineCount, "\" data-lines=\"")).call(_context, lineCount, "\">");
for (var i = 0; contentLines[i]; i++) {
if (i !== 0) {
var leadIndent = computeLeadingSpaces(contentLines[i]);
if (leadIndent <= lastIndent && listRegex.test(contentLines[i])) {
break;
}
lastIndent = leadIndent;
}
/* eslint-disable no-loop-func */
var $line = contentLines[i].replace(replaceReg, function (leadSymbol) {
var leadSymbols = leadSymbol.match(countReg); // 本行引用嵌套层级比上层要多
if (leadSymbols && leadSymbols.length > lastLevel) {
level = leadSymbols.length;
} else {
// 否则保持当前缩进层级
level = lastLevel;
}
return '';
}); // 同层级,且不为首行时补充一个换行
if (lastLevel === level && i !== 0) {
handledHtml += '<br>';
} // 补充缩进
if (lastLevel < level) {
var _context3;
handledHtml += repeat$3(_context3 = '<blockquote>').call(_context3, level - lastLevel);
lastLevel = level;
} // 插入当前行内容
handledHtml += $line;
} // 标签闭合
handledHtml += repeat$3(_context4 = '</blockquote>').call(_context4, lastLevel);
return _this.getCacheWithSpace(_this.pushCache(handledHtml, sign, lineCount), match);
});
}
}, {
key: "makeHtml",
value: function makeHtml(str, sentenceMakeFunc) {
if (!this.test(str)) {
return str;
}
return this.handleMatch(str, sentenceMakeFunc);
}
}, {
key: "rule",
value: function rule() {
var ret = {
begin: '(?:^|\\n)(\\s*)',
content: ['(', '>(?:.+?\\n(?![*+-]|\\d+[.]|[a-z]\\.))(?:>*.+?\\n(?![*+-]|\\d+[.]|[a-z]\\.))*(?:>*.+?)', // multiline
'|', // or
'>(?:.+?)', // single line
')'].join(''),
end: '(?=(\\n)|$)'
};
ret.reg = compileRegExp(ret, 'g');
return ret;
}
}]);
return Blockquote;
}(ParagraphBase);
_defineProperty(Blockquote, "HOOK_NAME", 'blockquote');
function _createSuper$l(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$l(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$l() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var AutoLink = /*#__PURE__*/function (_SyntaxBase) {
_inherits(AutoLink, _SyntaxBase);
var _super = _createSuper$l(AutoLink);
function AutoLink(_ref) {
var _this;
var config = _ref.config,
globalConfig = _ref.globalConfig;
_classCallCheck(this, AutoLink);
_this = _super.call(this, {
config: config
});
_this.urlProcessor = globalConfig.urlProcessor;
_this.enableShortLink = !!config.enableShortLink;
_this.shortLinkLength = config.shortLinkLength; // eslint-disable-next-line no-nested-ternary
_this.target = config.target ? "target=\"".concat(config.target, "\"") : !!config.openNewPage ? 'target="_blank"' : '';
_this.rel = config.rel ? "rel=\"".concat(config.rel, "\"") : '';
return _this;
}
_createClass(AutoLink, [{
key: "isLinkInHtmlAttribute",
value: function isLinkInHtmlAttribute(str, index, linkLength) {
var xmlTagRegex = new RegExp(['<', // tag start
'([a-zA-Z][a-zA-Z0-9-]*)', // tagName
'(', // attrs start
['\\s+[a-zA-Z_:][a-zA-Z0-9_.:-]*', // attr name
'(', // attr value start
['\\s*=\\s*', '(', ['([^\\s"\'=<>`]+)', // unquoted value
"('[^']*')", // single-quoted value
'("[^"]*")' // double-quoted value
].join('|'), // either is ok
')'].join(''), ')?' // attr value end
].join(''), ')*', // attrs end
'\\s*[/]?>' // tag end
].join(''), 'g');
var match;
while ((match = xmlTagRegex.exec(str)) !== null) {
// 搜索范围超过了字符串匹配到的位置
if (match.index > index + linkLength) {
break;
} // 正好在范围内说明是HTML的属性取等号是因为AutoLink的正则可能会匹配到标签的结束符号如<img src="http://www.google.com">
if (match.index < index && match.index + match[0].length >= index + linkLength) {
return true;
}
}
return false;
}
/**
* 判断链接是否被包裹在a标签内部如果被包裹则不识别为自动链接
* @param {string} str
* @param {number} index
* @param {number} linkLength
*/
}, {
key: "isLinkInATag",
value: function isLinkInATag(str, index, linkLength) {
var aTagRegex = /<a.*>[^<]*<\/a>/g;
var match;
while ((match = aTagRegex.exec(str)) !== null) {
// 搜索范围超过了字符串匹配到的位置
if (match.index > index + linkLength) {
break;
} // 正好在范围内说明是HTML的属性取等号是因为AutoLink的正则可能会匹配到标签的结束符号
// 如<a href="http://www.google.com">http://www.google.com</a>
if (match.index < index && match.index + match[0].length >= index + linkLength) {
return true;
}
}
return false;
}
}, {
key: "makeHtml",
value: function makeHtml(str, sentenceMakeFunc) {
var _this2 = this;
if (!(this.test(str) && (EMAIL_INLINE.test(str) || URL_INLINE_NO_SLASH.test(str)))) {
return str;
}
return str.replace(this.RULE.reg, function (match, left, protocol, address, right, index, str) {
var _context17, _context18, _context19;
// 数字实体字符系临时处理方法详情参见HTMLBlock注释
// maybe a html attr, skip it
if ( // ((left !== '<' || left !== '&#60;') && (right !== '>' || right !== '&#62;')) ||
_this2.isLinkInHtmlAttribute(str, index, protocol.length + address.length) || _this2.isLinkInATag(str, index, protocol.length + address.length)) {
return match;
}
var $protocol = protocol.toLowerCase();
var prefix = '';
var suffix = '';
var isWrappedByBracket = true; // not a pair
if (!((left === '<' || left === '&#60;') && (right === '>' || right === '&#62;'))) {
prefix = left;
suffix = right;
isWrappedByBracket = false;
} // not a valid address
// 不被尖括号包裹不带协议头且不以www.开头的不识别
if (trim$3(address).call(address) === '' || !isWrappedByBracket && $protocol === '' && !/www\./.test(address)) {
return match;
}
switch ($protocol) {
case 'javascript:':
return match;
case 'mailto:':
// email
if (EMAIL.test(address)) {
var _context, _context2, _context3, _context4, _context5, _context6;
return concat$5(_context = concat$5(_context2 = concat$5(_context3 = concat$5(_context4 = concat$5(_context5 = "".concat(prefix, "<a href=\"")).call(_context5, encodeURIOnce(concat$5(_context6 = "".concat($protocol)).call(_context6, address)), "\" ")).call(_context4, _this2.target, " ")).call(_context3, _this2.rel, ">")).call(_context2, escapeHTMLSpecialCharOnce(address), "</a>")).call(_context, suffix);
}
return match;
case '':
// 协议为空
// 不被<>包裹或单边无效包裹prefix === suffix 时都为空串
if (prefix === suffix || !isWrappedByBracket) {
// mailto
if (EMAIL.test(address)) {
var _context7, _context8, _context9, _context10, _context11;
return concat$5(_context7 = concat$5(_context8 = concat$5(_context9 = concat$5(_context10 = concat$5(_context11 = "".concat(prefix, "<a href=\"mailto:")).call(_context11, encodeURIOnce(address), "\" ")).call(_context10, _this2.target, " ")).call(_context9, _this2.rel, ">")).call(_context8, escapeHTMLSpecialCharOnce(address), "</a>")).call(_context7, suffix);
} // 不识别无协议头的URL且开头不应该含有斜杠
if (URL_NO_SLASH.test(address)) {
var _context12, _context13;
return concat$5(_context12 = concat$5(_context13 = "".concat(prefix)).call(_context13, _this2.renderLink("//".concat(address), address))).call(_context12, suffix);
} // 其他的属于非法情况
return match;
} // 被<>包裹
if (isWrappedByBracket) {
// mailto
if (EMAIL.test(address)) {
var _context14, _context15, _context16;
return concat$5(_context14 = concat$5(_context15 = concat$5(_context16 = "<a href=\"mailto:".concat(encodeURIOnce(address), "\" ")).call(_context16, _this2.target, " ")).call(_context15, _this2.rel, ">")).call(_context14, escapeHTMLSpecialCharOnce(address), "</a>");
} // 可识别任意协议的URL或不以斜杠开头的URL
if (URL$1.test(address) || URL_NO_SLASH.test(address)) {
return _this2.renderLink(address);
} // 其他非法
return match;
}
default:
// 协议头不为空时的非法URL
if (!URL$1.test(address)) {
return match;
} // TODO: Url Validator
return concat$5(_context17 = concat$5(_context18 = "".concat(prefix)).call(_context18, _this2.renderLink(concat$5(_context19 = "".concat($protocol)).call(_context19, address)))).call(_context17, suffix);
} // this should never happen
return match;
});
}
}, {
key: "rule",
value: function rule() {
var _context20;
// (?<protocol>\\w+:)\\/\\/
var ret = {
// ?<left>
begin: '(<?)',
content: [// ?<protocol>
'((?:[a-z][a-z0-9+.-]{1,31}:)?)', // protocol is any seq of 2-32 chars beginning with letter
// '(?<slash>(?:\\/{2})?)',
// ?<address>
// '([^\\s\\x00-\\x1f"<>]+)',
concat$5(_context20 = "((?:".concat(URL_INLINE.source, ")|(?:")).call(_context20, EMAIL_INLINE.source, "))") // [
// `(?<url>${ URL_INLINE.source })`,
// `(?<email>${ EMAIL_INLINE.source })`, // email
// ].join('|'),
// ')'
].join(''),
// ?<right>
end: '(>?)' // TODO: extend attrs e.g. {target=_blank}
};
ret.reg = compileRegExp(ret, 'ig');
return ret;
}
/**
* 渲染链接为a标签返回html
* @param {string} url src链接
* @param {string} [text] 展示的链接文本不传默认使用url
* @returns 渲染的a标签
*/
}, {
key: "renderLink",
value: function renderLink(url, text) {
var _context22, _context23, _context24, _context25;
var linkText = text;
if (typeof linkText !== 'string') {
if (this.enableShortLink) {
var _context21;
var Url = url.replace(/^https?:\/\//i, '');
linkText = concat$5(_context21 = "".concat(Url.substring(0, this.shortLinkLength))).call(_context21, Url.length > this.shortLinkLength ? '...' : '');
} else {
linkText = url;
}
}
var processedURL = this.urlProcessor(url, 'autolink');
return concat$5(_context22 = concat$5(_context23 = concat$5(_context24 = concat$5(_context25 = "<a ".concat(this.target, " ")).call(_context25, this.rel, " title=\"")).call(_context24, escapeHTMLSpecialCharOnce(url).replace(/_/g, '\\_'), "\" href=\"")).call(_context23, encodeURIOnce(processedURL).replace(/_/g, '\\_'), "\">")).call(_context22, escapeHTMLSpecialCharOnce(linkText).replace(/_/g, '\\_'), "</a>");
}
}]);
return AutoLink;
}(SyntaxBase);
_defineProperty(AutoLink, "HOOK_NAME", 'autoLink');
/**
* 装饰器,挂载对应的模块到实例上
*/
function LoadMathModule() {
var _this$externals$katex, _this$externals, _this$externals$MathJ, _this$externals2;
if (!isBrowser()) {
return;
} // @ts-ignore
this.katex = (_this$externals$katex = (_this$externals = this.externals) === null || _this$externals === void 0 ? void 0 : _this$externals.katex) !== null && _this$externals$katex !== void 0 ? _this$externals$katex : window.katex; // @ts-ignore
this.MathJax = (_this$externals$MathJ = (_this$externals2 = this.externals) === null || _this$externals2 === void 0 ? void 0 : _this$externals2.MathJax) !== null && _this$externals$MathJ !== void 0 ? _this$externals$MathJ : window.MathJax;
}
var configureMathJax = function configureMathJax(usePlugins) {
if (!isBrowser()) {
console.log('mathjax disabled');
return;
}
var plugins = usePlugins ? ['input/asciimath', '[tex]/noerrors', '[tex]/cancel', '[tex]/color', '[tex]/boldsymbol'] : []; // @ts-ignore
window.MathJax = {
startup: {
elements: ['.Cherry-Math', '.Cherry-InlineMath'],
typeset: true
},
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']],
displayMath: [['$$', '$$'], ['\\[', '\\]']],
tags: 'ams',
packages: {
'[+]': ['noerrors', 'cancel', 'color']
},
macros: {
bm: ['{\\boldsymbol{#1}}', 1]
}
},
options: {
skipHtmlTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code', 'a'],
ignoreHtmlClass: 'tex2jax_ignore',
processHtmlClass: 'tex2jax_process',
// 关闭 mathjax 菜单
enableMenu: false
},
loader: {
load: plugins
}
};
};
var noEscape = ['&', '<', '>', '"', "'"]; // 需要转换为HTML实体字符的符号
// 用于预处理会在Markdown中被反转义的字符\\ 会被反转义为 \
var escapeFormulaPunctuations = function escapeFormulaPunctuations(formula) {
var $formula = formula.replace(new RegExp(PUNCTUATION, 'g'), function (match) {
if (indexOf$8(noEscape).call(noEscape, match) !== -1) {
// HTML特殊字符需要转换为实体字符防XSS注入
return escapeHTMLSpecialChar(match);
}
return "\\".concat(match); // 先转义特殊字符防止在afterMakeHtml中被反转义
});
return $formula;
};
function _createSuper$m(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$m(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$m() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var MathBlock = /*#__PURE__*/function (_ParagraphBase) {
_inherits(MathBlock, _ParagraphBase);
var _super = _createSuper$m(MathBlock);
/**
* 块级公式语法
* 该语法具有排他性,并且需要优先其他段落级语法进行渲染
* @type {'katex' | 'MathJax' | 'node'}
*/
// 渲染引擎默认为MathJaxMathJax支持2.x与3.x版本
function MathBlock(_ref) {
var _config$engine;
var _this;
var config = _ref.config;
_classCallCheck(this, MathBlock);
_this = _super.call(this, {
needCache: true
}); // 非浏览器环境下配置为 node
_defineProperty(_assertThisInitialized(_this), "engine", 'MathJax');
_defineProperty(_assertThisInitialized(_this), "katex", void 0);
_defineProperty(_assertThisInitialized(_this), "MathJax", void 0);
_this.engine = isBrowser() ? (_config$engine = config.engine) !== null && _config$engine !== void 0 ? _config$engine : 'MathJax' : 'node';
return _this;
}
_createClass(MathBlock, [{
key: "toHtml",
value: function toHtml(wholeMatch, lineSpace, leadingChar, content) {
var _this$MathJax, _context5, _context6;
bind$5(LoadMathModule).call(LoadMathModule, this)('engine'); // 去掉开头的空字符,去掉结尾的换行符
var wholeMatchWithoutSpace = wholeMatch.replace(/^[ \f\r\t\v]*/, '').replace(/\s*$/, ''); // 去掉匹配到的第一个换行符
var lineSpaceWithoutPreSpace = lineSpace.replace(/^[ \f\r\t\v]*\n/, '');
var sign = this.$engine.md5(wholeMatch);
var lines = this.getLineCount(wholeMatchWithoutSpace, lineSpaceWithoutPreSpace); // 判断公式是不是新行输入如果不是新行则行号减1
if (!/\n/.test(lineSpace)) {
lines -= 1;
} // 判断公式后面有没有尾接内容如果尾接了内容则行号减1
if (!/\n\s*$/.test(wholeMatch)) {
lines -= 1;
} // 目前的机制还没有测过lines为负数的情况先不处理
lines = lines > 0 ? lines : 0;
if (this.engine === 'katex') {
var _context, _context2;
// katex渲染
var html = this.katex.renderToString(content, {
throwOnError: false,
displayMode: true
});
var _result = concat$5(_context = concat$5(_context2 = "<div data-sign=\"".concat(sign, "\" class=\"Cherry-Math\" data-type=\"mathBlock\"\n data-lines=\"")).call(_context2, lines, "\">")).call(_context, html, "</div>");
return leadingChar + this.getCacheWithSpace(this.pushCache(_result, sign, lines), wholeMatch);
}
if ((_this$MathJax = this.MathJax) !== null && _this$MathJax !== void 0 && _this$MathJax.tex2svg) {
var _context3, _context4;
// MathJax渲染
var svg = getHTML(this.MathJax.tex2svg(content), true);
var _result2 = concat$5(_context3 = concat$5(_context4 = "<div data-sign=\"".concat(sign, "\" class=\"Cherry-Math\" data-type=\"mathBlock\"\n data-lines=\"")).call(_context4, lines, "\">")).call(_context3, svg, "</div>");
return leadingChar + this.getCacheWithSpace(this.pushCache(_result2, sign, lines), wholeMatch);
} // 既无MathJax又无katex时原样输出
var result = concat$5(_context5 = concat$5(_context6 = "<div data-sign=\"".concat(sign, "\" class=\"Cherry-Math\" data-type=\"mathBlock\"\n data-lines=\"")).call(_context6, lines, "\">$$")).call(_context5, escapeFormulaPunctuations(content), "$$</div>");
return leadingChar + this.getCacheWithSpace(this.pushCache(result, sign, lines), wholeMatch);
}
}, {
key: "beforeMakeHtml",
value: function beforeMakeHtml(str) {
var _context8;
if (isLookbehindSupported()) {
var _context7;
return str.replace(this.RULE.reg, bind$5(_context7 = this.toHtml).call(_context7, this));
}
return replaceLookbehind(str, this.RULE.reg, bind$5(_context8 = this.toHtml).call(_context8, this), true, 1);
}
}, {
key: "makeHtml",
value: function makeHtml(str) {
return str;
}
}, {
key: "rule",
value: function rule() {
var ret = {
begin: isLookbehindSupported() ? '(\\s*)((?<!\\\\))~D~D\\s*' : '(\\s*)(^|[^\\\\])~D~D\\s*',
content: '([\\w\\W]*?)',
end: '(\\s*)~D~D(?:\\s{0,1})'
};
ret.reg = new RegExp(ret.begin + ret.content + ret.end, 'g');
return ret;
}
}]);
return MathBlock;
}(ParagraphBase);
_defineProperty(MathBlock, "HOOK_NAME", 'mathBlock');
function _createSuper$n(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$n(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$n() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 行内公式的语法
* 虽然叫做行内公式Cherry依然将其视为“段落级语法”因为其具备排他性并且需要优先渲染
*/
var InlineMath = /*#__PURE__*/function (_ParagraphBase) {
_inherits(InlineMath, _ParagraphBase);
var _super = _createSuper$n(InlineMath);
/** @type {'katex' | 'MathJax' | 'node'} */
// 渲染引擎默认为MathJaxMathJax支持2.x与3.x版本
function InlineMath(_ref) {
var _config$engine;
var _this;
var config = _ref.config;
_classCallCheck(this, InlineMath);
_this = _super.call(this, {
needCache: true
}); // 非浏览器环境下配置为 node
_defineProperty(_assertThisInitialized(_this), "engine", 'MathJax');
_defineProperty(_assertThisInitialized(_this), "katex", void 0);
_defineProperty(_assertThisInitialized(_this), "MathJax", void 0);
_this.engine = isBrowser() ? (_config$engine = config.engine) !== null && _config$engine !== void 0 ? _config$engine : 'MathJax' : 'node';
return _this;
}
_createClass(InlineMath, [{
key: "toHtml",
value: function toHtml(wholeMatch, leadingChar, m1) {
var _this$katex, _this$MathJax, _context5, _context6;
if (!m1) {
return wholeMatch;
}
bind$5(LoadMathModule).call(LoadMathModule, this)('engine');
var linesArr = m1.match(/\n/g);
var lines = linesArr ? linesArr.length + 2 : 2;
var sign = this.$engine.md5(wholeMatch);
if (this.engine === 'katex' && (_this$katex = this.katex) !== null && _this$katex !== void 0 && _this$katex.renderToString) {
var _context, _context2;
// katex渲染
var html = this.katex.renderToString(m1, {
throwOnError: false
});
var _result = concat$5(_context = concat$5(_context2 = "".concat(leadingChar, "<span class=\"Cherry-InlineMath\" data-type=\"mathBlock\" data-lines=\"")).call(_context2, lines, "\">")).call(_context, html, "</span>");
return this.pushCache(_result, ParagraphBase.IN_PARAGRAPH_CACHE_KEY_PREFIX + sign);
}
if ((_this$MathJax = this.MathJax) !== null && _this$MathJax !== void 0 && _this$MathJax.tex2svg) {
var _context3, _context4;
// MathJax渲染
var svg = getHTML(this.MathJax.tex2svg(m1, {
em: 12,
ex: 6,
display: false
}), true);
var _result2 = concat$5(_context3 = concat$5(_context4 = "".concat(leadingChar, "<span class=\"Cherry-InlineMath\" data-type=\"mathBlock\" data-lines=\"")).call(_context4, lines, "\">")).call(_context3, svg, "</span>");
return this.pushCache(_result2, ParagraphBase.IN_PARAGRAPH_CACHE_KEY_PREFIX + sign);
} // 既无MathJax又无katex时原样输出
var result = concat$5(_context5 = concat$5(_context6 = "".concat(leadingChar, "<span class=\"Cherry-InlineMath\" data-type=\"mathBlock\"\n data-lines=\"")).call(_context6, lines, "\">$")).call(_context5, escapeFormulaPunctuations(m1), "$</span>");
return this.pushCache(result, ParagraphBase.IN_PARAGRAPH_CACHE_KEY_PREFIX + sign);
}
}, {
key: "beforeMakeHtml",
value: function beforeMakeHtml(str) {
var _this2 = this;
var $str = str; // 格里处理行内公式让一个td里的行内公式语法生效让跨td的行内公式语法失效
$str = $str.replace(getTableRule(true), function (whole) {
var _context7;
return map$3(_context7 = whole.split('|')).call(_context7, function (oneTd) {
return _this2.makeInlineMath(oneTd);
}).join('|').replace(/\\~D/g, '~D') // 出现反斜杠的情况(如/$e=m^2$)会导致多一个反斜杠,这里替换掉
.replace(/~D/g, '\\~D');
});
return this.makeInlineMath($str);
}
}, {
key: "makeInlineMath",
value: function makeInlineMath(str) {
var _context9;
if (!this.test(str)) {
return str;
}
if (isLookbehindSupported()) {
var _context8;
return str.replace(this.RULE.reg, bind$5(_context8 = this.toHtml).call(_context8, this));
}
return replaceLookbehind(str, this.RULE.reg, bind$5(_context9 = this.toHtml).call(_context9, this), true, 1);
}
}, {
key: "makeHtml",
value: function makeHtml(str) {
return str;
}
}, {
key: "rule",
value: function rule() {
var ret = {
begin: isLookbehindSupported() ? '((?<!\\\\))~D\\n?' : '(^|[^\\\\])~D\\n?',
content: '(.*?)\\n?',
end: '~D'
};
ret.reg = new RegExp(ret.begin + ret.content + ret.end, 'g');
return ret;
}
}]);
return InlineMath;
}(ParagraphBase);
_defineProperty(InlineMath, "HOOK_NAME", 'inlineMath');
// `Array.prototype.fill` method implementation
// https://tc39.es/ecma262/#sec-array.prototype.fill
var arrayFill = function fill(value /* , start = 0, end = @length */) {
var O = toObject(this);
var length = lengthOfArrayLike(O);
var argumentsLength = arguments.length;
var index = toAbsoluteIndex(argumentsLength > 1 ? arguments[1] : undefined, length);
var end = argumentsLength > 2 ? arguments[2] : undefined;
var endPos = end === undefined ? length : toAbsoluteIndex(end, length);
while (endPos > index) O[index++] = value;
return O;
};
// `Array.prototype.fill` method
// https://tc39.es/ecma262/#sec-array.prototype.fill
_export({ target: 'Array', proto: true }, {
fill: arrayFill
});
var fill = entryVirtual('Array').fill;
var ArrayPrototype$b = Array.prototype;
var fill$1 = function (it) {
var own = it.fill;
return it === ArrayPrototype$b || (objectIsPrototypeOf(ArrayPrototype$b, it) && own === ArrayPrototype$b.fill) ? fill : own;
};
var fill$2 = fill$1;
var fill$3 = fill$2;
function _createSuper$o(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$o(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$o() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function defaultLinkProcessor(link) {
return link;
}
var defaultOptions = {
tocStyle: 'plain',
// plain or nested
tocNodeClass: 'toc-li',
tocContainerClass: 'toc',
tocTitleClass: 'toc-title',
linkProcessor: defaultLinkProcessor
};
var emptyLinePlaceholder = '<p data-sign="empty-toc" data-lines="1">&nbsp;</p>';
var Toc = /*#__PURE__*/function (_ParagraphBase) {
_inherits(Toc, _ParagraphBase);
var _super = _createSuper$o(Toc);
// plain or nested
/** 标记当前是否处于第一个toc且仅渲染一个toc */
/** 允许渲染多个TOC */
function Toc(_ref) {
var _context;
var _this;
var externals = _ref.externals,
config = _ref.config;
_classCallCheck(this, Toc);
_this = _super.call(this, {
needCache: true
});
_defineProperty(_assertThisInitialized(_this), "tocStyle", 'nested');
_defineProperty(_assertThisInitialized(_this), "tocNodeClass", 'toc-li');
_defineProperty(_assertThisInitialized(_this), "tocContainerClass", 'toc');
_defineProperty(_assertThisInitialized(_this), "tocTitleClass", 'toc-title');
_defineProperty(_assertThisInitialized(_this), "linkProcessor", defaultLinkProcessor);
_defineProperty(_assertThisInitialized(_this), "baseLevel", 1);
_defineProperty(_assertThisInitialized(_this), "isFirstTocToken", true);
_defineProperty(_assertThisInitialized(_this), "allowMultiToc", false);
forEach$3(_context = keys$3(defaultOptions)).call(_context, function (key) {
_this[key] = config[key] || defaultOptions[key];
});
return _this;
}
_createClass(Toc, [{
key: "beforeMakeHtml",
value: function beforeMakeHtml(str) {
var _this2 = this;
var $str = str;
if (this.test($str, 'extend')) {
$str = $str.replace(this.RULE.extend.reg, function (match, lines, toc) {
if (!_this2.allowMultiToc && !_this2.isFirstTocToken) {
var _context2;
// 需要补齐非捕获的\n以及第一个分组中的\n
return concat$5(_context2 = "\n".concat(lines)).call(_context2, emptyLinePlaceholder);
}
var placeHolder = _this2.pushCache(match);
_this2.isFirstTocToken = false;
return prependLineFeedForParagraph(match, placeHolder);
});
}
if (this.test($str, 'standard')) {
$str = $str.replace(this.RULE.standard.reg, function (match, lines, toc) {
if (!_this2.allowMultiToc && !_this2.isFirstTocToken) {
var _context3;
// 需要补齐非捕获的\n以及第一个分组中的\n
return concat$5(_context3 = "\n".concat(lines)).call(_context3, emptyLinePlaceholder);
}
_this2.isFirstTocToken = false;
var placeHolder = _this2.pushCache(match);
return prependLineFeedForParagraph(match, placeHolder);
});
}
return $str;
}
}, {
key: "makeHtml",
value: function makeHtml(str) {
return str;
}
}, {
key: "$makeLevel",
value: function $makeLevel(num) {
var ret = '';
for (var i = this.baseLevel; i < num; i++) {
ret += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
}
return ret;
}
/**
* 生成TOC节点HTML
* @param {{ level: number; id: string; text: string }} node Toc节点对象
* @param {boolean} prependWhitespaceIndent 是否在文本前插入缩进空格
* @param {boolean} [closeTag=true] 是否闭合标签
* @returns {string}
*/
}, {
key: "$makeTocItem",
value: function $makeTocItem(node, prependWhitespaceIndent) {
var _context4, _context5, _context6, _context7, _context8;
var closeTag = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var nodePrefix = '';
if (prependWhitespaceIndent) {
nodePrefix = this.$makeLevel(node.level);
}
var tocLink = this.linkProcessor("#".concat(node.id).replace(/safe_/g, '')); // transform header id to avoid being sanitized
return concat$5(_context4 = concat$5(_context5 = concat$5(_context6 = concat$5(_context7 = concat$5(_context8 = "<li class=\"".concat(this.tocNodeClass, "\">")).call(_context8, nodePrefix, "<a href=\"")).call(_context7, tocLink, "\" class=\"level-")).call(_context6, node.level, "\">")).call(_context5, node.text, "</a>")).call(_context4, closeTag ? '</li>' : '');
}
}, {
key: "$makePlainToc",
value: function $makePlainToc(tocNodeList) {
var _this3 = this;
// this.baseLevel = Math.min(...tocNodeList.map((node) => node.level));
var items = map$3(tocNodeList).call(tocNodeList, function (node) {
return _this3.$makeTocItem(node, true);
});
return items.join('');
}
/**
* 生成嵌套的TOC列表算法思路参考flexmark
* @see https://github.com/vsch/flexmark-java/blob/master/flexmark-ext-toc/
* src/main/java/com/vladsch/flexmark/ext/toc/TocUtils.java#L140-L227
*
* @param {{ level:number; id:string; text:string }[]} nodeList 节点列表
* @returns {string}
*/
}, {
key: "$makeNestedToc",
value: function $makeNestedToc(nodeList) {
var _context9,
_context10,
_this4 = this;
var lastLevel = 0;
var unclosedItem = fill$3(_context9 = new Array(7)).call(_context9, false);
var unclosedList = fill$3(_context10 = new Array(7)).call(_context10, false); // lists nodes for debug
// const lists = [];
// const nodes = [];
var html = '';
forEach$3(nodeList).call(nodeList, function (node) {
var nodeLevel = node.level;
if (lastLevel === 0) {
for (var i = nodeLevel; i >= _this4.baseLevel; i--) {
html += '<ul>'; // lists.push('ul');
// nodes.push(null);
unclosedList[i] = true;
}
html += _this4.$makeTocItem(node, false, false); // lists.push('li');
// nodes.push(node);
unclosedItem[nodeLevel] = true;
lastLevel = nodeLevel;
return;
}
if (nodeLevel < lastLevel) {
// 减少层级
for (var _i = lastLevel; _i >= nodeLevel; _i--) {
if (unclosedItem[_i]) {
html += '</li>'; // lists.push('/li');
// nodes.push(null);
unclosedItem[_i] = false;
} // 减少层级时,不闭合当前层级的列表,只闭合同层级的列表项
if (unclosedList[_i] && _i > nodeLevel) {
html += '</ul>'; // lists.push('/ul');
// nodes.push(null);
unclosedList[_i] = false;
}
}
unclosedItem[nodeLevel] = true;
html += _this4.$makeTocItem(node, false, false); // lists.push('li');
// nodes.push(node);
lastLevel = nodeLevel;
} else if (nodeLevel === lastLevel) {
if (unclosedItem[lastLevel]) {
html += '</li>'; // lists.push('/li');
// nodes.push(null);
}
html += _this4.$makeTocItem(node, false, false); // lists.push('li');
// nodes.push(node);
unclosedItem[nodeLevel] = true;
unclosedList[nodeLevel] = true;
} else {
// 增加层级
for (var _i2 = lastLevel + 1; _i2 <= nodeLevel; _i2++) {
html += '<ul>'; // lists.push('ul');
// nodes.push(null);
unclosedList[_i2] = true;
}
unclosedItem[nodeLevel] = true;
html += _this4.$makeTocItem(node, false, false); // lists.push('li');
// nodes.push(node);
lastLevel = nodeLevel;
}
});
for (var i = lastLevel; i >= this.baseLevel; i--) {
if (unclosedItem[i]) {
html += '</li>'; // lists.push('/li');
// nodes.push(null);
unclosedItem[i] = false;
}
if (unclosedList[i]) {
html += '</ul>'; // lists.push('/ul');
// nodes.push(null);
unclosedList[i] = false;
}
} // console.log(lists, nodes);
// console.log(html);
return html;
}
}, {
key: "$makeToc",
value: function $makeToc(arr, dataSign, preLinesMatch) {
var _context11, _context12, _context13;
var lines = calculateLinesOfParagraph(preLinesMatch, 1);
var ret = concat$5(_context11 = concat$5(_context12 = concat$5(_context13 = "<dir class=\"".concat(this.tocContainerClass, "\" data-sign=\"")).call(_context13, dataSign, "-")).call(_context12, lines, "\" data-lines=\"")).call(_context11, lines, "\">");
ret += "<p class=\"".concat(this.tocTitleClass, "\">\u76EE\u5F55</p>");
if (arr.length <= 0) {
return '';
}
this.baseLevel = Math.min.apply(Math, _toConsumableArray(map$3(arr).call(arr, function (node) {
return node.level;
})));
if (this.tocStyle === 'nested') {
ret += this.$makeNestedToc(arr);
} else {
ret += this.$makePlainToc(arr);
}
ret += '</dir>';
return ret;
}
}, {
key: "afterMakeHtml",
value: function afterMakeHtml(str) {
var _this5 = this;
var $str = _get(_getPrototypeOf(Toc.prototype), "afterMakeHtml", this).call(this, str);
var headerList = [];
var headerRegex = /<h([1-6])[^>]*? id="([^"]+?)"[^>]*?>(?:<a[^/]+?\/a>|)(.+?)<\/h\1>/g;
var str2Md5 = '';
$str.replace(headerRegex, function (match, level, id, text) {
var _context14;
var $text = text.replace(/~fn#[0-9]+#/g, '');
headerList.push({
level: +level,
id: id,
text: $text
});
str2Md5 += concat$5(_context14 = "".concat(level)).call(_context14, id);
});
str2Md5 = this.$engine.md5(str2Md5);
$str = $str.replace(/(?:^|\n)(\[\[|\[|【【)(toc|TOC)(\]\]|\]|】】)([<~])/, function (match) {
return match.replace(/(\]\]|\]|】】)([<~])/, '$1\n$2');
}); // 首先识别扩展语法
$str = $str.replace(this.RULE.extend.reg, function (match, preLinesMatch) {
return _this5.$makeToc(headerList, str2Md5, preLinesMatch);
}); // 处理标准语法
$str = $str.replace(this.RULE.standard.reg, function (match, preLinesMatch) {
return _this5.$makeToc(headerList, str2Md5, preLinesMatch);
}); // 重置toc状态
this.isFirstTocToken = true;
return $str;
}
}, {
key: "test",
value: function test(str, flavor) {
return this.RULE[flavor].reg ? this.RULE[flavor].reg.test(str) : false;
}
}, {
key: "rule",
value: function rule() {
var extend = {
begin: '(?:^|\\n)(\\n*)',
end: '(?=$|\\n)',
content: '[ ]*((?:【【|\\[\\[)(?:toc|TOC)(?:\\]\\]|】】))[ ]*'
};
extend.reg = new RegExp(extend.begin + extend.content + extend.end, 'g');
var standard = {
begin: '(?:^|\\n)(\\n*)',
end: '(?=$|\\n)',
content: '[ ]*(\\[(?:toc|TOC)\\])[ ]*'
};
standard.reg = new RegExp(standard.begin + standard.content + standard.end, 'g');
return {
extend: extend,
standard: standard
};
}
}]);
return Toc;
}(ParagraphBase);
_defineProperty(Toc, "HOOK_NAME", 'toc');
function _createSuper$p(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$p(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$p() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Footnote = /*#__PURE__*/function (_ParagraphBase) {
_inherits(Footnote, _ParagraphBase);
var _super = _createSuper$p(Footnote);
function Footnote(_ref) {
var _this;
var externals = _ref.externals,
config = _ref.config;
_classCallCheck(this, Footnote);
_this = _super.call(this);
_this.footnoteCache = {};
_this.footnoteMap = {}; // 角标缓存索引
_this.footnote = [];
return _this;
}
_createClass(Footnote, [{
key: "$cleanCache",
value: function $cleanCache() {
this.footnoteCache = {};
this.footnoteMap = {}; // 角标缓存索引
this.footnote = [];
}
}, {
key: "pushFootnoteCache",
value: function pushFootnoteCache(key, cache) {
this.footnoteCache[key] = cache;
}
}, {
key: "getFootnoteCache",
value: function getFootnoteCache(key) {
return this.footnoteCache[key] || null;
}
}, {
key: "pushFootNote",
value: function pushFootNote(key, note) {
var _context, _context2, _context3, _context4, _context5, _context6;
if (this.footnoteMap[key]) {
// 重复引用时返回已缓存下标
return this.footnoteMap[key];
}
var num = this.footnote.length + 1;
var fn = {};
fn.fn = concat$5(_context = concat$5(_context2 = concat$5(_context3 = "<sup><a href=\"#fn:".concat(num, "\" id=\"fnref:")).call(_context3, num, "\" title=\"")).call(_context2, key, "\" class=\"footnote\">[")).call(_context, num, "]</a></sup>");
fn.fnref = concat$5(_context4 = concat$5(_context5 = concat$5(_context6 = "<a href=\"#fnref:".concat(num, "\" id=\"fn:")).call(_context6, num, "\" title=\"")).call(_context5, key, "\" class=\"footnote-ref\">[")).call(_context4, num, "]</a>");
fn.num = num;
fn.note = trim$3(note).call(note);
this.footnote.push(fn);
var replaceKey = "\0~fn#".concat(num - 1, "#\0");
this.footnoteMap[key] = replaceKey;
return replaceKey;
}
}, {
key: "getFootNote",
value: function getFootNote() {
return this.footnote;
}
}, {
key: "formatFootNote",
value: function formatFootNote() {
var _context8;
var footnote = this.getFootNote();
if (footnote.length <= 0) {
return '';
}
var html = map$3(footnote).call(footnote, function (note) {
var _context7;
return concat$5(_context7 = "<div class=\"one-footnote\">\n".concat(note.fnref)).call(_context7, note.note, "\n</div>");
}).join('');
var sign = this.$engine.md5(html);
html = concat$5(_context8 = "<div class=\"footnote\" data-sign=\"".concat(sign, "\" data-lines=\"0\"><div class=\"footnote-title\">\u811A\u6CE8</div>")).call(_context8, html, "</div>");
return html;
} // getParagraphHook() {
// return this.commentPAR;
// }
}, {
key: "beforeMakeHtml",
value: function beforeMakeHtml(str) {
var _this2 = this;
// 单行注释TODO: 替换为引用
// str = str.replace(/(^|\n)\[([^^][^\]]*?)\]:([^\n]+?)(?=$|\n)/g, '$1');
var $str = str;
if (this.test($str)) {
$str = $str.replace(this.RULE.reg, function (match, leading, key, content) {
_this2.pushFootnoteCache(key, content);
var LF = match.match(/\n/g) || [];
return LF.join('');
}); // 替换实际引用
$str = $str.replace(/\[\^([^\]]+?)\](?!:)/g, function (match, key) {
var cache = _this2.getFootnoteCache(key);
if (cache) {
return _this2.pushFootNote(key, cache);
}
return match;
});
$str += this.formatFootNote();
}
return $str;
}
}, {
key: "makeHtml",
value: function makeHtml(str, sentenceMakeFunc) {
return str;
}
}, {
key: "afterMakeHtml",
value: function afterMakeHtml(str) {
var footNotes = this.getFootNote();
var $str = str.replace(/\0~fn#([0-9]+)#\0/g, function (match, num) {
return footNotes[num].fn;
});
this.$cleanCache();
return $str;
}
}, {
key: "rule",
value: function rule() {
var ret = {
begin: '(^|\\n)[ \t]*',
content: ['\\[\\^([^\\]]+?)\\]:\\h*', // footnote key
'([\\s\\S]+?)' // footnote content
].join(''),
end: '(?=\\s*$|\\n\\n)'
};
ret.reg = compileRegExp(ret, 'g', true);
return ret;
}
}]);
return Footnote;
}(ParagraphBase);
_defineProperty(Footnote, "HOOK_NAME", 'footnote');
function _createSuper$q(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$q(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$q() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 脚注和引用语法
* 示例:
* 这里需要一个脚注[^脚注别名1],另外这里也需要一个脚注[^another]。
* [^脚注别名1]: 无论脚注内容写在哪里,脚注的内容总会显示在页面最底部
* 以两次回车结束
*
* [^another]: 另外脚注里也可以使用一些简单的markdown语法
* >比如 !!#ff0000 这里!!有一段**引用**
*/
var CommentReference = /*#__PURE__*/function (_ParagraphBase) {
_inherits(CommentReference, _ParagraphBase);
var _super = _createSuper$q(CommentReference);
function CommentReference(_ref) {
var _this;
var externals = _ref.externals,
config = _ref.config;
_classCallCheck(this, CommentReference);
_this = _super.call(this);
_this.commentCache = {};
return _this;
}
_createClass(CommentReference, [{
key: "$cleanCache",
value: function $cleanCache() {
this.commentCache = {};
}
}, {
key: "pushCommentReferenceCache",
value: function pushCommentReferenceCache(key, cache) {
var _context;
var _cache$split = cache.split(/[ ]+/g),
_cache$split2 = _toArray(_cache$split),
url = _cache$split2[0],
args = slice$7(_cache$split2).call(_cache$split2, 1);
var innerUrl = UrlCache.set(url);
this.commentCache["".concat(key).toLowerCase()] = concat$5(_context = [innerUrl]).call(_context, _toConsumableArray(args)).join(' ');
}
}, {
key: "getCommentReferenceCache",
value: function getCommentReferenceCache(key) {
return this.commentCache["".concat(key).toLowerCase()] || null;
}
}, {
key: "beforeMakeHtml",
value: function beforeMakeHtml(str) {
var _this2 = this;
var $str = str;
if (this.test($str)) {
$str = $str.replace(this.RULE.reg, function (match, leading, key, content) {
var _match$match;
_this2.pushCommentReferenceCache(key, content);
var lineFeeds = (_match$match = match.match(/\n/g)) !== null && _match$match !== void 0 ? _match$match : [];
return lineFeeds.join('');
}); // 替换实际引用
var refRegex = /(\[[^\]\n]+?\])?(?:\[([^\]\n]+?)\])/g; // 匹配[xxx][ref]形式的内容,不严格大小写
$str = $str.replace(refRegex, function (match, leadingContent, key) {
var cache = _this2.getCommentReferenceCache(key);
if (cache) {
var _context3;
if (leadingContent) {
var _context2;
return concat$5(_context2 = "".concat(leadingContent, "(")).call(_context2, cache, ")"); // 替换为[xx](cache)形式交给Link或多媒体标签处理
}
return concat$5(_context3 = "[".concat(key, "](")).call(_context3, cache, ")"); // 替换为[ref](cache)形式交给Link或多媒体标签处理
}
return match;
});
this.$cleanCache();
}
return $str;
}
}, {
key: "makeHtml",
value: function makeHtml(str, sentenceMakeFunc) {
return str;
}
}, {
key: "afterMakeHtml",
value: function afterMakeHtml(str) {
return UrlCache.restoreAll(str);
}
}, {
key: "rule",
value: function rule() {
var ret = {
begin: '(^|\\n)[ \t]*',
content: ['\\[([^^][^\\]]*?)\\]:\\h*', // comment key
'([^\\n]+?)' // comment content
].join(''),
end: '(?=$|\\n)'
};
ret.reg = compileRegExp(ret, 'g', true);
return ret;
}
}]);
return CommentReference;
}(ParagraphBase);
_defineProperty(CommentReference, "HOOK_NAME", 'commentReference');
var $some = arrayIteration.some;
var STRICT_METHOD$3 = arrayMethodIsStrict('some');
// `Array.prototype.some` method
// https://tc39.es/ecma262/#sec-array.prototype.some
_export({ target: 'Array', proto: true, forced: !STRICT_METHOD$3 }, {
some: function some(callbackfn /* , thisArg */) {
return $some(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
var some = entryVirtual('Array').some;
var ArrayPrototype$c = Array.prototype;
var some$1 = function (it) {
var own = it.some;
return it === ArrayPrototype$c || (objectIsPrototypeOf(ArrayPrototype$c, it) && own === ArrayPrototype$c.some) ? some : own;
};
var some$2 = some$1;
var some$3 = some$2;
var purify = createCommonjsModule(function (module, exports) {
/*! @license DOMPurify 2.4.0 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.4.0/LICENSE */
(function (global, factory) {
module.exports = factory() ;
})(commonjsGlobal, (function () {
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 _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _construct(Parent, args, Class) {
if (_isNativeReflectConstruct()) {
_construct = Reflect.construct;
} else {
_construct = function _construct(Parent, args, Class) {
var a = [null];
a.push.apply(a, args);
var Constructor = Function.bind.apply(Parent, a);
var instance = new Constructor();
if (Class) _setPrototypeOf(instance, Class.prototype);
return instance;
};
}
return _construct.apply(null, arguments);
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
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 _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.");
}
var hasOwnProperty = Object.hasOwnProperty,
setPrototypeOf = Object.setPrototypeOf,
isFrozen = Object.isFrozen,
getPrototypeOf = Object.getPrototypeOf,
getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var freeze = Object.freeze,
seal = Object.seal,
create = Object.create; // eslint-disable-line import/no-mutable-exports
var _ref = typeof Reflect !== 'undefined' && Reflect,
apply = _ref.apply,
construct = _ref.construct;
if (!apply) {
apply = function apply(fun, thisValue, args) {
return fun.apply(thisValue, args);
};
}
if (!freeze) {
freeze = function freeze(x) {
return x;
};
}
if (!seal) {
seal = function seal(x) {
return x;
};
}
if (!construct) {
construct = function construct(Func, args) {
return _construct(Func, _toConsumableArray(args));
};
}
var arrayForEach = unapply(Array.prototype.forEach);
var arrayPop = unapply(Array.prototype.pop);
var arrayPush = unapply(Array.prototype.push);
var stringToLowerCase = unapply(String.prototype.toLowerCase);
var stringMatch = unapply(String.prototype.match);
var stringReplace = unapply(String.prototype.replace);
var stringIndexOf = unapply(String.prototype.indexOf);
var stringTrim = unapply(String.prototype.trim);
var regExpTest = unapply(RegExp.prototype.test);
var typeErrorCreate = unconstruct(TypeError);
function unapply(func) {
return function (thisArg) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return apply(func, thisArg, args);
};
}
function unconstruct(func) {
return function () {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return construct(func, args);
};
}
/* Add properties to a lookup table */
function addToSet(set, array, transformCaseFunc) {
transformCaseFunc = transformCaseFunc ? transformCaseFunc : stringToLowerCase;
if (setPrototypeOf) {
// Make 'in' and truthy checks like Boolean(set.constructor)
// independent of any properties defined on Object.prototype.
// Prevent prototype setters from intercepting set as a this value.
setPrototypeOf(set, null);
}
var l = array.length;
while (l--) {
var element = array[l];
if (typeof element === 'string') {
var lcElement = transformCaseFunc(element);
if (lcElement !== element) {
// Config presets (e.g. tags.js, attrs.js) are immutable.
if (!isFrozen(array)) {
array[l] = lcElement;
}
element = lcElement;
}
}
set[element] = true;
}
return set;
}
/* Shallow clone an object */
function clone(object) {
var newObject = create(null);
var property;
for (property in object) {
if (apply(hasOwnProperty, object, [property])) {
newObject[property] = object[property];
}
}
return newObject;
}
/* IE10 doesn't support __lookupGetter__ so lets'
* simulate it. It also automatically checks
* if the prop is function or getter and behaves
* accordingly. */
function lookupGetter(object, prop) {
while (object !== null) {
var desc = getOwnPropertyDescriptor(object, prop);
if (desc) {
if (desc.get) {
return unapply(desc.get);
}
if (typeof desc.value === 'function') {
return unapply(desc.value);
}
}
object = getPrototypeOf(object);
}
function fallbackValue(element) {
console.warn('fallback value for', element);
return null;
}
return fallbackValue;
}
var html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']); // SVG
var svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);
var svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']); // List of SVG elements that are disallowed by default.
// We still need to know them so that we can do namespace
// checks properly in case one wants to add them to
// allow-list.
var svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'fedropshadow', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);
var mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover']); // Similarly to SVG, we want to know all MathML elements,
// even those that we disallow by default.
var mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
var text = freeze(['#text']);
var html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'xmlns', 'slot']);
var svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);
var mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);
var xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
var MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
var ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/); // eslint-disable-line no-useless-escape
var ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
var IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape
);
var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
var ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
);
var DOCTYPE_NAME = seal(/^html$/i);
var getGlobal = function getGlobal() {
return typeof window === 'undefined' ? null : window;
};
/**
* Creates a no-op policy for internal use only.
* Don't export this function outside this module!
* @param {?TrustedTypePolicyFactory} trustedTypes The policy factory.
* @param {Document} document The document object (to determine policy name suffix)
* @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types
* are not supported).
*/
var _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, document) {
if (_typeof(trustedTypes) !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
return null;
} // Allow the callers to control the unique policy name
// by adding a data-tt-policy-suffix to the script element with the DOMPurify.
// Policy creation with duplicate names throws in Trusted Types.
var suffix = null;
var ATTR_NAME = 'data-tt-policy-suffix';
if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME)) {
suffix = document.currentScript.getAttribute(ATTR_NAME);
}
var policyName = 'dompurify' + (suffix ? '#' + suffix : '');
try {
return trustedTypes.createPolicy(policyName, {
createHTML: function createHTML(html) {
return html;
},
createScriptURL: function createScriptURL(scriptUrl) {
return scriptUrl;
}
});
} catch (_) {
// Policy creation failed (most likely another DOMPurify script has
// already run). Skip creating the policy, as this will only cause errors
// if TT are enforced.
console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
return null;
}
};
function createDOMPurify() {
var window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
var DOMPurify = function DOMPurify(root) {
return createDOMPurify(root);
};
/**
* Version label, exposed for easier checks
* if DOMPurify is up to date or not
*/
DOMPurify.version = '2.4.0';
/**
* Array of elements that DOMPurify removed during sanitation.
* Empty if nothing was removed.
*/
DOMPurify.removed = [];
if (!window || !window.document || window.document.nodeType !== 9) {
// Not running in a browser, provide a factory function
// so that you can pass your own Window
DOMPurify.isSupported = false;
return DOMPurify;
}
var originalDocument = window.document;
var document = window.document;
var DocumentFragment = window.DocumentFragment,
HTMLTemplateElement = window.HTMLTemplateElement,
Node = window.Node,
Element = window.Element,
NodeFilter = window.NodeFilter,
_window$NamedNodeMap = window.NamedNodeMap,
NamedNodeMap = _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap,
HTMLFormElement = window.HTMLFormElement,
DOMParser = window.DOMParser,
trustedTypes = window.trustedTypes;
var ElementPrototype = Element.prototype;
var cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
var getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
var getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
var getParentNode = lookupGetter(ElementPrototype, 'parentNode'); // As per issue #47, the web-components registry is inherited by a
// new document created via createHTMLDocument. As per the spec
// (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
// a new empty registry is used when creating a template contents owner
// document, so we use that as our parent document to ensure nothing
// is inherited.
if (typeof HTMLTemplateElement === 'function') {
var template = document.createElement('template');
if (template.content && template.content.ownerDocument) {
document = template.content.ownerDocument;
}
}
var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);
var emptyHTML = trustedTypesPolicy ? trustedTypesPolicy.createHTML('') : '';
var _document = document,
implementation = _document.implementation,
createNodeIterator = _document.createNodeIterator,
createDocumentFragment = _document.createDocumentFragment,
getElementsByTagName = _document.getElementsByTagName;
var importNode = originalDocument.importNode;
var documentMode = {};
try {
documentMode = clone(document).documentMode ? document.documentMode : {};
} catch (_) {}
var hooks = {};
/**
* Expose whether this browser supports running the full DOMPurify.
*/
DOMPurify.isSupported = typeof getParentNode === 'function' && implementation && typeof implementation.createHTMLDocument !== 'undefined' && documentMode !== 9;
var MUSTACHE_EXPR$1 = MUSTACHE_EXPR,
ERB_EXPR$1 = ERB_EXPR,
DATA_ATTR$1 = DATA_ATTR,
ARIA_ATTR$1 = ARIA_ATTR,
IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,
ATTR_WHITESPACE$1 = ATTR_WHITESPACE;
var IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
/**
* We consider the elements and attributes below to be safe. Ideally
* don't add any new ones but feel free to remove unwanted ones.
*/
/* allowed element names */
var ALLOWED_TAGS = null;
var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray(html$1), _toConsumableArray(svg$1), _toConsumableArray(svgFilters), _toConsumableArray(mathMl$1), _toConsumableArray(text)));
/* Allowed attribute names */
var ALLOWED_ATTR = null;
var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray(html), _toConsumableArray(svg), _toConsumableArray(mathMl), _toConsumableArray(xml)));
/*
* Configure how DOMPUrify should handle custom elements and their attributes as well as customized built-in elements.
* @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
* @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
* @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
*/
var CUSTOM_ELEMENT_HANDLING = Object.seal(Object.create(null, {
tagNameCheck: {
writable: true,
configurable: false,
enumerable: true,
value: null
},
attributeNameCheck: {
writable: true,
configurable: false,
enumerable: true,
value: null
},
allowCustomizedBuiltInElements: {
writable: true,
configurable: false,
enumerable: true,
value: false
}
}));
/* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
var FORBID_TAGS = null;
/* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
var FORBID_ATTR = null;
/* Decide if ARIA attributes are okay */
var ALLOW_ARIA_ATTR = true;
/* Decide if custom data attributes are okay */
var ALLOW_DATA_ATTR = true;
/* Decide if unknown protocols are okay */
var ALLOW_UNKNOWN_PROTOCOLS = false;
/* Output should be safe for common template engines.
* This means, DOMPurify removes data attributes, mustaches and ERB
*/
var SAFE_FOR_TEMPLATES = false;
/* Decide if document with <html>... should be returned */
var WHOLE_DOCUMENT = false;
/* Track whether config is already set on this instance of DOMPurify. */
var SET_CONFIG = false;
/* Decide if all elements (e.g. style, script) must be children of
* document.body. By default, browsers might move them to document.head */
var FORCE_BODY = false;
/* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
* string (or a TrustedHTML object if Trusted Types are supported).
* If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
*/
var RETURN_DOM = false;
/* Decide if a DOM `DocumentFragment` should be returned, instead of a html
* string (or a TrustedHTML object if Trusted Types are supported) */
var RETURN_DOM_FRAGMENT = false;
/* Try to return a Trusted Type object instead of a string, return a string in
* case Trusted Types are not supported */
var RETURN_TRUSTED_TYPE = false;
/* Output should be free from DOM clobbering attacks?
* This sanitizes markups named with colliding, clobberable built-in DOM APIs.
*/
var SANITIZE_DOM = true;
/* Achieve full DOM Clobbering protection by isolating the namespace of named
* properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
*
* HTML/DOM spec rules that enable DOM Clobbering:
* - Named Access on Window (§7.3.3)
* - DOM Tree Accessors (§3.1.5)
* - Form Element Parent-Child Relations (§4.10.3)
* - Iframe srcdoc / Nested WindowProxies (§4.8.5)
* - HTMLCollection (§4.2.10.2)
*
* Namespace isolation is implemented by prefixing `id` and `name` attributes
* with a constant string, i.e., `user-content-`
*/
var SANITIZE_NAMED_PROPS = false;
var SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
/* Keep element content when removing element? */
var KEEP_CONTENT = true;
/* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
* of importing it into a new Document and returning a sanitized copy */
var IN_PLACE = false;
/* Allow usage of profiles like html, svg and mathMl */
var USE_PROFILES = {};
/* Tags to ignore content of when KEEP_CONTENT is true */
var FORBID_CONTENTS = null;
var DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
/* Tags that are safe for data: URIs */
var DATA_URI_TAGS = null;
var DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
/* Attributes safe for values like "javascript:" */
var URI_SAFE_ATTRIBUTES = null;
var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
var MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
/* Document namespace */
var NAMESPACE = HTML_NAMESPACE;
var IS_EMPTY_INPUT = false;
/* Parsing of strict XHTML documents */
var PARSER_MEDIA_TYPE;
var SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
var DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
var transformCaseFunc;
/* Keep a reference to config to pass to hooks */
var CONFIG = null;
/* Ideally, do not touch anything below this line */
/* ______________________________________________ */
var formElement = document.createElement('form');
var isRegexOrFunction = function isRegexOrFunction(testValue) {
return testValue instanceof RegExp || testValue instanceof Function;
};
/**
* _parseConfig
*
* @param {Object} cfg optional config literal
*/
// eslint-disable-next-line complexity
var _parseConfig = function _parseConfig(cfg) {
if (CONFIG && CONFIG === cfg) {
return;
}
/* Shield configuration object from tampering */
if (!cfg || _typeof(cfg) !== 'object') {
cfg = {};
}
/* Shield configuration object from prototype pollution */
cfg = clone(cfg);
PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes
SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? PARSER_MEDIA_TYPE = DEFAULT_PARSER_MEDIA_TYPE : PARSER_MEDIA_TYPE = cfg.PARSER_MEDIA_TYPE; // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? function (x) {
return x;
} : stringToLowerCase;
/* Set configuration parameters */
ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), // eslint-disable-line indent
cfg.ADD_URI_SAFE_ATTR, // eslint-disable-line indent
transformCaseFunc // eslint-disable-line indent
) // eslint-disable-line indent
: DEFAULT_URI_SAFE_ATTRIBUTES;
DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), // eslint-disable-line indent
cfg.ADD_DATA_URI_TAGS, // eslint-disable-line indent
transformCaseFunc // eslint-disable-line indent
) // eslint-disable-line indent
: DEFAULT_DATA_URI_TAGS;
FORBID_CONTENTS = 'FORBID_CONTENTS' in cfg ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {};
FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {};
USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false;
ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
RETURN_DOM = cfg.RETURN_DOM || false; // Default false
RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
FORCE_BODY = cfg.FORCE_BODY || false; // Default false
SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
IN_PLACE = cfg.IN_PLACE || false; // Default false
IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$1;
NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
}
if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
}
if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
}
if (SAFE_FOR_TEMPLATES) {
ALLOW_DATA_ATTR = false;
}
if (RETURN_DOM_FRAGMENT) {
RETURN_DOM = true;
}
/* Parse profile info */
if (USE_PROFILES) {
ALLOWED_TAGS = addToSet({}, _toConsumableArray(text));
ALLOWED_ATTR = [];
if (USE_PROFILES.html === true) {
addToSet(ALLOWED_TAGS, html$1);
addToSet(ALLOWED_ATTR, html);
}
if (USE_PROFILES.svg === true) {
addToSet(ALLOWED_TAGS, svg$1);
addToSet(ALLOWED_ATTR, svg);
addToSet(ALLOWED_ATTR, xml);
}
if (USE_PROFILES.svgFilters === true) {
addToSet(ALLOWED_TAGS, svgFilters);
addToSet(ALLOWED_ATTR, svg);
addToSet(ALLOWED_ATTR, xml);
}
if (USE_PROFILES.mathMl === true) {
addToSet(ALLOWED_TAGS, mathMl$1);
addToSet(ALLOWED_ATTR, mathMl);
addToSet(ALLOWED_ATTR, xml);
}
}
/* Merge configuration parameters */
if (cfg.ADD_TAGS) {
if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
ALLOWED_TAGS = clone(ALLOWED_TAGS);
}
addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
}
if (cfg.ADD_ATTR) {
if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
ALLOWED_ATTR = clone(ALLOWED_ATTR);
}
addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
}
if (cfg.ADD_URI_SAFE_ATTR) {
addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
}
if (cfg.FORBID_CONTENTS) {
if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
FORBID_CONTENTS = clone(FORBID_CONTENTS);
}
addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
}
/* Add #text in case KEEP_CONTENT is set to true */
if (KEEP_CONTENT) {
ALLOWED_TAGS['#text'] = true;
}
/* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
if (WHOLE_DOCUMENT) {
addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
}
/* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
if (ALLOWED_TAGS.table) {
addToSet(ALLOWED_TAGS, ['tbody']);
delete FORBID_TAGS.tbody;
} // Prevent further manipulation of configuration.
// Not available in IE8, Safari 5, etc.
if (freeze) {
freeze(cfg);
}
CONFIG = cfg;
};
var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
var HTML_INTEGRATION_POINTS = addToSet({}, ['foreignobject', 'desc', 'title', 'annotation-xml']); // Certain elements are allowed in both SVG and HTML
// namespace. We need to specify them explicitly
// so that they don't get erroneously deleted from
// HTML namespace.
var COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
/* Keep track of all possible SVG and MathML tags
* so that we can perform the namespace checks
* correctly. */
var ALL_SVG_TAGS = addToSet({}, svg$1);
addToSet(ALL_SVG_TAGS, svgFilters);
addToSet(ALL_SVG_TAGS, svgDisallowed);
var ALL_MATHML_TAGS = addToSet({}, mathMl$1);
addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
/**
*
*
* @param {Element} element a DOM element whose namespace is being checked
* @returns {boolean} Return false if the element has a
* namespace that a spec-compliant parser would never
* return. Return true otherwise.
*/
var _checkValidNamespace = function _checkValidNamespace(element) {
var parent = getParentNode(element); // In JSDOM, if we're inside shadow DOM, then parentNode
// can be null. We just simulate parent in this case.
if (!parent || !parent.tagName) {
parent = {
namespaceURI: HTML_NAMESPACE,
tagName: 'template'
};
}
var tagName = stringToLowerCase(element.tagName);
var parentTagName = stringToLowerCase(parent.tagName);
if (element.namespaceURI === SVG_NAMESPACE) {
// The only way to switch from HTML namespace to SVG
// is via <svg>. If it happens via any other tag, then
// it should be killed.
if (parent.namespaceURI === HTML_NAMESPACE) {
return tagName === 'svg';
} // The only way to switch from MathML to SVG is via
// svg if parent is either <annotation-xml> or MathML
// text integration points.
if (parent.namespaceURI === MATHML_NAMESPACE) {
return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
} // We only allow elements that are defined in SVG
// spec. All others are disallowed in SVG namespace.
return Boolean(ALL_SVG_TAGS[tagName]);
}
if (element.namespaceURI === MATHML_NAMESPACE) {
// The only way to switch from HTML namespace to MathML
// is via <math>. If it happens via any other tag, then
// it should be killed.
if (parent.namespaceURI === HTML_NAMESPACE) {
return tagName === 'math';
} // The only way to switch from SVG to MathML is via
// <math> and HTML integration points
if (parent.namespaceURI === SVG_NAMESPACE) {
return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
} // We only allow elements that are defined in MathML
// spec. All others are disallowed in MathML namespace.
return Boolean(ALL_MATHML_TAGS[tagName]);
}
if (element.namespaceURI === HTML_NAMESPACE) {
// The only way to switch from SVG to HTML is via
// HTML integration points, and from MathML to HTML
// is via MathML text integration points
if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
return false;
}
if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
return false;
} // We disallow tags that are specific for MathML
// or SVG and should never appear in HTML namespace
return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
} // The code should never reach this place (this means
// that the element somehow got namespace that is not
// HTML, SVG or MathML). Return false just in case.
return false;
};
/**
* _forceRemove
*
* @param {Node} node a DOM node
*/
var _forceRemove = function _forceRemove(node) {
arrayPush(DOMPurify.removed, {
element: node
});
try {
// eslint-disable-next-line unicorn/prefer-dom-node-remove
node.parentNode.removeChild(node);
} catch (_) {
try {
node.outerHTML = emptyHTML;
} catch (_) {
node.remove();
}
}
};
/**
* _removeAttribute
*
* @param {String} name an Attribute name
* @param {Node} node a DOM node
*/
var _removeAttribute = function _removeAttribute(name, node) {
try {
arrayPush(DOMPurify.removed, {
attribute: node.getAttributeNode(name),
from: node
});
} catch (_) {
arrayPush(DOMPurify.removed, {
attribute: null,
from: node
});
}
node.removeAttribute(name); // We void attribute values for unremovable "is"" attributes
if (name === 'is' && !ALLOWED_ATTR[name]) {
if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
try {
_forceRemove(node);
} catch (_) {}
} else {
try {
node.setAttribute(name, '');
} catch (_) {}
}
}
};
/**
* _initDocument
*
* @param {String} dirty a string of dirty markup
* @return {Document} a DOM, filled with the dirty markup
*/
var _initDocument = function _initDocument(dirty) {
/* Create a HTML document */
var doc;
var leadingWhitespace;
if (FORCE_BODY) {
dirty = '<remove></remove>' + dirty;
} else {
/* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
var matches = stringMatch(dirty, /^[\r\n\t ]+/);
leadingWhitespace = matches && matches[0];
}
if (PARSER_MEDIA_TYPE === 'application/xhtml+xml') {
// Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
}
var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
/*
* Use the DOMParser API by default, fallback later if needs be
* DOMParser not work for svg when has multiple root element.
*/
if (NAMESPACE === HTML_NAMESPACE) {
try {
doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
} catch (_) {}
}
/* Use createHTMLDocument in case DOMParser is not available */
if (!doc || !doc.documentElement) {
doc = implementation.createDocument(NAMESPACE, 'template', null);
try {
doc.documentElement.innerHTML = IS_EMPTY_INPUT ? '' : dirtyPayload;
} catch (_) {// Syntax error if dirtyPayload is invalid xml
}
}
var body = doc.body || doc.documentElement;
if (dirty && leadingWhitespace) {
body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
}
/* Work on whole document or just its body */
if (NAMESPACE === HTML_NAMESPACE) {
return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
}
return WHOLE_DOCUMENT ? doc.documentElement : body;
};
/**
* _createIterator
*
* @param {Document} root document/fragment to create iterator for
* @return {Iterator} iterator instance
*/
var _createIterator = function _createIterator(root) {
return createNodeIterator.call(root.ownerDocument || root, root, // eslint-disable-next-line no-bitwise
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false);
};
/**
* _isClobbered
*
* @param {Node} elm element to check for clobbering attacks
* @return {Boolean} true if clobbered, false if safe
*/
var _isClobbered = function _isClobbered(elm) {
return elm instanceof HTMLFormElement && (typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function' || typeof elm.namespaceURI !== 'string' || typeof elm.insertBefore !== 'function');
};
/**
* _isNode
*
* @param {Node} obj object to check whether it's a DOM node
* @return {Boolean} true is object is a DOM node
*/
var _isNode = function _isNode(object) {
return _typeof(Node) === 'object' ? object instanceof Node : object && _typeof(object) === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string';
};
/**
* _executeHook
* Execute user configurable hooks
*
* @param {String} entryPoint Name of the hook's entry point
* @param {Node} currentNode node to work on with the hook
* @param {Object} data additional hook parameters
*/
var _executeHook = function _executeHook(entryPoint, currentNode, data) {
if (!hooks[entryPoint]) {
return;
}
arrayForEach(hooks[entryPoint], function (hook) {
hook.call(DOMPurify, currentNode, data, CONFIG);
});
};
/**
* _sanitizeElements
*
* @protect nodeName
* @protect textContent
* @protect removeChild
*
* @param {Node} currentNode to check for permission to exist
* @return {Boolean} true if node was killed, false if left alive
*/
var _sanitizeElements = function _sanitizeElements(currentNode) {
var content;
/* Execute a hook if present */
_executeHook('beforeSanitizeElements', currentNode, null);
/* Check if element is clobbered or can clobber */
if (_isClobbered(currentNode)) {
_forceRemove(currentNode);
return true;
}
/* Check if tagname contains Unicode */
if (regExpTest(/[\u0080-\uFFFF]/, currentNode.nodeName)) {
_forceRemove(currentNode);
return true;
}
/* Now let's check the element's type and name */
var tagName = transformCaseFunc(currentNode.nodeName);
/* Execute a hook if present */
_executeHook('uponSanitizeElement', currentNode, {
tagName: tagName,
allowedTags: ALLOWED_TAGS
});
/* Detect mXSS attempts abusing namespace confusion */
if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
_forceRemove(currentNode);
return true;
}
/* Mitigate a problem with templates inside select */
if (tagName === 'select' && regExpTest(/<template/i, currentNode.innerHTML)) {
_forceRemove(currentNode);
return true;
}
/* Remove element if anything forbids its presence */
if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
/* Check if we have a custom element to handle */
if (!FORBID_TAGS[tagName] && _basicCustomElementTest(tagName)) {
if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) return false;
if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) return false;
}
/* Keep content except for bad-listed elements */
if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
var parentNode = getParentNode(currentNode) || currentNode.parentNode;
var childNodes = getChildNodes(currentNode) || currentNode.childNodes;
if (childNodes && parentNode) {
var childCount = childNodes.length;
for (var i = childCount - 1; i >= 0; --i) {
parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));
}
}
}
_forceRemove(currentNode);
return true;
}
/* Check whether element has a valid namespace */
if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
_forceRemove(currentNode);
return true;
}
if ((tagName === 'noscript' || tagName === 'noembed') && regExpTest(/<\/no(script|embed)/i, currentNode.innerHTML)) {
_forceRemove(currentNode);
return true;
}
/* Sanitize element content to be template-safe */
if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
/* Get the element's text content */
content = currentNode.textContent;
content = stringReplace(content, MUSTACHE_EXPR$1, ' ');
content = stringReplace(content, ERB_EXPR$1, ' ');
if (currentNode.textContent !== content) {
arrayPush(DOMPurify.removed, {
element: currentNode.cloneNode()
});
currentNode.textContent = content;
}
}
/* Execute a hook if present */
_executeHook('afterSanitizeElements', currentNode, null);
return false;
};
/**
* _isValidAttribute
*
* @param {string} lcTag Lowercase tag name of containing element.
* @param {string} lcName Lowercase attribute name.
* @param {string} value Attribute value.
* @return {Boolean} Returns true if `value` is valid, otherwise false.
*/
// eslint-disable-next-line complexity
var _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
/* Make sure attribute cannot clobber */
if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
return false;
}
/* Allow valid data-* attributes: At least one character after "-"
(https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
We don't need to check the value; it's always URI safe. */
if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
if ( // First condition does a very basic check if a) it's basically a valid custom element tagname AND
// b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
// and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
_basicCustomElementTest(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) || // Alternative, second condition checks if it's an `is`-attribute, AND
// the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {
return false;
}
/* Check value is safe. First, is attr inert? If so, is safe */
} else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if (!value) ; else {
return false;
}
return true;
};
/**
* _basicCustomElementCheck
* checks if at least one dash is included in tagName, and it's not the first char
* for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
* @param {string} tagName name of the tag of the node to sanitize
*/
var _basicCustomElementTest = function _basicCustomElementTest(tagName) {
return tagName.indexOf('-') > 0;
};
/**
* _sanitizeAttributes
*
* @protect attributes
* @protect nodeName
* @protect removeAttribute
* @protect setAttribute
*
* @param {Node} currentNode to sanitize
*/
var _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
var attr;
var value;
var lcName;
var l;
/* Execute a hook if present */
_executeHook('beforeSanitizeAttributes', currentNode, null);
var attributes = currentNode.attributes;
/* Check if we have attributes; if not we might have a text node */
if (!attributes) {
return;
}
var hookEvent = {
attrName: '',
attrValue: '',
keepAttr: true,
allowedAttributes: ALLOWED_ATTR
};
l = attributes.length;
/* Go backwards over all attributes; safely remove bad ones */
while (l--) {
attr = attributes[l];
var _attr = attr,
name = _attr.name,
namespaceURI = _attr.namespaceURI;
value = name === 'value' ? attr.value : stringTrim(attr.value);
lcName = transformCaseFunc(name);
/* Execute a hook if present */
hookEvent.attrName = lcName;
hookEvent.attrValue = value;
hookEvent.keepAttr = true;
hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
_executeHook('uponSanitizeAttribute', currentNode, hookEvent);
value = hookEvent.attrValue;
/* Did the hooks approve of the attribute? */
if (hookEvent.forceKeepAttr) {
continue;
}
/* Remove attribute */
_removeAttribute(name, currentNode);
/* Did the hooks approve of the attribute? */
if (!hookEvent.keepAttr) {
continue;
}
/* Work around a security issue in jQuery 3.0 */
if (regExpTest(/\/>/i, value)) {
_removeAttribute(name, currentNode);
continue;
}
/* Sanitize attribute content to be template-safe */
if (SAFE_FOR_TEMPLATES) {
value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
value = stringReplace(value, ERB_EXPR$1, ' ');
}
/* Is `value` valid for this attribute? */
var lcTag = transformCaseFunc(currentNode.nodeName);
if (!_isValidAttribute(lcTag, lcName, value)) {
continue;
}
/* Full DOM Clobbering protection via namespace isolation,
* Prefix id and name attributes with `user-content-`
*/
if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {
// Remove the attribute with this value
_removeAttribute(name, currentNode); // Prefix the value and later re-create the attribute with the sanitized value
value = SANITIZE_NAMED_PROPS_PREFIX + value;
}
/* Handle attributes that require Trusted Types */
if (trustedTypesPolicy && _typeof(trustedTypes) === 'object' && typeof trustedTypes.getAttributeType === 'function') {
if (namespaceURI) ; else {
switch (trustedTypes.getAttributeType(lcTag, lcName)) {
case 'TrustedHTML':
value = trustedTypesPolicy.createHTML(value);
break;
case 'TrustedScriptURL':
value = trustedTypesPolicy.createScriptURL(value);
break;
}
}
}
/* Handle invalid data-* attribute set by try-catching it */
try {
if (namespaceURI) {
currentNode.setAttributeNS(namespaceURI, name, value);
} else {
/* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
currentNode.setAttribute(name, value);
}
arrayPop(DOMPurify.removed);
} catch (_) {}
}
/* Execute a hook if present */
_executeHook('afterSanitizeAttributes', currentNode, null);
};
/**
* _sanitizeShadowDOM
*
* @param {DocumentFragment} fragment to iterate over recursively
*/
var _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
var shadowNode;
var shadowIterator = _createIterator(fragment);
/* Execute a hook if present */
_executeHook('beforeSanitizeShadowDOM', fragment, null);
while (shadowNode = shadowIterator.nextNode()) {
/* Execute a hook if present */
_executeHook('uponSanitizeShadowNode', shadowNode, null);
/* Sanitize tags and elements */
if (_sanitizeElements(shadowNode)) {
continue;
}
/* Deep shadow DOM detected */
if (shadowNode.content instanceof DocumentFragment) {
_sanitizeShadowDOM(shadowNode.content);
}
/* Check attributes, sanitize if necessary */
_sanitizeAttributes(shadowNode);
}
/* Execute a hook if present */
_executeHook('afterSanitizeShadowDOM', fragment, null);
};
/**
* Sanitize
* Public method providing core sanitation functionality
*
* @param {String|Node} dirty string or DOM node
* @param {Object} configuration object
*/
// eslint-disable-next-line complexity
DOMPurify.sanitize = function (dirty) {
var cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var body;
var importedNode;
var currentNode;
var oldNode;
var returnNode;
/* Make sure we have a string to sanitize.
DO NOT return early, as this will return the wrong type if
the user has requested a DOM object rather than a string */
IS_EMPTY_INPUT = !dirty;
if (IS_EMPTY_INPUT) {
dirty = '<!-->';
}
/* Stringify, in case dirty is an object */
if (typeof dirty !== 'string' && !_isNode(dirty)) {
// eslint-disable-next-line no-negated-condition
if (typeof dirty.toString !== 'function') {
throw typeErrorCreate('toString is not a function');
} else {
dirty = dirty.toString();
if (typeof dirty !== 'string') {
throw typeErrorCreate('dirty is not a string, aborting');
}
}
}
/* Check we can run. Otherwise fall back or ignore */
if (!DOMPurify.isSupported) {
if (_typeof(window.toStaticHTML) === 'object' || typeof window.toStaticHTML === 'function') {
if (typeof dirty === 'string') {
return window.toStaticHTML(dirty);
}
if (_isNode(dirty)) {
return window.toStaticHTML(dirty.outerHTML);
}
}
return dirty;
}
/* Assign config vars */
if (!SET_CONFIG) {
_parseConfig(cfg);
}
/* Clean up removed elements */
DOMPurify.removed = [];
/* Check if dirty is correctly typed for IN_PLACE */
if (typeof dirty === 'string') {
IN_PLACE = false;
}
if (IN_PLACE) {
/* Do some early pre-sanitization to avoid unsafe root nodes */
if (dirty.nodeName) {
var tagName = transformCaseFunc(dirty.nodeName);
if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
}
}
} else if (dirty instanceof Node) {
/* If dirty is a DOM element, append to an empty document to avoid
elements being stripped by the parser */
body = _initDocument('<!---->');
importedNode = body.ownerDocument.importNode(dirty, true);
if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {
/* Node is already a body, use as is */
body = importedNode;
} else if (importedNode.nodeName === 'HTML') {
body = importedNode;
} else {
// eslint-disable-next-line unicorn/prefer-dom-node-append
body.appendChild(importedNode);
}
} else {
/* Exit directly if we have nothing to do */
if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && // eslint-disable-next-line unicorn/prefer-includes
dirty.indexOf('<') === -1) {
return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
}
/* Initialize the document to work on */
body = _initDocument(dirty);
/* Check we have a DOM node from the data */
if (!body) {
return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
}
}
/* Remove first element node (ours) if FORCE_BODY is set */
if (body && FORCE_BODY) {
_forceRemove(body.firstChild);
}
/* Get node iterator */
var nodeIterator = _createIterator(IN_PLACE ? dirty : body);
/* Now start iterating over the created document */
while (currentNode = nodeIterator.nextNode()) {
/* Fix IE's strange behavior with manipulated textNodes #89 */
if (currentNode.nodeType === 3 && currentNode === oldNode) {
continue;
}
/* Sanitize tags and elements */
if (_sanitizeElements(currentNode)) {
continue;
}
/* Shadow DOM detected, sanitize it */
if (currentNode.content instanceof DocumentFragment) {
_sanitizeShadowDOM(currentNode.content);
}
/* Check attributes, sanitize if necessary */
_sanitizeAttributes(currentNode);
oldNode = currentNode;
}
oldNode = null;
/* If we sanitized `dirty` in-place, return it. */
if (IN_PLACE) {
return dirty;
}
/* Return sanitized string or DOM */
if (RETURN_DOM) {
if (RETURN_DOM_FRAGMENT) {
returnNode = createDocumentFragment.call(body.ownerDocument);
while (body.firstChild) {
// eslint-disable-next-line unicorn/prefer-dom-node-append
returnNode.appendChild(body.firstChild);
}
} else {
returnNode = body;
}
if (ALLOWED_ATTR.shadowroot) {
/*
AdoptNode() is not used because internal state is not reset
(e.g. the past names map of a HTMLFormElement), this is safe
in theory but we would rather not risk another attack vector.
The state that is cloned by importNode() is explicitly defined
by the specs.
*/
returnNode = importNode.call(originalDocument, returnNode, true);
}
return returnNode;
}
var serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
/* Serialize doctype if allowed */
if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
}
/* Sanitize final string template-safe */
if (SAFE_FOR_TEMPLATES) {
serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR$1, ' ');
serializedHTML = stringReplace(serializedHTML, ERB_EXPR$1, ' ');
}
return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
};
/**
* Public method to set the configuration once
* setConfig
*
* @param {Object} cfg configuration object
*/
DOMPurify.setConfig = function (cfg) {
_parseConfig(cfg);
SET_CONFIG = true;
};
/**
* Public method to remove the configuration
* clearConfig
*
*/
DOMPurify.clearConfig = function () {
CONFIG = null;
SET_CONFIG = false;
};
/**
* Public method to check if an attribute value is valid.
* Uses last set config, if any. Otherwise, uses config defaults.
* isValidAttribute
*
* @param {string} tag Tag name of containing element.
* @param {string} attr Attribute name.
* @param {string} value Attribute value.
* @return {Boolean} Returns true if `value` is valid. Otherwise, returns false.
*/
DOMPurify.isValidAttribute = function (tag, attr, value) {
/* Initialize shared config vars if necessary. */
if (!CONFIG) {
_parseConfig({});
}
var lcTag = transformCaseFunc(tag);
var lcName = transformCaseFunc(attr);
return _isValidAttribute(lcTag, lcName, value);
};
/**
* AddHook
* Public method to add DOMPurify hooks
*
* @param {String} entryPoint entry point for the hook to add
* @param {Function} hookFunction function to execute
*/
DOMPurify.addHook = function (entryPoint, hookFunction) {
if (typeof hookFunction !== 'function') {
return;
}
hooks[entryPoint] = hooks[entryPoint] || [];
arrayPush(hooks[entryPoint], hookFunction);
};
/**
* RemoveHook
* Public method to remove a DOMPurify hook at a given entryPoint
* (pops it from the stack of hooks if more are present)
*
* @param {String} entryPoint entry point for the hook to remove
* @return {Function} removed(popped) hook
*/
DOMPurify.removeHook = function (entryPoint) {
if (hooks[entryPoint]) {
return arrayPop(hooks[entryPoint]);
}
};
/**
* RemoveHooks
* Public method to remove all DOMPurify hooks at a given entryPoint
*
* @param {String} entryPoint entry point for the hooks to remove
*/
DOMPurify.removeHooks = function (entryPoint) {
if (hooks[entryPoint]) {
hooks[entryPoint] = [];
}
};
/**
* RemoveAllHooks
* Public method to remove all DOMPurify hooks
*
*/
DOMPurify.removeAllHooks = function () {
hooks = {};
};
return DOMPurify;
}
var purify = createDOMPurify();
return purify;
}));
});
var sanitizer = purify(window);
function _createSuper$r(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$r(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$r() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var HtmlBlock = /*#__PURE__*/function (_ParagraphBase) {
_inherits(HtmlBlock, _ParagraphBase);
var _super = _createSuper$r(HtmlBlock);
function HtmlBlock() {
_classCallCheck(this, HtmlBlock);
return _super.call(this, {
needCache: true
});
} // ref: http://www.vfmd.org/vfmd-spec/specification/#procedure-for-detecting-automatic-links
_createClass(HtmlBlock, [{
key: "isAutoLinkTag",
value: function isAutoLinkTag(tagMatch) {
var REGEX_GROUP = [/^<([a-z][a-z0-9+.-]{1,31}:\/\/[^<> `]+)>$/i, /^<(mailto:[^<> `]+)>$/i, /^<([^()<>[\]:'@\\,"\s`]+@[^()<>[\]:'@\\,"\s`.]+\.[^()<>[\]:'@\\,"\s`]+)>$/i];
return some$3(REGEX_GROUP).call(REGEX_GROUP, function (regex) {
return regex.test(tagMatch);
});
}
}, {
key: "isHtmlComment",
value: function isHtmlComment(match) {
var htmlComment = /^<!--.*?-->$/;
return htmlComment.test(match);
}
}, {
key: "beforeMakeHtml",
value: function beforeMakeHtml(str, sentenceMakeFunc) {
var _this = this;
if (this.$engine.htmlWhiteListAppend) {
/**
* @property
* @type {false | RegExp}
*/
this.htmlWhiteListAppend = new RegExp("^(".concat(this.$engine.htmlWhiteListAppend, ")( |$|/)"), 'i');
/**
* @property
* @type {string[]}
*/
this.htmlWhiteList = this.$engine.htmlWhiteListAppend.split('|');
} else {
this.htmlWhiteListAppend = false;
this.htmlWhiteList = [];
}
var $str = str;
$str = convertHTMLNumberToName($str);
$str = escapeHTMLEntitiesWithoutSemicolon($str);
$str = $str.replace(/<[/]?(.*?)>/g, function (whole, m1) {
// 匹配到非白名单且非AutoLink语法的尖括号会被转义
// 如果是HTML注释放行
if (!whiteList.test(m1) && !_this.isAutoLinkTag(whole) && !_this.isHtmlComment(whole)) {
if (_this.htmlWhiteListAppend === false || !_this.htmlWhiteListAppend.test(m1)) {
return whole.replace(/</g, '&#60;').replace(/>/g, '&#62;');
}
} // 到达此分支的包含被尖括号包裹的AutoLink语法以及在白名单内的HTML标签
// 没有被AutoLink解析并渲染的标签会被DOMPurify过滤掉正常情况下不会出现遗漏
// 临时替换完整的HTML标签首尾为$#60;和$#62;供下一步剔除损坏的HTML标签
return whole.replace(/</g, '$#60;').replace(/>/g, '$#62;');
}); // 替换所有形如「<abcd」和「</abcd」的左尖括号
$str = $str.replace(/<(?=\/?(\w|\n|$))/g, '&#60;'); // 还原被替换的尖括号
$str = $str.replace(/\$#60;/g, '<').replace(/\$#62;/g, '>');
return $str;
} // beforeMakeHtml(str) {
// return str;
// }
}, {
key: "makeHtml",
value: function makeHtml(str, sentenceMakeFunc) {
return str;
}
}, {
key: "afterMakeHtml",
value: function afterMakeHtml(str) {
var $str = str;
var config = {
ALLOW_UNKNOWN_PROTOCOLS: true,
ADD_ATTR: ['target']
};
if (this.htmlWhiteListAppend !== false) {
config.ADD_TAGS = this.htmlWhiteList;
if (this.htmlWhiteListAppend.test('style') || this.htmlWhiteListAppend.test('ALL')) {
$str = $str.replace(/<style(>| [^>]*>).*?<\/style>/gi, function (match) {
return match.replace(/<br>/gi, '');
});
}
if (this.htmlWhiteListAppend.test('iframe') || this.htmlWhiteListAppend.test('ALL')) {
var _context;
config.ADD_ATTR = concat$5(_context = config.ADD_ATTR).call(_context, ['align', 'frameborder', 'height', 'longdesc', 'marginheight', 'marginwidth', 'name', 'sandbox', 'scrolling', 'seamless', 'src', 'srcdoc', 'width']);
config.SANITIZE_DOM = false;
$str = $str.replace(/<iframe(>| [^>]*>).*?<\/iframe>/gi, function (match) {
return match.replace(/<br>/gi, '').replace(/\n/g, '');
});
}
if (this.htmlWhiteListAppend.test('script') || this.htmlWhiteListAppend.test('ALL')) {
// 如果允许script或者输入了ALL则不做任何过滤了
$str = $str.replace(/<script(>| [^>]*>).*?<\/script>/gi, function (match) {
return match.replace(/<br>/gi, '');
});
return $str;
}
} // node 环境下不输出sign和lines
if (!isBrowser()) {
config.FORBID_ATTR = ['data-sign', 'data-lines'];
}
return sanitizer.sanitize($str, config);
}
}]);
return HtmlBlock;
}(ParagraphBase);
_defineProperty(HtmlBlock, "HOOK_NAME", 'htmlBlock');
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var gfmUnicode = {
defaultURL: 'https://github.githubassets.com/images/icons/emoji/unicode/${code}.png?v8',
emojis: {
'+1': '1f44d',
'-1': '1f44e',
100: '1f4af',
1234: '1f522',
'1st_place_medal': '1f947',
'2nd_place_medal': '1f948',
'3rd_place_medal': '1f949',
'8ball': '1f3b1',
a: '1f170',
ab: '1f18e',
abacus: '1f9ee',
abc: '1f524',
abcd: '1f521',
accept: '1f251',
adhesive_bandage: '1fa79',
adult: '1f9d1',
aerial_tramway: '1f6a1',
afghanistan: '1f1e6-1f1eb',
airplane: '2708',
aland_islands: '1f1e6-1f1fd',
alarm_clock: '23f0',
albania: '1f1e6-1f1f1',
alembic: '2697',
algeria: '1f1e9-1f1ff',
alien: '1f47d',
ambulance: '1f691',
american_samoa: '1f1e6-1f1f8',
amphora: '1f3fa',
anchor: '2693',
andorra: '1f1e6-1f1e9',
angel: '1f47c',
anger: '1f4a2',
angola: '1f1e6-1f1f4',
angry: '1f620',
anguilla: '1f1e6-1f1ee',
anguished: '1f627',
ant: '1f41c',
antarctica: '1f1e6-1f1f6',
antigua_barbuda: '1f1e6-1f1ec',
apple: '1f34e',
aquarius: '2652',
argentina: '1f1e6-1f1f7',
aries: '2648',
armenia: '1f1e6-1f1f2',
arrow_backward: '25c0',
arrow_double_down: '23ec',
arrow_double_up: '23eb',
arrow_down: '2b07',
arrow_down_small: '1f53d',
arrow_forward: '25b6',
arrow_heading_down: '2935',
arrow_heading_up: '2934',
arrow_left: '2b05',
arrow_lower_left: '2199',
arrow_lower_right: '2198',
arrow_right: '27a1',
arrow_right_hook: '21aa',
arrow_up: '2b06',
arrow_up_down: '2195',
arrow_up_small: '1f53c',
arrow_upper_left: '2196',
arrow_upper_right: '2197',
arrows_clockwise: '1f503',
arrows_counterclockwise: '1f504',
art: '1f3a8',
articulated_lorry: '1f69b',
artificial_satellite: '1f6f0',
artist: '1f9d1-1f3a8',
aruba: '1f1e6-1f1fc',
ascension_island: '1f1e6-1f1e8',
asterisk: '002a-20e3',
astonished: '1f632',
astronaut: '1f9d1-1f680',
athletic_shoe: '1f45f',
atm: '1f3e7',
atom_symbol: '269b',
australia: '1f1e6-1f1fa',
austria: '1f1e6-1f1f9',
auto_rickshaw: '1f6fa',
avocado: '1f951',
axe: '1fa93',
azerbaijan: '1f1e6-1f1ff',
b: '1f171',
baby: '1f476',
baby_bottle: '1f37c',
baby_chick: '1f424',
baby_symbol: '1f6bc',
back: '1f519',
bacon: '1f953',
badger: '1f9a1',
badminton: '1f3f8',
bagel: '1f96f',
baggage_claim: '1f6c4',
baguette_bread: '1f956',
bahamas: '1f1e7-1f1f8',
bahrain: '1f1e7-1f1ed',
balance_scale: '2696',
bald_man: '1f468-1f9b2',
bald_woman: '1f469-1f9b2',
ballet_shoes: '1fa70',
balloon: '1f388',
ballot_box: '1f5f3',
ballot_box_with_check: '2611',
bamboo: '1f38d',
banana: '1f34c',
bangbang: '203c',
bangladesh: '1f1e7-1f1e9',
banjo: '1fa95',
bank: '1f3e6',
bar_chart: '1f4ca',
barbados: '1f1e7-1f1e7',
barber: '1f488',
baseball: '26be',
basket: '1f9fa',
basketball: '1f3c0',
basketball_man: '26f9-2642',
basketball_woman: '26f9-2640',
bat: '1f987',
bath: '1f6c0',
bathtub: '1f6c1',
battery: '1f50b',
beach_umbrella: '1f3d6',
bear: '1f43b',
bearded_person: '1f9d4',
bed: '1f6cf',
bee: '1f41d',
beer: '1f37a',
beers: '1f37b',
beetle: '1f41e',
beginner: '1f530',
belarus: '1f1e7-1f1fe',
belgium: '1f1e7-1f1ea',
belize: '1f1e7-1f1ff',
bell: '1f514',
bellhop_bell: '1f6ce',
benin: '1f1e7-1f1ef',
bento: '1f371',
bermuda: '1f1e7-1f1f2',
beverage_box: '1f9c3',
bhutan: '1f1e7-1f1f9',
bicyclist: '1f6b4',
bike: '1f6b2',
biking_man: '1f6b4-2642',
biking_woman: '1f6b4-2640',
bikini: '1f459',
billed_cap: '1f9e2',
biohazard: '2623',
bird: '1f426',
birthday: '1f382',
black_circle: '26ab',
black_flag: '1f3f4',
black_heart: '1f5a4',
black_joker: '1f0cf',
black_large_square: '2b1b',
black_medium_small_square: '25fe',
black_medium_square: '25fc',
black_nib: '2712',
black_small_square: '25aa',
black_square_button: '1f532',
blond_haired_man: '1f471-2642',
blond_haired_person: '1f471',
blond_haired_woman: '1f471-2640',
blonde_woman: '1f471-2640',
blossom: '1f33c',
blowfish: '1f421',
blue_book: '1f4d8',
blue_car: '1f699',
blue_heart: '1f499',
blue_square: '1f7e6',
blush: '1f60a',
boar: '1f417',
boat: '26f5',
bolivia: '1f1e7-1f1f4',
bomb: '1f4a3',
bone: '1f9b4',
book: '1f4d6',
bookmark: '1f516',
bookmark_tabs: '1f4d1',
books: '1f4da',
boom: '1f4a5',
boot: '1f462',
bosnia_herzegovina: '1f1e7-1f1e6',
botswana: '1f1e7-1f1fc',
bouncing_ball_man: '26f9-2642',
bouncing_ball_person: '26f9',
bouncing_ball_woman: '26f9-2640',
bouquet: '1f490',
bouvet_island: '1f1e7-1f1fb',
bow: '1f647',
bow_and_arrow: '1f3f9',
bowing_man: '1f647-2642',
bowing_woman: '1f647-2640',
bowl_with_spoon: '1f963',
bowling: '1f3b3',
boxing_glove: '1f94a',
boy: '1f466',
brain: '1f9e0',
brazil: '1f1e7-1f1f7',
bread: '1f35e',
breast_feeding: '1f931',
bricks: '1f9f1',
bride_with_veil: '1f470',
bridge_at_night: '1f309',
briefcase: '1f4bc',
british_indian_ocean_territory: '1f1ee-1f1f4',
british_virgin_islands: '1f1fb-1f1ec',
broccoli: '1f966',
broken_heart: '1f494',
broom: '1f9f9',
brown_circle: '1f7e4',
brown_heart: '1f90e',
brown_square: '1f7eb',
brunei: '1f1e7-1f1f3',
bug: '1f41b',
building_construction: '1f3d7',
bulb: '1f4a1',
bulgaria: '1f1e7-1f1ec',
bullettrain_front: '1f685',
bullettrain_side: '1f684',
burkina_faso: '1f1e7-1f1eb',
burrito: '1f32f',
burundi: '1f1e7-1f1ee',
bus: '1f68c',
business_suit_levitating: '1f574',
busstop: '1f68f',
bust_in_silhouette: '1f464',
busts_in_silhouette: '1f465',
butter: '1f9c8',
butterfly: '1f98b',
cactus: '1f335',
cake: '1f370',
calendar: '1f4c6',
call_me_hand: '1f919',
calling: '1f4f2',
cambodia: '1f1f0-1f1ed',
camel: '1f42b',
camera: '1f4f7',
camera_flash: '1f4f8',
cameroon: '1f1e8-1f1f2',
camping: '1f3d5',
canada: '1f1e8-1f1e6',
canary_islands: '1f1ee-1f1e8',
cancer: '264b',
candle: '1f56f',
candy: '1f36c',
canned_food: '1f96b',
canoe: '1f6f6',
cape_verde: '1f1e8-1f1fb',
capital_abcd: '1f520',
capricorn: '2651',
car: '1f697',
card_file_box: '1f5c3',
card_index: '1f4c7',
card_index_dividers: '1f5c2',
caribbean_netherlands: '1f1e7-1f1f6',
carousel_horse: '1f3a0',
carrot: '1f955',
cartwheeling: '1f938',
cat: '1f431',
cat2: '1f408',
cayman_islands: '1f1f0-1f1fe',
cd: '1f4bf',
central_african_republic: '1f1e8-1f1eb',
ceuta_melilla: '1f1ea-1f1e6',
chad: '1f1f9-1f1e9',
chains: '26d3',
chair: '1fa91',
champagne: '1f37e',
chart: '1f4b9',
chart_with_downwards_trend: '1f4c9',
chart_with_upwards_trend: '1f4c8',
checkered_flag: '1f3c1',
cheese: '1f9c0',
cherries: '1f352',
cherry_blossom: '1f338',
chess_pawn: '265f',
chestnut: '1f330',
chicken: '1f414',
child: '1f9d2',
children_crossing: '1f6b8',
chile: '1f1e8-1f1f1',
chipmunk: '1f43f',
chocolate_bar: '1f36b',
chopsticks: '1f962',
christmas_island: '1f1e8-1f1fd',
christmas_tree: '1f384',
church: '26ea',
cinema: '1f3a6',
circus_tent: '1f3aa',
city_sunrise: '1f307',
city_sunset: '1f306',
cityscape: '1f3d9',
cl: '1f191',
clamp: '1f5dc',
clap: '1f44f',
clapper: '1f3ac',
classical_building: '1f3db',
climbing: '1f9d7',
climbing_man: '1f9d7-2642',
climbing_woman: '1f9d7-2640',
clinking_glasses: '1f942',
clipboard: '1f4cb',
clipperton_island: '1f1e8-1f1f5',
clock1: '1f550',
clock10: '1f559',
clock1030: '1f565',
clock11: '1f55a',
clock1130: '1f566',
clock12: '1f55b',
clock1230: '1f567',
clock130: '1f55c',
clock2: '1f551',
clock230: '1f55d',
clock3: '1f552',
clock330: '1f55e',
clock4: '1f553',
clock430: '1f55f',
clock5: '1f554',
clock530: '1f560',
clock6: '1f555',
clock630: '1f561',
clock7: '1f556',
clock730: '1f562',
clock8: '1f557',
clock830: '1f563',
clock9: '1f558',
clock930: '1f564',
closed_book: '1f4d5',
closed_lock_with_key: '1f510',
closed_umbrella: '1f302',
cloud: '2601',
cloud_with_lightning: '1f329',
cloud_with_lightning_and_rain: '26c8',
cloud_with_rain: '1f327',
cloud_with_snow: '1f328',
clown_face: '1f921',
clubs: '2663',
cn: '1f1e8-1f1f3',
coat: '1f9e5',
cocktail: '1f378',
coconut: '1f965',
cocos_islands: '1f1e8-1f1e8',
coffee: '2615',
coffin: '26b0',
cold_face: '1f976',
cold_sweat: '1f630',
collision: '1f4a5',
colombia: '1f1e8-1f1f4',
comet: '2604',
comoros: '1f1f0-1f1f2',
compass: '1f9ed',
computer: '1f4bb',
computer_mouse: '1f5b1',
confetti_ball: '1f38a',
confounded: '1f616',
confused: '1f615',
congo_brazzaville: '1f1e8-1f1ec',
congo_kinshasa: '1f1e8-1f1e9',
congratulations: '3297',
construction: '1f6a7',
construction_worker: '1f477',
construction_worker_man: '1f477-2642',
construction_worker_woman: '1f477-2640',
control_knobs: '1f39b',
convenience_store: '1f3ea',
cook: '1f9d1-1f373',
cook_islands: '1f1e8-1f1f0',
cookie: '1f36a',
cool: '1f192',
cop: '1f46e',
copyright: '00a9',
corn: '1f33d',
costa_rica: '1f1e8-1f1f7',
cote_divoire: '1f1e8-1f1ee',
couch_and_lamp: '1f6cb',
couple: '1f46b',
couple_with_heart: '1f491',
couple_with_heart_man_man: '1f468-2764-1f468',
couple_with_heart_woman_man: '1f469-2764-1f468',
couple_with_heart_woman_woman: '1f469-2764-1f469',
couplekiss: '1f48f',
couplekiss_man_man: '1f468-2764-1f48b-1f468',
couplekiss_man_woman: '1f469-2764-1f48b-1f468',
couplekiss_woman_woman: '1f469-2764-1f48b-1f469',
cow: '1f42e',
cow2: '1f404',
cowboy_hat_face: '1f920',
crab: '1f980',
crayon: '1f58d',
credit_card: '1f4b3',
crescent_moon: '1f319',
cricket: '1f997',
cricket_game: '1f3cf',
croatia: '1f1ed-1f1f7',
crocodile: '1f40a',
croissant: '1f950',
crossed_fingers: '1f91e',
crossed_flags: '1f38c',
crossed_swords: '2694',
crown: '1f451',
cry: '1f622',
crying_cat_face: '1f63f',
crystal_ball: '1f52e',
cuba: '1f1e8-1f1fa',
cucumber: '1f952',
cup_with_straw: '1f964',
cupcake: '1f9c1',
cupid: '1f498',
curacao: '1f1e8-1f1fc',
curling_stone: '1f94c',
curly_haired_man: '1f468-1f9b1',
curly_haired_woman: '1f469-1f9b1',
curly_loop: '27b0',
currency_exchange: '1f4b1',
curry: '1f35b',
cursing_face: '1f92c',
custard: '1f36e',
customs: '1f6c3',
cut_of_meat: '1f969',
cyclone: '1f300',
cyprus: '1f1e8-1f1fe',
czech_republic: '1f1e8-1f1ff',
dagger: '1f5e1',
dancer: '1f483',
dancers: '1f46f',
dancing_men: '1f46f-2642',
dancing_women: '1f46f-2640',
dango: '1f361',
dark_sunglasses: '1f576',
dart: '1f3af',
dash: '1f4a8',
date: '1f4c5',
de: '1f1e9-1f1ea',
deaf_man: '1f9cf-2642',
deaf_person: '1f9cf',
deaf_woman: '1f9cf-2640',
deciduous_tree: '1f333',
deer: '1f98c',
denmark: '1f1e9-1f1f0',
department_store: '1f3ec',
derelict_house: '1f3da',
desert: '1f3dc',
desert_island: '1f3dd',
desktop_computer: '1f5a5',
detective: '1f575',
diamond_shape_with_a_dot_inside: '1f4a0',
diamonds: '2666',
diego_garcia: '1f1e9-1f1ec',
disappointed: '1f61e',
disappointed_relieved: '1f625',
diving_mask: '1f93f',
diya_lamp: '1fa94',
dizzy: '1f4ab',
dizzy_face: '1f635',
djibouti: '1f1e9-1f1ef',
dna: '1f9ec',
do_not_litter: '1f6af',
dog: '1f436',
dog2: '1f415',
dollar: '1f4b5',
dolls: '1f38e',
dolphin: '1f42c',
dominica: '1f1e9-1f1f2',
dominican_republic: '1f1e9-1f1f4',
door: '1f6aa',
doughnut: '1f369',
dove: '1f54a',
dragon: '1f409',
dragon_face: '1f432',
dress: '1f457',
dromedary_camel: '1f42a',
drooling_face: '1f924',
drop_of_blood: '1fa78',
droplet: '1f4a7',
drum: '1f941',
duck: '1f986',
dumpling: '1f95f',
dvd: '1f4c0',
'e-mail': '1f4e7',
eagle: '1f985',
ear: '1f442',
ear_of_rice: '1f33e',
ear_with_hearing_aid: '1f9bb',
earth_africa: '1f30d',
earth_americas: '1f30e',
earth_asia: '1f30f',
ecuador: '1f1ea-1f1e8',
egg: '1f95a',
eggplant: '1f346',
egypt: '1f1ea-1f1ec',
eight: '0038-20e3',
eight_pointed_black_star: '2734',
eight_spoked_asterisk: '2733',
eject_button: '23cf',
el_salvador: '1f1f8-1f1fb',
electric_plug: '1f50c',
elephant: '1f418',
elf: '1f9dd',
elf_man: '1f9dd-2642',
elf_woman: '1f9dd-2640',
email: '2709',
end: '1f51a',
england: '1f3f4-e0067-e0062-e0065-e006e-e0067-e007f',
envelope: '2709',
envelope_with_arrow: '1f4e9',
equatorial_guinea: '1f1ec-1f1f6',
eritrea: '1f1ea-1f1f7',
es: '1f1ea-1f1f8',
estonia: '1f1ea-1f1ea',
ethiopia: '1f1ea-1f1f9',
eu: '1f1ea-1f1fa',
euro: '1f4b6',
european_castle: '1f3f0',
european_post_office: '1f3e4',
european_union: '1f1ea-1f1fa',
evergreen_tree: '1f332',
exclamation: '2757',
exploding_head: '1f92f',
expressionless: '1f611',
eye: '1f441',
eye_speech_bubble: '1f441-1f5e8',
eyeglasses: '1f453',
eyes: '1f440',
face_with_head_bandage: '1f915',
face_with_thermometer: '1f912',
facepalm: '1f926',
facepunch: '1f44a',
factory: '1f3ed',
factory_worker: '1f9d1-1f3ed',
fairy: '1f9da',
fairy_man: '1f9da-2642',
fairy_woman: '1f9da-2640',
falafel: '1f9c6',
falkland_islands: '1f1eb-1f1f0',
fallen_leaf: '1f342',
family: '1f46a',
family_man_boy: '1f468-1f466',
family_man_boy_boy: '1f468-1f466-1f466',
family_man_girl: '1f468-1f467',
family_man_girl_boy: '1f468-1f467-1f466',
family_man_girl_girl: '1f468-1f467-1f467',
family_man_man_boy: '1f468-1f468-1f466',
family_man_man_boy_boy: '1f468-1f468-1f466-1f466',
family_man_man_girl: '1f468-1f468-1f467',
family_man_man_girl_boy: '1f468-1f468-1f467-1f466',
family_man_man_girl_girl: '1f468-1f468-1f467-1f467',
family_man_woman_boy: '1f468-1f469-1f466',
family_man_woman_boy_boy: '1f468-1f469-1f466-1f466',
family_man_woman_girl: '1f468-1f469-1f467',
family_man_woman_girl_boy: '1f468-1f469-1f467-1f466',
family_man_woman_girl_girl: '1f468-1f469-1f467-1f467',
family_woman_boy: '1f469-1f466',
family_woman_boy_boy: '1f469-1f466-1f466',
family_woman_girl: '1f469-1f467',
family_woman_girl_boy: '1f469-1f467-1f466',
family_woman_girl_girl: '1f469-1f467-1f467',
family_woman_woman_boy: '1f469-1f469-1f466',
family_woman_woman_boy_boy: '1f469-1f469-1f466-1f466',
family_woman_woman_girl: '1f469-1f469-1f467',
family_woman_woman_girl_boy: '1f469-1f469-1f467-1f466',
family_woman_woman_girl_girl: '1f469-1f469-1f467-1f467',
farmer: '1f9d1-1f33e',
faroe_islands: '1f1eb-1f1f4',
fast_forward: '23e9',
fax: '1f4e0',
fearful: '1f628',
feet: '1f43e',
female_detective: '1f575-2640',
female_sign: '2640',
ferris_wheel: '1f3a1',
ferry: '26f4',
field_hockey: '1f3d1',
fiji: '1f1eb-1f1ef',
file_cabinet: '1f5c4',
file_folder: '1f4c1',
film_projector: '1f4fd',
film_strip: '1f39e',
finland: '1f1eb-1f1ee',
fire: '1f525',
fire_engine: '1f692',
fire_extinguisher: '1f9ef',
firecracker: '1f9e8',
firefighter: '1f9d1-1f692',
fireworks: '1f386',
first_quarter_moon: '1f313',
first_quarter_moon_with_face: '1f31b',
fish: '1f41f',
fish_cake: '1f365',
fishing_pole_and_fish: '1f3a3',
fist: '270a',
fist_left: '1f91b',
fist_oncoming: '1f44a',
fist_raised: '270a',
fist_right: '1f91c',
five: '0035-20e3',
flags: '1f38f',
flamingo: '1f9a9',
flashlight: '1f526',
flat_shoe: '1f97f',
fleur_de_lis: '269c',
flight_arrival: '1f6ec',
flight_departure: '1f6eb',
flipper: '1f42c',
floppy_disk: '1f4be',
flower_playing_cards: '1f3b4',
flushed: '1f633',
flying_disc: '1f94f',
flying_saucer: '1f6f8',
fog: '1f32b',
foggy: '1f301',
foot: '1f9b6',
football: '1f3c8',
footprints: '1f463',
fork_and_knife: '1f374',
fortune_cookie: '1f960',
fountain: '26f2',
fountain_pen: '1f58b',
four: '0034-20e3',
four_leaf_clover: '1f340',
fox_face: '1f98a',
fr: '1f1eb-1f1f7',
framed_picture: '1f5bc',
free: '1f193',
french_guiana: '1f1ec-1f1eb',
french_polynesia: '1f1f5-1f1eb',
french_southern_territories: '1f1f9-1f1eb',
fried_egg: '1f373',
fried_shrimp: '1f364',
fries: '1f35f',
frog: '1f438',
frowning: '1f626',
frowning_face: '2639',
frowning_man: '1f64d-2642',
frowning_person: '1f64d',
frowning_woman: '1f64d-2640',
fu: '1f595',
fuelpump: '26fd',
full_moon: '1f315',
full_moon_with_face: '1f31d',
funeral_urn: '26b1',
gabon: '1f1ec-1f1e6',
gambia: '1f1ec-1f1f2',
game_die: '1f3b2',
garlic: '1f9c4',
gb: '1f1ec-1f1e7',
gear: '2699',
gem: '1f48e',
gemini: '264a',
genie: '1f9de',
genie_man: '1f9de-2642',
genie_woman: '1f9de-2640',
georgia: '1f1ec-1f1ea',
ghana: '1f1ec-1f1ed',
ghost: '1f47b',
gibraltar: '1f1ec-1f1ee',
gift: '1f381',
gift_heart: '1f49d',
giraffe: '1f992',
girl: '1f467',
globe_with_meridians: '1f310',
gloves: '1f9e4',
goal_net: '1f945',
goat: '1f410',
goggles: '1f97d',
golf: '26f3',
golfing: '1f3cc',
golfing_man: '1f3cc-2642',
golfing_woman: '1f3cc-2640',
gorilla: '1f98d',
grapes: '1f347',
greece: '1f1ec-1f1f7',
green_apple: '1f34f',
green_book: '1f4d7',
green_circle: '1f7e2',
green_heart: '1f49a',
green_salad: '1f957',
green_square: '1f7e9',
greenland: '1f1ec-1f1f1',
grenada: '1f1ec-1f1e9',
grey_exclamation: '2755',
grey_question: '2754',
grimacing: '1f62c',
grin: '1f601',
grinning: '1f600',
guadeloupe: '1f1ec-1f1f5',
guam: '1f1ec-1f1fa',
guard: '1f482',
guardsman: '1f482-2642',
guardswoman: '1f482-2640',
guatemala: '1f1ec-1f1f9',
guernsey: '1f1ec-1f1ec',
guide_dog: '1f9ae',
guinea: '1f1ec-1f1f3',
guinea_bissau: '1f1ec-1f1fc',
guitar: '1f3b8',
gun: '1f52b',
guyana: '1f1ec-1f1fe',
haircut: '1f487',
haircut_man: '1f487-2642',
haircut_woman: '1f487-2640',
haiti: '1f1ed-1f1f9',
hamburger: '1f354',
hammer: '1f528',
hammer_and_pick: '2692',
hammer_and_wrench: '1f6e0',
hamster: '1f439',
hand: '270b',
hand_over_mouth: '1f92d',
handbag: '1f45c',
handball_person: '1f93e',
handshake: '1f91d',
hankey: '1f4a9',
hash: '0023-20e3',
hatched_chick: '1f425',
hatching_chick: '1f423',
headphones: '1f3a7',
health_worker: '1f9d1-2695',
hear_no_evil: '1f649',
heard_mcdonald_islands: '1f1ed-1f1f2',
heart: '2764',
heart_decoration: '1f49f',
heart_eyes: '1f60d',
heart_eyes_cat: '1f63b',
heartbeat: '1f493',
heartpulse: '1f497',
hearts: '2665',
heavy_check_mark: '2714',
heavy_division_sign: '2797',
heavy_dollar_sign: '1f4b2',
heavy_exclamation_mark: '2757',
heavy_heart_exclamation: '2763',
heavy_minus_sign: '2796',
heavy_multiplication_x: '2716',
heavy_plus_sign: '2795',
hedgehog: '1f994',
helicopter: '1f681',
herb: '1f33f',
hibiscus: '1f33a',
high_brightness: '1f506',
high_heel: '1f460',
hiking_boot: '1f97e',
hindu_temple: '1f6d5',
hippopotamus: '1f99b',
hocho: '1f52a',
hole: '1f573',
honduras: '1f1ed-1f1f3',
honey_pot: '1f36f',
honeybee: '1f41d',
hong_kong: '1f1ed-1f1f0',
horse: '1f434',
horse_racing: '1f3c7',
hospital: '1f3e5',
hot_face: '1f975',
hot_pepper: '1f336',
hotdog: '1f32d',
hotel: '1f3e8',
hotsprings: '2668',
hourglass: '231b',
hourglass_flowing_sand: '23f3',
house: '1f3e0',
house_with_garden: '1f3e1',
houses: '1f3d8',
hugs: '1f917',
hungary: '1f1ed-1f1fa',
hushed: '1f62f',
ice_cream: '1f368',
ice_cube: '1f9ca',
ice_hockey: '1f3d2',
ice_skate: '26f8',
icecream: '1f366',
iceland: '1f1ee-1f1f8',
id: '1f194',
ideograph_advantage: '1f250',
imp: '1f47f',
inbox_tray: '1f4e5',
incoming_envelope: '1f4e8',
india: '1f1ee-1f1f3',
indonesia: '1f1ee-1f1e9',
infinity: '267e',
information_desk_person: '1f481',
information_source: '2139',
innocent: '1f607',
interrobang: '2049',
iphone: '1f4f1',
iran: '1f1ee-1f1f7',
iraq: '1f1ee-1f1f6',
ireland: '1f1ee-1f1ea',
isle_of_man: '1f1ee-1f1f2',
israel: '1f1ee-1f1f1',
it: '1f1ee-1f1f9',
izakaya_lantern: '1f3ee',
jack_o_lantern: '1f383',
jamaica: '1f1ef-1f1f2',
japan: '1f5fe',
japanese_castle: '1f3ef',
japanese_goblin: '1f47a',
japanese_ogre: '1f479',
jeans: '1f456',
jersey: '1f1ef-1f1ea',
jigsaw: '1f9e9',
jordan: '1f1ef-1f1f4',
joy: '1f602',
joy_cat: '1f639',
joystick: '1f579',
jp: '1f1ef-1f1f5',
judge: '1f9d1-2696',
juggling_person: '1f939',
kaaba: '1f54b',
kangaroo: '1f998',
kazakhstan: '1f1f0-1f1ff',
kenya: '1f1f0-1f1ea',
key: '1f511',
keyboard: '2328',
keycap_ten: '1f51f',
kick_scooter: '1f6f4',
kimono: '1f458',
kiribati: '1f1f0-1f1ee',
kiss: '1f48b',
kissing: '1f617',
kissing_cat: '1f63d',
kissing_closed_eyes: '1f61a',
kissing_heart: '1f618',
kissing_smiling_eyes: '1f619',
kite: '1fa81',
kiwi_fruit: '1f95d',
kneeling_man: '1f9ce-2642',
kneeling_person: '1f9ce',
kneeling_woman: '1f9ce-2640',
knife: '1f52a',
koala: '1f428',
koko: '1f201',
kosovo: '1f1fd-1f1f0',
kr: '1f1f0-1f1f7',
kuwait: '1f1f0-1f1fc',
kyrgyzstan: '1f1f0-1f1ec',
lab_coat: '1f97c',
label: '1f3f7',
lacrosse: '1f94d',
lantern: '1f3ee',
laos: '1f1f1-1f1e6',
large_blue_circle: '1f535',
large_blue_diamond: '1f537',
large_orange_diamond: '1f536',
last_quarter_moon: '1f317',
last_quarter_moon_with_face: '1f31c',
latin_cross: '271d',
latvia: '1f1f1-1f1fb',
laughing: '1f606',
leafy_green: '1f96c',
leaves: '1f343',
lebanon: '1f1f1-1f1e7',
ledger: '1f4d2',
left_luggage: '1f6c5',
left_right_arrow: '2194',
left_speech_bubble: '1f5e8',
leftwards_arrow_with_hook: '21a9',
leg: '1f9b5',
lemon: '1f34b',
leo: '264c',
leopard: '1f406',
lesotho: '1f1f1-1f1f8',
level_slider: '1f39a',
liberia: '1f1f1-1f1f7',
libra: '264e',
libya: '1f1f1-1f1fe',
liechtenstein: '1f1f1-1f1ee',
light_rail: '1f688',
link: '1f517',
lion: '1f981',
lips: '1f444',
lipstick: '1f484',
lithuania: '1f1f1-1f1f9',
lizard: '1f98e',
llama: '1f999',
lobster: '1f99e',
lock: '1f512',
lock_with_ink_pen: '1f50f',
lollipop: '1f36d',
loop: '27bf',
lotion_bottle: '1f9f4',
lotus_position: '1f9d8',
lotus_position_man: '1f9d8-2642',
lotus_position_woman: '1f9d8-2640',
loud_sound: '1f50a',
loudspeaker: '1f4e2',
love_hotel: '1f3e9',
love_letter: '1f48c',
love_you_gesture: '1f91f',
low_brightness: '1f505',
luggage: '1f9f3',
luxembourg: '1f1f1-1f1fa',
lying_face: '1f925',
m: '24c2',
macau: '1f1f2-1f1f4',
macedonia: '1f1f2-1f1f0',
madagascar: '1f1f2-1f1ec',
mag: '1f50d',
mag_right: '1f50e',
mage: '1f9d9',
mage_man: '1f9d9-2642',
mage_woman: '1f9d9-2640',
magnet: '1f9f2',
mahjong: '1f004',
mailbox: '1f4eb',
mailbox_closed: '1f4ea',
mailbox_with_mail: '1f4ec',
mailbox_with_no_mail: '1f4ed',
malawi: '1f1f2-1f1fc',
malaysia: '1f1f2-1f1fe',
maldives: '1f1f2-1f1fb',
male_detective: '1f575-2642',
male_sign: '2642',
mali: '1f1f2-1f1f1',
malta: '1f1f2-1f1f9',
man: '1f468',
man_artist: '1f468-1f3a8',
man_astronaut: '1f468-1f680',
man_cartwheeling: '1f938-2642',
man_cook: '1f468-1f373',
man_dancing: '1f57a',
man_facepalming: '1f926-2642',
man_factory_worker: '1f468-1f3ed',
man_farmer: '1f468-1f33e',
man_firefighter: '1f468-1f692',
man_health_worker: '1f468-2695',
man_in_manual_wheelchair: '1f468-1f9bd',
man_in_motorized_wheelchair: '1f468-1f9bc',
man_in_tuxedo: '1f935',
man_judge: '1f468-2696',
man_juggling: '1f939-2642',
man_mechanic: '1f468-1f527',
man_office_worker: '1f468-1f4bc',
man_pilot: '1f468-2708',
man_playing_handball: '1f93e-2642',
man_playing_water_polo: '1f93d-2642',
man_scientist: '1f468-1f52c',
man_shrugging: '1f937-2642',
man_singer: '1f468-1f3a4',
man_student: '1f468-1f393',
man_teacher: '1f468-1f3eb',
man_technologist: '1f468-1f4bb',
man_with_gua_pi_mao: '1f472',
man_with_probing_cane: '1f468-1f9af',
man_with_turban: '1f473-2642',
mandarin: '1f34a',
mango: '1f96d',
mans_shoe: '1f45e',
mantelpiece_clock: '1f570',
manual_wheelchair: '1f9bd',
maple_leaf: '1f341',
marshall_islands: '1f1f2-1f1ed',
martial_arts_uniform: '1f94b',
martinique: '1f1f2-1f1f6',
mask: '1f637',
massage: '1f486',
massage_man: '1f486-2642',
massage_woman: '1f486-2640',
mate: '1f9c9',
mauritania: '1f1f2-1f1f7',
mauritius: '1f1f2-1f1fa',
mayotte: '1f1fe-1f1f9',
meat_on_bone: '1f356',
mechanic: '1f9d1-1f527',
mechanical_arm: '1f9be',
mechanical_leg: '1f9bf',
medal_military: '1f396',
medal_sports: '1f3c5',
medical_symbol: '2695',
mega: '1f4e3',
melon: '1f348',
memo: '1f4dd',
men_wrestling: '1f93c-2642',
menorah: '1f54e',
mens: '1f6b9',
mermaid: '1f9dc-2640',
merman: '1f9dc-2642',
merperson: '1f9dc',
metal: '1f918',
metro: '1f687',
mexico: '1f1f2-1f1fd',
microbe: '1f9a0',
micronesia: '1f1eb-1f1f2',
microphone: '1f3a4',
microscope: '1f52c',
middle_finger: '1f595',
milk_glass: '1f95b',
milky_way: '1f30c',
minibus: '1f690',
minidisc: '1f4bd',
mobile_phone_off: '1f4f4',
moldova: '1f1f2-1f1e9',
monaco: '1f1f2-1f1e8',
money_mouth_face: '1f911',
money_with_wings: '1f4b8',
moneybag: '1f4b0',
mongolia: '1f1f2-1f1f3',
monkey: '1f412',
monkey_face: '1f435',
monocle_face: '1f9d0',
monorail: '1f69d',
montenegro: '1f1f2-1f1ea',
montserrat: '1f1f2-1f1f8',
moon: '1f314',
moon_cake: '1f96e',
morocco: '1f1f2-1f1e6',
mortar_board: '1f393',
mosque: '1f54c',
mosquito: '1f99f',
motor_boat: '1f6e5',
motor_scooter: '1f6f5',
motorcycle: '1f3cd',
motorized_wheelchair: '1f9bc',
motorway: '1f6e3',
mount_fuji: '1f5fb',
mountain: '26f0',
mountain_bicyclist: '1f6b5',
mountain_biking_man: '1f6b5-2642',
mountain_biking_woman: '1f6b5-2640',
mountain_cableway: '1f6a0',
mountain_railway: '1f69e',
mountain_snow: '1f3d4',
mouse: '1f42d',
mouse2: '1f401',
movie_camera: '1f3a5',
moyai: '1f5ff',
mozambique: '1f1f2-1f1ff',
mrs_claus: '1f936',
muscle: '1f4aa',
mushroom: '1f344',
musical_keyboard: '1f3b9',
musical_note: '1f3b5',
musical_score: '1f3bc',
mute: '1f507',
myanmar: '1f1f2-1f1f2',
nail_care: '1f485',
name_badge: '1f4db',
namibia: '1f1f3-1f1e6',
national_park: '1f3de',
nauru: '1f1f3-1f1f7',
nauseated_face: '1f922',
nazar_amulet: '1f9ff',
necktie: '1f454',
negative_squared_cross_mark: '274e',
nepal: '1f1f3-1f1f5',
nerd_face: '1f913',
netherlands: '1f1f3-1f1f1',
neutral_face: '1f610',
"new": '1f195',
new_caledonia: '1f1f3-1f1e8',
new_moon: '1f311',
new_moon_with_face: '1f31a',
new_zealand: '1f1f3-1f1ff',
newspaper: '1f4f0',
newspaper_roll: '1f5de',
next_track_button: '23ed',
ng: '1f196',
ng_man: '1f645-2642',
ng_woman: '1f645-2640',
nicaragua: '1f1f3-1f1ee',
niger: '1f1f3-1f1ea',
nigeria: '1f1f3-1f1ec',
night_with_stars: '1f303',
nine: '0039-20e3',
niue: '1f1f3-1f1fa',
no_bell: '1f515',
no_bicycles: '1f6b3',
no_entry: '26d4',
no_entry_sign: '1f6ab',
no_good: '1f645',
no_good_man: '1f645-2642',
no_good_woman: '1f645-2640',
no_mobile_phones: '1f4f5',
no_mouth: '1f636',
no_pedestrians: '1f6b7',
no_smoking: '1f6ad',
'non-potable_water': '1f6b1',
norfolk_island: '1f1f3-1f1eb',
north_korea: '1f1f0-1f1f5',
northern_mariana_islands: '1f1f2-1f1f5',
norway: '1f1f3-1f1f4',
nose: '1f443',
notebook: '1f4d3',
notebook_with_decorative_cover: '1f4d4',
notes: '1f3b6',
nut_and_bolt: '1f529',
o: '2b55',
o2: '1f17e',
ocean: '1f30a',
octopus: '1f419',
oden: '1f362',
office: '1f3e2',
office_worker: '1f9d1-1f4bc',
oil_drum: '1f6e2',
ok: '1f197',
ok_hand: '1f44c',
ok_man: '1f646-2642',
ok_person: '1f646',
ok_woman: '1f646-2640',
old_key: '1f5dd',
older_adult: '1f9d3',
older_man: '1f474',
older_woman: '1f475',
om: '1f549',
oman: '1f1f4-1f1f2',
on: '1f51b',
oncoming_automobile: '1f698',
oncoming_bus: '1f68d',
oncoming_police_car: '1f694',
oncoming_taxi: '1f696',
one: '0031-20e3',
one_piece_swimsuit: '1fa71',
onion: '1f9c5',
open_book: '1f4d6',
open_file_folder: '1f4c2',
open_hands: '1f450',
open_mouth: '1f62e',
open_umbrella: '2602',
ophiuchus: '26ce',
orange: '1f34a',
orange_book: '1f4d9',
orange_circle: '1f7e0',
orange_heart: '1f9e1',
orange_square: '1f7e7',
orangutan: '1f9a7',
orthodox_cross: '2626',
otter: '1f9a6',
outbox_tray: '1f4e4',
owl: '1f989',
ox: '1f402',
oyster: '1f9aa',
"package": '1f4e6',
page_facing_up: '1f4c4',
page_with_curl: '1f4c3',
pager: '1f4df',
paintbrush: '1f58c',
pakistan: '1f1f5-1f1f0',
palau: '1f1f5-1f1fc',
palestinian_territories: '1f1f5-1f1f8',
palm_tree: '1f334',
palms_up_together: '1f932',
panama: '1f1f5-1f1e6',
pancakes: '1f95e',
panda_face: '1f43c',
paperclip: '1f4ce',
paperclips: '1f587',
papua_new_guinea: '1f1f5-1f1ec',
parachute: '1fa82',
paraguay: '1f1f5-1f1fe',
parasol_on_ground: '26f1',
parking: '1f17f',
parrot: '1f99c',
part_alternation_mark: '303d',
partly_sunny: '26c5',
partying_face: '1f973',
passenger_ship: '1f6f3',
passport_control: '1f6c2',
pause_button: '23f8',
paw_prints: '1f43e',
peace_symbol: '262e',
peach: '1f351',
peacock: '1f99a',
peanuts: '1f95c',
pear: '1f350',
pen: '1f58a',
pencil: '1f4dd',
pencil2: '270f',
penguin: '1f427',
pensive: '1f614',
people_holding_hands: '1f9d1-1f91d-1f9d1',
performing_arts: '1f3ad',
persevere: '1f623',
person_bald: '1f9d1-1f9b2',
person_curly_hair: '1f9d1-1f9b1',
person_fencing: '1f93a',
person_in_manual_wheelchair: '1f9d1-1f9bd',
person_in_motorized_wheelchair: '1f9d1-1f9bc',
person_red_hair: '1f9d1-1f9b0',
person_white_hair: '1f9d1-1f9b3',
person_with_probing_cane: '1f9d1-1f9af',
person_with_turban: '1f473',
peru: '1f1f5-1f1ea',
petri_dish: '1f9eb',
philippines: '1f1f5-1f1ed',
phone: '260e',
pick: '26cf',
pie: '1f967',
pig: '1f437',
pig2: '1f416',
pig_nose: '1f43d',
pill: '1f48a',
pilot: '1f9d1-2708',
pinching_hand: '1f90f',
pineapple: '1f34d',
ping_pong: '1f3d3',
pirate_flag: '1f3f4-2620',
pisces: '2653',
pitcairn_islands: '1f1f5-1f1f3',
pizza: '1f355',
place_of_worship: '1f6d0',
plate_with_cutlery: '1f37d',
play_or_pause_button: '23ef',
pleading_face: '1f97a',
point_down: '1f447',
point_left: '1f448',
point_right: '1f449',
point_up: '261d',
point_up_2: '1f446',
poland: '1f1f5-1f1f1',
police_car: '1f693',
police_officer: '1f46e',
policeman: '1f46e-2642',
policewoman: '1f46e-2640',
poodle: '1f429',
poop: '1f4a9',
popcorn: '1f37f',
portugal: '1f1f5-1f1f9',
post_office: '1f3e3',
postal_horn: '1f4ef',
postbox: '1f4ee',
potable_water: '1f6b0',
potato: '1f954',
pouch: '1f45d',
poultry_leg: '1f357',
pound: '1f4b7',
pout: '1f621',
pouting_cat: '1f63e',
pouting_face: '1f64e',
pouting_man: '1f64e-2642',
pouting_woman: '1f64e-2640',
pray: '1f64f',
prayer_beads: '1f4ff',
pregnant_woman: '1f930',
pretzel: '1f968',
previous_track_button: '23ee',
prince: '1f934',
princess: '1f478',
printer: '1f5a8',
probing_cane: '1f9af',
puerto_rico: '1f1f5-1f1f7',
punch: '1f44a',
purple_circle: '1f7e3',
purple_heart: '1f49c',
purple_square: '1f7ea',
purse: '1f45b',
pushpin: '1f4cc',
put_litter_in_its_place: '1f6ae',
qatar: '1f1f6-1f1e6',
question: '2753',
rabbit: '1f430',
rabbit2: '1f407',
raccoon: '1f99d',
racehorse: '1f40e',
racing_car: '1f3ce',
radio: '1f4fb',
radio_button: '1f518',
radioactive: '2622',
rage: '1f621',
railway_car: '1f683',
railway_track: '1f6e4',
rainbow: '1f308',
rainbow_flag: '1f3f3-1f308',
raised_back_of_hand: '1f91a',
raised_eyebrow: '1f928',
raised_hand: '270b',
raised_hand_with_fingers_splayed: '1f590',
raised_hands: '1f64c',
raising_hand: '1f64b',
raising_hand_man: '1f64b-2642',
raising_hand_woman: '1f64b-2640',
ram: '1f40f',
ramen: '1f35c',
rat: '1f400',
razor: '1fa92',
receipt: '1f9fe',
record_button: '23fa',
recycle: '267b',
red_car: '1f697',
red_circle: '1f534',
red_envelope: '1f9e7',
red_haired_man: '1f468-1f9b0',
red_haired_woman: '1f469-1f9b0',
red_square: '1f7e5',
registered: '00ae',
relaxed: '263a',
relieved: '1f60c',
reminder_ribbon: '1f397',
repeat: '1f501',
repeat_one: '1f502',
rescue_worker_helmet: '26d1',
restroom: '1f6bb',
reunion: '1f1f7-1f1ea',
revolving_hearts: '1f49e',
rewind: '23ea',
rhinoceros: '1f98f',
ribbon: '1f380',
rice: '1f35a',
rice_ball: '1f359',
rice_cracker: '1f358',
rice_scene: '1f391',
right_anger_bubble: '1f5ef',
ring: '1f48d',
ringed_planet: '1fa90',
robot: '1f916',
rocket: '1f680',
rofl: '1f923',
roll_eyes: '1f644',
roll_of_paper: '1f9fb',
roller_coaster: '1f3a2',
romania: '1f1f7-1f1f4',
rooster: '1f413',
rose: '1f339',
rosette: '1f3f5',
rotating_light: '1f6a8',
round_pushpin: '1f4cd',
rowboat: '1f6a3',
rowing_man: '1f6a3-2642',
rowing_woman: '1f6a3-2640',
ru: '1f1f7-1f1fa',
rugby_football: '1f3c9',
runner: '1f3c3',
running: '1f3c3',
running_man: '1f3c3-2642',
running_shirt_with_sash: '1f3bd',
running_woman: '1f3c3-2640',
rwanda: '1f1f7-1f1fc',
sa: '1f202',
safety_pin: '1f9f7',
safety_vest: '1f9ba',
sagittarius: '2650',
sailboat: '26f5',
sake: '1f376',
salt: '1f9c2',
samoa: '1f1fc-1f1f8',
san_marino: '1f1f8-1f1f2',
sandal: '1f461',
sandwich: '1f96a',
santa: '1f385',
sao_tome_principe: '1f1f8-1f1f9',
sari: '1f97b',
sassy_man: '1f481-2642',
sassy_woman: '1f481-2640',
satellite: '1f4e1',
satisfied: '1f606',
saudi_arabia: '1f1f8-1f1e6',
sauna_man: '1f9d6-2642',
sauna_person: '1f9d6',
sauna_woman: '1f9d6-2640',
sauropod: '1f995',
saxophone: '1f3b7',
scarf: '1f9e3',
school: '1f3eb',
school_satchel: '1f392',
scientist: '1f9d1-1f52c',
scissors: '2702',
scorpion: '1f982',
scorpius: '264f',
scotland: '1f3f4-e0067-e0062-e0073-e0063-e0074-e007f',
scream: '1f631',
scream_cat: '1f640',
scroll: '1f4dc',
seat: '1f4ba',
secret: '3299',
see_no_evil: '1f648',
seedling: '1f331',
selfie: '1f933',
senegal: '1f1f8-1f1f3',
serbia: '1f1f7-1f1f8',
service_dog: '1f415-1f9ba',
seven: '0037-20e3',
seychelles: '1f1f8-1f1e8',
shallow_pan_of_food: '1f958',
shamrock: '2618',
shark: '1f988',
shaved_ice: '1f367',
sheep: '1f411',
shell: '1f41a',
shield: '1f6e1',
shinto_shrine: '26e9',
ship: '1f6a2',
shirt: '1f455',
poo: '1f4a9',
shoe: '1f45e',
shopping: '1f6cd',
shopping_cart: '1f6d2',
shorts: '1fa73',
shower: '1f6bf',
shrimp: '1f990',
shrug: '1f937',
shushing_face: '1f92b',
sierra_leone: '1f1f8-1f1f1',
signal_strength: '1f4f6',
singapore: '1f1f8-1f1ec',
singer: '1f9d1-1f3a4',
sint_maarten: '1f1f8-1f1fd',
six: '0036-20e3',
six_pointed_star: '1f52f',
skateboard: '1f6f9',
ski: '1f3bf',
skier: '26f7',
skull: '1f480',
skull_and_crossbones: '2620',
skunk: '1f9a8',
sled: '1f6f7',
sleeping: '1f634',
sleeping_bed: '1f6cc',
sleepy: '1f62a',
slightly_frowning_face: '1f641',
slightly_smiling_face: '1f642',
slot_machine: '1f3b0',
sloth: '1f9a5',
slovakia: '1f1f8-1f1f0',
slovenia: '1f1f8-1f1ee',
small_airplane: '1f6e9',
small_blue_diamond: '1f539',
small_orange_diamond: '1f538',
small_red_triangle: '1f53a',
small_red_triangle_down: '1f53b',
smile: '1f604',
smile_cat: '1f638',
smiley: '1f603',
smiley_cat: '1f63a',
smiling_face_with_three_hearts: '1f970',
smiling_imp: '1f608',
smirk: '1f60f',
smirk_cat: '1f63c',
smoking: '1f6ac',
snail: '1f40c',
snake: '1f40d',
sneezing_face: '1f927',
snowboarder: '1f3c2',
snowflake: '2744',
snowman: '26c4',
snowman_with_snow: '2603',
soap: '1f9fc',
sob: '1f62d',
soccer: '26bd',
socks: '1f9e6',
softball: '1f94e',
solomon_islands: '1f1f8-1f1e7',
somalia: '1f1f8-1f1f4',
soon: '1f51c',
sos: '1f198',
sound: '1f509',
south_africa: '1f1ff-1f1e6',
south_georgia_south_sandwich_islands: '1f1ec-1f1f8',
south_sudan: '1f1f8-1f1f8',
space_invader: '1f47e',
spades: '2660',
spaghetti: '1f35d',
sparkle: '2747',
sparkler: '1f387',
sparkles: '2728',
sparkling_heart: '1f496',
speak_no_evil: '1f64a',
speaker: '1f508',
speaking_head: '1f5e3',
speech_balloon: '1f4ac',
speedboat: '1f6a4',
spider: '1f577',
spider_web: '1f578',
spiral_calendar: '1f5d3',
spiral_notepad: '1f5d2',
sponge: '1f9fd',
spoon: '1f944',
squid: '1f991',
sri_lanka: '1f1f1-1f1f0',
st_barthelemy: '1f1e7-1f1f1',
st_helena: '1f1f8-1f1ed',
st_kitts_nevis: '1f1f0-1f1f3',
st_lucia: '1f1f1-1f1e8',
st_martin: '1f1f2-1f1eb',
st_pierre_miquelon: '1f1f5-1f1f2',
st_vincent_grenadines: '1f1fb-1f1e8',
stadium: '1f3df',
standing_man: '1f9cd-2642',
standing_person: '1f9cd',
standing_woman: '1f9cd-2640',
star: '2b50',
star2: '1f31f',
star_and_crescent: '262a',
star_of_david: '2721',
star_struck: '1f929',
stars: '1f320',
station: '1f689',
statue_of_liberty: '1f5fd',
steam_locomotive: '1f682',
stethoscope: '1fa7a',
stew: '1f372',
stop_button: '23f9',
stop_sign: '1f6d1',
stopwatch: '23f1',
straight_ruler: '1f4cf',
strawberry: '1f353',
stuck_out_tongue: '1f61b',
stuck_out_tongue_closed_eyes: '1f61d',
stuck_out_tongue_winking_eye: '1f61c',
student: '1f9d1-1f393',
studio_microphone: '1f399',
stuffed_flatbread: '1f959',
sudan: '1f1f8-1f1e9',
sun_behind_large_cloud: '1f325',
sun_behind_rain_cloud: '1f326',
sun_behind_small_cloud: '1f324',
sun_with_face: '1f31e',
sunflower: '1f33b',
sunglasses: '1f60e',
sunny: '2600',
sunrise: '1f305',
sunrise_over_mountains: '1f304',
superhero: '1f9b8',
superhero_man: '1f9b8-2642',
superhero_woman: '1f9b8-2640',
supervillain: '1f9b9',
supervillain_man: '1f9b9-2642',
supervillain_woman: '1f9b9-2640',
surfer: '1f3c4',
surfing_man: '1f3c4-2642',
surfing_woman: '1f3c4-2640',
suriname: '1f1f8-1f1f7',
sushi: '1f363',
suspension_railway: '1f69f',
svalbard_jan_mayen: '1f1f8-1f1ef',
swan: '1f9a2',
swaziland: '1f1f8-1f1ff',
sweat: '1f613',
sweat_drops: '1f4a6',
sweat_smile: '1f605',
sweden: '1f1f8-1f1ea',
sweet_potato: '1f360',
swim_brief: '1fa72',
swimmer: '1f3ca',
swimming_man: '1f3ca-2642',
swimming_woman: '1f3ca-2640',
switzerland: '1f1e8-1f1ed',
symbols: '1f523',
synagogue: '1f54d',
syria: '1f1f8-1f1fe',
syringe: '1f489',
't-rex': '1f996',
taco: '1f32e',
tada: '1f389',
taiwan: '1f1f9-1f1fc',
tajikistan: '1f1f9-1f1ef',
takeout_box: '1f961',
tanabata_tree: '1f38b',
tangerine: '1f34a',
tanzania: '1f1f9-1f1ff',
taurus: '2649',
taxi: '1f695',
tea: '1f375',
teacher: '1f9d1-1f3eb',
technologist: '1f9d1-1f4bb',
teddy_bear: '1f9f8',
telephone: '260e',
telephone_receiver: '1f4de',
telescope: '1f52d',
tennis: '1f3be',
tent: '26fa',
test_tube: '1f9ea',
thailand: '1f1f9-1f1ed',
thermometer: '1f321',
thinking: '1f914',
thought_balloon: '1f4ad',
thread: '1f9f5',
three: '0033-20e3',
thumbsdown: '1f44e',
thumbsup: '1f44d',
ticket: '1f3ab',
tickets: '1f39f',
tiger: '1f42f',
tiger2: '1f405',
timer_clock: '23f2',
timor_leste: '1f1f9-1f1f1',
tipping_hand_man: '1f481-2642',
tipping_hand_person: '1f481',
tipping_hand_woman: '1f481-2640',
tired_face: '1f62b',
tm: '2122',
togo: '1f1f9-1f1ec',
toilet: '1f6bd',
tokelau: '1f1f9-1f1f0',
tokyo_tower: '1f5fc',
tomato: '1f345',
tonga: '1f1f9-1f1f4',
tongue: '1f445',
toolbox: '1f9f0',
tooth: '1f9b7',
top: '1f51d',
tophat: '1f3a9',
tornado: '1f32a',
tr: '1f1f9-1f1f7',
trackball: '1f5b2',
tractor: '1f69c',
traffic_light: '1f6a5',
train: '1f68b',
train2: '1f686',
tram: '1f68a',
triangular_flag_on_post: '1f6a9',
triangular_ruler: '1f4d0',
trident: '1f531',
trinidad_tobago: '1f1f9-1f1f9',
tristan_da_cunha: '1f1f9-1f1e6',
triumph: '1f624',
trolleybus: '1f68e',
trophy: '1f3c6',
tropical_drink: '1f379',
tropical_fish: '1f420',
truck: '1f69a',
trumpet: '1f3ba',
tshirt: '1f455',
tulip: '1f337',
tumbler_glass: '1f943',
tunisia: '1f1f9-1f1f3',
turkey: '1f983',
turkmenistan: '1f1f9-1f1f2',
turks_caicos_islands: '1f1f9-1f1e8',
turtle: '1f422',
tuvalu: '1f1f9-1f1fb',
tv: '1f4fa',
twisted_rightwards_arrows: '1f500',
two: '0032-20e3',
two_hearts: '1f495',
two_men_holding_hands: '1f46c',
two_women_holding_hands: '1f46d',
u5272: '1f239',
u5408: '1f234',
u55b6: '1f23a',
u6307: '1f22f',
u6708: '1f237',
u6709: '1f236',
u6e80: '1f235',
u7121: '1f21a',
u7533: '1f238',
u7981: '1f232',
u7a7a: '1f233',
uganda: '1f1fa-1f1ec',
uk: '1f1ec-1f1e7',
ukraine: '1f1fa-1f1e6',
umbrella: '2614',
unamused: '1f612',
underage: '1f51e',
unicorn: '1f984',
united_arab_emirates: '1f1e6-1f1ea',
united_nations: '1f1fa-1f1f3',
unlock: '1f513',
up: '1f199',
upside_down_face: '1f643',
uruguay: '1f1fa-1f1fe',
us: '1f1fa-1f1f8',
us_outlying_islands: '1f1fa-1f1f2',
us_virgin_islands: '1f1fb-1f1ee',
uzbekistan: '1f1fa-1f1ff',
v: '270c',
vampire: '1f9db',
vampire_man: '1f9db-2642',
vampire_woman: '1f9db-2640',
vanuatu: '1f1fb-1f1fa',
vatican_city: '1f1fb-1f1e6',
venezuela: '1f1fb-1f1ea',
vertical_traffic_light: '1f6a6',
vhs: '1f4fc',
vibration_mode: '1f4f3',
video_camera: '1f4f9',
video_game: '1f3ae',
vietnam: '1f1fb-1f1f3',
violin: '1f3bb',
virgo: '264d',
volcano: '1f30b',
volleyball: '1f3d0',
vomiting_face: '1f92e',
vs: '1f19a',
vulcan_salute: '1f596',
waffle: '1f9c7',
wales: '1f3f4-e0067-e0062-e0077-e006c-e0073-e007f',
walking: '1f6b6',
walking_man: '1f6b6-2642',
walking_woman: '1f6b6-2640',
wallis_futuna: '1f1fc-1f1eb',
waning_crescent_moon: '1f318',
waning_gibbous_moon: '1f316',
warning: '26a0',
wastebasket: '1f5d1',
watch: '231a',
water_buffalo: '1f403',
water_polo: '1f93d',
watermelon: '1f349',
wave: '1f44b',
wavy_dash: '3030',
waxing_crescent_moon: '1f312',
waxing_gibbous_moon: '1f314',
wc: '1f6be',
weary: '1f629',
wedding: '1f492',
weight_lifting: '1f3cb',
weight_lifting_man: '1f3cb-2642',
weight_lifting_woman: '1f3cb-2640',
western_sahara: '1f1ea-1f1ed',
whale: '1f433',
whale2: '1f40b',
wheel_of_dharma: '2638',
wheelchair: '267f',
white_check_mark: '2705',
white_circle: '26aa',
white_flag: '1f3f3',
white_flower: '1f4ae',
white_haired_man: '1f468-1f9b3',
white_haired_woman: '1f469-1f9b3',
white_heart: '1f90d',
white_large_square: '2b1c',
white_medium_small_square: '25fd',
white_medium_square: '25fb',
white_small_square: '25ab',
white_square_button: '1f533',
wilted_flower: '1f940',
wind_chime: '1f390',
wind_face: '1f32c',
wine_glass: '1f377',
wink: '1f609',
wolf: '1f43a',
woman: '1f469',
woman_artist: '1f469-1f3a8',
woman_astronaut: '1f469-1f680',
woman_cartwheeling: '1f938-2640',
woman_cook: '1f469-1f373',
woman_dancing: '1f483',
woman_facepalming: '1f926-2640',
woman_factory_worker: '1f469-1f3ed',
woman_farmer: '1f469-1f33e',
woman_firefighter: '1f469-1f692',
woman_health_worker: '1f469-2695',
woman_in_manual_wheelchair: '1f469-1f9bd',
woman_in_motorized_wheelchair: '1f469-1f9bc',
woman_judge: '1f469-2696',
woman_juggling: '1f939-2640',
woman_mechanic: '1f469-1f527',
woman_office_worker: '1f469-1f4bc',
woman_pilot: '1f469-2708',
woman_playing_handball: '1f93e-2640',
woman_playing_water_polo: '1f93d-2640',
woman_scientist: '1f469-1f52c',
woman_shrugging: '1f937-2640',
woman_singer: '1f469-1f3a4',
woman_student: '1f469-1f393',
woman_teacher: '1f469-1f3eb',
woman_technologist: '1f469-1f4bb',
woman_with_headscarf: '1f9d5',
woman_with_probing_cane: '1f469-1f9af',
woman_with_turban: '1f473-2640',
womans_clothes: '1f45a',
womans_hat: '1f452',
women_wrestling: '1f93c-2640',
womens: '1f6ba',
woozy_face: '1f974',
world_map: '1f5fa',
worried: '1f61f',
wrench: '1f527',
wrestling: '1f93c',
writing_hand: '270d',
x: '274c',
yarn: '1f9f6',
yawning_face: '1f971',
yellow_circle: '1f7e1',
yellow_heart: '1f49b',
yellow_square: '1f7e8',
yemen: '1f1fe-1f1ea',
yen: '1f4b4',
yin_yang: '262f',
yo_yo: '1fa80',
yum: '1f60b',
zambia: '1f1ff-1f1f2',
zany_face: '1f92a',
zap: '26a1',
zebra: '1f993',
zero: '0030-20e3',
zimbabwe: '1f1ff-1f1fc',
zipper_mouth_face: '1f910',
zombie: '1f9df',
zombie_man: '1f9df-2642',
zombie_woman: '1f9df-2640',
zzz: '1f4a4'
}
};
function ownKeys$7(object, enumerableOnly) { var keys = keys$3(object); if (getOwnPropertySymbols$2) { var symbols = getOwnPropertySymbols$2(object); enumerableOnly && (symbols = filter$3(symbols).call(symbols, function (sym) { return getOwnPropertyDescriptor$3(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$6(target) { for (var i = 1; i < arguments.length; i++) { var _context3, _context4; var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? forEach$3(_context3 = ownKeys$7(Object(source), !0)).call(_context3, function (key) { _defineProperty(target, key, source[key]); }) : getOwnPropertyDescriptors$2 ? defineProperties$2(target, getOwnPropertyDescriptors$2(source)) : forEach$3(_context4 = ownKeys$7(Object(source))).call(_context4, function (key) { defineProperty$5(target, key, getOwnPropertyDescriptor$3(source, key)); }); } return target; }
function _createSuper$s(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$s(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$s() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function fromCodePoint$3() {
var codeUnits = [];
var codeLen = 0;
var result = '';
for (var index = 0, len = arguments.length; index !== len; ++index) {
var codePoint = +(index < 0 || arguments.length <= index ? undefined : arguments[index]); // correctly handles all cases including `NaN`, `-Infinity`, `+Infinity`
// The surrounding `!(...)` is required to correctly handle `NaN` cases
// The (codePoint>>>0) === codePoint clause handles decimals and negatives
if (!(codePoint < 0x10ffff && codePoint >>> 0 === codePoint)) {
throw new RangeError("Invalid code point: ".concat(codePoint));
}
if (codePoint <= 0xffff) {
// BMP code point
codeLen = codeUnits.push(codePoint);
} else {
// Astral code point; split in surrogate halves
// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
codePoint -= 0x10000;
codeLen = codeUnits.push((codePoint >> 10) + 0xd800, // highSurrogate
codePoint % 0x400 + 0xdc00 // lowSurrogate
);
}
if (codeLen >= 0x3fff) {
result += String.fromCharCode.apply(null, codeUnits);
codeUnits.length = 0;
}
}
return result + String.fromCharCode.apply(null, codeUnits);
}
var Emoji = /*#__PURE__*/function (_SyntaxBase) {
_inherits(Emoji, _SyntaxBase);
var _super = _createSuper$s(Emoji);
function Emoji() {
var _this;
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
config: undefined
},
config = _ref.config;
_classCallCheck(this, Emoji);
_this = _super.call(this, {
config: config
});
_this.options = {
useUnicode: true,
upperCase: false,
customHandled: false,
resourceURL: 'https://github.githubassets.com/images/icons/emoji/unicode/${code}.png?v8',
emojis: _objectSpread$6({}, gfmUnicode.emojis)
};
if (_typeof(config) !== 'object') {
return _possibleConstructorReturn(_this);
}
var useUnicode = config.useUnicode,
customResourceURL = config.customResourceURL,
customRenderer = config.customRenderer,
upperCase = config.upperCase;
_this.options.useUnicode = typeof useUnicode === 'boolean' ? useUnicode : _this.options.useUnicode;
_this.options.upperCase = typeof useUnicode === 'boolean' ? upperCase : _this.options.upperCase;
if (useUnicode === false && typeof customResourceURL === 'string') {
_this.options.resourceURL = customResourceURL;
}
if (typeof customRenderer === 'function') {
_this.options.customHandled = true;
_this.options.customRenderer = customRenderer;
} // TODO: URL Validator
return _this;
}
_createClass(Emoji, [{
key: "makeHtml",
value: function makeHtml(str, sentenceMakeFunc) {
var _this2 = this;
if (!this.test(str)) {
return str;
}
return str.replace(this.RULE.reg, function (match, emojiKey) {
var _context2;
// 先走自定义渲染逻辑
if (_this2.options.customHandled && typeof _this2.options.customRenderer === 'function') {
return _this2.options.customRenderer(emojiKey);
}
var emojiCode = _this2.options.emojis[emojiKey];
if (typeof emojiCode !== 'string') {
return match;
}
if (_this2.options.useUnicode) {
var _context;
var codes = map$3(_context = emojiCode.split('-')).call(_context, function (unicode) {
return "0x".concat(unicode);
}); // convert to hex string
return fromCodePoint$3.apply(void 0, _toConsumableArray(codes));
}
if (_this2.options.upperCase) {
emojiCode = emojiCode.toUpperCase();
}
var src = _this2.options.resourceURL.replace(/\$\{code\}/g, emojiCode);
return concat$5(_context2 = "<img class=\"emoji\" src=\"".concat(src, "\" alt=\"")).call(_context2, escapeHTMLSpecialCharOnce(emojiKey), "\" />");
});
}
}, {
key: "rule",
value: function rule() {
// (?<protocol>\\w+:)\\/\\/
var ret = {
// ?<left>
begin: ':',
content: '([a-zA-Z0-9+_]+?)',
// ?<right>
end: ':'
};
ret.reg = compileRegExp(ret, 'g');
return ret;
}
}]);
return Emoji;
}(SyntaxBase);
_defineProperty(Emoji, "HOOK_NAME", 'emoji');
function _createSuper$t(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$t(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$t() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Underline = /*#__PURE__*/function (_SyntaxBase) {
_inherits(Underline, _SyntaxBase);
var _super = _createSuper$t(Underline);
function Underline() {
_classCallCheck(this, Underline);
return _super.apply(this, arguments);
}
_createClass(Underline, [{
key: "makeHtml",
value: // constructor() {
// super();
// }
function makeHtml(str) {
if (!this.test(str)) {
return str;
}
return str.replace(this.RULE.reg, '$1<span style="text-decoration: underline;">$2</span>$3');
}
}, {
key: "rule",
value: function rule() {
var ret = {
begin: '(^| )\\/',
end: '\\/( |$)',
content: '([^\\n]+?)'
};
ret.reg = new RegExp(ret.begin + ret.content + ret.end, 'g');
return ret;
}
}]);
return Underline;
}(SyntaxBase);
_defineProperty(Underline, "HOOK_NAME", 'underline');
function _createSuper$u(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$u(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$u() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var HighLight = /*#__PURE__*/function (_SyntaxBase) {
_inherits(HighLight, _SyntaxBase);
var _super = _createSuper$u(HighLight);
function HighLight() {
_classCallCheck(this, HighLight);
return _super.apply(this, arguments);
}
_createClass(HighLight, [{
key: "makeHtml",
value: function makeHtml(str) {
if (!this.test(str)) {
return str;
}
return str.replace(this.RULE.reg, '$1<mark>$2</mark>$3');
}
}, {
key: "rule",
value: function rule() {
var ret = {
begin: '(^| )==',
end: '==( |$|\\n)',
content: '([^\\n]+?)'
};
ret.reg = new RegExp(ret.begin + ret.content + ret.end, 'g');
return ret;
}
}]);
return HighLight;
}(SyntaxBase);
_defineProperty(HighLight, "HOOK_NAME", 'highLight');
// eslint-disable-next-line es-x/no-json -- safe
if (!path.JSON) path.JSON = { stringify: JSON.stringify };
// eslint-disable-next-line no-unused-vars -- required for `.length`
var stringify = function stringify(it, replacer, space) {
return functionApply(path.JSON.stringify, null, arguments);
};
var stringify$1 = stringify;
var stringify$2 = stringify$1;
var $includes = arrayIncludes.includes;
// FF99+ bug
var BROKEN_ON_SPARSE = fails(function () {
return !Array(1).includes();
});
// `Array.prototype.includes` method
// https://tc39.es/ecma262/#sec-array.prototype.includes
_export({ target: 'Array', proto: true, forced: BROKEN_ON_SPARSE }, {
includes: function includes(el /* , fromIndex = 0 */) {
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
var includes = entryVirtual('Array').includes;
var stringIndexOf = functionUncurryThis(''.indexOf);
// `String.prototype.includes` method
// https://tc39.es/ecma262/#sec-string.prototype.includes
_export({ target: 'String', proto: true, forced: !correctIsRegexpLogic('includes') }, {
includes: function includes(searchString /* , position = 0 */) {
return !!~stringIndexOf(
toString_1(requireObjectCoercible(this)),
toString_1(notARegexp(searchString)),
arguments.length > 1 ? arguments[1] : undefined
);
}
});
var includes$1 = entryVirtual('String').includes;
var ArrayPrototype$d = Array.prototype;
var StringPrototype$3 = String.prototype;
var includes$2 = function (it) {
var own = it.includes;
if (it === ArrayPrototype$d || (objectIsPrototypeOf(ArrayPrototype$d, it) && own === ArrayPrototype$d.includes)) return includes;
if (typeof it == 'string' || it === StringPrototype$3 || (objectIsPrototypeOf(StringPrototype$3, it) && own === StringPrototype$3.includes)) {
return includes$1;
} return own;
};
var includes$3 = includes$2;
var includes$4 = includes$3;
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
var _arrayMap = arrayMap;
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol$1(value) {
return typeof value == 'symbol' ||
(isObjectLike_1(value) && _baseGetTag(value) == symbolTag);
}
var isSymbol_1 = isSymbol$1;
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/** Used to convert symbols to primitives and strings. */
var symbolProto = _Symbol ? _Symbol.prototype : undefined,
symbolToString = symbolProto ? symbolProto.toString : undefined;
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isArray_1(value)) {
// Recursively convert values (susceptible to call stack limits).
return _arrayMap(value, baseToString) + '';
}
if (isSymbol_1(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
var _baseToString = baseToString;
/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString$2(value) {
return value == null ? '' : _baseToString(value);
}
var toString_1$1 = toString$2;
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar$1 = /[\\^$.*+?()[\]{}|]/g,
reHasRegExpChar = RegExp(reRegExpChar$1.source);
/**
* Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
* "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escapeRegExp('[lodash](https://lodash.com/)');
* // => '\[lodash\]\(https://lodash\.com/\)'
*/
function escapeRegExp(string) {
string = toString_1$1(string);
return (string && reHasRegExpChar.test(string))
? string.replace(reRegExpChar$1, '\\$&')
: string;
}
var escapeRegExp_1 = escapeRegExp;
// handling this'.
var Pass = {
toString: function toString() {
return "CodeMirror.Pass";
}
}; // Reused option objects for setSelection & friends
function _createSuper$v(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$v(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$v() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* @typedef {import('codemirror')} CodeMirror
*/
/**
* @typedef { Object } SuggestListItemObject 推荐列表项对象
* @property { string } icon 图标
* @property { string } label 候选列表回显的内容
* @property { string } value 点击候选项的时候回填的值
* @property { string } keyword 关键词,通过关键词控制候选项的显隐
* @typedef { SuggestListItemObject | string } SuggestListItem 推荐列表项
* @typedef { Array<SuggestListItem> } SuggestList 推荐列表
*/
/**
* @typedef {object} SuggesterConfigItem
* @property {function(string, function(SuggestList): void): void} suggestList
* @property {string} keyword
* @property {function} suggestListRender
* @property {function} echo
* @typedef {object} SuggesterConfig
* @property {Array<SuggesterConfigItem>} suggester
*/
var Suggester = /*#__PURE__*/function (_SyntaxBase) {
_inherits(Suggester, _SyntaxBase);
var _super = _createSuper$v(Suggester);
function Suggester(_ref) {
var _this;
var config = _ref.config;
_classCallCheck(this, Suggester);
/**
* config.suggester 内容
* [{
* 请求url
suggestList: '',
唤醒关键字
keyword: '@',
建议模板 function
suggestListRender(valueArray) {
},
回填回调 function
echo(value) {
}]
*
*/
_this = _super.call(this, {
needCache: true
});
_this.config = config;
_this.RULE = _this.rule();
return _this;
}
_createClass(Suggester, [{
key: "afterInit",
value: function afterInit(callback) {
if (typeof callback === 'function') {
callback();
}
this.initConfig(this.config);
}
/**
* 获取系统默认的候选项列表
* TODO后面考虑增加层级机制比如“公式”是一级“集合、逻辑运算、方程式”是公式的二级候选值
*/
}, {
key: "getSystemSuggestList",
value: function getSystemSuggestList() {
var locales = this.$locale;
var suggestList = [{
icon: 'h1',
label: locales['H1 Heading'],
keyword: 'head1',
value: '# '
}, {
icon: 'h2',
label: locales['H2 Heading'],
keyword: 'head2',
value: '## '
}, {
icon: 'h3',
label: locales['H3 Heading'],
keyword: 'head3',
value: '### '
}, {
icon: 'table',
label: locales.table,
keyword: 'table',
value: '| Header | Header | Header |\n| --- | --- | --- |\n| Content | Content | Content |\n'
}, {
icon: 'code',
label: locales.code,
keyword: 'code',
value: '```\n\n```\n'
}, {
icon: 'link',
label: locales.link,
keyword: 'link',
value: "[title](https://url)"
}, {
icon: 'checklist',
label: locales.checklist,
keyword: 'checklist',
value: "- [ ] item\n- [x] item"
}, {
icon: 'tips',
label: locales.panel,
keyword: 'panel tips info warning danger success',
value: "::: primary title\ncontent\n:::\n"
}, {
icon: 'insertFlow',
label: locales.detail,
keyword: 'detail',
value: "+++ \u70B9\u51FB\u5C55\u5F00\u66F4\u591A\n\u5185\u5BB9\n++- \u9ED8\u8BA4\u5C55\u5F00\n\u5185\u5BB9\n++ \u9ED8\u8BA4\u6536\u8D77\n\u5185\u5BB9\n+++\n"
} // {
// icon: 'pen',
// label: '续写',
// keyword: 'xu xie chatgpt',
// value: () => {
// if (!this.$engine.$cherry.options.openai.apiKey) {
// return '请先配置openai apiKey';
// }
// this.$engine.$cherry.toolbar.toolbarHandlers.chatgpt('complement');
// return `\n`;
// },
// },
// {
// icon: 'pen',
// label: '总结',
// keyword: 'zong jie chatgpt',
// value: () => {
// if (!this.$engine.$cherry.options.openai.apiKey) {
// return '请先配置openai apiKey';
// }
// this.$engine.$cherry.toolbar.toolbarHandlers.chatgpt('summary');
// return `\n`;
// },
// },
];
return suggestList;
}
/**
* 初始化配置
* @param {SuggesterConfig} config
*/
}, {
key: "initConfig",
value: function initConfig(config) {
var _this2 = this;
var suggester = config.suggester;
this.suggester = {};
if (!suggester) {
suggester = [];
}
var systemSuggestList = this.getSystemSuggestList(); // 默认的唤醒关键字
suggester.unshift({
keyword: '/',
suggestList: function suggestList(word, callback) {
var $word = word.replace(/^\//, ''); // 加个空格就直接退出联想
if (/^\s$/.test($word)) {
callback(false);
return;
}
var keyword = $word.replace(/\s+/g, '').split('').join('.*?');
var test = new RegExp("^.*?".concat(keyword, ".*?$"), 'i');
var suggestList = filter$3(systemSuggestList).call(systemSuggestList, function (item) {
// TODO: 首次联想的时候会把所有的候选项列出来,后续可以增加一些机制改成默认拉取一部分候选项
return !$word || test.test(item.keyword);
});
callback(suggestList);
}
});
forEach$3(suggester).call(suggester, function (configItem) {
if (!configItem.suggestList) {
console.warn('[cherry-suggester]: the suggestList of config is missing.');
return;
}
if (!configItem.keyword) {
configItem.keyword = '@';
}
_this2.suggester[configItem.keyword] = configItem;
}); // 反复初始化时, 缓存还在, dom 已更新情况
if (suggesterPanel.hasEditor()) {
suggesterPanel.editor = null;
}
}
}, {
key: "makeHtml",
value: function makeHtml(str) {
var _context2;
if (!this.RULE.reg) return str;
if (!suggesterPanel.hasEditor() && isBrowser()) {
var editor = this.$engine.$cherry.editor;
suggesterPanel.setEditor(editor);
suggesterPanel.setSuggester(this.suggester);
suggesterPanel.bindEvent();
}
if (isLookbehindSupported()) {
var _context;
return str.replace(this.RULE.reg, bind$5(_context = this.toHtml).call(_context, this));
}
return replaceLookbehind(str, this.RULE.reg, bind$5(_context2 = this.toHtml).call(_context2, this), true, 1);
}
}, {
key: "toHtml",
value: function toHtml(wholeMatch, leadingChar, keyword, text) {
var _this$suggester$keywo3;
if (text) {
var _this$suggester$keywo, _this$suggester$keywo2, _context3, _context4;
return ((_this$suggester$keywo = this.suggester[keyword]) === null || _this$suggester$keywo === void 0 ? void 0 : (_this$suggester$keywo2 = _this$suggester$keywo.echo) === null || _this$suggester$keywo2 === void 0 ? void 0 : _this$suggester$keywo2.call(this, text)) || concat$5(_context3 = concat$5(_context4 = "".concat(leadingChar, "<span class=\"cherry-suggestion\">")).call(_context4, keyword)).call(_context3, text, "</span>");
}
if (((_this$suggester$keywo3 = this.suggester[keyword]) === null || _this$suggester$keywo3 === void 0 ? void 0 : _this$suggester$keywo3.echo) === false) {
return "".concat(leadingChar);
}
if (!this.suggester[keyword]) {
return leadingChar + text;
}
return text ? leadingChar + text : "".concat(leadingChar);
}
}, {
key: "rule",
value: function rule() {
var _context5, _context6, _context7;
if (!this.suggester || keys$3(this.suggester).length <= 0) {
return {};
}
var keys = map$3(_context5 = keys$3(this.suggester)).call(_context5, function (key) {
return escapeRegExp_1(key);
}).join('|');
var reg = new RegExp(concat$5(_context6 = concat$5(_context7 = "".concat(isLookbehindSupported() ? '((?<!\\\\))[ ]' : '(^|[^\\\\])[ ]', "(")).call(_context7, keys, ")(([^")).call(_context6, keys, "\\s])+)"), 'g');
return {
reg: reg
};
}
}, {
key: "mounted",
value: function mounted() {
if (!suggesterPanel.hasEditor() && isBrowser()) {
var editor = this.$engine.$cherry.editor;
suggesterPanel.setEditor(editor);
suggesterPanel.setSuggester(this.suggester);
suggesterPanel.bindEvent();
}
}
}]);
return Suggester;
}(SyntaxBase);
_defineProperty(Suggester, "HOOK_NAME", 'suggester');
var SuggesterPanel = /*#__PURE__*/function () {
function SuggesterPanel() {
_classCallCheck(this, SuggesterPanel);
this.searchCache = false;
this.searchKeyCache = [];
this.optionList = [];
this.cursorMove = true;
this.suggesterConfig = {};
if (!this.$suggesterPanel && isBrowser() && document) {
var _document, _document$body, _document2;
(_document = document) === null || _document === void 0 ? void 0 : (_document$body = _document.body) === null || _document$body === void 0 ? void 0 : _document$body.appendChild(this.createDom(SuggesterPanel.panelWrap));
this.$suggesterPanel = (_document2 = document) === null || _document2 === void 0 ? void 0 : _document2.querySelector('.cherry-suggester-panel');
}
}
_createClass(SuggesterPanel, [{
key: "hasEditor",
value: function hasEditor() {
return !!this.editor && !!this.editor.editor.display && !!this.editor.editor.display.wrapper;
}
/**
* 设置编辑器
* @param {import('@/Editor').default} editor
*/
}, {
key: "setEditor",
value: function setEditor(editor) {
this.editor = editor;
}
}, {
key: "setSuggester",
value: function setSuggester(suggester) {
this.suggesterConfig = suggester;
}
}, {
key: "bindEvent",
value: function bindEvent() {
var _this3 = this;
var keyAction = false;
this.editor.editor.on('change', function (codemirror, evt) {
keyAction = true;
_this3.onCodeMirrorChange(codemirror, evt);
});
this.editor.editor.on('keydown', function (codemirror, evt) {
keyAction = true;
if (_this3.enableRelate()) {
_this3.onKeyDown(codemirror, evt);
}
});
this.editor.editor.on('cursorActivity', function () {
// 当编辑区光标位置改变时触发
if (!keyAction) {
_this3.stopRelate();
}
keyAction = false;
});
var extraKeys = this.editor.editor.getOption('extraKeys');
var decorateKeys = ['Up', 'Down', 'Enter'];
forEach$3(decorateKeys).call(decorateKeys, function (key) {
if (typeof extraKeys[key] === 'function') {
var proxyTarget = extraKeys[key];
extraKeys[key] = function (codemirror) {
if (suggesterPanel.cursorMove) {
var res = proxyTarget.call(codemirror, codemirror);
if (res) {
return res;
} // logic to decide whether to move up or not
// return Pass.toString();
}
};
} else if (!extraKeys[key]) {
extraKeys[key] = function () {
if (suggesterPanel.cursorMove) {
// logic to decide whether to move up or not
return Pass.toString();
}
};
} else if (typeof extraKeys[key] === 'string') {
var command = extraKeys[key];
extraKeys[key] = function (codemirror) {
if (suggesterPanel.cursorMove) {
_this3.editor.editor.execCommand(command); // logic to decide whether to move up or not
// return Pass.toString();
}
};
}
});
this.editor.editor.setOption('extraKeys', extraKeys);
this.editor.editor.on('scroll', function (codemirror, evt) {
if (!_this3.searchCache) {
return;
} // 当编辑器滚动时触发
_this3.relocatePanel(_this3.editor.editor);
});
this.onClickPancelItem();
}
}, {
key: "onClickPancelItem",
value: function onClickPancelItem() {
var _this4 = this;
this.$suggesterPanel.addEventListener('click', function (evt) {
var idx = isChildNode(_this4.$suggesterPanel, evt.target);
if (idx > -1) {
_this4.pasteSelectResult(idx);
}
_this4.stopRelate();
}, false);
function isChildNode(parent, node) {
var _context8;
var res = -1;
forEach$3(_context8 = parent.childNodes).call(_context8, function (item, idx) {
return item === node ? res = idx : '';
});
return res;
}
}
}, {
key: "showsuggesterPanel",
value: function showsuggesterPanel(_ref2) {
var left = _ref2.left,
top = _ref2.top,
items = _ref2.items;
if (!this.$suggesterPanel && isBrowser()) {
document.body.appendChild(this.createDom(SuggesterPanel.panelWrap));
this.$suggesterPanel = document.querySelector('.cherry-suggester-panel');
}
this.updatePanel(items);
this.$suggesterPanel.style.left = "".concat(left, "px");
this.$suggesterPanel.style.top = "".concat(top, "px");
this.$suggesterPanel.style.display = 'block';
this.$suggesterPanel.style.position = 'absolute';
this.$suggesterPanel.style.zIndex = '100';
}
}, {
key: "hidesuggesterPanel",
value: function hidesuggesterPanel() {
// const $suggesterPanel = document.querySelector('.cherry-suggester-panel');
if (this.$suggesterPanel) {
this.$suggesterPanel.style.display = 'none';
}
}
/**
* 更新suggesterPanel
* @param {SuggestList} suggestList
*/
}, {
key: "updatePanel",
value: function updatePanel(suggestList) {
var _this5 = this;
var defaultValue = map$3(suggestList).call(suggestList, function (suggest, idx) {
if (_typeof(suggest) === 'object' && suggest !== null) {
var renderContent = suggest.label;
if (suggest !== null && suggest !== void 0 && suggest.icon) {
var _context9;
renderContent = concat$5(_context9 = "<i class=\"ch-icon ch-icon-".concat(suggest.icon, "\"></i>")).call(_context9, renderContent);
}
return _this5.renderPanelItem(renderContent, idx === 0);
}
return _this5.renderPanelItem(suggest, idx === 0);
}).join('');
/**
* @type { SuggesterConfigItem }
*/
var suggesterConfig = this.suggesterConfig[this.keyword]; // 用户自定义渲染逻辑 suggestListRender
if (suggesterConfig && typeof suggesterConfig.suggestListRender === 'function') {
defaultValue = suggesterConfig.suggestListRender.call(this, suggestList) || defaultValue;
}
this.$suggesterPanel.innerHTML = ''; // 清空
if (typeof defaultValue === 'string') {
this.$suggesterPanel.innerHTML = defaultValue;
} else if (isArray$8(defaultValue) && defaultValue.length > 0) {
forEach$3(defaultValue).call(defaultValue, function (item) {
_this5.$suggesterPanel.appendChild(item);
});
} else if (_typeof(defaultValue) === 'object' && defaultValue.nodeType === 1) {
this.$suggesterPanel.appendChild(defaultValue);
}
}
/**
* 渲染suggesterPanel item
* @param {string} item 渲染内容
* @param {boolean} selected 是否选中
* @returns {string} html
*/
}, {
key: "renderPanelItem",
value: function renderPanelItem(item, selected) {
if (selected) {
return "<div class=\"cherry-suggester-panel__item cherry-suggester-panel__item--selected\">".concat(item, "</div>");
}
return "<div class=\"cherry-suggester-panel__item\">".concat(item, "</div>");
}
}, {
key: "createDom",
value: function createDom() {
var string = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
if (!this.template) {
this.template = document.createElement('div');
}
this.template.innerHTML = trim$3(string).call(string); // Change this to div.childNodes to support multiple top-level nodes
var frag = document.createDocumentFragment();
map$3(Array.prototype).call(this.template.childNodes, function (item, idx) {
frag.appendChild(item);
});
return frag;
} // 面板重定位
}, {
key: "relocatePanel",
value: function relocatePanel(codemirror) {
var $cursor = document.querySelector('.CodeMirror-cursors .CodeMirror-cursor');
if (!$cursor) {
return false;
}
var pos = codemirror.getCursor();
var lineHeight = codemirror.lineInfo(pos.line).handle.height;
var rect = $cursor.getBoundingClientRect();
var top = rect.top + lineHeight;
var left = rect.left;
this.showsuggesterPanel({
left: left,
top: top,
items: this.optionList
});
}
/**
* 获取光标位置
* @param {CodeMirror} codemirror
* @returns {{ left: number, top: number }}
*/
}, {
key: "getCursorPos",
value: function getCursorPos(codemirror) {
var $cursor = document.querySelector('.CodeMirror-cursors .CodeMirror-cursor');
if (!$cursor) return null;
var pos = codemirror.getCursor();
var lineHeight = codemirror.lineInfo(pos.line).handle.height;
var rect = $cursor.getBoundingClientRect();
var top = rect.top + lineHeight;
var left = rect.left;
return {
left: left,
top: top
};
} // 开启关联
}, {
key: "startRelate",
value: function startRelate(codemirror, keyword, from) {
this.cursorFrom = from;
this.keyword = keyword;
this.searchCache = true;
this.relocatePanel(codemirror);
} // 关闭关联
}, {
key: "stopRelate",
value: function stopRelate() {
this.hidesuggesterPanel();
this.cursorFrom = null;
this.cursorTo = null;
this.keyword = '';
this.searchKeyCache = [];
this.searchCache = false;
this.cursorMove = true;
this.optionList = [];
}
/**
* 粘贴选择结果
* @param {number} idx 选择的结果索引
* @param {KeyboardEvent} evt 键盘事件
*/
}, {
key: "pasteSelectResult",
value: function pasteSelectResult(idx, evt) {
if (!this.cursorTo) {
this.cursorTo = JSON.parse(stringify$2(this.cursorFrom));
}
if (!this.cursorTo) {
return;
}
this.cursorTo.ch += 1;
var cursorFrom = this.cursorFrom,
cursorTo = this.cursorTo; // 缓存光标位置
if (this.optionList[idx]) {
var result = '';
if (_typeof(this.optionList[idx]) === 'object' && this.optionList[idx] !== null && typeof this.optionList[idx].value === 'string') {
result = this.optionList[idx].value;
}
if (_typeof(this.optionList[idx]) === 'object' && this.optionList[idx] !== null && typeof this.optionList[idx].value === 'function') {
result = this.optionList[idx].value();
}
if (typeof this.optionList[idx] === 'string') {
var _context10;
result = concat$5(_context10 = " ".concat(this.keyword)).call(_context10, this.optionList[idx], " ");
} // this.cursorTo.ch = this.cursorFrom.ch + result.length;
if (result) {
this.editor.editor.replaceRange(result, cursorFrom, cursorTo);
}
}
}
/**
* 寻找当前选中项的索引
* @returns {number}
*/
}, {
key: "findSelectedItemIndex",
value: function findSelectedItemIndex() {
return findIndex$3(Array.prototype).call(this.$suggesterPanel.childNodes, function (item) {
return item.classList.contains('cherry-suggester-panel__item--selected');
});
}
}, {
key: "enableRelate",
value: function enableRelate() {
return this.searchCache;
}
/**
* codeMirror change事件
* @param {CodeMirror.Editor} codemirror
* @param {CodeMirror.EditorChange} evt
* @returns
*/
}, {
key: "onCodeMirrorChange",
value: function onCodeMirrorChange(codemirror, evt) {
var _this6 = this;
var text = evt.text,
from = evt.from,
to = evt.to,
origin = evt.origin;
var changeValue = text.length === 1 ? text[0] : ''; // 首次输入命中关键词的时候开启联想
if (!this.enableRelate() && this.suggesterConfig[changeValue]) {
this.startRelate(codemirror, changeValue, from);
}
if (this.enableRelate() && (changeValue || origin === '+delete')) {
var _this$suggesterConfig;
this.cursorTo = to;
if (changeValue) {
this.searchKeyCache.push(changeValue);
} else if (origin === '+delete') {
this.searchKeyCache.pop();
if (this.searchKeyCache.length === 0) {
this.stopRelate();
return;
}
} // 展示推荐列表
if (typeof ((_this$suggesterConfig = this.suggesterConfig[this.keyword]) === null || _this$suggesterConfig === void 0 ? void 0 : _this$suggesterConfig.suggestList) === 'function') {
// 请求api 返回结果拼凑
this.suggesterConfig[this.keyword].suggestList(this.searchKeyCache.join(''), function (res) {
// 如果返回了false则强制退出联想
if (res === false) {
_this6.stopRelate();
return;
} // 回显命中的结果
_this6.optionList = !res || !res.length ? [] : res;
_this6.updatePanel(_this6.optionList);
});
}
}
}
/**
* 监听方向键选择 options
* @param {CodeMirror.Editor} codemirror
* @param {KeyboardEvent} evt
*/
}, {
key: "onKeyDown",
value: function onKeyDown(codemirror, evt) {
var _context11,
_this7 = this;
if (!this.$suggesterPanel) {
return false;
}
var keyCode = evt.keyCode; // up down
if (includes$4(_context11 = [38, 40]).call(_context11, keyCode)) {
this.cursorMove = false;
var selectedItem = this.$suggesterPanel.querySelector('.cherry-suggester-panel__item--selected');
var nextElement = null;
if (keyCode === 38 && !selectedItem.previousElementSibling) {
nextElement = this.$suggesterPanel.lastElementChild; // codemirror.focus();
} else if (keyCode === 40 && !selectedItem.nextElementSibling) {
nextElement = this.$suggesterPanel.firstElementChild; // codemirror.focus();
} else {
if (keyCode === 38) {
nextElement = selectedItem.previousElementSibling;
} else if (keyCode === 40) {
nextElement = selectedItem.nextElementSibling;
}
}
selectedItem.classList.remove('cherry-suggester-panel__item--selected');
nextElement.classList.add('cherry-suggester-panel__item--selected');
} else if (keyCode === 13) {
evt.stopPropagation();
this.cursorMove = false;
this.pasteSelectResult(this.findSelectedItemIndex(), evt);
codemirror.focus(); // const cache = JSON.parse(JSON.stringify(this.cursorTo));
// setTimeout(() => {
// codemirror.setCursor(cache);
// }, 100);
setTimeout$3(function () {
_this7.stopRelate();
}, 0);
} else if (keyCode === 27) {
// 按下esc的时候退出联想
evt.stopPropagation();
codemirror.focus();
setTimeout$3(function () {
_this7.stopRelate();
}, 0);
}
}
}]);
return SuggesterPanel;
}();
_defineProperty(SuggesterPanel, "panelWrap", "<div class=\"cherry-suggester-panel\"></div>");
var suggesterPanel = new SuggesterPanel();
function _createSuper$w(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$w(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$w() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Ruby = /*#__PURE__*/function (_SyntaxBase) {
_inherits(Ruby, _SyntaxBase);
var _super = _createSuper$w(Ruby);
function Ruby() {
_classCallCheck(this, Ruby);
return _super.apply(this, arguments);
}
_createClass(Ruby, [{
key: "makeHtml",
value: function makeHtml(str) {
if (!this.test(str)) {
return str;
}
return str.replace(this.RULE.reg, "$1<ruby>$2<rt>$3</rt></ruby>$4");
}
}, {
key: "rule",
value: function rule() {
var ret = {
begin: '(^| )\\{',
end: '\\}( |$)',
content: '([^\n]+?)\\|([^\n]+?)'
};
ret.reg = new RegExp(ret.begin + ret.content + ret.end, 'g');
return ret;
}
}]);
return Ruby;
}(SyntaxBase);
_defineProperty(Ruby, "HOOK_NAME", 'ruby');
function _createSuper$x(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$x(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$x() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 面板语法
* 例:
* :::tip
* 这是一段提示信息
* :::
* :::warning
* 这是一段警告信息
* :::
* :::danger
* 这是一段危险信息
* :::
*/
var Panel = /*#__PURE__*/function (_ParagraphBase) {
_inherits(Panel, _ParagraphBase);
var _super = _createSuper$x(Panel);
function Panel(options) {
var _this;
_classCallCheck(this, Panel);
_this = _super.call(this, {
needCache: true
});
_this.initBrReg(options.globalConfig.classicBr);
return _this;
}
_createClass(Panel, [{
key: "makeHtml",
value: function makeHtml(str, sentenceMakeFunc) {
var _this2 = this;
return str.replace(this.RULE.reg, function (match, preLines, name, content) {
var _context, _context2, _context3, _context4, _context5;
var lineCount = _this2.getLineCount(match, preLines);
var sign = _this2.$engine.md5(match);
var _this2$$getPanelInfo = _this2.$getPanelInfo(name, content, sentenceMakeFunc),
title = _this2$$getPanelInfo.title,
body = _this2$$getPanelInfo.body,
appendStyle = _this2$$getPanelInfo.appendStyle,
className = _this2$$getPanelInfo.className;
var ret = _this2.pushCache(concat$5(_context = concat$5(_context2 = concat$5(_context3 = concat$5(_context4 = concat$5(_context5 = "<div class=\"".concat(className, "\" data-sign=\"")).call(_context5, sign, "\" data-lines=\"")).call(_context4, lineCount, "\" ")).call(_context3, appendStyle, ">")).call(_context2, title)).call(_context, body, "</div>"), sign, lineCount);
return prependLineFeedForParagraph(match, ret);
});
}
}, {
key: "$getClassByType",
value: function $getClassByType(type) {
if (/(left|right|center)/i.test(type)) {
return "cherry-text-align cherry-text-align__".concat(type);
}
return "cherry-panel cherry-panel__".concat(type);
}
}, {
key: "$getPanelInfo",
value: function $getPanelInfo(name, str, sentenceMakeFunc) {
var _context6,
_this3 = this;
var ret = {
type: this.$getTargetType(name),
title: sentenceMakeFunc(this.$getTitle(name)).html,
body: str,
appendStyle: '',
className: ''
};
ret.className = this.$getClassByType(ret.type);
if (/(left|right|center)/i.test(ret.type)) {
ret.appendStyle = "style=\"text-align:".concat(ret.type, ";\"");
}
ret.title = concat$5(_context6 = "<div class=\"cherry-panel--title ".concat(ret.title ? 'cherry-panel--title__not-empty' : '', "\">")).call(_context6, ret.title, "</div>");
var paragraphProcessor = function paragraphProcessor(str) {
var _context7, _context8;
if (trim$3(str).call(str) === '') {
return '';
} // 调用行内语法获得段落的签名和对应html内容
var _sentenceMakeFunc = sentenceMakeFunc(str),
html = _sentenceMakeFunc.html;
var domName = 'p'; // 如果包含html块级标签比如div、blockquote等则当前段落外层用div包裹反之用p包裹
var isContainBlockTest = new RegExp("<(".concat(blockNames, ")[^>]*>"), 'i');
if (isContainBlockTest.test(html)) {
domName = 'div';
}
return concat$5(_context7 = concat$5(_context8 = "<".concat(domName, ">")).call(_context8, _this3.$cleanParagraph(html), "</")).call(_context7, domName, ">");
};
var $body = '';
if (this.isContainsCache(ret.body)) {
$body = this.makeExcludingCached(ret.body, paragraphProcessor);
} else {
$body = paragraphProcessor(ret.body);
}
ret.body = "<div class=\"cherry-panel--body\">".concat($body, "</div>");
return ret;
}
}, {
key: "$getTitle",
value: function $getTitle(name) {
var $name = trim$3(name).call(name);
return /\s/.test($name) ? $name.replace(/[^\s]+\s/, '') : '';
}
}, {
key: "$getTargetType",
value: function $getTargetType(name) {
var $name = /\s/.test(trim$3(name).call(name)) ? trim$3(name).call(name).replace(/\s.*$/, '') : name;
switch (trim$3($name).call($name).toLowerCase()) {
case 'primary':
case 'p':
return 'primary';
case 'info':
case 'i':
return 'info';
case 'warning':
case 'w':
return 'warning';
case 'danger':
case 'd':
return 'danger';
case 'success':
case 's':
return 'success';
case 'right':
case 'r':
return 'right';
case 'center':
case 'c':
return 'center';
case 'left':
case 'l':
return 'left';
default:
return 'primary';
}
}
}, {
key: "rule",
value: function rule() {
return getPanelRule();
}
}]);
return Panel;
}(ParagraphBase);
_defineProperty(Panel, "HOOK_NAME", 'panel');
function _createSuper$y(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$y(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$y() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* +++(-) 点击查看详情
* body
* body
* ++ 标题(默认收起内容)
* 内容
* ++- 标题(默认展开内容)
* 内容2
* +++
*/
var Detail = /*#__PURE__*/function (_ParagraphBase) {
_inherits(Detail, _ParagraphBase);
var _super = _createSuper$y(Detail);
function Detail() {
_classCallCheck(this, Detail);
return _super.call(this, {
needCache: true
});
}
_createClass(Detail, [{
key: "makeHtml",
value: function makeHtml(str, sentenceMakeFunc) {
var _this = this;
return str.replace(this.RULE.reg, function (match, preLines, isOpen, title, content) {
var _context, _context2, _context3;
var lineCount = _this.getLineCount(match, preLines);
var sign = _this.$engine.md5(match);
var _this$$getDetailInfo = _this.$getDetailInfo(isOpen, title, content, sentenceMakeFunc),
type = _this$$getDetailInfo.type,
html = _this$$getDetailInfo.html;
var ret = _this.pushCache(concat$5(_context = concat$5(_context2 = concat$5(_context3 = "<div class=\"cherry-detail cherry-detail__".concat(type, "\" data-sign=\"")).call(_context3, sign, "\" data-lines=\"")).call(_context2, lineCount, "\" >")).call(_context, html, "</div>"), sign, lineCount);
return prependLineFeedForParagraph(match, ret);
});
}
}, {
key: "$getDetailInfo",
value: function $getDetailInfo(isOpen, title, str, sentenceMakeFunc) {
var _this2 = this;
var type = /\n\s*(\+\+|\+\+-)\s*[^\n]+\n/.test(str) ? 'multiple' : 'single';
var arr = str.split(/\n\s*(\+\+[-]{0,1}\s*[^\n]+)\n/);
var defaultOpen = isOpen === '-';
var currentTitle = title;
var html = '';
if (type === 'multiple') {
forEach$3(arr).call(arr, function (item) {
if (/\+\+/.test(item)) {
defaultOpen = /\+\+-/.test(item);
currentTitle = item.replace(/\+\+[-]{0,1}\s*([^\n]+)$/, '$1');
return true;
}
html += _this2.$getDetailHtml(defaultOpen, currentTitle, item, sentenceMakeFunc);
});
} else {
html = this.$getDetailHtml(defaultOpen, currentTitle, str, sentenceMakeFunc);
}
return {
type: type,
html: html
};
}
}, {
key: "$getDetailHtml",
value: function $getDetailHtml(defaultOpen, title, str, sentenceMakeFunc) {
var _this3 = this;
var ret = "<details ".concat(defaultOpen ? 'open' : '', ">");
var paragraphProcessor = function paragraphProcessor(str) {
var _context4, _context5;
if (trim$3(str).call(str) === '') {
return '';
} // 调用行内语法获得段落的签名和对应html内容
var _sentenceMakeFunc = sentenceMakeFunc(str),
html = _sentenceMakeFunc.html;
var domName = 'p'; // 如果包含html块级标签比如div、blockquote等则当前段落外层用div包裹反之用p包裹
var isContainBlockTest = new RegExp("<(".concat(blockNames, ")[^>]*>"), 'i');
if (isContainBlockTest.test(html)) {
domName = 'div';
}
return concat$5(_context4 = concat$5(_context5 = "<".concat(domName, ">")).call(_context5, _this3.$cleanParagraph(html), "</")).call(_context4, domName, ">");
};
ret += "<summary>".concat(sentenceMakeFunc(title).html, "</summary>");
var $body = '';
if (this.isContainsCache(str)) {
$body = this.makeExcludingCached(str, paragraphProcessor);
} else {
$body = paragraphProcessor(str);
}
ret += "<div class=\"cherry-detail-body\">".concat($body, "</div>");
ret += "</details>";
return ret;
}
}, {
key: "rule",
value: function rule() {
return getDetailRule();
}
}]);
return Detail;
}(ParagraphBase);
_defineProperty(Detail, "HOOK_NAME", 'detail');
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* 引擎各语法的配置
* 主要决定支持哪些语法,以及各语法的执行顺序
*/
var hooksConfig = [// 段落级 Hook
// 引擎会按当前排序顺序执行beforeMake、makeHtml方法
// 引擎会按当前排序逆序执行afterMake方法
CodeBlock, InlineCode, MathBlock, InlineMath, HtmlBlock, Footnote, CommentReference, Transfer, Br, Table, Blockquote, Toc, Header, // 处理标题, 传入strict属性严格要求ATX风格标题#后带空格
Hr, List, Detail, Panel, Paragraph, // 普通段落
// 行内Hook
// 引擎会按当前顺序执行makeHtml方法
Emoji, Image$1, Link, AutoLink, Emphasis, BackgroundColor, Color, Size, Sub, Sup, Ruby, Strikethrough, Underline, HighLight, Suggester];
var Engine = /*#__PURE__*/function () {
/**
*
* @param {Partial<import('./Cherry').CherryOptions>} markdownParams 初始化Cherry时传入的选项
* @param {import('./Cherry').default} cherry Cherry实例
*/
function Engine(markdownParams, cherry) {
_classCallCheck(this, Engine);
this.$cherry = cherry; // Deprecated
defineProperty$5(this, '_cherry', {
get: function get() {
Logger.warn('`_engine._cherry` is deprecated. Use `$engine.$cherry` instead.');
return this.$cherry;
}
});
this.initMath(markdownParams);
this.$configInit(markdownParams);
this.hookCenter = new HookCenter(hooksConfig, markdownParams, cherry);
this.hooks = this.hookCenter.getHookList();
this.md5Cache = {};
this.md5StrMap = {};
this.markdownParams = markdownParams;
this.currentStrMd5 = [];
this.htmlWhiteListAppend = markdownParams.engine.global.htmlWhiteList;
}
_createClass(Engine, [{
key: "initMath",
value: function initMath(opts) {
// 无论MathJax还是Katex都可以先进行MathJax配置
var externals = opts.externals,
engine = opts.engine;
var syntax = engine.syntax;
var plugins = syntax.mathBlock.plugins; // 未开启公式
if (!isBrowser() || !syntax.mathBlock.src && !syntax.inlineMath.src) {
return;
} // 已经加载过MathJax
if (externals.MathJax || window.MathJax) {
return;
}
configureMathJax(plugins); // 等待MathJax各种插件加载
var script = document.createElement('script');
script.src = syntax.mathBlock.src ? syntax.mathBlock.src : syntax.inlineMath.src;
script.async = true;
if (script.src) document.head.appendChild(script);
}
}, {
key: "$configInit",
value: function $configInit(params) {
if (params.hooksConfig && $expectTarget(params.hooksConfig.hooksList, Array)) {
for (var key = 0; key < params.hooksConfig.hooksList.length; key++) {
var hook = params.hooksConfig.hooksList[key];
try {
if (hook.getType() === 'sentence') {
$expectInherit(hook, SyntaxBase);
}
if (hook.getType() === 'paragraph') {
$expectInherit(hook, ParagraphBase);
}
$expectInstance(hook);
hooksConfig.push(hook);
} catch (e) {
throw new Error('the hook does not correctly inherit');
}
}
}
}
}, {
key: "$beforeMakeHtml",
value: function $beforeMakeHtml(str) {
var $str = str.replace(/~/g, '~T');
$str = $str.replace(/\$/g, '~D');
$str = $str.replace(/\r\n/g, '\n'); // DOS to Unix
$str = $str.replace(/\r/g, '\n'); // Mac to Unix
// 避免正则性能问题,如/.+\n/.test(' '.repeat(99999)), 回溯次数过多
// 参考文章http://www.alloyteam.com/2019/07/13574/
if ($str[$str.length - 1] !== '\n') {
$str += '\n';
}
$str = this.$fireHookAction($str, 'sentence', 'beforeMakeHtml');
$str = this.$fireHookAction($str, 'paragraph', 'beforeMakeHtml');
return $str;
}
}, {
key: "$afterMakeHtml",
value: function $afterMakeHtml(str) {
var $str = this.$fireHookAction(str, 'paragraph', 'afterMakeHtml'); // str = this._fireHookAction(str, 'sentence', 'afterMakeHtml');
$str = $str.replace(/~D/g, '$');
$str = $str.replace(/~T/g, '~');
$str = $str.replace(/\\<\//g, '\\ </');
$str = $str.replace(new RegExp("\\\\(".concat(PUNCTUATION, ")"), 'g'), function (match, escapeChar) {
if (escapeChar === '&') {
// & 字符需要特殊处理
return match;
}
return escapeHTMLSpecialChar(escapeChar);
}).replace(/\\&(?!(amp|lt|gt|quot|apos);)/, function () {
return '&amp;';
});
$str = $str.replace(/\\ <\//g, '\\</');
$str = $str.replace(/id="safe_(?=.*?")/g, 'id="'); // transform header id to avoid being sanitized
$str = UrlCache.restoreAll($str);
return $str;
}
}, {
key: "$dealSentenceByCache",
value: function $dealSentenceByCache(md) {
var _this = this;
return this.$checkCache(md, function (str) {
return _this.$dealSentence(str);
});
}
}, {
key: "$dealSentence",
value: function $dealSentence(md) {
var _context;
return this.$fireHookAction(md, 'sentence', 'makeHtml', bind$5(_context = this.$dealSentenceByCache).call(_context, this));
}
}, {
key: "$fireHookAction",
value: function $fireHookAction(md, type, action, actionArgs) {
var _this2 = this;
var $md = md;
var method = action === 'afterMakeHtml' ? 'reduceRight' : 'reduce';
if (!this.hooks && !this.hooks[type] && !this.hooks[type][method]) {
return $md;
}
try {
$md = this.hooks[type][method](function (newMd, oneHook) {
if (!oneHook.$engine) {
oneHook.$engine = _this2; // Deprecated
defineProperty$5(oneHook, '_engine', {
get: function get() {
Logger.warn('`this._engine` is deprecated. Use `this.$engine` instead.');
return this.$engine;
}
});
}
if (!oneHook[action]) {
return newMd;
}
return oneHook[action](newMd, actionArgs, _this2.markdownParams);
}, $md);
} catch (e) {
throw new NestedError(e);
}
return $md;
}
}, {
key: "md5",
value: function md5$1(str) {
if (!this.md5StrMap[str]) {
this.md5StrMap[str] = md5(str);
}
return this.md5StrMap[str];
}
}, {
key: "$checkCache",
value: function $checkCache(str, func) {
var sign = this.md5(str);
if (typeof this.md5Cache[sign] === 'undefined') {
this.md5Cache[sign] = func(str);
{
// 生产环境屏蔽
// Logger.log('markdown引擎渲染了', str);
}
}
return {
sign: sign,
html: this.md5Cache[sign]
};
}
}, {
key: "$dealParagraph",
value: function $dealParagraph(md) {
var _context2;
return this.$fireHookAction(md, 'paragraph', 'makeHtml', bind$5(_context2 = this.$dealSentenceByCache).call(_context2, this));
}
}, {
key: "makeHtml",
value: function makeHtml(md) {
var $md = this.$beforeMakeHtml(md);
$md = this.$dealParagraph($md);
$md = this.$afterMakeHtml($md);
return $md;
}
}, {
key: "mounted",
value: function mounted() {
this.$fireHookAction('', 'sentence', 'mounted');
this.$fireHookAction('', 'paragraph', 'mounted'); // UrlCache.clear();
}
}, {
key: "makeMarkdown",
value: function makeMarkdown(html) {
return htmlParser.run(html);
}
}]);
return Engine;
}();
var nativeIsArray = Array.isArray;
var toString$3 = Object.prototype.toString;
var xIsArray = nativeIsArray || isArray$9;
function isArray$9(obj) {
return toString$3.call(obj) === "[object Array]"
}
var version$1 = "2";
var isVnode = isVirtualNode;
function isVirtualNode(x) {
return x && x.type === "VirtualNode" && x.version === version$1
}
var isWidget_1 = isWidget;
function isWidget(w) {
return w && w.type === "Widget"
}
var isThunk_1 = isThunk;
function isThunk(t) {
return t && t.type === "Thunk"
}
var isVhook = isHook;
function isHook(hook) {
return hook &&
(typeof hook.hook === "function" && !hook.hasOwnProperty("hook") ||
typeof hook.unhook === "function" && !hook.hasOwnProperty("unhook"))
}
var vnode = VirtualNode;
var noProperties = {};
var noChildren = [];
function VirtualNode(tagName, properties, children, key, namespace) {
this.tagName = tagName;
this.properties = properties || noProperties;
this.children = children || noChildren;
this.key = key != null ? String(key) : undefined;
this.namespace = (typeof namespace === "string") ? namespace : null;
var count = (children && children.length) || 0;
var descendants = 0;
var hasWidgets = false;
var hasThunks = false;
var descendantHooks = false;
var hooks;
for (var propName in properties) {
if (properties.hasOwnProperty(propName)) {
var property = properties[propName];
if (isVhook(property) && property.unhook) {
if (!hooks) {
hooks = {};
}
hooks[propName] = property;
}
}
}
for (var i = 0; i < count; i++) {
var child = children[i];
if (isVnode(child)) {
descendants += child.count || 0;
if (!hasWidgets && child.hasWidgets) {
hasWidgets = true;
}
if (!hasThunks && child.hasThunks) {
hasThunks = true;
}
if (!descendantHooks && (child.hooks || child.descendantHooks)) {
descendantHooks = true;
}
} else if (!hasWidgets && isWidget_1(child)) {
if (typeof child.destroy === "function") {
hasWidgets = true;
}
} else if (!hasThunks && isThunk_1(child)) {
hasThunks = true;
}
}
this.count = count + descendants;
this.hasWidgets = hasWidgets;
this.hasThunks = hasThunks;
this.hooks = hooks;
this.descendantHooks = descendantHooks;
}
VirtualNode.prototype.version = version$1;
VirtualNode.prototype.type = "VirtualNode";
var vtext = VirtualText;
function VirtualText(text) {
this.text = String(text);
}
VirtualText.prototype.version = version$1;
VirtualText.prototype.type = "VirtualText";
var isVtext = isVirtualText;
function isVirtualText(x) {
return x && x.type === "VirtualText" && x.version === version$1
}
/*!
* Cross-Browser Split 1.1.1
* Copyright 2007-2012 Steven Levithan <stevenlevithan.com>
* Available under the MIT License
* ECMAScript compliant, uniform cross-browser split method
*/
/**
* Splits a string into an array of strings using a regex or string separator. Matches of the
* separator are not included in the result array. However, if `separator` is a regex that contains
* capturing groups, backreferences are spliced into the result each time `separator` is matched.
* Fixes browser bugs compared to the native `String.prototype.split` and can be used reliably
* cross-browser.
* @param {String} str String to split.
* @param {RegExp|String} separator Regex or string to use for separating the string.
* @param {Number} [limit] Maximum number of items to include in the result array.
* @returns {Array} Array of substrings.
* @example
*
* // Basic use
* split('a b c d', ' ');
* // -> ['a', 'b', 'c', 'd']
*
* // With limit
* split('a b c d', ' ', 2);
* // -> ['a', 'b']
*
* // Backreferences in result array
* split('..word1 word2..', /([a-z]+)(\d+)/i);
* // -> ['..', 'word', '1', ' ', 'word', '2', '..']
*/
var browserSplit = (function split(undef) {
var nativeSplit = String.prototype.split,
compliantExecNpcg = /()??/.exec("")[1] === undef,
// NPCG: nonparticipating capturing group
self;
self = function(str, separator, limit) {
// If `separator` is not a regex, use `nativeSplit`
if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
return nativeSplit.call(str, separator, limit);
}
var output = [],
flags = (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : "") + (separator.extended ? "x" : "") + // Proposed for ES6
(separator.sticky ? "y" : ""),
// Firefox 3+
lastLastIndex = 0,
// Make `global` and avoid `lastIndex` issues by working with a copy
separator = new RegExp(separator.source, flags + "g"),
separator2, match, lastIndex, lastLength;
str += ""; // Type-convert
if (!compliantExecNpcg) {
// Doesn't need flags gy, but they don't hurt
separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags);
}
/* Values for `limit`, per the spec:
* If undefined: 4294967295 // Math.pow(2, 32) - 1
* If 0, Infinity, or NaN: 0
* If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;
* If negative number: 4294967296 - Math.floor(Math.abs(limit))
* If other: Type-convert, then use the above rules
*/
limit = limit === undef ? -1 >>> 0 : // Math.pow(2, 32) - 1
limit >>> 0; // ToUint32(limit)
while (match = separator.exec(str)) {
// `separator.lastIndex` is not reliable cross-browser
lastIndex = match.index + match[0].length;
if (lastIndex > lastLastIndex) {
output.push(str.slice(lastLastIndex, match.index));
// Fix browsers whose `exec` methods don't consistently return `undefined` for
// nonparticipating capturing groups
if (!compliantExecNpcg && match.length > 1) {
match[0].replace(separator2, function() {
for (var i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undef) {
match[i] = undef;
}
}
});
}
if (match.length > 1 && match.index < str.length) {
Array.prototype.push.apply(output, match.slice(1));
}
lastLength = match[0].length;
lastLastIndex = lastIndex;
if (output.length >= limit) {
break;
}
}
if (separator.lastIndex === match.index) {
separator.lastIndex++; // Avoid an infinite loop
}
}
if (lastLastIndex === str.length) {
if (lastLength || !separator.test("")) {
output.push("");
}
} else {
output.push(str.slice(lastLastIndex));
}
return output.length > limit ? output.slice(0, limit) : output;
};
return self;
})();
var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/;
var notClassId = /^\.|#/;
var parseTag_1 = parseTag;
function parseTag(tag, props) {
if (!tag) {
return 'DIV';
}
var noId = !(props.hasOwnProperty('id'));
var tagParts = browserSplit(tag, classIdSplit);
var tagName = null;
if (notClassId.test(tagParts[1])) {
tagName = 'DIV';
}
var classes, part, type, i;
for (i = 0; i < tagParts.length; i++) {
part = tagParts[i];
if (!part) {
continue;
}
type = part.charAt(0);
if (!tagName) {
tagName = part;
} else if (type === '.') {
classes = classes || [];
classes.push(part.substring(1, part.length));
} else if (type === '#' && noId) {
props.id = part.substring(1, part.length);
}
}
if (classes) {
if (props.className) {
classes.push(props.className);
}
props.className = classes.join(' ');
}
return props.namespace ? tagName : tagName.toUpperCase();
}
var softSetHook = SoftSetHook;
function SoftSetHook(value) {
if (!(this instanceof SoftSetHook)) {
return new SoftSetHook(value);
}
this.value = value;
}
SoftSetHook.prototype.hook = function (node, propertyName) {
if (node[propertyName] !== this.value) {
node[propertyName] = this.value;
}
};
/*global window, global*/
var root$1 = typeof window !== 'undefined' ?
window : typeof commonjsGlobal !== 'undefined' ?
commonjsGlobal : {};
var individual = Individual;
function Individual(key, value) {
if (key in root$1) {
return root$1[key];
}
root$1[key] = value;
return value;
}
var oneVersion = OneVersion;
function OneVersion(moduleName, version, defaultValue) {
var key = '__INDIVIDUAL_ONE_VERSION_' + moduleName;
var enforceKey = key + '_ENFORCE_SINGLETON';
var versionValue = individual(enforceKey, version);
if (versionValue !== version) {
throw new Error('Can only have one copy of ' +
moduleName + '.\n' +
'You already have version ' + versionValue +
' installed.\n' +
'This means you cannot install version ' + version);
}
return individual(key, defaultValue);
}
var MY_VERSION = '7';
oneVersion('ev-store', MY_VERSION);
var hashKey = '__EV_STORE_KEY@' + MY_VERSION;
var evStore = EvStore;
function EvStore(elem) {
var hash = elem[hashKey];
if (!hash) {
hash = elem[hashKey] = {};
}
return hash;
}
var evHook = EvHook;
function EvHook(value) {
if (!(this instanceof EvHook)) {
return new EvHook(value);
}
this.value = value;
}
EvHook.prototype.hook = function (node, propertyName) {
var es = evStore(node);
var propName = propertyName.substr(3);
es[propName] = this.value;
};
EvHook.prototype.unhook = function(node, propertyName) {
var es = evStore(node);
var propName = propertyName.substr(3);
es[propName] = undefined;
};
var virtualHyperscript = h;
function h(tagName, properties, children) {
var childNodes = [];
var tag, props, key, namespace;
if (!children && isChildren(properties)) {
children = properties;
props = {};
}
props = props || properties || {};
tag = parseTag_1(tagName, props);
// support keys
if (props.hasOwnProperty('key')) {
key = props.key;
props.key = undefined;
}
// support namespace
if (props.hasOwnProperty('namespace')) {
namespace = props.namespace;
props.namespace = undefined;
}
// fix cursor bug
if (tag === 'INPUT' &&
!namespace &&
props.hasOwnProperty('value') &&
props.value !== undefined &&
!isVhook(props.value)
) {
props.value = softSetHook(props.value);
}
transformProperties(props);
if (children !== undefined && children !== null) {
addChild(children, childNodes, tag, props);
}
return new vnode(tag, props, childNodes, key, namespace);
}
function addChild(c, childNodes, tag, props) {
if (typeof c === 'string') {
childNodes.push(new vtext(c));
} else if (typeof c === 'number') {
childNodes.push(new vtext(String(c)));
} else if (isChild(c)) {
childNodes.push(c);
} else if (xIsArray(c)) {
for (var i = 0; i < c.length; i++) {
addChild(c[i], childNodes, tag, props);
}
} else if (c === null || c === undefined) {
return;
} else {
throw UnexpectedVirtualElement({
foreignObject: c,
parentVnode: {
tagName: tag,
properties: props
}
});
}
}
function transformProperties(props) {
for (var propName in props) {
if (props.hasOwnProperty(propName)) {
var value = props[propName];
if (isVhook(value)) {
continue;
}
if (propName.substr(0, 3) === 'ev-') {
// add ev-foo support
props[propName] = evHook(value);
}
}
}
}
function isChild(x) {
return isVnode(x) || isVtext(x) || isWidget_1(x) || isThunk_1(x);
}
function isChildren(x) {
return typeof x === 'string' || xIsArray(x) || isChild(x);
}
function UnexpectedVirtualElement(data) {
var err = new Error();
err.type = 'virtual-hyperscript.unexpected.virtual-element';
err.message = 'Unexpected virtual child passed to h().\n' +
'Expected a VNode / Vthunk / VWidget / string but:\n' +
'got:\n' +
errorString(data.foreignObject) +
'.\n' +
'The parent vnode is:\n' +
errorString(data.parentVnode);
err.foreignObject = data.foreignObject;
err.parentVnode = data.parentVnode;
return err;
}
function errorString(obj) {
try {
return JSON.stringify(obj, null, ' ');
} catch (e) {
return String(obj);
}
}
var h_1 = virtualHyperscript;
VirtualPatch.NONE = 0;
VirtualPatch.VTEXT = 1;
VirtualPatch.VNODE = 2;
VirtualPatch.WIDGET = 3;
VirtualPatch.PROPS = 4;
VirtualPatch.ORDER = 5;
VirtualPatch.INSERT = 6;
VirtualPatch.REMOVE = 7;
VirtualPatch.THUNK = 8;
var vpatch = VirtualPatch;
function VirtualPatch(type, vNode, patch) {
this.type = Number(type);
this.vNode = vNode;
this.patch = patch;
}
VirtualPatch.prototype.version = version$1;
VirtualPatch.prototype.type = "VirtualPatch";
var handleThunk_1 = handleThunk;
function handleThunk(a, b) {
var renderedA = a;
var renderedB = b;
if (isThunk_1(b)) {
renderedB = renderThunk(b, a);
}
if (isThunk_1(a)) {
renderedA = renderThunk(a, null);
}
return {
a: renderedA,
b: renderedB
}
}
function renderThunk(thunk, previous) {
var renderedThunk = thunk.vnode;
if (!renderedThunk) {
renderedThunk = thunk.vnode = thunk.render(previous);
}
if (!(isVnode(renderedThunk) ||
isVtext(renderedThunk) ||
isWidget_1(renderedThunk))) {
throw new Error("thunk did not return a valid node");
}
return renderedThunk
}
var isObject$2 = function isObject(x) {
return typeof x === 'object' && x !== null;
};
var diffProps_1 = diffProps;
function diffProps(a, b) {
var diff;
for (var aKey in a) {
if (!(aKey in b)) {
diff = diff || {};
diff[aKey] = undefined;
}
var aValue = a[aKey];
var bValue = b[aKey];
if (aValue === bValue) {
continue
} else if (isObject$2(aValue) && isObject$2(bValue)) {
if (getPrototype$1(bValue) !== getPrototype$1(aValue)) {
diff = diff || {};
diff[aKey] = bValue;
} else if (isVhook(bValue)) {
diff = diff || {};
diff[aKey] = bValue;
} else {
var objectDiff = diffProps(aValue, bValue);
if (objectDiff) {
diff = diff || {};
diff[aKey] = objectDiff;
}
}
} else {
diff = diff || {};
diff[aKey] = bValue;
}
}
for (var bKey in b) {
if (!(bKey in a)) {
diff = diff || {};
diff[bKey] = b[bKey];
}
}
return diff
}
function getPrototype$1(value) {
if (Object.getPrototypeOf) {
return Object.getPrototypeOf(value)
} else if (value.__proto__) {
return value.__proto__
} else if (value.constructor) {
return value.constructor.prototype
}
}
var diff_1 = diff;
function diff(a, b) {
var patch = { a: a };
walk(a, b, patch, 0);
return patch
}
function walk(a, b, patch, index) {
if (a === b) {
return
}
var apply = patch[index];
var applyClear = false;
if (isThunk_1(a) || isThunk_1(b)) {
thunks(a, b, patch, index);
} else if (b == null) {
// If a is a widget we will add a remove patch for it
// Otherwise any child widgets/hooks must be destroyed.
// This prevents adding two remove patches for a widget.
if (!isWidget_1(a)) {
clearState(a, patch, index);
apply = patch[index];
}
apply = appendPatch(apply, new vpatch(vpatch.REMOVE, a, b));
} else if (isVnode(b)) {
if (isVnode(a)) {
if (a.tagName === b.tagName &&
a.namespace === b.namespace &&
a.key === b.key) {
var propsPatch = diffProps_1(a.properties, b.properties);
if (propsPatch) {
apply = appendPatch(apply,
new vpatch(vpatch.PROPS, a, propsPatch));
}
apply = diffChildren(a, b, patch, apply, index);
} else {
apply = appendPatch(apply, new vpatch(vpatch.VNODE, a, b));
applyClear = true;
}
} else {
apply = appendPatch(apply, new vpatch(vpatch.VNODE, a, b));
applyClear = true;
}
} else if (isVtext(b)) {
if (!isVtext(a)) {
apply = appendPatch(apply, new vpatch(vpatch.VTEXT, a, b));
applyClear = true;
} else if (a.text !== b.text) {
apply = appendPatch(apply, new vpatch(vpatch.VTEXT, a, b));
}
} else if (isWidget_1(b)) {
if (!isWidget_1(a)) {
applyClear = true;
}
apply = appendPatch(apply, new vpatch(vpatch.WIDGET, a, b));
}
if (apply) {
patch[index] = apply;
}
if (applyClear) {
clearState(a, patch, index);
}
}
function diffChildren(a, b, patch, apply, index) {
var aChildren = a.children;
var orderedSet = reorder(aChildren, b.children);
var bChildren = orderedSet.children;
var aLen = aChildren.length;
var bLen = bChildren.length;
var len = aLen > bLen ? aLen : bLen;
for (var i = 0; i < len; i++) {
var leftNode = aChildren[i];
var rightNode = bChildren[i];
index += 1;
if (!leftNode) {
if (rightNode) {
// Excess nodes in b need to be added
apply = appendPatch(apply,
new vpatch(vpatch.INSERT, null, rightNode));
}
} else {
walk(leftNode, rightNode, patch, index);
}
if (isVnode(leftNode) && leftNode.count) {
index += leftNode.count;
}
}
if (orderedSet.moves) {
// Reorder nodes last
apply = appendPatch(apply, new vpatch(
vpatch.ORDER,
a,
orderedSet.moves
));
}
return apply
}
function clearState(vNode, patch, index) {
// TODO: Make this a single walk, not two
unhook(vNode, patch, index);
destroyWidgets(vNode, patch, index);
}
// Patch records for all destroyed widgets must be added because we need
// a DOM node reference for the destroy function
function destroyWidgets(vNode, patch, index) {
if (isWidget_1(vNode)) {
if (typeof vNode.destroy === "function") {
patch[index] = appendPatch(
patch[index],
new vpatch(vpatch.REMOVE, vNode, null)
);
}
} else if (isVnode(vNode) && (vNode.hasWidgets || vNode.hasThunks)) {
var children = vNode.children;
var len = children.length;
for (var i = 0; i < len; i++) {
var child = children[i];
index += 1;
destroyWidgets(child, patch, index);
if (isVnode(child) && child.count) {
index += child.count;
}
}
} else if (isThunk_1(vNode)) {
thunks(vNode, null, patch, index);
}
}
// Create a sub-patch for thunks
function thunks(a, b, patch, index) {
var nodes = handleThunk_1(a, b);
var thunkPatch = diff(nodes.a, nodes.b);
if (hasPatches(thunkPatch)) {
patch[index] = new vpatch(vpatch.THUNK, null, thunkPatch);
}
}
function hasPatches(patch) {
for (var index in patch) {
if (index !== "a") {
return true
}
}
return false
}
// Execute hooks when two nodes are identical
function unhook(vNode, patch, index) {
if (isVnode(vNode)) {
if (vNode.hooks) {
patch[index] = appendPatch(
patch[index],
new vpatch(
vpatch.PROPS,
vNode,
undefinedKeys(vNode.hooks)
)
);
}
if (vNode.descendantHooks || vNode.hasThunks) {
var children = vNode.children;
var len = children.length;
for (var i = 0; i < len; i++) {
var child = children[i];
index += 1;
unhook(child, patch, index);
if (isVnode(child) && child.count) {
index += child.count;
}
}
}
} else if (isThunk_1(vNode)) {
thunks(vNode, null, patch, index);
}
}
function undefinedKeys(obj) {
var result = {};
for (var key in obj) {
result[key] = undefined;
}
return result
}
// List diff, naive left to right reordering
function reorder(aChildren, bChildren) {
// O(M) time, O(M) memory
var bChildIndex = keyIndex(bChildren);
var bKeys = bChildIndex.keys;
var bFree = bChildIndex.free;
if (bFree.length === bChildren.length) {
return {
children: bChildren,
moves: null
}
}
// O(N) time, O(N) memory
var aChildIndex = keyIndex(aChildren);
var aKeys = aChildIndex.keys;
var aFree = aChildIndex.free;
if (aFree.length === aChildren.length) {
return {
children: bChildren,
moves: null
}
}
// O(MAX(N, M)) memory
var newChildren = [];
var freeIndex = 0;
var freeCount = bFree.length;
var deletedItems = 0;
// Iterate through a and match a node in b
// O(N) time,
for (var i = 0 ; i < aChildren.length; i++) {
var aItem = aChildren[i];
var itemIndex;
if (aItem.key) {
if (bKeys.hasOwnProperty(aItem.key)) {
// Match up the old keys
itemIndex = bKeys[aItem.key];
newChildren.push(bChildren[itemIndex]);
} else {
// Remove old keyed items
itemIndex = i - deletedItems++;
newChildren.push(null);
}
} else {
// Match the item in a with the next free item in b
if (freeIndex < freeCount) {
itemIndex = bFree[freeIndex++];
newChildren.push(bChildren[itemIndex]);
} else {
// There are no free items in b to match with
// the free items in a, so the extra free nodes
// are deleted.
itemIndex = i - deletedItems++;
newChildren.push(null);
}
}
}
var lastFreeIndex = freeIndex >= bFree.length ?
bChildren.length :
bFree[freeIndex];
// Iterate through b and append any new keys
// O(M) time
for (var j = 0; j < bChildren.length; j++) {
var newItem = bChildren[j];
if (newItem.key) {
if (!aKeys.hasOwnProperty(newItem.key)) {
// Add any new keyed items
// We are adding new items to the end and then sorting them
// in place. In future we should insert new items in place.
newChildren.push(newItem);
}
} else if (j >= lastFreeIndex) {
// Add any leftover non-keyed items
newChildren.push(newItem);
}
}
var simulate = newChildren.slice();
var simulateIndex = 0;
var removes = [];
var inserts = [];
var simulateItem;
for (var k = 0; k < bChildren.length;) {
var wantedItem = bChildren[k];
simulateItem = simulate[simulateIndex];
// remove items
while (simulateItem === null && simulate.length) {
removes.push(remove(simulate, simulateIndex, null));
simulateItem = simulate[simulateIndex];
}
if (!simulateItem || simulateItem.key !== wantedItem.key) {
// if we need a key in this position...
if (wantedItem.key) {
if (simulateItem && simulateItem.key) {
// if an insert doesn't put this key in place, it needs to move
if (bKeys[simulateItem.key] !== k + 1) {
removes.push(remove(simulate, simulateIndex, simulateItem.key));
simulateItem = simulate[simulateIndex];
// if the remove didn't put the wanted item in place, we need to insert it
if (!simulateItem || simulateItem.key !== wantedItem.key) {
inserts.push({key: wantedItem.key, to: k});
}
// items are matching, so skip ahead
else {
simulateIndex++;
}
}
else {
inserts.push({key: wantedItem.key, to: k});
}
}
else {
inserts.push({key: wantedItem.key, to: k});
}
k++;
}
// a key in simulate has no matching wanted key, remove it
else if (simulateItem && simulateItem.key) {
removes.push(remove(simulate, simulateIndex, simulateItem.key));
}
}
else {
simulateIndex++;
k++;
}
}
// remove all the remaining nodes from simulate
while(simulateIndex < simulate.length) {
simulateItem = simulate[simulateIndex];
removes.push(remove(simulate, simulateIndex, simulateItem && simulateItem.key));
}
// If the only moves we have are deletes then we can just
// let the delete patch remove these items.
if (removes.length === deletedItems && !inserts.length) {
return {
children: newChildren,
moves: null
}
}
return {
children: newChildren,
moves: {
removes: removes,
inserts: inserts
}
}
}
function remove(arr, index, key) {
arr.splice(index, 1);
return {
from: index,
key: key
}
}
function keyIndex(children) {
var keys = {};
var free = [];
var length = children.length;
for (var i = 0; i < length; i++) {
var child = children[i];
if (child.key) {
keys[child.key] = i;
} else {
free.push(i);
}
}
return {
keys: keys, // A hash of key name to index
free: free // An array of unkeyed item indices
}
}
function appendPatch(apply, patch) {
if (apply) {
if (xIsArray(apply)) {
apply.push(patch);
} else {
apply = [apply, patch];
}
return apply
} else {
return patch
}
}
var diff_1$1 = diff_1;
var _nodeResolve_empty = {};
var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
'default': _nodeResolve_empty
});
var minDoc = getCjsExportFromNamespace(_nodeResolve_empty$1);
var topLevel = typeof commonjsGlobal !== 'undefined' ? commonjsGlobal :
typeof window !== 'undefined' ? window : {};
var doccy;
if (typeof document !== 'undefined') {
doccy = document;
} else {
doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
if (!doccy) {
doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
}
}
var document_1 = doccy;
var applyProperties_1 = applyProperties;
function applyProperties(node, props, previous) {
for (var propName in props) {
var propValue = props[propName];
if (propValue === undefined) {
removeProperty(node, propName, propValue, previous);
} else if (isVhook(propValue)) {
removeProperty(node, propName, propValue, previous);
if (propValue.hook) {
propValue.hook(node,
propName,
previous ? previous[propName] : undefined);
}
} else {
if (isObject$2(propValue)) {
patchObject(node, props, previous, propName, propValue);
} else {
node[propName] = propValue;
}
}
}
}
function removeProperty(node, propName, propValue, previous) {
if (previous) {
var previousValue = previous[propName];
if (!isVhook(previousValue)) {
if (propName === "attributes") {
for (var attrName in previousValue) {
node.removeAttribute(attrName);
}
} else if (propName === "style") {
for (var i in previousValue) {
node.style[i] = "";
}
} else if (typeof previousValue === "string") {
node[propName] = "";
} else {
node[propName] = null;
}
} else if (previousValue.unhook) {
previousValue.unhook(node, propName, propValue);
}
}
}
function patchObject(node, props, previous, propName, propValue) {
var previousValue = previous ? previous[propName] : undefined;
// Set attributes
if (propName === "attributes") {
for (var attrName in propValue) {
var attrValue = propValue[attrName];
if (attrValue === undefined) {
node.removeAttribute(attrName);
} else {
node.setAttribute(attrName, attrValue);
}
}
return
}
if(previousValue && isObject$2(previousValue) &&
getPrototype$2(previousValue) !== getPrototype$2(propValue)) {
node[propName] = propValue;
return
}
if (!isObject$2(node[propName])) {
node[propName] = {};
}
var replacer = propName === "style" ? "" : undefined;
for (var k in propValue) {
var value = propValue[k];
node[propName][k] = (value === undefined) ? replacer : value;
}
}
function getPrototype$2(value) {
if (Object.getPrototypeOf) {
return Object.getPrototypeOf(value)
} else if (value.__proto__) {
return value.__proto__
} else if (value.constructor) {
return value.constructor.prototype
}
}
var createElement_1 = createElement$1;
function createElement$1(vnode, opts) {
var doc = opts ? opts.document || document_1 : document_1;
var warn = opts ? opts.warn : null;
vnode = handleThunk_1(vnode).a;
if (isWidget_1(vnode)) {
return vnode.init()
} else if (isVtext(vnode)) {
return doc.createTextNode(vnode.text)
} else if (!isVnode(vnode)) {
if (warn) {
warn("Item is not a valid virtual dom node", vnode);
}
return null
}
var node = (vnode.namespace === null) ?
doc.createElement(vnode.tagName) :
doc.createElementNS(vnode.namespace, vnode.tagName);
var props = vnode.properties;
applyProperties_1(node, props);
var children = vnode.children;
for (var i = 0; i < children.length; i++) {
var childNode = createElement$1(children[i], opts);
if (childNode) {
node.appendChild(childNode);
}
}
return node
}
// Maps a virtual DOM tree onto a real DOM tree in an efficient manner.
// We don't want to read all of the DOM nodes in the tree so we use
// the in-order tree indexing to eliminate recursion down certain branches.
// We only recurse into a DOM node if we know that it contains a child of
// interest.
var noChild = {};
var domIndex_1 = domIndex;
function domIndex(rootNode, tree, indices, nodes) {
if (!indices || indices.length === 0) {
return {}
} else {
indices.sort(ascending);
return recurse(rootNode, tree, indices, nodes, 0)
}
}
function recurse(rootNode, tree, indices, nodes, rootIndex) {
nodes = nodes || {};
if (rootNode) {
if (indexInRange(indices, rootIndex, rootIndex)) {
nodes[rootIndex] = rootNode;
}
var vChildren = tree.children;
if (vChildren) {
var childNodes = rootNode.childNodes;
for (var i = 0; i < tree.children.length; i++) {
rootIndex += 1;
var vChild = vChildren[i] || noChild;
var nextIndex = rootIndex + (vChild.count || 0);
// skip recursion down the tree if there are no nodes down here
if (indexInRange(indices, rootIndex, nextIndex)) {
recurse(childNodes[i], vChild, indices, nodes, rootIndex);
}
rootIndex = nextIndex;
}
}
}
return nodes
}
// Binary search for an index in the interval [left, right]
function indexInRange(indices, left, right) {
if (indices.length === 0) {
return false
}
var minIndex = 0;
var maxIndex = indices.length - 1;
var currentIndex;
var currentItem;
while (minIndex <= maxIndex) {
currentIndex = ((maxIndex + minIndex) / 2) >> 0;
currentItem = indices[currentIndex];
if (minIndex === maxIndex) {
return currentItem >= left && currentItem <= right
} else if (currentItem < left) {
minIndex = currentIndex + 1;
} else if (currentItem > right) {
maxIndex = currentIndex - 1;
} else {
return true
}
}
return false;
}
function ascending(a, b) {
return a > b ? 1 : -1
}
var updateWidget_1 = updateWidget;
function updateWidget(a, b) {
if (isWidget_1(a) && isWidget_1(b)) {
if ("name" in a && "name" in b) {
return a.id === b.id
} else {
return a.init === b.init
}
}
return false
}
var patchOp = applyPatch;
function applyPatch(vpatch$1, domNode, renderOptions) {
var type = vpatch$1.type;
var vNode = vpatch$1.vNode;
var patch = vpatch$1.patch;
switch (type) {
case vpatch.REMOVE:
return removeNode(domNode, vNode)
case vpatch.INSERT:
return insertNode(domNode, patch, renderOptions)
case vpatch.VTEXT:
return stringPatch(domNode, vNode, patch, renderOptions)
case vpatch.WIDGET:
return widgetPatch(domNode, vNode, patch, renderOptions)
case vpatch.VNODE:
return vNodePatch(domNode, vNode, patch, renderOptions)
case vpatch.ORDER:
reorderChildren(domNode, patch);
return domNode
case vpatch.PROPS:
applyProperties_1(domNode, patch, vNode.properties);
return domNode
case vpatch.THUNK:
return replaceRoot(domNode,
renderOptions.patch(domNode, patch, renderOptions))
default:
return domNode
}
}
function removeNode(domNode, vNode) {
var parentNode = domNode.parentNode;
if (parentNode) {
parentNode.removeChild(domNode);
}
destroyWidget(domNode, vNode);
return null
}
function insertNode(parentNode, vNode, renderOptions) {
var newNode = renderOptions.render(vNode, renderOptions);
if (parentNode) {
parentNode.appendChild(newNode);
}
return parentNode
}
function stringPatch(domNode, leftVNode, vText, renderOptions) {
var newNode;
if (domNode.nodeType === 3) {
domNode.replaceData(0, domNode.length, vText.text);
newNode = domNode;
} else {
var parentNode = domNode.parentNode;
newNode = renderOptions.render(vText, renderOptions);
if (parentNode && newNode !== domNode) {
parentNode.replaceChild(newNode, domNode);
}
}
return newNode
}
function widgetPatch(domNode, leftVNode, widget, renderOptions) {
var updating = updateWidget_1(leftVNode, widget);
var newNode;
if (updating) {
newNode = widget.update(leftVNode, domNode) || domNode;
} else {
newNode = renderOptions.render(widget, renderOptions);
}
var parentNode = domNode.parentNode;
if (parentNode && newNode !== domNode) {
parentNode.replaceChild(newNode, domNode);
}
if (!updating) {
destroyWidget(domNode, leftVNode);
}
return newNode
}
function vNodePatch(domNode, leftVNode, vNode, renderOptions) {
var parentNode = domNode.parentNode;
var newNode = renderOptions.render(vNode, renderOptions);
if (parentNode && newNode !== domNode) {
parentNode.replaceChild(newNode, domNode);
}
return newNode
}
function destroyWidget(domNode, w) {
if (typeof w.destroy === "function" && isWidget_1(w)) {
w.destroy(domNode);
}
}
function reorderChildren(domNode, moves) {
var childNodes = domNode.childNodes;
var keyMap = {};
var node;
var remove;
var insert;
for (var i = 0; i < moves.removes.length; i++) {
remove = moves.removes[i];
node = childNodes[remove.from];
if (remove.key) {
keyMap[remove.key] = node;
}
domNode.removeChild(node);
}
var length = childNodes.length;
for (var j = 0; j < moves.inserts.length; j++) {
insert = moves.inserts[j];
node = keyMap[insert.key];
// this is the weirdest bug i've ever seen in webkit
domNode.insertBefore(node, insert.to >= length++ ? null : childNodes[insert.to]);
}
}
function replaceRoot(oldRoot, newRoot) {
if (oldRoot && newRoot && oldRoot !== newRoot && oldRoot.parentNode) {
oldRoot.parentNode.replaceChild(newRoot, oldRoot);
}
return newRoot;
}
var patch_1 = patch;
function patch(rootNode, patches, renderOptions) {
renderOptions = renderOptions || {};
renderOptions.patch = renderOptions.patch && renderOptions.patch !== patch
? renderOptions.patch
: patchRecursive;
renderOptions.render = renderOptions.render || createElement_1;
return renderOptions.patch(rootNode, patches, renderOptions)
}
function patchRecursive(rootNode, patches, renderOptions) {
var indices = patchIndices(patches);
if (indices.length === 0) {
return rootNode
}
var index = domIndex_1(rootNode, patches.a, indices);
var ownerDocument = rootNode.ownerDocument;
if (!renderOptions.document && ownerDocument !== document_1) {
renderOptions.document = ownerDocument;
}
for (var i = 0; i < indices.length; i++) {
var nodeIndex = indices[i];
rootNode = applyPatch$1(rootNode,
index[nodeIndex],
patches[nodeIndex],
renderOptions);
}
return rootNode
}
function applyPatch$1(rootNode, domNode, patchList, renderOptions) {
if (!domNode) {
return rootNode
}
var newNode;
if (xIsArray(patchList)) {
for (var i = 0; i < patchList.length; i++) {
newNode = patchOp(patchList[i], domNode, renderOptions);
if (domNode === rootNode) {
rootNode = newNode;
}
}
} else {
newNode = patchOp(patchList, domNode, renderOptions);
if (domNode === rootNode) {
rootNode = newNode;
}
}
return rootNode
}
function patchIndices(patches) {
var indices = [];
for (var key in patches) {
if (key !== "a") {
indices.push(Number(key));
}
}
return indices
}
var patch_1$1 = patch_1;
var MyersDiff = /*#__PURE__*/function () {
function MyersDiff(newObj, oldObj, getElement) {
_classCallCheck(this, MyersDiff);
this.options = {
newObj: newObj,
// 用于diff的新列表/字符串
oldObj: oldObj,
// 用于diff的旧列表/字符串
getElement: getElement // 获取用于比较的元素的函数
};
}
/**
* 执行diff操作
*/
_createClass(MyersDiff, [{
key: "doDiff",
value: function doDiff() {
var snakes = this.findSnakes(this.options.newObj, this.options.oldObj);
var result = this.assembleResult(snakes, this.options.newObj, this.options.oldObj);
return result;
}
/**
* 用于判断列表/字符串元素是否相等的判据函数
*/
}, {
key: "getElement",
value: function getElement(obj, index) {
if (typeof this.options.getElement === 'function') {
// 支持传入自定义的比较函数
return this.options.getElement(obj, index);
}
return obj[index];
}
/**
* 寻找从起点到终点的折线
*/
}, {
key: "findSnakes",
value: function findSnakes(newObj, oldObj) {
var newLen = newObj.length || 0; // 新diff对象的长度
var oldLen = oldObj.length || 0; // 旧diff对象的长度
var lengthSum = newLen + oldLen; // 长度之和
var v = {
1: 0
}; // "每个节点的深度值"的缓存对象
var allSnakes = {
0: {
1: 0
}
}; // "每个节点对应的折线"的缓存对象
// d是起点到对应节点的编辑距离,简而言之,若把新增一个节点或删除一个节点都视作一次"操作",那么通过d次操作可以从起点到达对应节点
for (var d = 0; d <= lengthSum; d++) {
var tmp = {};
for (var k = -d; k <= d; k += 2) {
// 转换坐标系,k可以视为对应节点(x,y)的x坐标值减y坐标值
var down = k === -d || k !== d && v[k - 1] < v[k + 1];
var kPrev = down ? k + 1 : k - 1;
var xStart = v[kPrev]; // let yStart = xStart - kPrev;
var xMid = down ? xStart : xStart + 1;
var yMid = xMid - k;
var xEnd = xMid;
var yEnd = yMid;
while (xEnd < oldLen && yEnd < newLen && this.getElement(oldObj, xEnd) === this.getElement(newObj, yEnd)) {
xEnd += 1;
yEnd += 1;
}
v[k] = xEnd;
tmp[k] = xEnd;
if (xEnd >= oldLen && yEnd >= newLen) {
// 成功抵达终点
allSnakes[d] = tmp;
return this.$backtraceSnakes(allSnakes, newLen, oldLen, d);
}
}
allSnakes[d] = tmp;
}
return [];
}
/**
* 回溯,找出关键路径对应的折线
*/
}, {
key: "$backtraceSnakes",
value: function $backtraceSnakes(allSnakes, newLen, oldLen, d) {
var keySnakes = [];
var p = {
x: oldLen,
y: newLen
}; // 模拟节点,从终点开始
// 执行回溯,倒回起点,找到并记录关键路径
for (var i = d; i > 0; i--) {
var v = allSnakes[i];
var vPrev = allSnakes[i - 1];
var k = p.x - p.y;
var xEnd = v[k]; // let yEnd = xEnd - k;
var down = k === -i || k !== i && vPrev[k + 1] > vPrev[k - 1];
var kPrev = down ? k + 1 : k - 1;
var xStart = vPrev[kPrev];
var yStart = xStart - kPrev;
var xMid = down ? xStart : xStart + 1; // let yMid = xMid - k;
keySnakes.unshift({
xStart: xStart,
xMid: xMid,
xEnd: xEnd
});
p.x = xStart;
p.y = yStart;
}
return keySnakes;
}
/**
* 组装出返回值
*/
}, {
key: "assembleResult",
value: function assembleResult(snakes, newObj, oldObj) {
var _this = this,
_context;
var grayColor = 'color: gray';
var redColor = 'color: red';
var greenColor = 'color: green';
var blueColor = 'color: blue';
var consoleStr = '';
var args = [];
var yOffset = 0;
var result = []; // 返回的操作集
var change = {}; // 本次操作
var lastChange = {}; // 缓存上一次操作
var firstDeleteChange = {}; // 连续删除时用来缓存最初的删除
forEach$3(snakes).call(snakes, function (snake, index) {
var currentPos = snake.xStart;
if (index === 0 && snake.xStart !== 0) {
for (var j = 0; j < snake.xStart; j++) {
consoleStr += "%c".concat(_this.getElement(oldObj, j), ", ");
args.push(grayColor);
yOffset += 1;
}
}
if (snake.xMid - snake.xStart === 1) {
// 删除
change = {
type: 'delete',
oldIndex: snake.xStart,
newIndex: 0
};
if (lastChange.type === 'delete' && lastChange.oldIndex === change.oldIndex - 1) {
// 检测到连续删除,缓存最初的删除
firstDeleteChange = firstDeleteChange ? lastChange : firstDeleteChange;
}
result.push(change);
lastChange = change;
consoleStr += "%c".concat(_this.getElement(oldObj, snake.xStart), ", ");
args.push(redColor);
currentPos = snake.xMid;
} else {
// 添加
change = {
type: 'insert',
oldIndex: snake.xStart,
newIndex: yOffset
};
if (lastChange.type === 'delete' && lastChange.oldIndex === change.oldIndex - 1) {
// 和上一条删除合并为"更新"
result.pop();
firstDeleteChange = firstDeleteChange ? lastChange : firstDeleteChange;
change = {
type: 'update',
oldIndex: firstDeleteChange.oldIndex,
// 合并时,更新目标定位连续删除块中的首个元素
newIndex: yOffset
};
args.push(blueColor);
} else {
args.push(greenColor);
}
firstDeleteChange = {};
result.push(change);
lastChange = change;
consoleStr += "%c".concat(_this.getElement(newObj, yOffset), ", ");
yOffset += 1;
} // 不变
for (var i = 0; i < snake.xEnd - currentPos; i++) {
consoleStr += "%c".concat(_this.getElement(oldObj, currentPos + i), ", ");
args.push(grayColor);
yOffset += 1;
}
});
Logger.log.apply(Logger, concat$5(_context = [consoleStr]).call(_context, args));
return result;
}
}]);
return MyersDiff;
}();
var ITERATOR$7 = wellKnownSymbol('iterator');
var nativeUrl = !fails(function () {
// eslint-disable-next-line unicorn/relative-url-style -- required for testing
var url = new URL('b?a=1&b=2&c=3', 'http://a');
var searchParams = url.searchParams;
var result = '';
url.pathname = 'c%20d';
searchParams.forEach(function (value, key) {
searchParams['delete']('b');
result += key + value;
});
return (isPure && !url.toJSON)
|| !searchParams.sort
|| url.href !== 'http://a/c%20d?a=1&c=3'
|| searchParams.get('c') !== '3'
|| String(new URLSearchParams('?a=1')) !== 'a=1'
|| !searchParams[ITERATOR$7]
// throws in Edge
|| new URL('https://a@b').username !== 'a'
|| new URLSearchParams(new URLSearchParams('a=b')).get('a') !== 'b'
// not punycoded in Edge
|| new URL('http://тест').host !== 'xn--e1aybc'
// not escaped in Chrome 62-
|| new URL('http://a#б').hash !== '#%D0%B1'
// fails in Chrome 66-
|| result !== 'a1c3'
// throws in Safari
|| new URL('http://x', undefined).host !== 'x';
});
var defineBuiltInAccessor = function (target, name, descriptor) {
return objectDefineProperty.f(target, name, descriptor);
};
// based on https://github.com/bestiejs/punycode.js/blob/master/punycode.js
var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
var base = 36;
var tMin = 1;
var tMax = 26;
var skew = 38;
var damp = 700;
var initialBias = 72;
var initialN = 128; // 0x80
var delimiter = '-'; // '\x2D'
var regexNonASCII = /[^\0-\u007E]/; // non-ASCII chars
var regexSeparators = /[.\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
var OVERFLOW_ERROR = 'Overflow: input needs wider integers to process';
var baseMinusTMin = base - tMin;
var RangeError$3 = global_1.RangeError;
var exec$3 = functionUncurryThis(regexSeparators.exec);
var floor$1 = Math.floor;
var fromCharCode$1 = String.fromCharCode;
var charCodeAt$2 = functionUncurryThis(''.charCodeAt);
var join$2 = functionUncurryThis([].join);
var push$6 = functionUncurryThis([].push);
var replace$2 = functionUncurryThis(''.replace);
var split$1 = functionUncurryThis(''.split);
var toLowerCase = functionUncurryThis(''.toLowerCase);
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
*/
var ucs2decode = function (string) {
var output = [];
var counter = 0;
var length = string.length;
while (counter < length) {
var value = charCodeAt$2(string, counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// It's a high surrogate, and there is a next character.
var extra = charCodeAt$2(string, counter++);
if ((extra & 0xFC00) == 0xDC00) { // Low surrogate.
push$6(output, ((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// It's an unmatched surrogate; only append this code unit, in case the
// next code unit is the high surrogate of a surrogate pair.
push$6(output, value);
counter--;
}
} else {
push$6(output, value);
}
}
return output;
};
/**
* Converts a digit/integer into a basic code point.
*/
var digitToBasic = function (digit) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26);
};
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* https://tools.ietf.org/html/rfc3492#section-3.4
*/
var adapt = function (delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor$1(delta / damp) : delta >> 1;
delta += floor$1(delta / numPoints);
while (delta > baseMinusTMin * tMax >> 1) {
delta = floor$1(delta / baseMinusTMin);
k += base;
}
return floor$1(k + (baseMinusTMin + 1) * delta / (delta + skew));
};
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
*/
var encode = function (input) {
var output = [];
// Convert the input in UCS-2 to an array of Unicode code points.
input = ucs2decode(input);
// Cache the length.
var inputLength = input.length;
// Initialize the state.
var n = initialN;
var delta = 0;
var bias = initialBias;
var i, currentValue;
// Handle the basic code points.
for (i = 0; i < input.length; i++) {
currentValue = input[i];
if (currentValue < 0x80) {
push$6(output, fromCharCode$1(currentValue));
}
}
var basicLength = output.length; // number of basic code points.
var handledCPCount = basicLength; // number of code points that have been handled;
// Finish the basic string with a delimiter unless it's empty.
if (basicLength) {
push$6(output, delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next larger one:
var m = maxInt;
for (i = 0; i < input.length; i++) {
currentValue = input[i];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, but guard against overflow.
var handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor$1((maxInt - delta) / handledCPCountPlusOne)) {
throw RangeError$3(OVERFLOW_ERROR);
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (i = 0; i < input.length; i++) {
currentValue = input[i];
if (currentValue < n && ++delta > maxInt) {
throw RangeError$3(OVERFLOW_ERROR);
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer.
var q = delta;
var k = base;
while (true) {
var t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) break;
var qMinusT = q - t;
var baseMinusT = base - t;
push$6(output, fromCharCode$1(digitToBasic(t + qMinusT % baseMinusT)));
q = floor$1(qMinusT / baseMinusT);
k += base;
}
push$6(output, fromCharCode$1(digitToBasic(q)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
handledCPCount++;
}
}
delta++;
n++;
}
return join$2(output, '');
};
var stringPunycodeToAscii = function (input) {
var encoded = [];
var labels = split$1(replace$2(toLowerCase(input), regexSeparators, '\u002E'), '.');
var i, label;
for (i = 0; i < labels.length; i++) {
label = labels[i];
push$6(encoded, exec$3(regexNonASCII, label) ? 'xn--' + encode(label) : label);
}
return join$2(encoded, '.');
};
var floor$2 = Math.floor;
var mergeSort = function (array, comparefn) {
var length = array.length;
var middle = floor$2(length / 2);
return length < 8 ? insertionSort(array, comparefn) : merge(
array,
mergeSort(arraySliceSimple(array, 0, middle), comparefn),
mergeSort(arraySliceSimple(array, middle), comparefn),
comparefn
);
};
var insertionSort = function (array, comparefn) {
var length = array.length;
var i = 1;
var element, j;
while (i < length) {
j = i;
element = array[i];
while (j && comparefn(array[j - 1], element) > 0) {
array[j] = array[--j];
}
if (j !== i++) array[j] = element;
} return array;
};
var merge = function (array, left, right, comparefn) {
var llength = left.length;
var rlength = right.length;
var lindex = 0;
var rindex = 0;
while (lindex < llength || rindex < rlength) {
array[lindex + rindex] = (lindex < llength && rindex < rlength)
? comparefn(left[lindex], right[rindex]) <= 0 ? left[lindex++] : right[rindex++]
: lindex < llength ? left[lindex++] : right[rindex++];
} return array;
};
var arraySort = mergeSort;
// TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env`
var ITERATOR$8 = wellKnownSymbol('iterator');
var URL_SEARCH_PARAMS = 'URLSearchParams';
var URL_SEARCH_PARAMS_ITERATOR = URL_SEARCH_PARAMS + 'Iterator';
var setInternalState$5 = internalState.set;
var getInternalParamsState = internalState.getterFor(URL_SEARCH_PARAMS);
var getInternalIteratorState = internalState.getterFor(URL_SEARCH_PARAMS_ITERATOR);
// eslint-disable-next-line es-x/no-object-getownpropertydescriptor -- safe
var getOwnPropertyDescriptor$8 = Object.getOwnPropertyDescriptor;
// Avoid NodeJS experimental warning
var safeGetBuiltIn = function (name) {
if (!descriptors) return global_1[name];
var descriptor = getOwnPropertyDescriptor$8(global_1, name);
return descriptor && descriptor.value;
};
var nativeFetch = safeGetBuiltIn('fetch');
var NativeRequest = safeGetBuiltIn('Request');
var Headers = safeGetBuiltIn('Headers');
var RequestPrototype = NativeRequest && NativeRequest.prototype;
var HeadersPrototype = Headers && Headers.prototype;
var RegExp$1 = global_1.RegExp;
var TypeError$m = global_1.TypeError;
var decodeURIComponent$1 = global_1.decodeURIComponent;
var encodeURIComponent$1 = global_1.encodeURIComponent;
var charAt$4 = functionUncurryThis(''.charAt);
var join$3 = functionUncurryThis([].join);
var push$7 = functionUncurryThis([].push);
var replace$3 = functionUncurryThis(''.replace);
var shift = functionUncurryThis([].shift);
var splice$5 = functionUncurryThis([].splice);
var split$2 = functionUncurryThis(''.split);
var stringSlice$3 = functionUncurryThis(''.slice);
var plus = /\+/g;
var sequences = Array(4);
var percentSequence = function (bytes) {
return sequences[bytes - 1] || (sequences[bytes - 1] = RegExp$1('((?:%[\\da-f]{2}){' + bytes + '})', 'gi'));
};
var percentDecode = function (sequence) {
try {
return decodeURIComponent$1(sequence);
} catch (error) {
return sequence;
}
};
var deserialize = function (it) {
var result = replace$3(it, plus, ' ');
var bytes = 4;
try {
return decodeURIComponent$1(result);
} catch (error) {
while (bytes) {
result = replace$3(result, percentSequence(bytes--), percentDecode);
}
return result;
}
};
var find$4 = /[!'()~]|%20/g;
var replacements = {
'!': '%21',
"'": '%27',
'(': '%28',
')': '%29',
'~': '%7E',
'%20': '+'
};
var replacer = function (match) {
return replacements[match];
};
var serialize = function (it) {
return replace$3(encodeURIComponent$1(it), find$4, replacer);
};
var URLSearchParamsIterator = createIteratorConstructor(function Iterator(params, kind) {
setInternalState$5(this, {
type: URL_SEARCH_PARAMS_ITERATOR,
iterator: getIterator(getInternalParamsState(params).entries),
kind: kind
});
}, 'Iterator', function next() {
var state = getInternalIteratorState(this);
var kind = state.kind;
var step = state.iterator.next();
var entry = step.value;
if (!step.done) {
step.value = kind === 'keys' ? entry.key : kind === 'values' ? entry.value : [entry.key, entry.value];
} return step;
}, true);
var URLSearchParamsState = function (init) {
this.entries = [];
this.url = null;
if (init !== undefined) {
if (isObject(init)) this.parseObject(init);
else this.parseQuery(typeof init == 'string' ? charAt$4(init, 0) === '?' ? stringSlice$3(init, 1) : init : toString_1(init));
}
};
URLSearchParamsState.prototype = {
type: URL_SEARCH_PARAMS,
bindURL: function (url) {
this.url = url;
this.update();
},
parseObject: function (object) {
var iteratorMethod = getIteratorMethod(object);
var iterator, next, step, entryIterator, entryNext, first, second;
if (iteratorMethod) {
iterator = getIterator(object, iteratorMethod);
next = iterator.next;
while (!(step = functionCall(next, iterator)).done) {
entryIterator = getIterator(anObject(step.value));
entryNext = entryIterator.next;
if (
(first = functionCall(entryNext, entryIterator)).done ||
(second = functionCall(entryNext, entryIterator)).done ||
!functionCall(entryNext, entryIterator).done
) throw TypeError$m('Expected sequence with length 2');
push$7(this.entries, { key: toString_1(first.value), value: toString_1(second.value) });
}
} else for (var key in object) if (hasOwnProperty_1(object, key)) {
push$7(this.entries, { key: key, value: toString_1(object[key]) });
}
},
parseQuery: function (query) {
if (query) {
var attributes = split$2(query, '&');
var index = 0;
var attribute, entry;
while (index < attributes.length) {
attribute = attributes[index++];
if (attribute.length) {
entry = split$2(attribute, '=');
push$7(this.entries, {
key: deserialize(shift(entry)),
value: deserialize(join$3(entry, '='))
});
}
}
}
},
serialize: function () {
var entries = this.entries;
var result = [];
var index = 0;
var entry;
while (index < entries.length) {
entry = entries[index++];
push$7(result, serialize(entry.key) + '=' + serialize(entry.value));
} return join$3(result, '&');
},
update: function () {
this.entries.length = 0;
this.parseQuery(this.url.query);
},
updateURL: function () {
if (this.url) this.url.update();
}
};
// `URLSearchParams` constructor
// https://url.spec.whatwg.org/#interface-urlsearchparams
var URLSearchParamsConstructor = function URLSearchParams(/* init */) {
anInstance(this, URLSearchParamsPrototype);
var init = arguments.length > 0 ? arguments[0] : undefined;
setInternalState$5(this, new URLSearchParamsState(init));
};
var URLSearchParamsPrototype = URLSearchParamsConstructor.prototype;
defineBuiltIns(URLSearchParamsPrototype, {
// `URLSearchParams.prototype.append` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-append
append: function append(name, value) {
validateArgumentsLength(arguments.length, 2);
var state = getInternalParamsState(this);
push$7(state.entries, { key: toString_1(name), value: toString_1(value) });
state.updateURL();
},
// `URLSearchParams.prototype.delete` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-delete
'delete': function (name) {
validateArgumentsLength(arguments.length, 1);
var state = getInternalParamsState(this);
var entries = state.entries;
var key = toString_1(name);
var index = 0;
while (index < entries.length) {
if (entries[index].key === key) splice$5(entries, index, 1);
else index++;
}
state.updateURL();
},
// `URLSearchParams.prototype.get` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-get
get: function get(name) {
validateArgumentsLength(arguments.length, 1);
var entries = getInternalParamsState(this).entries;
var key = toString_1(name);
var index = 0;
for (; index < entries.length; index++) {
if (entries[index].key === key) return entries[index].value;
}
return null;
},
// `URLSearchParams.prototype.getAll` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-getall
getAll: function getAll(name) {
validateArgumentsLength(arguments.length, 1);
var entries = getInternalParamsState(this).entries;
var key = toString_1(name);
var result = [];
var index = 0;
for (; index < entries.length; index++) {
if (entries[index].key === key) push$7(result, entries[index].value);
}
return result;
},
// `URLSearchParams.prototype.has` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-has
has: function has(name) {
validateArgumentsLength(arguments.length, 1);
var entries = getInternalParamsState(this).entries;
var key = toString_1(name);
var index = 0;
while (index < entries.length) {
if (entries[index++].key === key) return true;
}
return false;
},
// `URLSearchParams.prototype.set` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-set
set: function set(name, value) {
validateArgumentsLength(arguments.length, 1);
var state = getInternalParamsState(this);
var entries = state.entries;
var found = false;
var key = toString_1(name);
var val = toString_1(value);
var index = 0;
var entry;
for (; index < entries.length; index++) {
entry = entries[index];
if (entry.key === key) {
if (found) splice$5(entries, index--, 1);
else {
found = true;
entry.value = val;
}
}
}
if (!found) push$7(entries, { key: key, value: val });
state.updateURL();
},
// `URLSearchParams.prototype.sort` method
// https://url.spec.whatwg.org/#dom-urlsearchparams-sort
sort: function sort() {
var state = getInternalParamsState(this);
arraySort(state.entries, function (a, b) {
return a.key > b.key ? 1 : -1;
});
state.updateURL();
},
// `URLSearchParams.prototype.forEach` method
forEach: function forEach(callback /* , thisArg */) {
var entries = getInternalParamsState(this).entries;
var boundFunction = functionBindContext(callback, arguments.length > 1 ? arguments[1] : undefined);
var index = 0;
var entry;
while (index < entries.length) {
entry = entries[index++];
boundFunction(entry.value, entry.key, this);
}
},
// `URLSearchParams.prototype.keys` method
keys: function keys() {
return new URLSearchParamsIterator(this, 'keys');
},
// `URLSearchParams.prototype.values` method
values: function values() {
return new URLSearchParamsIterator(this, 'values');
},
// `URLSearchParams.prototype.entries` method
entries: function entries() {
return new URLSearchParamsIterator(this, 'entries');
}
}, { enumerable: true });
// `URLSearchParams.prototype[@@iterator]` method
defineBuiltIn(URLSearchParamsPrototype, ITERATOR$8, URLSearchParamsPrototype.entries, { name: 'entries' });
// `URLSearchParams.prototype.toString` method
// https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior
defineBuiltIn(URLSearchParamsPrototype, 'toString', function toString() {
return getInternalParamsState(this).serialize();
}, { enumerable: true });
setToStringTag(URLSearchParamsConstructor, URL_SEARCH_PARAMS);
_export({ global: true, constructor: true, forced: !nativeUrl }, {
URLSearchParams: URLSearchParamsConstructor
});
// Wrap `fetch` and `Request` for correct work with polyfilled `URLSearchParams`
if (!nativeUrl && isCallable(Headers)) {
var headersHas = functionUncurryThis(HeadersPrototype.has);
var headersSet = functionUncurryThis(HeadersPrototype.set);
var wrapRequestOptions = function (init) {
if (isObject(init)) {
var body = init.body;
var headers;
if (classof(body) === URL_SEARCH_PARAMS) {
headers = init.headers ? new Headers(init.headers) : new Headers();
if (!headersHas(headers, 'content-type')) {
headersSet(headers, 'content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
}
return objectCreate(init, {
body: createPropertyDescriptor(0, toString_1(body)),
headers: createPropertyDescriptor(0, headers)
});
}
} return init;
};
if (isCallable(nativeFetch)) {
_export({ global: true, enumerable: true, dontCallGetSet: true, forced: true }, {
fetch: function fetch(input /* , init */) {
return nativeFetch(input, arguments.length > 1 ? wrapRequestOptions(arguments[1]) : {});
}
});
}
if (isCallable(NativeRequest)) {
var RequestConstructor = function Request(input /* , init */) {
anInstance(this, RequestPrototype);
return new NativeRequest(input, arguments.length > 1 ? wrapRequestOptions(arguments[1]) : {});
};
RequestPrototype.constructor = RequestConstructor;
RequestConstructor.prototype = RequestPrototype;
_export({ global: true, constructor: true, dontCallGetSet: true, forced: true }, {
Request: RequestConstructor
});
}
}
var web_urlSearchParams_constructor = {
URLSearchParams: URLSearchParamsConstructor,
getState: getInternalParamsState
};
// TODO: in core-js@4, move /modules/ dependencies to public entries for better optimization by tools like `preset-env`
var codeAt = stringMultibyte.codeAt;
var setInternalState$6 = internalState.set;
var getInternalURLState = internalState.getterFor('URL');
var URLSearchParams$1 = web_urlSearchParams_constructor.URLSearchParams;
var getInternalSearchParamsState = web_urlSearchParams_constructor.getState;
var NativeURL = global_1.URL;
var TypeError$n = global_1.TypeError;
var parseInt$1 = global_1.parseInt;
var floor$3 = Math.floor;
var pow = Math.pow;
var charAt$5 = functionUncurryThis(''.charAt);
var exec$4 = functionUncurryThis(/./.exec);
var join$4 = functionUncurryThis([].join);
var numberToString$1 = functionUncurryThis(1.0.toString);
var pop = functionUncurryThis([].pop);
var push$8 = functionUncurryThis([].push);
var replace$4 = functionUncurryThis(''.replace);
var shift$1 = functionUncurryThis([].shift);
var split$3 = functionUncurryThis(''.split);
var stringSlice$4 = functionUncurryThis(''.slice);
var toLowerCase$1 = functionUncurryThis(''.toLowerCase);
var unshift = functionUncurryThis([].unshift);
var INVALID_AUTHORITY = 'Invalid authority';
var INVALID_SCHEME = 'Invalid scheme';
var INVALID_HOST = 'Invalid host';
var INVALID_PORT = 'Invalid port';
var ALPHA = /[a-z]/i;
// eslint-disable-next-line regexp/no-obscure-range -- safe
var ALPHANUMERIC = /[\d+-.a-z]/i;
var DIGIT = /\d/;
var HEX_START = /^0x/i;
var OCT = /^[0-7]+$/;
var DEC = /^\d+$/;
var HEX = /^[\da-f]+$/i;
/* eslint-disable regexp/no-control-character -- safe */
var FORBIDDEN_HOST_CODE_POINT = /[\0\t\n\r #%/:<>?@[\\\]^|]/;
var FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT = /[\0\t\n\r #/:<>?@[\\\]^|]/;
var LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE = /^[\u0000-\u0020]+|[\u0000-\u0020]+$/g;
var TAB_AND_NEW_LINE = /[\t\n\r]/g;
/* eslint-enable regexp/no-control-character -- safe */
var EOF;
// https://url.spec.whatwg.org/#ipv4-number-parser
var parseIPv4 = function (input) {
var parts = split$3(input, '.');
var partsLength, numbers, index, part, radix, number, ipv4;
if (parts.length && parts[parts.length - 1] == '') {
parts.length--;
}
partsLength = parts.length;
if (partsLength > 4) return input;
numbers = [];
for (index = 0; index < partsLength; index++) {
part = parts[index];
if (part == '') return input;
radix = 10;
if (part.length > 1 && charAt$5(part, 0) == '0') {
radix = exec$4(HEX_START, part) ? 16 : 8;
part = stringSlice$4(part, radix == 8 ? 1 : 2);
}
if (part === '') {
number = 0;
} else {
if (!exec$4(radix == 10 ? DEC : radix == 8 ? OCT : HEX, part)) return input;
number = parseInt$1(part, radix);
}
push$8(numbers, number);
}
for (index = 0; index < partsLength; index++) {
number = numbers[index];
if (index == partsLength - 1) {
if (number >= pow(256, 5 - partsLength)) return null;
} else if (number > 255) return null;
}
ipv4 = pop(numbers);
for (index = 0; index < numbers.length; index++) {
ipv4 += numbers[index] * pow(256, 3 - index);
}
return ipv4;
};
// https://url.spec.whatwg.org/#concept-ipv6-parser
// eslint-disable-next-line max-statements -- TODO
var parseIPv6 = function (input) {
var address = [0, 0, 0, 0, 0, 0, 0, 0];
var pieceIndex = 0;
var compress = null;
var pointer = 0;
var value, length, numbersSeen, ipv4Piece, number, swaps, swap;
var chr = function () {
return charAt$5(input, pointer);
};
if (chr() == ':') {
if (charAt$5(input, 1) != ':') return;
pointer += 2;
pieceIndex++;
compress = pieceIndex;
}
while (chr()) {
if (pieceIndex == 8) return;
if (chr() == ':') {
if (compress !== null) return;
pointer++;
pieceIndex++;
compress = pieceIndex;
continue;
}
value = length = 0;
while (length < 4 && exec$4(HEX, chr())) {
value = value * 16 + parseInt$1(chr(), 16);
pointer++;
length++;
}
if (chr() == '.') {
if (length == 0) return;
pointer -= length;
if (pieceIndex > 6) return;
numbersSeen = 0;
while (chr()) {
ipv4Piece = null;
if (numbersSeen > 0) {
if (chr() == '.' && numbersSeen < 4) pointer++;
else return;
}
if (!exec$4(DIGIT, chr())) return;
while (exec$4(DIGIT, chr())) {
number = parseInt$1(chr(), 10);
if (ipv4Piece === null) ipv4Piece = number;
else if (ipv4Piece == 0) return;
else ipv4Piece = ipv4Piece * 10 + number;
if (ipv4Piece > 255) return;
pointer++;
}
address[pieceIndex] = address[pieceIndex] * 256 + ipv4Piece;
numbersSeen++;
if (numbersSeen == 2 || numbersSeen == 4) pieceIndex++;
}
if (numbersSeen != 4) return;
break;
} else if (chr() == ':') {
pointer++;
if (!chr()) return;
} else if (chr()) return;
address[pieceIndex++] = value;
}
if (compress !== null) {
swaps = pieceIndex - compress;
pieceIndex = 7;
while (pieceIndex != 0 && swaps > 0) {
swap = address[pieceIndex];
address[pieceIndex--] = address[compress + swaps - 1];
address[compress + --swaps] = swap;
}
} else if (pieceIndex != 8) return;
return address;
};
var findLongestZeroSequence = function (ipv6) {
var maxIndex = null;
var maxLength = 1;
var currStart = null;
var currLength = 0;
var index = 0;
for (; index < 8; index++) {
if (ipv6[index] !== 0) {
if (currLength > maxLength) {
maxIndex = currStart;
maxLength = currLength;
}
currStart = null;
currLength = 0;
} else {
if (currStart === null) currStart = index;
++currLength;
}
}
if (currLength > maxLength) {
maxIndex = currStart;
maxLength = currLength;
}
return maxIndex;
};
// https://url.spec.whatwg.org/#host-serializing
var serializeHost = function (host) {
var result, index, compress, ignore0;
// ipv4
if (typeof host == 'number') {
result = [];
for (index = 0; index < 4; index++) {
unshift(result, host % 256);
host = floor$3(host / 256);
} return join$4(result, '.');
// ipv6
} else if (typeof host == 'object') {
result = '';
compress = findLongestZeroSequence(host);
for (index = 0; index < 8; index++) {
if (ignore0 && host[index] === 0) continue;
if (ignore0) ignore0 = false;
if (compress === index) {
result += index ? ':' : '::';
ignore0 = true;
} else {
result += numberToString$1(host[index], 16);
if (index < 7) result += ':';
}
}
return '[' + result + ']';
} return host;
};
var C0ControlPercentEncodeSet = {};
var fragmentPercentEncodeSet = objectAssign({}, C0ControlPercentEncodeSet, {
' ': 1, '"': 1, '<': 1, '>': 1, '`': 1
});
var pathPercentEncodeSet = objectAssign({}, fragmentPercentEncodeSet, {
'#': 1, '?': 1, '{': 1, '}': 1
});
var userinfoPercentEncodeSet = objectAssign({}, pathPercentEncodeSet, {
'/': 1, ':': 1, ';': 1, '=': 1, '@': 1, '[': 1, '\\': 1, ']': 1, '^': 1, '|': 1
});
var percentEncode = function (chr, set) {
var code = codeAt(chr, 0);
return code > 0x20 && code < 0x7F && !hasOwnProperty_1(set, chr) ? chr : encodeURIComponent(chr);
};
// https://url.spec.whatwg.org/#special-scheme
var specialSchemes = {
ftp: 21,
file: null,
http: 80,
https: 443,
ws: 80,
wss: 443
};
// https://url.spec.whatwg.org/#windows-drive-letter
var isWindowsDriveLetter = function (string, normalized) {
var second;
return string.length == 2 && exec$4(ALPHA, charAt$5(string, 0))
&& ((second = charAt$5(string, 1)) == ':' || (!normalized && second == '|'));
};
// https://url.spec.whatwg.org/#start-with-a-windows-drive-letter
var startsWithWindowsDriveLetter = function (string) {
var third;
return string.length > 1 && isWindowsDriveLetter(stringSlice$4(string, 0, 2)) && (
string.length == 2 ||
((third = charAt$5(string, 2)) === '/' || third === '\\' || third === '?' || third === '#')
);
};
// https://url.spec.whatwg.org/#single-dot-path-segment
var isSingleDot = function (segment) {
return segment === '.' || toLowerCase$1(segment) === '%2e';
};
// https://url.spec.whatwg.org/#double-dot-path-segment
var isDoubleDot = function (segment) {
segment = toLowerCase$1(segment);
return segment === '..' || segment === '%2e.' || segment === '.%2e' || segment === '%2e%2e';
};
// States:
var SCHEME_START = {};
var SCHEME = {};
var NO_SCHEME = {};
var SPECIAL_RELATIVE_OR_AUTHORITY = {};
var PATH_OR_AUTHORITY = {};
var RELATIVE = {};
var RELATIVE_SLASH = {};
var SPECIAL_AUTHORITY_SLASHES = {};
var SPECIAL_AUTHORITY_IGNORE_SLASHES = {};
var AUTHORITY = {};
var HOST = {};
var HOSTNAME = {};
var PORT = {};
var FILE = {};
var FILE_SLASH = {};
var FILE_HOST = {};
var PATH_START = {};
var PATH = {};
var CANNOT_BE_A_BASE_URL_PATH = {};
var QUERY = {};
var FRAGMENT = {};
var URLState = function (url, isBase, base) {
var urlString = toString_1(url);
var baseState, failure, searchParams;
if (isBase) {
failure = this.parse(urlString);
if (failure) throw TypeError$n(failure);
this.searchParams = null;
} else {
if (base !== undefined) baseState = new URLState(base, true);
failure = this.parse(urlString, null, baseState);
if (failure) throw TypeError$n(failure);
searchParams = getInternalSearchParamsState(new URLSearchParams$1());
searchParams.bindURL(this);
this.searchParams = searchParams;
}
};
URLState.prototype = {
type: 'URL',
// https://url.spec.whatwg.org/#url-parsing
// eslint-disable-next-line max-statements -- TODO
parse: function (input, stateOverride, base) {
var url = this;
var state = stateOverride || SCHEME_START;
var pointer = 0;
var buffer = '';
var seenAt = false;
var seenBracket = false;
var seenPasswordToken = false;
var codePoints, chr, bufferCodePoints, failure;
input = toString_1(input);
if (!stateOverride) {
url.scheme = '';
url.username = '';
url.password = '';
url.host = null;
url.port = null;
url.path = [];
url.query = null;
url.fragment = null;
url.cannotBeABaseURL = false;
input = replace$4(input, LEADING_AND_TRAILING_C0_CONTROL_OR_SPACE, '');
}
input = replace$4(input, TAB_AND_NEW_LINE, '');
codePoints = arrayFrom(input);
while (pointer <= codePoints.length) {
chr = codePoints[pointer];
switch (state) {
case SCHEME_START:
if (chr && exec$4(ALPHA, chr)) {
buffer += toLowerCase$1(chr);
state = SCHEME;
} else if (!stateOverride) {
state = NO_SCHEME;
continue;
} else return INVALID_SCHEME;
break;
case SCHEME:
if (chr && (exec$4(ALPHANUMERIC, chr) || chr == '+' || chr == '-' || chr == '.')) {
buffer += toLowerCase$1(chr);
} else if (chr == ':') {
if (stateOverride && (
(url.isSpecial() != hasOwnProperty_1(specialSchemes, buffer)) ||
(buffer == 'file' && (url.includesCredentials() || url.port !== null)) ||
(url.scheme == 'file' && !url.host)
)) return;
url.scheme = buffer;
if (stateOverride) {
if (url.isSpecial() && specialSchemes[url.scheme] == url.port) url.port = null;
return;
}
buffer = '';
if (url.scheme == 'file') {
state = FILE;
} else if (url.isSpecial() && base && base.scheme == url.scheme) {
state = SPECIAL_RELATIVE_OR_AUTHORITY;
} else if (url.isSpecial()) {
state = SPECIAL_AUTHORITY_SLASHES;
} else if (codePoints[pointer + 1] == '/') {
state = PATH_OR_AUTHORITY;
pointer++;
} else {
url.cannotBeABaseURL = true;
push$8(url.path, '');
state = CANNOT_BE_A_BASE_URL_PATH;
}
} else if (!stateOverride) {
buffer = '';
state = NO_SCHEME;
pointer = 0;
continue;
} else return INVALID_SCHEME;
break;
case NO_SCHEME:
if (!base || (base.cannotBeABaseURL && chr != '#')) return INVALID_SCHEME;
if (base.cannotBeABaseURL && chr == '#') {
url.scheme = base.scheme;
url.path = arraySliceSimple(base.path);
url.query = base.query;
url.fragment = '';
url.cannotBeABaseURL = true;
state = FRAGMENT;
break;
}
state = base.scheme == 'file' ? FILE : RELATIVE;
continue;
case SPECIAL_RELATIVE_OR_AUTHORITY:
if (chr == '/' && codePoints[pointer + 1] == '/') {
state = SPECIAL_AUTHORITY_IGNORE_SLASHES;
pointer++;
} else {
state = RELATIVE;
continue;
} break;
case PATH_OR_AUTHORITY:
if (chr == '/') {
state = AUTHORITY;
break;
} else {
state = PATH;
continue;
}
case RELATIVE:
url.scheme = base.scheme;
if (chr == EOF) {
url.username = base.username;
url.password = base.password;
url.host = base.host;
url.port = base.port;
url.path = arraySliceSimple(base.path);
url.query = base.query;
} else if (chr == '/' || (chr == '\\' && url.isSpecial())) {
state = RELATIVE_SLASH;
} else if (chr == '?') {
url.username = base.username;
url.password = base.password;
url.host = base.host;
url.port = base.port;
url.path = arraySliceSimple(base.path);
url.query = '';
state = QUERY;
} else if (chr == '#') {
url.username = base.username;
url.password = base.password;
url.host = base.host;
url.port = base.port;
url.path = arraySliceSimple(base.path);
url.query = base.query;
url.fragment = '';
state = FRAGMENT;
} else {
url.username = base.username;
url.password = base.password;
url.host = base.host;
url.port = base.port;
url.path = arraySliceSimple(base.path);
url.path.length--;
state = PATH;
continue;
} break;
case RELATIVE_SLASH:
if (url.isSpecial() && (chr == '/' || chr == '\\')) {
state = SPECIAL_AUTHORITY_IGNORE_SLASHES;
} else if (chr == '/') {
state = AUTHORITY;
} else {
url.username = base.username;
url.password = base.password;
url.host = base.host;
url.port = base.port;
state = PATH;
continue;
} break;
case SPECIAL_AUTHORITY_SLASHES:
state = SPECIAL_AUTHORITY_IGNORE_SLASHES;
if (chr != '/' || charAt$5(buffer, pointer + 1) != '/') continue;
pointer++;
break;
case SPECIAL_AUTHORITY_IGNORE_SLASHES:
if (chr != '/' && chr != '\\') {
state = AUTHORITY;
continue;
} break;
case AUTHORITY:
if (chr == '@') {
if (seenAt) buffer = '%40' + buffer;
seenAt = true;
bufferCodePoints = arrayFrom(buffer);
for (var i = 0; i < bufferCodePoints.length; i++) {
var codePoint = bufferCodePoints[i];
if (codePoint == ':' && !seenPasswordToken) {
seenPasswordToken = true;
continue;
}
var encodedCodePoints = percentEncode(codePoint, userinfoPercentEncodeSet);
if (seenPasswordToken) url.password += encodedCodePoints;
else url.username += encodedCodePoints;
}
buffer = '';
} else if (
chr == EOF || chr == '/' || chr == '?' || chr == '#' ||
(chr == '\\' && url.isSpecial())
) {
if (seenAt && buffer == '') return INVALID_AUTHORITY;
pointer -= arrayFrom(buffer).length + 1;
buffer = '';
state = HOST;
} else buffer += chr;
break;
case HOST:
case HOSTNAME:
if (stateOverride && url.scheme == 'file') {
state = FILE_HOST;
continue;
} else if (chr == ':' && !seenBracket) {
if (buffer == '') return INVALID_HOST;
failure = url.parseHost(buffer);
if (failure) return failure;
buffer = '';
state = PORT;
if (stateOverride == HOSTNAME) return;
} else if (
chr == EOF || chr == '/' || chr == '?' || chr == '#' ||
(chr == '\\' && url.isSpecial())
) {
if (url.isSpecial() && buffer == '') return INVALID_HOST;
if (stateOverride && buffer == '' && (url.includesCredentials() || url.port !== null)) return;
failure = url.parseHost(buffer);
if (failure) return failure;
buffer = '';
state = PATH_START;
if (stateOverride) return;
continue;
} else {
if (chr == '[') seenBracket = true;
else if (chr == ']') seenBracket = false;
buffer += chr;
} break;
case PORT:
if (exec$4(DIGIT, chr)) {
buffer += chr;
} else if (
chr == EOF || chr == '/' || chr == '?' || chr == '#' ||
(chr == '\\' && url.isSpecial()) ||
stateOverride
) {
if (buffer != '') {
var port = parseInt$1(buffer, 10);
if (port > 0xFFFF) return INVALID_PORT;
url.port = (url.isSpecial() && port === specialSchemes[url.scheme]) ? null : port;
buffer = '';
}
if (stateOverride) return;
state = PATH_START;
continue;
} else return INVALID_PORT;
break;
case FILE:
url.scheme = 'file';
if (chr == '/' || chr == '\\') state = FILE_SLASH;
else if (base && base.scheme == 'file') {
if (chr == EOF) {
url.host = base.host;
url.path = arraySliceSimple(base.path);
url.query = base.query;
} else if (chr == '?') {
url.host = base.host;
url.path = arraySliceSimple(base.path);
url.query = '';
state = QUERY;
} else if (chr == '#') {
url.host = base.host;
url.path = arraySliceSimple(base.path);
url.query = base.query;
url.fragment = '';
state = FRAGMENT;
} else {
if (!startsWithWindowsDriveLetter(join$4(arraySliceSimple(codePoints, pointer), ''))) {
url.host = base.host;
url.path = arraySliceSimple(base.path);
url.shortenPath();
}
state = PATH;
continue;
}
} else {
state = PATH;
continue;
} break;
case FILE_SLASH:
if (chr == '/' || chr == '\\') {
state = FILE_HOST;
break;
}
if (base && base.scheme == 'file' && !startsWithWindowsDriveLetter(join$4(arraySliceSimple(codePoints, pointer), ''))) {
if (isWindowsDriveLetter(base.path[0], true)) push$8(url.path, base.path[0]);
else url.host = base.host;
}
state = PATH;
continue;
case FILE_HOST:
if (chr == EOF || chr == '/' || chr == '\\' || chr == '?' || chr == '#') {
if (!stateOverride && isWindowsDriveLetter(buffer)) {
state = PATH;
} else if (buffer == '') {
url.host = '';
if (stateOverride) return;
state = PATH_START;
} else {
failure = url.parseHost(buffer);
if (failure) return failure;
if (url.host == 'localhost') url.host = '';
if (stateOverride) return;
buffer = '';
state = PATH_START;
} continue;
} else buffer += chr;
break;
case PATH_START:
if (url.isSpecial()) {
state = PATH;
if (chr != '/' && chr != '\\') continue;
} else if (!stateOverride && chr == '?') {
url.query = '';
state = QUERY;
} else if (!stateOverride && chr == '#') {
url.fragment = '';
state = FRAGMENT;
} else if (chr != EOF) {
state = PATH;
if (chr != '/') continue;
} break;
case PATH:
if (
chr == EOF || chr == '/' ||
(chr == '\\' && url.isSpecial()) ||
(!stateOverride && (chr == '?' || chr == '#'))
) {
if (isDoubleDot(buffer)) {
url.shortenPath();
if (chr != '/' && !(chr == '\\' && url.isSpecial())) {
push$8(url.path, '');
}
} else if (isSingleDot(buffer)) {
if (chr != '/' && !(chr == '\\' && url.isSpecial())) {
push$8(url.path, '');
}
} else {
if (url.scheme == 'file' && !url.path.length && isWindowsDriveLetter(buffer)) {
if (url.host) url.host = '';
buffer = charAt$5(buffer, 0) + ':'; // normalize windows drive letter
}
push$8(url.path, buffer);
}
buffer = '';
if (url.scheme == 'file' && (chr == EOF || chr == '?' || chr == '#')) {
while (url.path.length > 1 && url.path[0] === '') {
shift$1(url.path);
}
}
if (chr == '?') {
url.query = '';
state = QUERY;
} else if (chr == '#') {
url.fragment = '';
state = FRAGMENT;
}
} else {
buffer += percentEncode(chr, pathPercentEncodeSet);
} break;
case CANNOT_BE_A_BASE_URL_PATH:
if (chr == '?') {
url.query = '';
state = QUERY;
} else if (chr == '#') {
url.fragment = '';
state = FRAGMENT;
} else if (chr != EOF) {
url.path[0] += percentEncode(chr, C0ControlPercentEncodeSet);
} break;
case QUERY:
if (!stateOverride && chr == '#') {
url.fragment = '';
state = FRAGMENT;
} else if (chr != EOF) {
if (chr == "'" && url.isSpecial()) url.query += '%27';
else if (chr == '#') url.query += '%23';
else url.query += percentEncode(chr, C0ControlPercentEncodeSet);
} break;
case FRAGMENT:
if (chr != EOF) url.fragment += percentEncode(chr, fragmentPercentEncodeSet);
break;
}
pointer++;
}
},
// https://url.spec.whatwg.org/#host-parsing
parseHost: function (input) {
var result, codePoints, index;
if (charAt$5(input, 0) == '[') {
if (charAt$5(input, input.length - 1) != ']') return INVALID_HOST;
result = parseIPv6(stringSlice$4(input, 1, -1));
if (!result) return INVALID_HOST;
this.host = result;
// opaque host
} else if (!this.isSpecial()) {
if (exec$4(FORBIDDEN_HOST_CODE_POINT_EXCLUDING_PERCENT, input)) return INVALID_HOST;
result = '';
codePoints = arrayFrom(input);
for (index = 0; index < codePoints.length; index++) {
result += percentEncode(codePoints[index], C0ControlPercentEncodeSet);
}
this.host = result;
} else {
input = stringPunycodeToAscii(input);
if (exec$4(FORBIDDEN_HOST_CODE_POINT, input)) return INVALID_HOST;
result = parseIPv4(input);
if (result === null) return INVALID_HOST;
this.host = result;
}
},
// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
cannotHaveUsernamePasswordPort: function () {
return !this.host || this.cannotBeABaseURL || this.scheme == 'file';
},
// https://url.spec.whatwg.org/#include-credentials
includesCredentials: function () {
return this.username != '' || this.password != '';
},
// https://url.spec.whatwg.org/#is-special
isSpecial: function () {
return hasOwnProperty_1(specialSchemes, this.scheme);
},
// https://url.spec.whatwg.org/#shorten-a-urls-path
shortenPath: function () {
var path = this.path;
var pathSize = path.length;
if (pathSize && (this.scheme != 'file' || pathSize != 1 || !isWindowsDriveLetter(path[0], true))) {
path.length--;
}
},
// https://url.spec.whatwg.org/#concept-url-serializer
serialize: function () {
var url = this;
var scheme = url.scheme;
var username = url.username;
var password = url.password;
var host = url.host;
var port = url.port;
var path = url.path;
var query = url.query;
var fragment = url.fragment;
var output = scheme + ':';
if (host !== null) {
output += '//';
if (url.includesCredentials()) {
output += username + (password ? ':' + password : '') + '@';
}
output += serializeHost(host);
if (port !== null) output += ':' + port;
} else if (scheme == 'file') output += '//';
output += url.cannotBeABaseURL ? path[0] : path.length ? '/' + join$4(path, '/') : '';
if (query !== null) output += '?' + query;
if (fragment !== null) output += '#' + fragment;
return output;
},
// https://url.spec.whatwg.org/#dom-url-href
setHref: function (href) {
var failure = this.parse(href);
if (failure) throw TypeError$n(failure);
this.searchParams.update();
},
// https://url.spec.whatwg.org/#dom-url-origin
getOrigin: function () {
var scheme = this.scheme;
var port = this.port;
if (scheme == 'blob') try {
return new URLConstructor(scheme.path[0]).origin;
} catch (error) {
return 'null';
}
if (scheme == 'file' || !this.isSpecial()) return 'null';
return scheme + '://' + serializeHost(this.host) + (port !== null ? ':' + port : '');
},
// https://url.spec.whatwg.org/#dom-url-protocol
getProtocol: function () {
return this.scheme + ':';
},
setProtocol: function (protocol) {
this.parse(toString_1(protocol) + ':', SCHEME_START);
},
// https://url.spec.whatwg.org/#dom-url-username
getUsername: function () {
return this.username;
},
setUsername: function (username) {
var codePoints = arrayFrom(toString_1(username));
if (this.cannotHaveUsernamePasswordPort()) return;
this.username = '';
for (var i = 0; i < codePoints.length; i++) {
this.username += percentEncode(codePoints[i], userinfoPercentEncodeSet);
}
},
// https://url.spec.whatwg.org/#dom-url-password
getPassword: function () {
return this.password;
},
setPassword: function (password) {
var codePoints = arrayFrom(toString_1(password));
if (this.cannotHaveUsernamePasswordPort()) return;
this.password = '';
for (var i = 0; i < codePoints.length; i++) {
this.password += percentEncode(codePoints[i], userinfoPercentEncodeSet);
}
},
// https://url.spec.whatwg.org/#dom-url-host
getHost: function () {
var host = this.host;
var port = this.port;
return host === null ? ''
: port === null ? serializeHost(host)
: serializeHost(host) + ':' + port;
},
setHost: function (host) {
if (this.cannotBeABaseURL) return;
this.parse(host, HOST);
},
// https://url.spec.whatwg.org/#dom-url-hostname
getHostname: function () {
var host = this.host;
return host === null ? '' : serializeHost(host);
},
setHostname: function (hostname) {
if (this.cannotBeABaseURL) return;
this.parse(hostname, HOSTNAME);
},
// https://url.spec.whatwg.org/#dom-url-port
getPort: function () {
var port = this.port;
return port === null ? '' : toString_1(port);
},
setPort: function (port) {
if (this.cannotHaveUsernamePasswordPort()) return;
port = toString_1(port);
if (port == '') this.port = null;
else this.parse(port, PORT);
},
// https://url.spec.whatwg.org/#dom-url-pathname
getPathname: function () {
var path = this.path;
return this.cannotBeABaseURL ? path[0] : path.length ? '/' + join$4(path, '/') : '';
},
setPathname: function (pathname) {
if (this.cannotBeABaseURL) return;
this.path = [];
this.parse(pathname, PATH_START);
},
// https://url.spec.whatwg.org/#dom-url-search
getSearch: function () {
var query = this.query;
return query ? '?' + query : '';
},
setSearch: function (search) {
search = toString_1(search);
if (search == '') {
this.query = null;
} else {
if ('?' == charAt$5(search, 0)) search = stringSlice$4(search, 1);
this.query = '';
this.parse(search, QUERY);
}
this.searchParams.update();
},
// https://url.spec.whatwg.org/#dom-url-searchparams
getSearchParams: function () {
return this.searchParams.facade;
},
// https://url.spec.whatwg.org/#dom-url-hash
getHash: function () {
var fragment = this.fragment;
return fragment ? '#' + fragment : '';
},
setHash: function (hash) {
hash = toString_1(hash);
if (hash == '') {
this.fragment = null;
return;
}
if ('#' == charAt$5(hash, 0)) hash = stringSlice$4(hash, 1);
this.fragment = '';
this.parse(hash, FRAGMENT);
},
update: function () {
this.query = this.searchParams.serialize() || null;
}
};
// `URL` constructor
// https://url.spec.whatwg.org/#url-class
var URLConstructor = function URL(url /* , base */) {
var that = anInstance(this, URLPrototype);
var base = validateArgumentsLength(arguments.length, 1) > 1 ? arguments[1] : undefined;
var state = setInternalState$6(that, new URLState(url, false, base));
if (!descriptors) {
that.href = state.serialize();
that.origin = state.getOrigin();
that.protocol = state.getProtocol();
that.username = state.getUsername();
that.password = state.getPassword();
that.host = state.getHost();
that.hostname = state.getHostname();
that.port = state.getPort();
that.pathname = state.getPathname();
that.search = state.getSearch();
that.searchParams = state.getSearchParams();
that.hash = state.getHash();
}
};
var URLPrototype = URLConstructor.prototype;
var accessorDescriptor = function (getter, setter) {
return {
get: function () {
return getInternalURLState(this)[getter]();
},
set: setter && function (value) {
return getInternalURLState(this)[setter](value);
},
configurable: true,
enumerable: true
};
};
if (descriptors) {
// `URL.prototype.href` accessors pair
// https://url.spec.whatwg.org/#dom-url-href
defineBuiltInAccessor(URLPrototype, 'href', accessorDescriptor('serialize', 'setHref'));
// `URL.prototype.origin` getter
// https://url.spec.whatwg.org/#dom-url-origin
defineBuiltInAccessor(URLPrototype, 'origin', accessorDescriptor('getOrigin'));
// `URL.prototype.protocol` accessors pair
// https://url.spec.whatwg.org/#dom-url-protocol
defineBuiltInAccessor(URLPrototype, 'protocol', accessorDescriptor('getProtocol', 'setProtocol'));
// `URL.prototype.username` accessors pair
// https://url.spec.whatwg.org/#dom-url-username
defineBuiltInAccessor(URLPrototype, 'username', accessorDescriptor('getUsername', 'setUsername'));
// `URL.prototype.password` accessors pair
// https://url.spec.whatwg.org/#dom-url-password
defineBuiltInAccessor(URLPrototype, 'password', accessorDescriptor('getPassword', 'setPassword'));
// `URL.prototype.host` accessors pair
// https://url.spec.whatwg.org/#dom-url-host
defineBuiltInAccessor(URLPrototype, 'host', accessorDescriptor('getHost', 'setHost'));
// `URL.prototype.hostname` accessors pair
// https://url.spec.whatwg.org/#dom-url-hostname
defineBuiltInAccessor(URLPrototype, 'hostname', accessorDescriptor('getHostname', 'setHostname'));
// `URL.prototype.port` accessors pair
// https://url.spec.whatwg.org/#dom-url-port
defineBuiltInAccessor(URLPrototype, 'port', accessorDescriptor('getPort', 'setPort'));
// `URL.prototype.pathname` accessors pair
// https://url.spec.whatwg.org/#dom-url-pathname
defineBuiltInAccessor(URLPrototype, 'pathname', accessorDescriptor('getPathname', 'setPathname'));
// `URL.prototype.search` accessors pair
// https://url.spec.whatwg.org/#dom-url-search
defineBuiltInAccessor(URLPrototype, 'search', accessorDescriptor('getSearch', 'setSearch'));
// `URL.prototype.searchParams` getter
// https://url.spec.whatwg.org/#dom-url-searchparams
defineBuiltInAccessor(URLPrototype, 'searchParams', accessorDescriptor('getSearchParams'));
// `URL.prototype.hash` accessors pair
// https://url.spec.whatwg.org/#dom-url-hash
defineBuiltInAccessor(URLPrototype, 'hash', accessorDescriptor('getHash', 'setHash'));
}
// `URL.prototype.toJSON` method
// https://url.spec.whatwg.org/#dom-url-tojson
defineBuiltIn(URLPrototype, 'toJSON', function toJSON() {
return getInternalURLState(this).serialize();
}, { enumerable: true });
// `URL.prototype.toString` method
// https://url.spec.whatwg.org/#URL-stringification-behavior
defineBuiltIn(URLPrototype, 'toString', function toString() {
return getInternalURLState(this).serialize();
}, { enumerable: true });
if (NativeURL) {
var nativeCreateObjectURL = NativeURL.createObjectURL;
var nativeRevokeObjectURL = NativeURL.revokeObjectURL;
// `URL.createObjectURL` method
// https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
if (nativeCreateObjectURL) defineBuiltIn(URLConstructor, 'createObjectURL', functionBindContext(nativeCreateObjectURL, NativeURL));
// `URL.revokeObjectURL` method
// https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL
if (nativeRevokeObjectURL) defineBuiltIn(URLConstructor, 'revokeObjectURL', functionBindContext(nativeRevokeObjectURL, NativeURL));
}
setToStringTag(URLConstructor, 'URL');
_export({ global: true, constructor: true, forced: !nativeUrl, sham: !descriptors }, {
URL: URLConstructor
});
var url = path.URL;
var url$1 = url;
var url$2 = url$1;
var html2canvas = createCommonjsModule(function (module, exports) {
/*!
* html2canvas 1.4.1 <https://html2canvas.hertzen.com>
* Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
* Released under MIT License
*/
(function (global, factory) {
module.exports = factory() ;
}(commonjsGlobal, (function () {
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || from);
}
var Bounds = /** @class */ (function () {
function Bounds(left, top, width, height) {
this.left = left;
this.top = top;
this.width = width;
this.height = height;
}
Bounds.prototype.add = function (x, y, w, h) {
return new Bounds(this.left + x, this.top + y, this.width + w, this.height + h);
};
Bounds.fromClientRect = function (context, clientRect) {
return new Bounds(clientRect.left + context.windowBounds.left, clientRect.top + context.windowBounds.top, clientRect.width, clientRect.height);
};
Bounds.fromDOMRectList = function (context, domRectList) {
var domRect = Array.from(domRectList).find(function (rect) { return rect.width !== 0; });
return domRect
? new Bounds(domRect.left + context.windowBounds.left, domRect.top + context.windowBounds.top, domRect.width, domRect.height)
: Bounds.EMPTY;
};
Bounds.EMPTY = new Bounds(0, 0, 0, 0);
return Bounds;
}());
var parseBounds = function (context, node) {
return Bounds.fromClientRect(context, node.getBoundingClientRect());
};
var parseDocumentSize = function (document) {
var body = document.body;
var documentElement = document.documentElement;
if (!body || !documentElement) {
throw new Error("Unable to get document size");
}
var width = Math.max(Math.max(body.scrollWidth, documentElement.scrollWidth), Math.max(body.offsetWidth, documentElement.offsetWidth), Math.max(body.clientWidth, documentElement.clientWidth));
var height = Math.max(Math.max(body.scrollHeight, documentElement.scrollHeight), Math.max(body.offsetHeight, documentElement.offsetHeight), Math.max(body.clientHeight, documentElement.clientHeight));
return new Bounds(0, 0, width, height);
};
/*
* css-line-break 2.1.0 <https://github.com/niklasvh/css-line-break#readme>
* Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
* Released under MIT License
*/
var toCodePoints$1 = function (str) {
var codePoints = [];
var i = 0;
var length = str.length;
while (i < length) {
var value = str.charCodeAt(i++);
if (value >= 0xd800 && value <= 0xdbff && i < length) {
var extra = str.charCodeAt(i++);
if ((extra & 0xfc00) === 0xdc00) {
codePoints.push(((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000);
}
else {
codePoints.push(value);
i--;
}
}
else {
codePoints.push(value);
}
}
return codePoints;
};
var fromCodePoint$1 = function () {
var codePoints = [];
for (var _i = 0; _i < arguments.length; _i++) {
codePoints[_i] = arguments[_i];
}
if (String.fromCodePoint) {
return String.fromCodePoint.apply(String, codePoints);
}
var length = codePoints.length;
if (!length) {
return '';
}
var codeUnits = [];
var index = -1;
var result = '';
while (++index < length) {
var codePoint = codePoints[index];
if (codePoint <= 0xffff) {
codeUnits.push(codePoint);
}
else {
codePoint -= 0x10000;
codeUnits.push((codePoint >> 10) + 0xd800, (codePoint % 0x400) + 0xdc00);
}
if (index + 1 === length || codeUnits.length > 0x4000) {
result += String.fromCharCode.apply(String, codeUnits);
codeUnits.length = 0;
}
}
return result;
};
var chars$2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// Use a lookup table to find the index.
var lookup$2 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
for (var i$2 = 0; i$2 < chars$2.length; i$2++) {
lookup$2[chars$2.charCodeAt(i$2)] = i$2;
}
/*
* utrie 1.0.2 <https://github.com/niklasvh/utrie>
* Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
* Released under MIT License
*/
var chars$1$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// Use a lookup table to find the index.
var lookup$1$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
for (var i$1$1 = 0; i$1$1 < chars$1$1.length; i$1$1++) {
lookup$1$1[chars$1$1.charCodeAt(i$1$1)] = i$1$1;
}
var decode$1 = function (base64) {
var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
if (base64[base64.length - 1] === '=') {
bufferLength--;
if (base64[base64.length - 2] === '=') {
bufferLength--;
}
}
var buffer = typeof ArrayBuffer !== 'undefined' &&
typeof Uint8Array !== 'undefined' &&
typeof Uint8Array.prototype.slice !== 'undefined'
? new ArrayBuffer(bufferLength)
: new Array(bufferLength);
var bytes = Array.isArray(buffer) ? buffer : new Uint8Array(buffer);
for (i = 0; i < len; i += 4) {
encoded1 = lookup$1$1[base64.charCodeAt(i)];
encoded2 = lookup$1$1[base64.charCodeAt(i + 1)];
encoded3 = lookup$1$1[base64.charCodeAt(i + 2)];
encoded4 = lookup$1$1[base64.charCodeAt(i + 3)];
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return buffer;
};
var polyUint16Array$1 = function (buffer) {
var length = buffer.length;
var bytes = [];
for (var i = 0; i < length; i += 2) {
bytes.push((buffer[i + 1] << 8) | buffer[i]);
}
return bytes;
};
var polyUint32Array$1 = function (buffer) {
var length = buffer.length;
var bytes = [];
for (var i = 0; i < length; i += 4) {
bytes.push((buffer[i + 3] << 24) | (buffer[i + 2] << 16) | (buffer[i + 1] << 8) | buffer[i]);
}
return bytes;
};
/** Shift size for getting the index-2 table offset. */
var UTRIE2_SHIFT_2$1 = 5;
/** Shift size for getting the index-1 table offset. */
var UTRIE2_SHIFT_1$1 = 6 + 5;
/**
* Shift size for shifting left the index array values.
* Increases possible data size with 16-bit index values at the cost
* of compactability.
* This requires data blocks to be aligned by UTRIE2_DATA_GRANULARITY.
*/
var UTRIE2_INDEX_SHIFT$1 = 2;
/**
* Difference between the two shift sizes,
* for getting an index-1 offset from an index-2 offset. 6=11-5
*/
var UTRIE2_SHIFT_1_2$1 = UTRIE2_SHIFT_1$1 - UTRIE2_SHIFT_2$1;
/**
* The part of the index-2 table for U+D800..U+DBFF stores values for
* lead surrogate code _units_ not code _points_.
* Values for lead surrogate code _points_ are indexed with this portion of the table.
* Length=32=0x20=0x400>>UTRIE2_SHIFT_2. (There are 1024=0x400 lead surrogates.)
*/
var UTRIE2_LSCP_INDEX_2_OFFSET$1 = 0x10000 >> UTRIE2_SHIFT_2$1;
/** Number of entries in a data block. 32=0x20 */
var UTRIE2_DATA_BLOCK_LENGTH$1 = 1 << UTRIE2_SHIFT_2$1;
/** Mask for getting the lower bits for the in-data-block offset. */
var UTRIE2_DATA_MASK$1 = UTRIE2_DATA_BLOCK_LENGTH$1 - 1;
var UTRIE2_LSCP_INDEX_2_LENGTH$1 = 0x400 >> UTRIE2_SHIFT_2$1;
/** Count the lengths of both BMP pieces. 2080=0x820 */
var UTRIE2_INDEX_2_BMP_LENGTH$1 = UTRIE2_LSCP_INDEX_2_OFFSET$1 + UTRIE2_LSCP_INDEX_2_LENGTH$1;
/**
* The 2-byte UTF-8 version of the index-2 table follows at offset 2080=0x820.
* Length 32=0x20 for lead bytes C0..DF, regardless of UTRIE2_SHIFT_2.
*/
var UTRIE2_UTF8_2B_INDEX_2_OFFSET$1 = UTRIE2_INDEX_2_BMP_LENGTH$1;
var UTRIE2_UTF8_2B_INDEX_2_LENGTH$1 = 0x800 >> 6; /* U+0800 is the first code point after 2-byte UTF-8 */
/**
* The index-1 table, only used for supplementary code points, at offset 2112=0x840.
* Variable length, for code points up to highStart, where the last single-value range starts.
* Maximum length 512=0x200=0x100000>>UTRIE2_SHIFT_1.
* (For 0x100000 supplementary code points U+10000..U+10ffff.)
*
* The part of the index-2 table for supplementary code points starts
* after this index-1 table.
*
* Both the index-1 table and the following part of the index-2 table
* are omitted completely if there is only BMP data.
*/
var UTRIE2_INDEX_1_OFFSET$1 = UTRIE2_UTF8_2B_INDEX_2_OFFSET$1 + UTRIE2_UTF8_2B_INDEX_2_LENGTH$1;
/**
* Number of index-1 entries for the BMP. 32=0x20
* This part of the index-1 table is omitted from the serialized form.
*/
var UTRIE2_OMITTED_BMP_INDEX_1_LENGTH$1 = 0x10000 >> UTRIE2_SHIFT_1$1;
/** Number of entries in an index-2 block. 64=0x40 */
var UTRIE2_INDEX_2_BLOCK_LENGTH$1 = 1 << UTRIE2_SHIFT_1_2$1;
/** Mask for getting the lower bits for the in-index-2-block offset. */
var UTRIE2_INDEX_2_MASK$1 = UTRIE2_INDEX_2_BLOCK_LENGTH$1 - 1;
var slice16$1 = function (view, start, end) {
if (view.slice) {
return view.slice(start, end);
}
return new Uint16Array(Array.prototype.slice.call(view, start, end));
};
var slice32$1 = function (view, start, end) {
if (view.slice) {
return view.slice(start, end);
}
return new Uint32Array(Array.prototype.slice.call(view, start, end));
};
var createTrieFromBase64$1 = function (base64, _byteLength) {
var buffer = decode$1(base64);
var view32 = Array.isArray(buffer) ? polyUint32Array$1(buffer) : new Uint32Array(buffer);
var view16 = Array.isArray(buffer) ? polyUint16Array$1(buffer) : new Uint16Array(buffer);
var headerLength = 24;
var index = slice16$1(view16, headerLength / 2, view32[4] / 2);
var data = view32[5] === 2
? slice16$1(view16, (headerLength + view32[4]) / 2)
: slice32$1(view32, Math.ceil((headerLength + view32[4]) / 4));
return new Trie$1(view32[0], view32[1], view32[2], view32[3], index, data);
};
var Trie$1 = /** @class */ (function () {
function Trie(initialValue, errorValue, highStart, highValueIndex, index, data) {
this.initialValue = initialValue;
this.errorValue = errorValue;
this.highStart = highStart;
this.highValueIndex = highValueIndex;
this.index = index;
this.data = data;
}
/**
* Get the value for a code point as stored in the Trie.
*
* @param codePoint the code point
* @return the value
*/
Trie.prototype.get = function (codePoint) {
var ix;
if (codePoint >= 0) {
if (codePoint < 0x0d800 || (codePoint > 0x0dbff && codePoint <= 0x0ffff)) {
// Ordinary BMP code point, excluding leading surrogates.
// BMP uses a single level lookup. BMP index starts at offset 0 in the Trie2 index.
// 16 bit data is stored in the index array itself.
ix = this.index[codePoint >> UTRIE2_SHIFT_2$1];
ix = (ix << UTRIE2_INDEX_SHIFT$1) + (codePoint & UTRIE2_DATA_MASK$1);
return this.data[ix];
}
if (codePoint <= 0xffff) {
// Lead Surrogate Code Point. A Separate index section is stored for
// lead surrogate code units and code points.
// The main index has the code unit data.
// For this function, we need the code point data.
// Note: this expression could be refactored for slightly improved efficiency, but
// surrogate code points will be so rare in practice that it's not worth it.
ix = this.index[UTRIE2_LSCP_INDEX_2_OFFSET$1 + ((codePoint - 0xd800) >> UTRIE2_SHIFT_2$1)];
ix = (ix << UTRIE2_INDEX_SHIFT$1) + (codePoint & UTRIE2_DATA_MASK$1);
return this.data[ix];
}
if (codePoint < this.highStart) {
// Supplemental code point, use two-level lookup.
ix = UTRIE2_INDEX_1_OFFSET$1 - UTRIE2_OMITTED_BMP_INDEX_1_LENGTH$1 + (codePoint >> UTRIE2_SHIFT_1$1);
ix = this.index[ix];
ix += (codePoint >> UTRIE2_SHIFT_2$1) & UTRIE2_INDEX_2_MASK$1;
ix = this.index[ix];
ix = (ix << UTRIE2_INDEX_SHIFT$1) + (codePoint & UTRIE2_DATA_MASK$1);
return this.data[ix];
}
if (codePoint <= 0x10ffff) {
return this.data[this.highValueIndex];
}
}
// Fall through. The code point is outside of the legal range of 0..0x10ffff.
return this.errorValue;
};
return Trie;
}());
/*
* base64-arraybuffer 1.0.2 <https://github.com/niklasvh/base64-arraybuffer>
* Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
* Released under MIT License
*/
var chars$3 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// Use a lookup table to find the index.
var lookup$3 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
for (var i$3 = 0; i$3 < chars$3.length; i$3++) {
lookup$3[chars$3.charCodeAt(i$3)] = i$3;
}
var base64$1 = 'KwAAAAAAAAAACA4AUD0AADAgAAACAAAAAAAIABAAGABAAEgAUABYAGAAaABgAGgAYgBqAF8AZwBgAGgAcQB5AHUAfQCFAI0AlQCdAKIAqgCyALoAYABoAGAAaABgAGgAwgDKAGAAaADGAM4A0wDbAOEA6QDxAPkAAQEJAQ8BFwF1AH0AHAEkASwBNAE6AUIBQQFJAVEBWQFhAWgBcAF4ATAAgAGGAY4BlQGXAZ8BpwGvAbUBvQHFAc0B0wHbAeMB6wHxAfkBAQIJAvEBEQIZAiECKQIxAjgCQAJGAk4CVgJeAmQCbAJ0AnwCgQKJApECmQKgAqgCsAK4ArwCxAIwAMwC0wLbAjAA4wLrAvMC+AIAAwcDDwMwABcDHQMlAy0DNQN1AD0DQQNJA0kDSQNRA1EDVwNZA1kDdQB1AGEDdQBpA20DdQN1AHsDdQCBA4kDkQN1AHUAmQOhA3UAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AKYDrgN1AHUAtgO+A8YDzgPWAxcD3gPjA+sD8wN1AHUA+wMDBAkEdQANBBUEHQQlBCoEFwMyBDgEYABABBcDSARQBFgEYARoBDAAcAQzAXgEgASIBJAEdQCXBHUAnwSnBK4EtgS6BMIEyAR1AHUAdQB1AHUAdQCVANAEYABgAGAAYABgAGAAYABgANgEYADcBOQEYADsBPQE/AQEBQwFFAUcBSQFLAU0BWQEPAVEBUsFUwVbBWAAYgVgAGoFcgV6BYIFigWRBWAAmQWfBaYFYABgAGAAYABgAKoFYACxBbAFuQW6BcEFwQXHBcEFwQXPBdMF2wXjBeoF8gX6BQIGCgYSBhoGIgYqBjIGOgZgAD4GRgZMBmAAUwZaBmAAYABgAGAAYABgAGAAYABgAGAAYABgAGIGYABpBnAGYABgAGAAYABgAGAAYABgAGAAYAB4Bn8GhQZgAGAAYAB1AHcDFQSLBmAAYABgAJMGdQA9A3UAmwajBqsGqwaVALMGuwbDBjAAywbSBtIG1QbSBtIG0gbSBtIG0gbdBuMG6wbzBvsGAwcLBxMHAwcbByMHJwcsBywHMQcsB9IGOAdAB0gHTgfSBkgHVgfSBtIG0gbSBtIG0gbSBtIG0gbSBiwHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAdgAGAALAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAdbB2MHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsB2kH0gZwB64EdQB1AHUAdQB1AHUAdQB1AHUHfQdgAIUHjQd1AHUAlQedB2AAYAClB6sHYACzB7YHvgfGB3UAzgfWBzMB3gfmB1EB7gf1B/0HlQENAQUIDQh1ABUIHQglCBcDLQg1CD0IRQhNCEEDUwh1AHUAdQBbCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIcAh3CHoIMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIgggwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAALAcsBywHLAcsBywHLAcsBywHLAcsB4oILAcsB44I0gaWCJ4Ipgh1AHUAqgiyCHUAdQB1AHUAdQB1AHUAdQB1AHUAtwh8AXUAvwh1AMUIyQjRCNkI4AjoCHUAdQB1AO4I9gj+CAYJDgkTCS0HGwkjCYIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiAAIAAAAFAAYABgAGIAXwBgAHEAdQBFAJUAogCyAKAAYABgAEIA4ABGANMA4QDxAMEBDwE1AFwBLAE6AQEBUQF4QkhCmEKoQrhCgAHIQsAB0MLAAcABwAHAAeDC6ABoAHDCwMMAAcABwAHAAdDDGMMAAcAB6MM4wwjDWMNow3jDaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAEjDqABWw6bDqABpg6gAaABoAHcDvwOPA+gAaABfA/8DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DpcPAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcAB9cPKwkyCToJMAB1AHUAdQBCCUoJTQl1AFUJXAljCWcJawkwADAAMAAwAHMJdQB2CX4JdQCECYoJjgmWCXUAngkwAGAAYABxAHUApgn3A64JtAl1ALkJdQDACTAAMAAwADAAdQB1AHUAdQB1AHUAdQB1AHUAowYNBMUIMAAwADAAMADICcsJ0wnZCRUE4QkwAOkJ8An4CTAAMAB1AAAKvwh1AAgKDwoXCh8KdQAwACcKLgp1ADYKqAmICT4KRgowADAAdQB1AE4KMAB1AFYKdQBeCnUAZQowADAAMAAwADAAMAAwADAAMAAVBHUAbQowADAAdQC5CXUKMAAwAHwBxAijBogEMgF9CoQKiASMCpQKmgqIBKIKqgquCogEDQG2Cr4KxgrLCjAAMADTCtsKCgHjCusK8Qr5CgELMAAwADAAMAB1AIsECQsRC3UANAEZCzAAMAAwADAAMAB1ACELKQswAHUANAExCzkLdQBBC0kLMABRC1kLMAAwADAAMAAwADAAdQBhCzAAMAAwAGAAYABpC3ELdwt/CzAAMACHC4sLkwubC58Lpwt1AK4Ltgt1APsDMAAwADAAMAAwADAAMAAwAL4LwwvLC9IL1wvdCzAAMADlC+kL8Qv5C/8LSQswADAAMAAwADAAMAAwADAAMAAHDDAAMAAwADAAMAAODBYMHgx1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1ACYMMAAwADAAdQB1AHUALgx1AHUAdQB1AHUAdQA2DDAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AD4MdQBGDHUAdQB1AHUAdQB1AEkMdQB1AHUAdQB1AFAMMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQBYDHUAdQB1AF8MMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUA+wMVBGcMMAAwAHwBbwx1AHcMfwyHDI8MMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAYABgAJcMMAAwADAAdQB1AJ8MlQClDDAAMACtDCwHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsB7UMLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AA0EMAC9DDAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAsBywHLAcsBywHLAcsBywHLQcwAMEMyAwsBywHLAcsBywHLAcsBywHLAcsBywHzAwwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAHUAdQB1ANQM2QzhDDAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMABgAGAAYABgAGAAYABgAOkMYADxDGAA+AwADQYNYABhCWAAYAAODTAAMAAwADAAFg1gAGAAHg37AzAAMAAwADAAYABgACYNYAAsDTQNPA1gAEMNPg1LDWAAYABgAGAAYABgAGAAYABgAGAAUg1aDYsGVglhDV0NcQBnDW0NdQ15DWAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAlQCBDZUAiA2PDZcNMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAnw2nDTAAMAAwADAAMAAwAHUArw23DTAAMAAwADAAMAAwADAAMAAwADAAMAB1AL8NMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAB1AHUAdQB1AHUAdQDHDTAAYABgAM8NMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAA1w11ANwNMAAwAD0B5A0wADAAMAAwADAAMADsDfQN/A0EDgwOFA4wABsOMAAwADAAMAAwADAAMAAwANIG0gbSBtIG0gbSBtIG0gYjDigOwQUuDsEFMw7SBjoO0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIGQg5KDlIOVg7SBtIGXg5lDm0OdQ7SBtIGfQ6EDooOjQ6UDtIGmg6hDtIG0gaoDqwO0ga0DrwO0gZgAGAAYADEDmAAYAAkBtIGzA5gANIOYADaDokO0gbSBt8O5w7SBu8O0gb1DvwO0gZgAGAAxA7SBtIG0gbSBtIGYABgAGAAYAAED2AAsAUMD9IG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIGFA8sBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAccD9IGLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHJA8sBywHLAcsBywHLAccDywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywPLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAc0D9IG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIGLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAccD9IG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIGFA8sBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHPA/SBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gYUD0QPlQCVAJUAMAAwADAAMACVAJUAlQCVAJUAlQCVAEwPMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAA//8EAAQABAAEAAQABAAEAAQABAANAAMAAQABAAIABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQACgATABcAHgAbABoAHgAXABYAEgAeABsAGAAPABgAHABLAEsASwBLAEsASwBLAEsASwBLABgAGAAeAB4AHgATAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQABYAGwASAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAWAA0AEQAeAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAFAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAJABYAGgAbABsAGwAeAB0AHQAeAE8AFwAeAA0AHgAeABoAGwBPAE8ADgBQAB0AHQAdAE8ATwAXAE8ATwBPABYAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAFAAUABQAFAAUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AHgAeAFAATwBAAE8ATwBPAEAATwBQAFAATwBQAB4AHgAeAB4AHgAeAB0AHQAdAB0AHgAdAB4ADgBQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgBQAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAJAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAkACQAJAAkACQAJAAkABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgAeAFAAHgAeAB4AKwArAFAAUABQAFAAGABQACsAKwArACsAHgAeAFAAHgBQAFAAUAArAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAUAAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAYAA0AKwArAB4AHgAbACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQADQAEAB4ABAAEAB4ABAAEABMABAArACsAKwArACsAKwArACsAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAKwArACsAKwBWAFYAVgBWAB4AHgArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AGgAaABoAGAAYAB4AHgAEAAQABAAEAAQABAAEAAQABAAEAAQAEwAEACsAEwATAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABLAEsASwBLAEsASwBLAEsASwBLABoAGQAZAB4AUABQAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQABMAUAAEAAQABAAEAAQABAAEAB4AHgAEAAQABAAEAAQABABQAFAABAAEAB4ABAAEAAQABABQAFAASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUAAeAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAFAABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQAUABQAB4AHgAYABMAUAArACsABAAbABsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAFAABAAEAAQABAAEAFAABAAEAAQAUAAEAAQABAAEAAQAKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAArACsAHgArAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAUAAEAAQABAAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAABAAEAA0ADQBLAEsASwBLAEsASwBLAEsASwBLAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAArAFAAUABQAFAAUABQAFAAUAArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUAArACsAKwBQAFAAUABQACsAKwAEAFAABAAEAAQABAAEAAQABAArACsABAAEACsAKwAEAAQABABQACsAKwArACsAKwArACsAKwAEACsAKwArACsAUABQACsAUABQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAFAAUAAaABoAUABQAFAAUABQAEwAHgAbAFAAHgAEACsAKwAEAAQABAArAFAAUABQAFAAUABQACsAKwArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQACsAUABQACsAKwAEACsABAAEAAQABAAEACsAKwArACsABAAEACsAKwAEAAQABAArACsAKwAEACsAKwArACsAKwArACsAUABQAFAAUAArAFAAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLAAQABABQAFAAUAAEAB4AKwArACsAKwArACsAKwArACsAKwAEAAQABAArAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQAFAAUABQACsAKwAEAFAABAAEAAQABAAEAAQABAAEACsABAAEAAQAKwAEAAQABAArACsAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAB4AGwArACsAKwArACsAKwArAFAABAAEAAQABAAEAAQAKwAEAAQABAArAFAAUABQAFAAUABQAFAAUAArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAArACsABAAEACsAKwAEAAQABAArACsAKwArACsAKwArAAQABAAEACsAKwArACsAUABQACsAUABQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAB4AUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArAAQAUAArAFAAUABQAFAAUABQACsAKwArAFAAUABQACsAUABQAFAAUAArACsAKwBQAFAAKwBQACsAUABQACsAKwArAFAAUAArACsAKwBQAFAAUAArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArAAQABAAEAAQABAArACsAKwAEAAQABAArAAQABAAEAAQAKwArAFAAKwArACsAKwArACsABAArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAHgAeAB4AHgAeAB4AGwAeACsAKwArACsAKwAEAAQABAAEAAQAUABQAFAAUABQAFAAUABQACsAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAUAAEAAQABAAEAAQABAAEACsABAAEAAQAKwAEAAQABAAEACsAKwArACsAKwArACsABAAEACsAUABQAFAAKwArACsAKwArAFAAUAAEAAQAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAKwAOAFAAUABQAFAAUABQAFAAHgBQAAQABAAEAA4AUABQAFAAUABQAFAAUABQACsAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAKwArAAQAUAAEAAQABAAEAAQABAAEACsABAAEAAQAKwAEAAQABAAEACsAKwArACsAKwArACsABAAEACsAKwArACsAKwArACsAUAArAFAAUAAEAAQAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwBQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAFAABAAEAAQABAAEAAQABAArAAQABAAEACsABAAEAAQABABQAB4AKwArACsAKwBQAFAAUAAEAFAAUABQAFAAUABQAFAAUABQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAFAAUABQAFAAUABQAFAAUABQABoAUABQAFAAUABQAFAAKwAEAAQABAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQACsAUAArACsAUABQAFAAUABQAFAAUAArACsAKwAEACsAKwArACsABAAEAAQABAAEAAQAKwAEACsABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArAAQABAAeACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAAqAFwAXAAqACoAKgAqACoAKgAqACsAKwArACsAGwBcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAeAEsASwBLAEsASwBLAEsASwBLAEsADQANACsAKwArACsAKwBcAFwAKwBcACsAXABcAFwAXABcACsAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACsAXAArAFwAXABcAFwAXABcAFwAXABcAFwAKgBcAFwAKgAqACoAKgAqACoAKgAqACoAXAArACsAXABcAFwAXABcACsAXAArACoAKgAqACoAKgAqACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwBcAFwAXABcAFAADgAOAA4ADgAeAA4ADgAJAA4ADgANAAkAEwATABMAEwATAAkAHgATAB4AHgAeAAQABAAeAB4AHgAeAB4AHgBLAEsASwBLAEsASwBLAEsASwBLAFAAUABQAFAAUABQAFAAUABQAFAADQAEAB4ABAAeAAQAFgARABYAEQAEAAQAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQADQAEAAQABAAEAAQADQAEAAQAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArAA0ADQAeAB4AHgAeAB4AHgAEAB4AHgAeAB4AHgAeACsAHgAeAA4ADgANAA4AHgAeAB4AHgAeAAkACQArACsAKwArACsAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgBcAEsASwBLAEsASwBLAEsASwBLAEsADQANAB4AHgAeAB4AXABcAFwAXABcAFwAKgAqACoAKgBcAFwAXABcACoAKgAqAFwAKgAqACoAXABcACoAKgAqACoAKgAqACoAXABcAFwAKgAqACoAKgBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAqACoAKgAqAFwAKgBLAEsASwBLAEsASwBLAEsASwBLACoAKgAqACoAKgAqAFAAUABQAFAAUABQACsAUAArACsAKwArACsAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgBQAFAAUABQAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUAArACsAUABQAFAAUABQAFAAUAArAFAAKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAKwBQACsAUABQAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsABAAEAAQAHgANAB4AHgAeAB4AHgAeAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUAArACsADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAANAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAWABEAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAA0ADQANAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAANAA0AKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUAArAAQABAArACsAKwArACsAKwArACsAKwArACsAKwBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqAA0ADQAVAFwADQAeAA0AGwBcACoAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwAeAB4AEwATAA0ADQAOAB4AEwATAB4ABAAEAAQACQArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUAAEAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAHgArACsAKwATABMASwBLAEsASwBLAEsASwBLAEsASwBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAArACsAXABcAFwAXABcACsAKwArACsAKwArACsAKwArACsAKwBcAFwAXABcAFwAXABcAFwAXABcAFwAXAArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAXAArACsAKwAqACoAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAArACsAHgAeAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAqACoAKwAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKwArAAQASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArACoAKgAqACoAKgAqACoAXAAqACoAKgAqACoAKgArACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABABQAFAAUABQAFAAUABQACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwANAA0AHgANAA0ADQANAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAEAAQAHgAeAB4AHgAeAB4AHgAeAB4AKwArACsABAAEAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwAeAB4AHgAeAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArAA0ADQANAA0ADQBLAEsASwBLAEsASwBLAEsASwBLACsAKwArAFAAUABQAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAA0ADQBQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUAAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArAAQABAAEAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAAQAUABQAFAAUABQAFAABABQAFAABAAEAAQAUAArACsAKwArACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsABAAEAAQABAAEAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAKwBQACsAUAArAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAB4AHgAeAB4AHgAeAB4AHgBQAB4AHgAeAFAAUABQACsAHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQACsAKwAeAB4AHgAeAB4AHgArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAFAAUABQACsAHgAeAB4AHgAeAB4AHgAOAB4AKwANAA0ADQANAA0ADQANAAkADQANAA0ACAAEAAsABAAEAA0ACQANAA0ADAAdAB0AHgAXABcAFgAXABcAFwAWABcAHQAdAB4AHgAUABQAFAANAAEAAQAEAAQABAAEAAQACQAaABoAGgAaABoAGgAaABoAHgAXABcAHQAVABUAHgAeAB4AHgAeAB4AGAAWABEAFQAVABUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ADQAeAA0ADQANAA0AHgANAA0ADQAHAB4AHgAeAB4AKwAEAAQABAAEAAQABAAEAAQABAAEAFAAUAArACsATwBQAFAAUABQAFAAHgAeAB4AFgARAE8AUABPAE8ATwBPAFAAUABQAFAAUAAeAB4AHgAWABEAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArABsAGwAbABsAGwAbABsAGgAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGgAbABsAGwAbABoAGwAbABoAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAHgAeAFAAGgAeAB0AHgBQAB4AGgAeAB4AHgAeAB4AHgAeAB4AHgBPAB4AUAAbAB4AHgBQAFAAUABQAFAAHgAeAB4AHQAdAB4AUAAeAFAAHgBQAB4AUABPAFAAUAAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAHgBQAFAAUABQAE8ATwBQAFAAUABQAFAATwBQAFAATwBQAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAFAAUABQAFAATwBPAE8ATwBPAE8ATwBPAE8ATwBQAFAAUABQAFAAUABQAFAAUAAeAB4AUABQAFAAUABPAB4AHgArACsAKwArAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHQAdAB4AHgAeAB0AHQAeAB4AHQAeAB4AHgAdAB4AHQAbABsAHgAdAB4AHgAeAB4AHQAeAB4AHQAdAB0AHQAeAB4AHQAeAB0AHgAdAB0AHQAdAB0AHQAeAB0AHgAeAB4AHgAeAB0AHQAdAB0AHgAeAB4AHgAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHgAeAB0AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHgAeAB0AHQAdAB0AHgAeAB0AHQAeAB4AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHQAeAB4AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAeAB4AHgAdAB4AHgAeAB4AHgAeAB4AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABYAEQAWABEAHgAeAB4AHgAeAB4AHQAeAB4AHgAeAB4AHgAeACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAWABEAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAFAAHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB4AHgAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAeAB4AHQAdAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHQAeAB0AHQAdAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB0AHQAeAB4AHQAdAB4AHgAeAB4AHQAdAB4AHgAeAB4AHQAdAB0AHgAeAB0AHgAeAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlAB4AHQAdAB4AHgAdAB4AHgAeAB4AHQAdAB4AHgAeAB4AJQAlAB0AHQAlAB4AJQAlACUAIAAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAeAB4AHgAeAB0AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHgAdAB0AHQAeAB0AJQAdAB0AHgAdAB0AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAdAB0AHQAdACUAHgAlACUAJQAdACUAJQAdAB0AHQAlACUAHQAdACUAHQAdACUAJQAlAB4AHQAeAB4AHgAeAB0AHQAlAB0AHQAdAB0AHQAdACUAJQAlACUAJQAdACUAJQAgACUAHQAdACUAJQAlACUAJQAlACUAJQAeAB4AHgAlACUAIAAgACAAIAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AFwAXABcAFwAXABcAHgATABMAJQAeAB4AHgAWABEAFgARABYAEQAWABEAFgARABYAEQAWABEATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABYAEQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAWABEAFgARABYAEQAWABEAFgARAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFgARABYAEQAWABEAFgARABYAEQAWABEAFgARABYAEQAWABEAFgARABYAEQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAWABEAFgARAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFgARAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAEAAQABAAeAB4AKwArACsAKwArABMADQANAA0AUAATAA0AUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAUAANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAA0ADQANAA0ADQANAA0ADQAeAA0AFgANAB4AHgAXABcAHgAeABcAFwAWABEAFgARABYAEQAWABEADQANAA0ADQATAFAADQANAB4ADQANAB4AHgAeAB4AHgAMAAwADQANAA0AHgANAA0AFgANAA0ADQANAA0ADQANAA0AHgANAB4ADQANAB4AHgAeACsAKwArACsAKwArACsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAKwArACsAKwArACsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArAA0AEQARACUAJQBHAFcAVwAWABEAFgARABYAEQAWABEAFgARACUAJQAWABEAFgARABYAEQAWABEAFQAWABEAEQAlAFcAVwBXAFcAVwBXAFcAVwBXAAQABAAEAAQABAAEACUAVwBXAFcAVwA2ACUAJQBXAFcAVwBHAEcAJQAlACUAKwBRAFcAUQBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFEAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBRAFcAUQBXAFEAVwBXAFcAVwBXAFcAUQBXAFcAVwBXAFcAVwBRAFEAKwArAAQABAAVABUARwBHAFcAFQBRAFcAUQBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBRAFcAVwBXAFcAVwBXAFEAUQBXAFcAVwBXABUAUQBHAEcAVwArACsAKwArACsAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwAlACUAVwBXAFcAVwAlACUAJQAlACUAJQAlACUAJQAlACsAKwArACsAKwArACsAKwArACsAKwArAFEAUQBRAFEAUQBRAFEAUQBRAFEAUQBRAFEAUQBRAFEAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBPAE8ATwBPAE8ATwBPAE8AJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAEcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAADQATAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABLAEsASwBLAEsASwBLAEsASwBLAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAABAAEAAQABAAeAAQABAAEAAQABAAEAAQABAAEAAQAHgBQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUABQAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAeAA0ADQANAA0ADQArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAB4AHgAeAB4AHgAeAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AUABQAFAAUABQAFAAUABQAFAAUABQAAQAUABQAFAABABQAFAAUABQAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAeAB4AHgAeAAQAKwArACsAUABQAFAAUABQAFAAHgAeABoAHgArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAADgAOABMAEwArACsAKwArACsAKwArACsABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwANAA0ASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAFAAUAAeAB4AHgBQAA4AUABQAAQAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAA0ADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArAB4AWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYACsAKwArAAQAHgAeAB4AHgAeAB4ADQANAA0AHgAeAB4AHgArAFAASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArAB4AHgBcAFwAXABcAFwAKgBcAFwAXABcAFwAXABcAFwAXABcAEsASwBLAEsASwBLAEsASwBLAEsAXABcAFwAXABcACsAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArAFAAUABQAAQAUABQAFAAUABQAFAAUABQAAQABAArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAHgANAA0ADQBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAXAAqACoAKgBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAAqAFwAKgAqACoAXABcACoAKgBcAFwAXABcAFwAKgAqAFwAKgBcACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcACoAKgBQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAA0ADQBQAFAAUAAEAAQAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUAArACsAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQADQAEAAQAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAVABVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBUAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVACsAKwArACsAKwArACsAKwArACsAKwArAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAKwArACsAKwBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAKwArACsAKwAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAKwArACsAKwArAFYABABWAFYAVgBWAFYAVgBWAFYAVgBWAB4AVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgArAFYAVgBWAFYAVgArAFYAKwBWAFYAKwBWAFYAKwBWAFYAVgBWAFYAVgBWAFYAVgBWAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAEQAWAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUAAaAB4AKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAGAARABEAGAAYABMAEwAWABEAFAArACsAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACUAJQAlACUAJQAWABEAFgARABYAEQAWABEAFgARABYAEQAlACUAFgARACUAJQAlACUAJQAlACUAEQAlABEAKwAVABUAEwATACUAFgARABYAEQAWABEAJQAlACUAJQAlACUAJQAlACsAJQAbABoAJQArACsAKwArAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAcAKwATACUAJQAbABoAJQAlABYAEQAlACUAEQAlABEAJQBXAFcAVwBXAFcAVwBXAFcAVwBXABUAFQAlACUAJQATACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXABYAJQARACUAJQAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwAWACUAEQAlABYAEQARABYAEQARABUAVwBRAFEAUQBRAFEAUQBRAFEAUQBRAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAEcARwArACsAVwBXAFcAVwBXAFcAKwArAFcAVwBXAFcAVwBXACsAKwBXAFcAVwBXAFcAVwArACsAVwBXAFcAKwArACsAGgAbACUAJQAlABsAGwArAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwAEAAQABAAQAB0AKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsADQANAA0AKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAAQAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAA0AUABQAFAAUAArACsAKwArAFAAUABQAFAAUABQAFAAUAANAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwAeACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAKwArAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUAArACsAKwBQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwANAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAUABQAFAAUABQAAQABAAEACsABAAEACsAKwArACsAKwAEAAQABAAEAFAAUABQAFAAKwBQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEACsAKwArACsABABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAA0ADQANAA0ADQANAA0ADQAeACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAArACsAKwArAFAAUABQAFAAUAANAA0ADQANAA0ADQAUACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsADQANAA0ADQANAA0ADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAAQABAAEAAQAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUAArAAQABAANACsAKwBQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAB4AHgAeAB4AHgArACsAKwArACsAKwAEAAQABAAEAAQABAAEAA0ADQAeAB4AHgAeAB4AKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwAeACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsASwBLAEsASwBLAEsASwBLAEsASwANAA0ADQANAFAABAAEAFAAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAeAA4AUAArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAADQANAB4ADQAEAAQABAAEAB4ABAAEAEsASwBLAEsASwBLAEsASwBLAEsAUAAOAFAADQANAA0AKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAANAA0AHgANAA0AHgAEACsAUABQAFAAUABQAFAAUAArAFAAKwBQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAA0AKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsABAAEAAQABAArAFAAUABQAFAAUABQAFAAUAArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQAFAAUABQACsABAAEAFAABAAEAAQABAAEAAQABAArACsABAAEACsAKwAEAAQABAArACsAUAArACsAKwArACsAKwAEACsAKwArACsAKwBQAFAAUABQAFAABAAEACsAKwAEAAQABAAEAAQABAAEACsAKwArAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAAQABABQAFAAUABQAA0ADQANAA0AHgBLAEsASwBLAEsASwBLAEsASwBLAA0ADQArAB4ABABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAAQABAAEAFAAUAAeAFAAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAArACsABAAEAAQABAAEAAQABAAEAAQADgANAA0AEwATAB4AHgAeAA0ADQANAA0ADQANAA0ADQANAA0ADQANAA0ADQANAFAAUABQAFAABAAEACsAKwAEAA0ADQAeAFAAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAFAAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKwArACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBcAFwADQANAA0AKgBQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAKwArAFAAKwArAFAAUABQAFAAUABQAFAAUAArAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQAKwAEAAQAKwArAAQABAAEAAQAUAAEAFAABAAEAA0ADQANACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAArACsABAAEAAQABAAEAAQABABQAA4AUAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAFAABAAEAAQABAAOAB4ADQANAA0ADQAOAB4ABAArACsAKwArACsAKwArACsAUAAEAAQABAAEAAQABAAEAAQABAAEAAQAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAA0ADQANAFAADgAOAA4ADQANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEACsABAAEAAQABAAEAAQABAAEAFAADQANAA0ADQANACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwAOABMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAArACsAKwAEACsABAAEACsABAAEAAQABAAEAAQABABQAAQAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAKwBQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQAKwAEAAQAKwAEAAQABAAEAAQAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAaABoAGgAaAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsADQANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAASABIAEgAQwBDAEMAUABQAFAAUABDAFAAUABQAEgAQwBIAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAASABDAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwAJAAkACQAJAAkACQAJABYAEQArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABIAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwANAA0AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEAAQABAANACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAA0ADQANAB4AHgAeAB4AHgAeAFAAUABQAFAADQAeACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAANAA0AHgAeACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwAEAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAARwBHABUARwAJACsAKwArACsAKwArACsAKwArACsAKwAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACsAKwArACsAKwArACsAKwBXAFcAVwBXAFcAVwBXAFcAVwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUQBRAFEAKwArACsAKwArACsAKwArACsAKwArACsAKwBRAFEAUQBRACsAKwArACsAKwArACsAKwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUAArACsAHgAEAAQADQAEAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArAB4AHgAeAB4AHgAeAB4AKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAAQABAAEAAQABAAeAB4AHgAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAB4AHgAEAAQABAAEAAQABAAEAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQAHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwBQAFAAKwArAFAAKwArAFAAUAArACsAUABQAFAAUAArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAUAArAFAAUABQAFAAUABQAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAHgAeAFAAUABQAFAAUAArAFAAKwArACsAUABQAFAAUABQAFAAUAArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeACsAKwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgAeAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgAeAB4AHgAeAB4ABAAeAB4AHgAeAB4AHgAeAB4AHgAeAAQAHgAeAA0ADQANAA0AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAAQABAAEAAQAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAEAAQAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArAAQABAAEAAQABAAEAAQAKwAEAAQAKwAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwAEAAQABAAEAAQABAAEAFAAUABQAFAAUABQAFAAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwBQAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArABsAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArAB4AHgAeAB4ABAAEAAQABAAEAAQABABQACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArABYAFgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAGgBQAFAAUAAaAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAKwBQACsAKwBQACsAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAKwBQACsAUAArACsAKwArACsAKwBQACsAKwArACsAUAArAFAAKwBQACsAUABQAFAAKwBQAFAAKwBQACsAKwBQACsAUAArAFAAKwBQACsAUAArAFAAUAArAFAAKwArAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUAArAFAAUABQAFAAKwBQACsAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAUABQAFAAKwBQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8AJQAlACUAHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB4AHgAeACUAJQAlAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAJQAlACUAJQAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAlACUAJQAlACUAHgAlACUAJQAlACUAIAAgACAAJQAlACAAJQAlACAAIAAgACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACEAIQAhACEAIQAlACUAIAAgACUAJQAgACAAIAAgACAAIAAgACAAIAAgACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAJQAlACUAIAAlACUAJQAlACAAIAAgACUAIAAgACAAJQAlACUAJQAlACUAJQAgACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAlAB4AJQAeACUAJQAlACUAJQAgACUAJQAlACUAHgAlAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAlACUAJQAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAJQAlACUAJQAgACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACAAIAAgACUAJQAlACAAIAAgACAAIAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABcAFwAXABUAFQAVAB4AHgAeAB4AJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAgACUAJQAlACUAJQAlACUAJQAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAgACUAJQAgACUAJQAlACUAJQAlACUAJQAgACAAIAAgACAAIAAgACAAJQAlACUAJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAgACAAIAAgACAAIAAgACAAIAAgACUAJQAgACAAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAgACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAlACAAIAAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAgACAAIAAlACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAJQAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAKwArAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwAlACUAJQAlACUAJQAlACUAJQAlACUAVwBXACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAKwAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAA==';
var LETTER_NUMBER_MODIFIER = 50;
// Non-tailorable Line Breaking Classes
var BK = 1; // Cause a line break (after)
var CR$1 = 2; // Cause a line break (after), except between CR and LF
var LF$1 = 3; // Cause a line break (after)
var CM = 4; // Prohibit a line break between the character and the preceding character
var NL = 5; // Cause a line break (after)
var WJ = 7; // Prohibit line breaks before and after
var ZW = 8; // Provide a break opportunity
var GL = 9; // Prohibit line breaks before and after
var SP = 10; // Enable indirect line breaks
var ZWJ$1 = 11; // Prohibit line breaks within joiner sequences
// Break Opportunities
var B2 = 12; // Provide a line break opportunity before and after the character
var BA = 13; // Generally provide a line break opportunity after the character
var BB = 14; // Generally provide a line break opportunity before the character
var HY = 15; // Provide a line break opportunity after the character, except in numeric context
var CB = 16; // Provide a line break opportunity contingent on additional information
// Characters Prohibiting Certain Breaks
var CL = 17; // Prohibit line breaks before
var CP = 18; // Prohibit line breaks before
var EX = 19; // Prohibit line breaks before
var IN = 20; // Allow only indirect line breaks between pairs
var NS = 21; // Allow only indirect line breaks before
var OP = 22; // Prohibit line breaks after
var QU = 23; // Act like they are both opening and closing
// Numeric Context
var IS = 24; // Prevent breaks after any and before numeric
var NU = 25; // Form numeric expressions for line breaking purposes
var PO = 26; // Do not break following a numeric expression
var PR = 27; // Do not break in front of a numeric expression
var SY = 28; // Prevent a break before; and allow a break after
// Other Characters
var AI = 29; // Act like AL when the resolvedEAW is N; otherwise; act as ID
var AL = 30; // Are alphabetic characters or symbols that are used with alphabetic characters
var CJ = 31; // Treat as NS or ID for strict or normal breaking.
var EB = 32; // Do not break from following Emoji Modifier
var EM = 33; // Do not break from preceding Emoji Base
var H2 = 34; // Form Korean syllable blocks
var H3 = 35; // Form Korean syllable blocks
var HL = 36; // Do not break around a following hyphen; otherwise act as Alphabetic
var ID = 37; // Break before or after; except in some numeric context
var JL = 38; // Form Korean syllable blocks
var JV = 39; // Form Korean syllable blocks
var JT = 40; // Form Korean syllable blocks
var RI$1 = 41; // Keep pairs together. For pairs; break before and after other classes
var SA = 42; // Provide a line break opportunity contingent on additional, language-specific context analysis
var XX = 43; // Have as yet unknown line breaking behavior or unassigned code positions
var ea_OP = [0x2329, 0xff08];
var BREAK_MANDATORY = '!';
var BREAK_NOT_ALLOWED$1 = '×';
var BREAK_ALLOWED$1 = '÷';
var UnicodeTrie$1 = createTrieFromBase64$1(base64$1);
var ALPHABETICS = [AL, HL];
var HARD_LINE_BREAKS = [BK, CR$1, LF$1, NL];
var SPACE$1 = [SP, ZW];
var PREFIX_POSTFIX = [PR, PO];
var LINE_BREAKS = HARD_LINE_BREAKS.concat(SPACE$1);
var KOREAN_SYLLABLE_BLOCK = [JL, JV, JT, H2, H3];
var HYPHEN = [HY, BA];
var codePointsToCharacterClasses = function (codePoints, lineBreak) {
if (lineBreak === void 0) { lineBreak = 'strict'; }
var types = [];
var indices = [];
var categories = [];
codePoints.forEach(function (codePoint, index) {
var classType = UnicodeTrie$1.get(codePoint);
if (classType > LETTER_NUMBER_MODIFIER) {
categories.push(true);
classType -= LETTER_NUMBER_MODIFIER;
}
else {
categories.push(false);
}
if (['normal', 'auto', 'loose'].indexOf(lineBreak) !== -1) {
// U+2010, U+2013, 〜 U+301C, U+30A0
if ([0x2010, 0x2013, 0x301c, 0x30a0].indexOf(codePoint) !== -1) {
indices.push(index);
return types.push(CB);
}
}
if (classType === CM || classType === ZWJ$1) {
// LB10 Treat any remaining combining mark or ZWJ as AL.
if (index === 0) {
indices.push(index);
return types.push(AL);
}
// LB9 Do not break a combining character sequence; treat it as if it has the line breaking class of
// the base character in all of the following rules. Treat ZWJ as if it were CM.
var prev = types[index - 1];
if (LINE_BREAKS.indexOf(prev) === -1) {
indices.push(indices[index - 1]);
return types.push(prev);
}
indices.push(index);
return types.push(AL);
}
indices.push(index);
if (classType === CJ) {
return types.push(lineBreak === 'strict' ? NS : ID);
}
if (classType === SA) {
return types.push(AL);
}
if (classType === AI) {
return types.push(AL);
}
// For supplementary characters, a useful default is to treat characters in the range 10000..1FFFD as AL
// and characters in the ranges 20000..2FFFD and 30000..3FFFD as ID, until the implementation can be revised
// to take into account the actual line breaking properties for these characters.
if (classType === XX) {
if ((codePoint >= 0x20000 && codePoint <= 0x2fffd) || (codePoint >= 0x30000 && codePoint <= 0x3fffd)) {
return types.push(ID);
}
else {
return types.push(AL);
}
}
types.push(classType);
});
return [indices, types, categories];
};
var isAdjacentWithSpaceIgnored = function (a, b, currentIndex, classTypes) {
var current = classTypes[currentIndex];
if (Array.isArray(a) ? a.indexOf(current) !== -1 : a === current) {
var i = currentIndex;
while (i <= classTypes.length) {
i++;
var next = classTypes[i];
if (next === b) {
return true;
}
if (next !== SP) {
break;
}
}
}
if (current === SP) {
var i = currentIndex;
while (i > 0) {
i--;
var prev = classTypes[i];
if (Array.isArray(a) ? a.indexOf(prev) !== -1 : a === prev) {
var n = currentIndex;
while (n <= classTypes.length) {
n++;
var next = classTypes[n];
if (next === b) {
return true;
}
if (next !== SP) {
break;
}
}
}
if (prev !== SP) {
break;
}
}
}
return false;
};
var previousNonSpaceClassType = function (currentIndex, classTypes) {
var i = currentIndex;
while (i >= 0) {
var type = classTypes[i];
if (type === SP) {
i--;
}
else {
return type;
}
}
return 0;
};
var _lineBreakAtIndex = function (codePoints, classTypes, indicies, index, forbiddenBreaks) {
if (indicies[index] === 0) {
return BREAK_NOT_ALLOWED$1;
}
var currentIndex = index - 1;
if (Array.isArray(forbiddenBreaks) && forbiddenBreaks[currentIndex] === true) {
return BREAK_NOT_ALLOWED$1;
}
var beforeIndex = currentIndex - 1;
var afterIndex = currentIndex + 1;
var current = classTypes[currentIndex];
// LB4 Always break after hard line breaks.
// LB5 Treat CR followed by LF, as well as CR, LF, and NL as hard line breaks.
var before = beforeIndex >= 0 ? classTypes[beforeIndex] : 0;
var next = classTypes[afterIndex];
if (current === CR$1 && next === LF$1) {
return BREAK_NOT_ALLOWED$1;
}
if (HARD_LINE_BREAKS.indexOf(current) !== -1) {
return BREAK_MANDATORY;
}
// LB6 Do not break before hard line breaks.
if (HARD_LINE_BREAKS.indexOf(next) !== -1) {
return BREAK_NOT_ALLOWED$1;
}
// LB7 Do not break before spaces or zero width space.
if (SPACE$1.indexOf(next) !== -1) {
return BREAK_NOT_ALLOWED$1;
}
// LB8 Break before any character following a zero-width space, even if one or more spaces intervene.
if (previousNonSpaceClassType(currentIndex, classTypes) === ZW) {
return BREAK_ALLOWED$1;
}
// LB8a Do not break after a zero width joiner.
if (UnicodeTrie$1.get(codePoints[currentIndex]) === ZWJ$1) {
return BREAK_NOT_ALLOWED$1;
}
// zwj emojis
if ((current === EB || current === EM) && UnicodeTrie$1.get(codePoints[afterIndex]) === ZWJ$1) {
return BREAK_NOT_ALLOWED$1;
}
// LB11 Do not break before or after Word joiner and related characters.
if (current === WJ || next === WJ) {
return BREAK_NOT_ALLOWED$1;
}
// LB12 Do not break after NBSP and related characters.
if (current === GL) {
return BREAK_NOT_ALLOWED$1;
}
// LB12a Do not break before NBSP and related characters, except after spaces and hyphens.
if ([SP, BA, HY].indexOf(current) === -1 && next === GL) {
return BREAK_NOT_ALLOWED$1;
}
// LB13 Do not break before ] or ! or ; or /, even after spaces.
if ([CL, CP, EX, IS, SY].indexOf(next) !== -1) {
return BREAK_NOT_ALLOWED$1;
}
// LB14 Do not break after [, even after spaces.
if (previousNonSpaceClassType(currentIndex, classTypes) === OP) {
return BREAK_NOT_ALLOWED$1;
}
// LB15 Do not break within ‘”[, even with intervening spaces.
if (isAdjacentWithSpaceIgnored(QU, OP, currentIndex, classTypes)) {
return BREAK_NOT_ALLOWED$1;
}
// LB16 Do not break between closing punctuation and a nonstarter (lb=NS), even with intervening spaces.
if (isAdjacentWithSpaceIgnored([CL, CP], NS, currentIndex, classTypes)) {
return BREAK_NOT_ALLOWED$1;
}
// LB17 Do not break within ‘——’, even with intervening spaces.
if (isAdjacentWithSpaceIgnored(B2, B2, currentIndex, classTypes)) {
return BREAK_NOT_ALLOWED$1;
}
// LB18 Break after spaces.
if (current === SP) {
return BREAK_ALLOWED$1;
}
// LB19 Do not break before or after quotation marks, such as .
if (current === QU || next === QU) {
return BREAK_NOT_ALLOWED$1;
}
// LB20 Break before and after unresolved CB.
if (next === CB || current === CB) {
return BREAK_ALLOWED$1;
}
// LB21 Do not break before hyphen-minus, other hyphens, fixed-width spaces, small kana, and other non-starters, or after acute accents.
if ([BA, HY, NS].indexOf(next) !== -1 || current === BB) {
return BREAK_NOT_ALLOWED$1;
}
// LB21a Don't break after Hebrew + Hyphen.
if (before === HL && HYPHEN.indexOf(current) !== -1) {
return BREAK_NOT_ALLOWED$1;
}
// LB21b Dont break between Solidus and Hebrew letters.
if (current === SY && next === HL) {
return BREAK_NOT_ALLOWED$1;
}
// LB22 Do not break before ellipsis.
if (next === IN) {
return BREAK_NOT_ALLOWED$1;
}
// LB23 Do not break between digits and letters.
if ((ALPHABETICS.indexOf(next) !== -1 && current === NU) || (ALPHABETICS.indexOf(current) !== -1 && next === NU)) {
return BREAK_NOT_ALLOWED$1;
}
// LB23a Do not break between numeric prefixes and ideographs, or between ideographs and numeric postfixes.
if ((current === PR && [ID, EB, EM].indexOf(next) !== -1) ||
([ID, EB, EM].indexOf(current) !== -1 && next === PO)) {
return BREAK_NOT_ALLOWED$1;
}
// LB24 Do not break between numeric prefix/postfix and letters, or between letters and prefix/postfix.
if ((ALPHABETICS.indexOf(current) !== -1 && PREFIX_POSTFIX.indexOf(next) !== -1) ||
(PREFIX_POSTFIX.indexOf(current) !== -1 && ALPHABETICS.indexOf(next) !== -1)) {
return BREAK_NOT_ALLOWED$1;
}
// LB25 Do not break between the following pairs of classes relevant to numbers:
if (
// (PR | PO) × ( OP | HY )? NU
([PR, PO].indexOf(current) !== -1 &&
(next === NU || ([OP, HY].indexOf(next) !== -1 && classTypes[afterIndex + 1] === NU))) ||
// ( OP | HY ) × NU
([OP, HY].indexOf(current) !== -1 && next === NU) ||
// NU × (NU | SY | IS)
(current === NU && [NU, SY, IS].indexOf(next) !== -1)) {
return BREAK_NOT_ALLOWED$1;
}
// NU (NU | SY | IS)* × (NU | SY | IS | CL | CP)
if ([NU, SY, IS, CL, CP].indexOf(next) !== -1) {
var prevIndex = currentIndex;
while (prevIndex >= 0) {
var type = classTypes[prevIndex];
if (type === NU) {
return BREAK_NOT_ALLOWED$1;
}
else if ([SY, IS].indexOf(type) !== -1) {
prevIndex--;
}
else {
break;
}
}
}
// NU (NU | SY | IS)* (CL | CP)? × (PO | PR))
if ([PR, PO].indexOf(next) !== -1) {
var prevIndex = [CL, CP].indexOf(current) !== -1 ? beforeIndex : currentIndex;
while (prevIndex >= 0) {
var type = classTypes[prevIndex];
if (type === NU) {
return BREAK_NOT_ALLOWED$1;
}
else if ([SY, IS].indexOf(type) !== -1) {
prevIndex--;
}
else {
break;
}
}
}
// LB26 Do not break a Korean syllable.
if ((JL === current && [JL, JV, H2, H3].indexOf(next) !== -1) ||
([JV, H2].indexOf(current) !== -1 && [JV, JT].indexOf(next) !== -1) ||
([JT, H3].indexOf(current) !== -1 && next === JT)) {
return BREAK_NOT_ALLOWED$1;
}
// LB27 Treat a Korean Syllable Block the same as ID.
if ((KOREAN_SYLLABLE_BLOCK.indexOf(current) !== -1 && [IN, PO].indexOf(next) !== -1) ||
(KOREAN_SYLLABLE_BLOCK.indexOf(next) !== -1 && current === PR)) {
return BREAK_NOT_ALLOWED$1;
}
// LB28 Do not break between alphabetics (“at”).
if (ALPHABETICS.indexOf(current) !== -1 && ALPHABETICS.indexOf(next) !== -1) {
return BREAK_NOT_ALLOWED$1;
}
// LB29 Do not break between numeric punctuation and alphabetics (“e.g.”).
if (current === IS && ALPHABETICS.indexOf(next) !== -1) {
return BREAK_NOT_ALLOWED$1;
}
// LB30 Do not break between letters, numbers, or ordinary symbols and opening or closing parentheses.
if ((ALPHABETICS.concat(NU).indexOf(current) !== -1 &&
next === OP &&
ea_OP.indexOf(codePoints[afterIndex]) === -1) ||
(ALPHABETICS.concat(NU).indexOf(next) !== -1 && current === CP)) {
return BREAK_NOT_ALLOWED$1;
}
// LB30a Break between two regional indicator symbols if and only if there are an even number of regional
// indicators preceding the position of the break.
if (current === RI$1 && next === RI$1) {
var i = indicies[currentIndex];
var count = 1;
while (i > 0) {
i--;
if (classTypes[i] === RI$1) {
count++;
}
else {
break;
}
}
if (count % 2 !== 0) {
return BREAK_NOT_ALLOWED$1;
}
}
// LB30b Do not break between an emoji base and an emoji modifier.
if (current === EB && next === EM) {
return BREAK_NOT_ALLOWED$1;
}
return BREAK_ALLOWED$1;
};
var cssFormattedClasses = function (codePoints, options) {
if (!options) {
options = { lineBreak: 'normal', wordBreak: 'normal' };
}
var _a = codePointsToCharacterClasses(codePoints, options.lineBreak), indicies = _a[0], classTypes = _a[1], isLetterNumber = _a[2];
if (options.wordBreak === 'break-all' || options.wordBreak === 'break-word') {
classTypes = classTypes.map(function (type) { return ([NU, AL, SA].indexOf(type) !== -1 ? ID : type); });
}
var forbiddenBreakpoints = options.wordBreak === 'keep-all'
? isLetterNumber.map(function (letterNumber, i) {
return letterNumber && codePoints[i] >= 0x4e00 && codePoints[i] <= 0x9fff;
})
: undefined;
return [indicies, classTypes, forbiddenBreakpoints];
};
var Break = /** @class */ (function () {
function Break(codePoints, lineBreak, start, end) {
this.codePoints = codePoints;
this.required = lineBreak === BREAK_MANDATORY;
this.start = start;
this.end = end;
}
Break.prototype.slice = function () {
return fromCodePoint$1.apply(void 0, this.codePoints.slice(this.start, this.end));
};
return Break;
}());
var LineBreaker = function (str, options) {
var codePoints = toCodePoints$1(str);
var _a = cssFormattedClasses(codePoints, options), indicies = _a[0], classTypes = _a[1], forbiddenBreakpoints = _a[2];
var length = codePoints.length;
var lastEnd = 0;
var nextIndex = 0;
return {
next: function () {
if (nextIndex >= length) {
return { done: true, value: null };
}
var lineBreak = BREAK_NOT_ALLOWED$1;
while (nextIndex < length &&
(lineBreak = _lineBreakAtIndex(codePoints, classTypes, indicies, ++nextIndex, forbiddenBreakpoints)) ===
BREAK_NOT_ALLOWED$1) { }
if (lineBreak !== BREAK_NOT_ALLOWED$1 || nextIndex === length) {
var value = new Break(codePoints, lineBreak, lastEnd, nextIndex);
lastEnd = nextIndex;
return { value: value, done: false };
}
return { done: true, value: null };
},
};
};
// https://www.w3.org/TR/css-syntax-3
var FLAG_UNRESTRICTED = 1 << 0;
var FLAG_ID = 1 << 1;
var FLAG_INTEGER = 1 << 2;
var FLAG_NUMBER = 1 << 3;
var LINE_FEED = 0x000a;
var SOLIDUS = 0x002f;
var REVERSE_SOLIDUS = 0x005c;
var CHARACTER_TABULATION = 0x0009;
var SPACE = 0x0020;
var QUOTATION_MARK = 0x0022;
var EQUALS_SIGN = 0x003d;
var NUMBER_SIGN = 0x0023;
var DOLLAR_SIGN = 0x0024;
var PERCENTAGE_SIGN = 0x0025;
var APOSTROPHE = 0x0027;
var LEFT_PARENTHESIS = 0x0028;
var RIGHT_PARENTHESIS = 0x0029;
var LOW_LINE = 0x005f;
var HYPHEN_MINUS = 0x002d;
var EXCLAMATION_MARK = 0x0021;
var LESS_THAN_SIGN = 0x003c;
var GREATER_THAN_SIGN = 0x003e;
var COMMERCIAL_AT = 0x0040;
var LEFT_SQUARE_BRACKET = 0x005b;
var RIGHT_SQUARE_BRACKET = 0x005d;
var CIRCUMFLEX_ACCENT = 0x003d;
var LEFT_CURLY_BRACKET = 0x007b;
var QUESTION_MARK = 0x003f;
var RIGHT_CURLY_BRACKET = 0x007d;
var VERTICAL_LINE = 0x007c;
var TILDE = 0x007e;
var CONTROL = 0x0080;
var REPLACEMENT_CHARACTER = 0xfffd;
var ASTERISK = 0x002a;
var PLUS_SIGN = 0x002b;
var COMMA = 0x002c;
var COLON = 0x003a;
var SEMICOLON = 0x003b;
var FULL_STOP = 0x002e;
var NULL = 0x0000;
var BACKSPACE = 0x0008;
var LINE_TABULATION = 0x000b;
var SHIFT_OUT = 0x000e;
var INFORMATION_SEPARATOR_ONE = 0x001f;
var DELETE = 0x007f;
var EOF = -1;
var ZERO = 0x0030;
var a = 0x0061;
var e = 0x0065;
var f = 0x0066;
var u = 0x0075;
var z = 0x007a;
var A = 0x0041;
var E = 0x0045;
var F = 0x0046;
var U = 0x0055;
var Z = 0x005a;
var isDigit = function (codePoint) { return codePoint >= ZERO && codePoint <= 0x0039; };
var isSurrogateCodePoint = function (codePoint) { return codePoint >= 0xd800 && codePoint <= 0xdfff; };
var isHex = function (codePoint) {
return isDigit(codePoint) || (codePoint >= A && codePoint <= F) || (codePoint >= a && codePoint <= f);
};
var isLowerCaseLetter = function (codePoint) { return codePoint >= a && codePoint <= z; };
var isUpperCaseLetter = function (codePoint) { return codePoint >= A && codePoint <= Z; };
var isLetter = function (codePoint) { return isLowerCaseLetter(codePoint) || isUpperCaseLetter(codePoint); };
var isNonASCIICodePoint = function (codePoint) { return codePoint >= CONTROL; };
var isWhiteSpace = function (codePoint) {
return codePoint === LINE_FEED || codePoint === CHARACTER_TABULATION || codePoint === SPACE;
};
var isNameStartCodePoint = function (codePoint) {
return isLetter(codePoint) || isNonASCIICodePoint(codePoint) || codePoint === LOW_LINE;
};
var isNameCodePoint = function (codePoint) {
return isNameStartCodePoint(codePoint) || isDigit(codePoint) || codePoint === HYPHEN_MINUS;
};
var isNonPrintableCodePoint = function (codePoint) {
return ((codePoint >= NULL && codePoint <= BACKSPACE) ||
codePoint === LINE_TABULATION ||
(codePoint >= SHIFT_OUT && codePoint <= INFORMATION_SEPARATOR_ONE) ||
codePoint === DELETE);
};
var isValidEscape = function (c1, c2) {
if (c1 !== REVERSE_SOLIDUS) {
return false;
}
return c2 !== LINE_FEED;
};
var isIdentifierStart = function (c1, c2, c3) {
if (c1 === HYPHEN_MINUS) {
return isNameStartCodePoint(c2) || isValidEscape(c2, c3);
}
else if (isNameStartCodePoint(c1)) {
return true;
}
else if (c1 === REVERSE_SOLIDUS && isValidEscape(c1, c2)) {
return true;
}
return false;
};
var isNumberStart = function (c1, c2, c3) {
if (c1 === PLUS_SIGN || c1 === HYPHEN_MINUS) {
if (isDigit(c2)) {
return true;
}
return c2 === FULL_STOP && isDigit(c3);
}
if (c1 === FULL_STOP) {
return isDigit(c2);
}
return isDigit(c1);
};
var stringToNumber = function (codePoints) {
var c = 0;
var sign = 1;
if (codePoints[c] === PLUS_SIGN || codePoints[c] === HYPHEN_MINUS) {
if (codePoints[c] === HYPHEN_MINUS) {
sign = -1;
}
c++;
}
var integers = [];
while (isDigit(codePoints[c])) {
integers.push(codePoints[c++]);
}
var int = integers.length ? parseInt(fromCodePoint$1.apply(void 0, integers), 10) : 0;
if (codePoints[c] === FULL_STOP) {
c++;
}
var fraction = [];
while (isDigit(codePoints[c])) {
fraction.push(codePoints[c++]);
}
var fracd = fraction.length;
var frac = fracd ? parseInt(fromCodePoint$1.apply(void 0, fraction), 10) : 0;
if (codePoints[c] === E || codePoints[c] === e) {
c++;
}
var expsign = 1;
if (codePoints[c] === PLUS_SIGN || codePoints[c] === HYPHEN_MINUS) {
if (codePoints[c] === HYPHEN_MINUS) {
expsign = -1;
}
c++;
}
var exponent = [];
while (isDigit(codePoints[c])) {
exponent.push(codePoints[c++]);
}
var exp = exponent.length ? parseInt(fromCodePoint$1.apply(void 0, exponent), 10) : 0;
return sign * (int + frac * Math.pow(10, -fracd)) * Math.pow(10, expsign * exp);
};
var LEFT_PARENTHESIS_TOKEN = {
type: 2 /* LEFT_PARENTHESIS_TOKEN */
};
var RIGHT_PARENTHESIS_TOKEN = {
type: 3 /* RIGHT_PARENTHESIS_TOKEN */
};
var COMMA_TOKEN = { type: 4 /* COMMA_TOKEN */ };
var SUFFIX_MATCH_TOKEN = { type: 13 /* SUFFIX_MATCH_TOKEN */ };
var PREFIX_MATCH_TOKEN = { type: 8 /* PREFIX_MATCH_TOKEN */ };
var COLUMN_TOKEN = { type: 21 /* COLUMN_TOKEN */ };
var DASH_MATCH_TOKEN = { type: 9 /* DASH_MATCH_TOKEN */ };
var INCLUDE_MATCH_TOKEN = { type: 10 /* INCLUDE_MATCH_TOKEN */ };
var LEFT_CURLY_BRACKET_TOKEN = {
type: 11 /* LEFT_CURLY_BRACKET_TOKEN */
};
var RIGHT_CURLY_BRACKET_TOKEN = {
type: 12 /* RIGHT_CURLY_BRACKET_TOKEN */
};
var SUBSTRING_MATCH_TOKEN = { type: 14 /* SUBSTRING_MATCH_TOKEN */ };
var BAD_URL_TOKEN = { type: 23 /* BAD_URL_TOKEN */ };
var BAD_STRING_TOKEN = { type: 1 /* BAD_STRING_TOKEN */ };
var CDO_TOKEN = { type: 25 /* CDO_TOKEN */ };
var CDC_TOKEN = { type: 24 /* CDC_TOKEN */ };
var COLON_TOKEN = { type: 26 /* COLON_TOKEN */ };
var SEMICOLON_TOKEN = { type: 27 /* SEMICOLON_TOKEN */ };
var LEFT_SQUARE_BRACKET_TOKEN = {
type: 28 /* LEFT_SQUARE_BRACKET_TOKEN */
};
var RIGHT_SQUARE_BRACKET_TOKEN = {
type: 29 /* RIGHT_SQUARE_BRACKET_TOKEN */
};
var WHITESPACE_TOKEN = { type: 31 /* WHITESPACE_TOKEN */ };
var EOF_TOKEN = { type: 32 /* EOF_TOKEN */ };
var Tokenizer = /** @class */ (function () {
function Tokenizer() {
this._value = [];
}
Tokenizer.prototype.write = function (chunk) {
this._value = this._value.concat(toCodePoints$1(chunk));
};
Tokenizer.prototype.read = function () {
var tokens = [];
var token = this.consumeToken();
while (token !== EOF_TOKEN) {
tokens.push(token);
token = this.consumeToken();
}
return tokens;
};
Tokenizer.prototype.consumeToken = function () {
var codePoint = this.consumeCodePoint();
switch (codePoint) {
case QUOTATION_MARK:
return this.consumeStringToken(QUOTATION_MARK);
case NUMBER_SIGN:
var c1 = this.peekCodePoint(0);
var c2 = this.peekCodePoint(1);
var c3 = this.peekCodePoint(2);
if (isNameCodePoint(c1) || isValidEscape(c2, c3)) {
var flags = isIdentifierStart(c1, c2, c3) ? FLAG_ID : FLAG_UNRESTRICTED;
var value = this.consumeName();
return { type: 5 /* HASH_TOKEN */, value: value, flags: flags };
}
break;
case DOLLAR_SIGN:
if (this.peekCodePoint(0) === EQUALS_SIGN) {
this.consumeCodePoint();
return SUFFIX_MATCH_TOKEN;
}
break;
case APOSTROPHE:
return this.consumeStringToken(APOSTROPHE);
case LEFT_PARENTHESIS:
return LEFT_PARENTHESIS_TOKEN;
case RIGHT_PARENTHESIS:
return RIGHT_PARENTHESIS_TOKEN;
case ASTERISK:
if (this.peekCodePoint(0) === EQUALS_SIGN) {
this.consumeCodePoint();
return SUBSTRING_MATCH_TOKEN;
}
break;
case PLUS_SIGN:
if (isNumberStart(codePoint, this.peekCodePoint(0), this.peekCodePoint(1))) {
this.reconsumeCodePoint(codePoint);
return this.consumeNumericToken();
}
break;
case COMMA:
return COMMA_TOKEN;
case HYPHEN_MINUS:
var e1 = codePoint;
var e2 = this.peekCodePoint(0);
var e3 = this.peekCodePoint(1);
if (isNumberStart(e1, e2, e3)) {
this.reconsumeCodePoint(codePoint);
return this.consumeNumericToken();
}
if (isIdentifierStart(e1, e2, e3)) {
this.reconsumeCodePoint(codePoint);
return this.consumeIdentLikeToken();
}
if (e2 === HYPHEN_MINUS && e3 === GREATER_THAN_SIGN) {
this.consumeCodePoint();
this.consumeCodePoint();
return CDC_TOKEN;
}
break;
case FULL_STOP:
if (isNumberStart(codePoint, this.peekCodePoint(0), this.peekCodePoint(1))) {
this.reconsumeCodePoint(codePoint);
return this.consumeNumericToken();
}
break;
case SOLIDUS:
if (this.peekCodePoint(0) === ASTERISK) {
this.consumeCodePoint();
while (true) {
var c = this.consumeCodePoint();
if (c === ASTERISK) {
c = this.consumeCodePoint();
if (c === SOLIDUS) {
return this.consumeToken();
}
}
if (c === EOF) {
return this.consumeToken();
}
}
}
break;
case COLON:
return COLON_TOKEN;
case SEMICOLON:
return SEMICOLON_TOKEN;
case LESS_THAN_SIGN:
if (this.peekCodePoint(0) === EXCLAMATION_MARK &&
this.peekCodePoint(1) === HYPHEN_MINUS &&
this.peekCodePoint(2) === HYPHEN_MINUS) {
this.consumeCodePoint();
this.consumeCodePoint();
return CDO_TOKEN;
}
break;
case COMMERCIAL_AT:
var a1 = this.peekCodePoint(0);
var a2 = this.peekCodePoint(1);
var a3 = this.peekCodePoint(2);
if (isIdentifierStart(a1, a2, a3)) {
var value = this.consumeName();
return { type: 7 /* AT_KEYWORD_TOKEN */, value: value };
}
break;
case LEFT_SQUARE_BRACKET:
return LEFT_SQUARE_BRACKET_TOKEN;
case REVERSE_SOLIDUS:
if (isValidEscape(codePoint, this.peekCodePoint(0))) {
this.reconsumeCodePoint(codePoint);
return this.consumeIdentLikeToken();
}
break;
case RIGHT_SQUARE_BRACKET:
return RIGHT_SQUARE_BRACKET_TOKEN;
case CIRCUMFLEX_ACCENT:
if (this.peekCodePoint(0) === EQUALS_SIGN) {
this.consumeCodePoint();
return PREFIX_MATCH_TOKEN;
}
break;
case LEFT_CURLY_BRACKET:
return LEFT_CURLY_BRACKET_TOKEN;
case RIGHT_CURLY_BRACKET:
return RIGHT_CURLY_BRACKET_TOKEN;
case u:
case U:
var u1 = this.peekCodePoint(0);
var u2 = this.peekCodePoint(1);
if (u1 === PLUS_SIGN && (isHex(u2) || u2 === QUESTION_MARK)) {
this.consumeCodePoint();
this.consumeUnicodeRangeToken();
}
this.reconsumeCodePoint(codePoint);
return this.consumeIdentLikeToken();
case VERTICAL_LINE:
if (this.peekCodePoint(0) === EQUALS_SIGN) {
this.consumeCodePoint();
return DASH_MATCH_TOKEN;
}
if (this.peekCodePoint(0) === VERTICAL_LINE) {
this.consumeCodePoint();
return COLUMN_TOKEN;
}
break;
case TILDE:
if (this.peekCodePoint(0) === EQUALS_SIGN) {
this.consumeCodePoint();
return INCLUDE_MATCH_TOKEN;
}
break;
case EOF:
return EOF_TOKEN;
}
if (isWhiteSpace(codePoint)) {
this.consumeWhiteSpace();
return WHITESPACE_TOKEN;
}
if (isDigit(codePoint)) {
this.reconsumeCodePoint(codePoint);
return this.consumeNumericToken();
}
if (isNameStartCodePoint(codePoint)) {
this.reconsumeCodePoint(codePoint);
return this.consumeIdentLikeToken();
}
return { type: 6 /* DELIM_TOKEN */, value: fromCodePoint$1(codePoint) };
};
Tokenizer.prototype.consumeCodePoint = function () {
var value = this._value.shift();
return typeof value === 'undefined' ? -1 : value;
};
Tokenizer.prototype.reconsumeCodePoint = function (codePoint) {
this._value.unshift(codePoint);
};
Tokenizer.prototype.peekCodePoint = function (delta) {
if (delta >= this._value.length) {
return -1;
}
return this._value[delta];
};
Tokenizer.prototype.consumeUnicodeRangeToken = function () {
var digits = [];
var codePoint = this.consumeCodePoint();
while (isHex(codePoint) && digits.length < 6) {
digits.push(codePoint);
codePoint = this.consumeCodePoint();
}
var questionMarks = false;
while (codePoint === QUESTION_MARK && digits.length < 6) {
digits.push(codePoint);
codePoint = this.consumeCodePoint();
questionMarks = true;
}
if (questionMarks) {
var start_1 = parseInt(fromCodePoint$1.apply(void 0, digits.map(function (digit) { return (digit === QUESTION_MARK ? ZERO : digit); })), 16);
var end = parseInt(fromCodePoint$1.apply(void 0, digits.map(function (digit) { return (digit === QUESTION_MARK ? F : digit); })), 16);
return { type: 30 /* UNICODE_RANGE_TOKEN */, start: start_1, end: end };
}
var start = parseInt(fromCodePoint$1.apply(void 0, digits), 16);
if (this.peekCodePoint(0) === HYPHEN_MINUS && isHex(this.peekCodePoint(1))) {
this.consumeCodePoint();
codePoint = this.consumeCodePoint();
var endDigits = [];
while (isHex(codePoint) && endDigits.length < 6) {
endDigits.push(codePoint);
codePoint = this.consumeCodePoint();
}
var end = parseInt(fromCodePoint$1.apply(void 0, endDigits), 16);
return { type: 30 /* UNICODE_RANGE_TOKEN */, start: start, end: end };
}
else {
return { type: 30 /* UNICODE_RANGE_TOKEN */, start: start, end: start };
}
};
Tokenizer.prototype.consumeIdentLikeToken = function () {
var value = this.consumeName();
if (value.toLowerCase() === 'url' && this.peekCodePoint(0) === LEFT_PARENTHESIS) {
this.consumeCodePoint();
return this.consumeUrlToken();
}
else if (this.peekCodePoint(0) === LEFT_PARENTHESIS) {
this.consumeCodePoint();
return { type: 19 /* FUNCTION_TOKEN */, value: value };
}
return { type: 20 /* IDENT_TOKEN */, value: value };
};
Tokenizer.prototype.consumeUrlToken = function () {
var value = [];
this.consumeWhiteSpace();
if (this.peekCodePoint(0) === EOF) {
return { type: 22 /* URL_TOKEN */, value: '' };
}
var next = this.peekCodePoint(0);
if (next === APOSTROPHE || next === QUOTATION_MARK) {
var stringToken = this.consumeStringToken(this.consumeCodePoint());
if (stringToken.type === 0 /* STRING_TOKEN */) {
this.consumeWhiteSpace();
if (this.peekCodePoint(0) === EOF || this.peekCodePoint(0) === RIGHT_PARENTHESIS) {
this.consumeCodePoint();
return { type: 22 /* URL_TOKEN */, value: stringToken.value };
}
}
this.consumeBadUrlRemnants();
return BAD_URL_TOKEN;
}
while (true) {
var codePoint = this.consumeCodePoint();
if (codePoint === EOF || codePoint === RIGHT_PARENTHESIS) {
return { type: 22 /* URL_TOKEN */, value: fromCodePoint$1.apply(void 0, value) };
}
else if (isWhiteSpace(codePoint)) {
this.consumeWhiteSpace();
if (this.peekCodePoint(0) === EOF || this.peekCodePoint(0) === RIGHT_PARENTHESIS) {
this.consumeCodePoint();
return { type: 22 /* URL_TOKEN */, value: fromCodePoint$1.apply(void 0, value) };
}
this.consumeBadUrlRemnants();
return BAD_URL_TOKEN;
}
else if (codePoint === QUOTATION_MARK ||
codePoint === APOSTROPHE ||
codePoint === LEFT_PARENTHESIS ||
isNonPrintableCodePoint(codePoint)) {
this.consumeBadUrlRemnants();
return BAD_URL_TOKEN;
}
else if (codePoint === REVERSE_SOLIDUS) {
if (isValidEscape(codePoint, this.peekCodePoint(0))) {
value.push(this.consumeEscapedCodePoint());
}
else {
this.consumeBadUrlRemnants();
return BAD_URL_TOKEN;
}
}
else {
value.push(codePoint);
}
}
};
Tokenizer.prototype.consumeWhiteSpace = function () {
while (isWhiteSpace(this.peekCodePoint(0))) {
this.consumeCodePoint();
}
};
Tokenizer.prototype.consumeBadUrlRemnants = function () {
while (true) {
var codePoint = this.consumeCodePoint();
if (codePoint === RIGHT_PARENTHESIS || codePoint === EOF) {
return;
}
if (isValidEscape(codePoint, this.peekCodePoint(0))) {
this.consumeEscapedCodePoint();
}
}
};
Tokenizer.prototype.consumeStringSlice = function (count) {
var SLICE_STACK_SIZE = 50000;
var value = '';
while (count > 0) {
var amount = Math.min(SLICE_STACK_SIZE, count);
value += fromCodePoint$1.apply(void 0, this._value.splice(0, amount));
count -= amount;
}
this._value.shift();
return value;
};
Tokenizer.prototype.consumeStringToken = function (endingCodePoint) {
var value = '';
var i = 0;
do {
var codePoint = this._value[i];
if (codePoint === EOF || codePoint === undefined || codePoint === endingCodePoint) {
value += this.consumeStringSlice(i);
return { type: 0 /* STRING_TOKEN */, value: value };
}
if (codePoint === LINE_FEED) {
this._value.splice(0, i);
return BAD_STRING_TOKEN;
}
if (codePoint === REVERSE_SOLIDUS) {
var next = this._value[i + 1];
if (next !== EOF && next !== undefined) {
if (next === LINE_FEED) {
value += this.consumeStringSlice(i);
i = -1;
this._value.shift();
}
else if (isValidEscape(codePoint, next)) {
value += this.consumeStringSlice(i);
value += fromCodePoint$1(this.consumeEscapedCodePoint());
i = -1;
}
}
}
i++;
} while (true);
};
Tokenizer.prototype.consumeNumber = function () {
var repr = [];
var type = FLAG_INTEGER;
var c1 = this.peekCodePoint(0);
if (c1 === PLUS_SIGN || c1 === HYPHEN_MINUS) {
repr.push(this.consumeCodePoint());
}
while (isDigit(this.peekCodePoint(0))) {
repr.push(this.consumeCodePoint());
}
c1 = this.peekCodePoint(0);
var c2 = this.peekCodePoint(1);
if (c1 === FULL_STOP && isDigit(c2)) {
repr.push(this.consumeCodePoint(), this.consumeCodePoint());
type = FLAG_NUMBER;
while (isDigit(this.peekCodePoint(0))) {
repr.push(this.consumeCodePoint());
}
}
c1 = this.peekCodePoint(0);
c2 = this.peekCodePoint(1);
var c3 = this.peekCodePoint(2);
if ((c1 === E || c1 === e) && (((c2 === PLUS_SIGN || c2 === HYPHEN_MINUS) && isDigit(c3)) || isDigit(c2))) {
repr.push(this.consumeCodePoint(), this.consumeCodePoint());
type = FLAG_NUMBER;
while (isDigit(this.peekCodePoint(0))) {
repr.push(this.consumeCodePoint());
}
}
return [stringToNumber(repr), type];
};
Tokenizer.prototype.consumeNumericToken = function () {
var _a = this.consumeNumber(), number = _a[0], flags = _a[1];
var c1 = this.peekCodePoint(0);
var c2 = this.peekCodePoint(1);
var c3 = this.peekCodePoint(2);
if (isIdentifierStart(c1, c2, c3)) {
var unit = this.consumeName();
return { type: 15 /* DIMENSION_TOKEN */, number: number, flags: flags, unit: unit };
}
if (c1 === PERCENTAGE_SIGN) {
this.consumeCodePoint();
return { type: 16 /* PERCENTAGE_TOKEN */, number: number, flags: flags };
}
return { type: 17 /* NUMBER_TOKEN */, number: number, flags: flags };
};
Tokenizer.prototype.consumeEscapedCodePoint = function () {
var codePoint = this.consumeCodePoint();
if (isHex(codePoint)) {
var hex = fromCodePoint$1(codePoint);
while (isHex(this.peekCodePoint(0)) && hex.length < 6) {
hex += fromCodePoint$1(this.consumeCodePoint());
}
if (isWhiteSpace(this.peekCodePoint(0))) {
this.consumeCodePoint();
}
var hexCodePoint = parseInt(hex, 16);
if (hexCodePoint === 0 || isSurrogateCodePoint(hexCodePoint) || hexCodePoint > 0x10ffff) {
return REPLACEMENT_CHARACTER;
}
return hexCodePoint;
}
if (codePoint === EOF) {
return REPLACEMENT_CHARACTER;
}
return codePoint;
};
Tokenizer.prototype.consumeName = function () {
var result = '';
while (true) {
var codePoint = this.consumeCodePoint();
if (isNameCodePoint(codePoint)) {
result += fromCodePoint$1(codePoint);
}
else if (isValidEscape(codePoint, this.peekCodePoint(0))) {
result += fromCodePoint$1(this.consumeEscapedCodePoint());
}
else {
this.reconsumeCodePoint(codePoint);
return result;
}
}
};
return Tokenizer;
}());
var Parser = /** @class */ (function () {
function Parser(tokens) {
this._tokens = tokens;
}
Parser.create = function (value) {
var tokenizer = new Tokenizer();
tokenizer.write(value);
return new Parser(tokenizer.read());
};
Parser.parseValue = function (value) {
return Parser.create(value).parseComponentValue();
};
Parser.parseValues = function (value) {
return Parser.create(value).parseComponentValues();
};
Parser.prototype.parseComponentValue = function () {
var token = this.consumeToken();
while (token.type === 31 /* WHITESPACE_TOKEN */) {
token = this.consumeToken();
}
if (token.type === 32 /* EOF_TOKEN */) {
throw new SyntaxError("Error parsing CSS component value, unexpected EOF");
}
this.reconsumeToken(token);
var value = this.consumeComponentValue();
do {
token = this.consumeToken();
} while (token.type === 31 /* WHITESPACE_TOKEN */);
if (token.type === 32 /* EOF_TOKEN */) {
return value;
}
throw new SyntaxError("Error parsing CSS component value, multiple values found when expecting only one");
};
Parser.prototype.parseComponentValues = function () {
var values = [];
while (true) {
var value = this.consumeComponentValue();
if (value.type === 32 /* EOF_TOKEN */) {
return values;
}
values.push(value);
values.push();
}
};
Parser.prototype.consumeComponentValue = function () {
var token = this.consumeToken();
switch (token.type) {
case 11 /* LEFT_CURLY_BRACKET_TOKEN */:
case 28 /* LEFT_SQUARE_BRACKET_TOKEN */:
case 2 /* LEFT_PARENTHESIS_TOKEN */:
return this.consumeSimpleBlock(token.type);
case 19 /* FUNCTION_TOKEN */:
return this.consumeFunction(token);
}
return token;
};
Parser.prototype.consumeSimpleBlock = function (type) {
var block = { type: type, values: [] };
var token = this.consumeToken();
while (true) {
if (token.type === 32 /* EOF_TOKEN */ || isEndingTokenFor(token, type)) {
return block;
}
this.reconsumeToken(token);
block.values.push(this.consumeComponentValue());
token = this.consumeToken();
}
};
Parser.prototype.consumeFunction = function (functionToken) {
var cssFunction = {
name: functionToken.value,
values: [],
type: 18 /* FUNCTION */
};
while (true) {
var token = this.consumeToken();
if (token.type === 32 /* EOF_TOKEN */ || token.type === 3 /* RIGHT_PARENTHESIS_TOKEN */) {
return cssFunction;
}
this.reconsumeToken(token);
cssFunction.values.push(this.consumeComponentValue());
}
};
Parser.prototype.consumeToken = function () {
var token = this._tokens.shift();
return typeof token === 'undefined' ? EOF_TOKEN : token;
};
Parser.prototype.reconsumeToken = function (token) {
this._tokens.unshift(token);
};
return Parser;
}());
var isDimensionToken = function (token) { return token.type === 15 /* DIMENSION_TOKEN */; };
var isNumberToken = function (token) { return token.type === 17 /* NUMBER_TOKEN */; };
var isIdentToken = function (token) { return token.type === 20 /* IDENT_TOKEN */; };
var isStringToken = function (token) { return token.type === 0 /* STRING_TOKEN */; };
var isIdentWithValue = function (token, value) {
return isIdentToken(token) && token.value === value;
};
var nonWhiteSpace = function (token) { return token.type !== 31 /* WHITESPACE_TOKEN */; };
var nonFunctionArgSeparator = function (token) {
return token.type !== 31 /* WHITESPACE_TOKEN */ && token.type !== 4 /* COMMA_TOKEN */;
};
var parseFunctionArgs = function (tokens) {
var args = [];
var arg = [];
tokens.forEach(function (token) {
if (token.type === 4 /* COMMA_TOKEN */) {
if (arg.length === 0) {
throw new Error("Error parsing function args, zero tokens for arg");
}
args.push(arg);
arg = [];
return;
}
if (token.type !== 31 /* WHITESPACE_TOKEN */) {
arg.push(token);
}
});
if (arg.length) {
args.push(arg);
}
return args;
};
var isEndingTokenFor = function (token, type) {
if (type === 11 /* LEFT_CURLY_BRACKET_TOKEN */ && token.type === 12 /* RIGHT_CURLY_BRACKET_TOKEN */) {
return true;
}
if (type === 28 /* LEFT_SQUARE_BRACKET_TOKEN */ && token.type === 29 /* RIGHT_SQUARE_BRACKET_TOKEN */) {
return true;
}
return type === 2 /* LEFT_PARENTHESIS_TOKEN */ && token.type === 3 /* RIGHT_PARENTHESIS_TOKEN */;
};
var isLength = function (token) {
return token.type === 17 /* NUMBER_TOKEN */ || token.type === 15 /* DIMENSION_TOKEN */;
};
var isLengthPercentage = function (token) {
return token.type === 16 /* PERCENTAGE_TOKEN */ || isLength(token);
};
var parseLengthPercentageTuple = function (tokens) {
return tokens.length > 1 ? [tokens[0], tokens[1]] : [tokens[0]];
};
var ZERO_LENGTH = {
type: 17 /* NUMBER_TOKEN */,
number: 0,
flags: FLAG_INTEGER
};
var FIFTY_PERCENT = {
type: 16 /* PERCENTAGE_TOKEN */,
number: 50,
flags: FLAG_INTEGER
};
var HUNDRED_PERCENT = {
type: 16 /* PERCENTAGE_TOKEN */,
number: 100,
flags: FLAG_INTEGER
};
var getAbsoluteValueForTuple = function (tuple, width, height) {
var x = tuple[0], y = tuple[1];
return [getAbsoluteValue(x, width), getAbsoluteValue(typeof y !== 'undefined' ? y : x, height)];
};
var getAbsoluteValue = function (token, parent) {
if (token.type === 16 /* PERCENTAGE_TOKEN */) {
return (token.number / 100) * parent;
}
if (isDimensionToken(token)) {
switch (token.unit) {
case 'rem':
case 'em':
return 16 * token.number; // TODO use correct font-size
case 'px':
default:
return token.number;
}
}
return token.number;
};
var DEG = 'deg';
var GRAD = 'grad';
var RAD = 'rad';
var TURN = 'turn';
var angle = {
name: 'angle',
parse: function (_context, value) {
if (value.type === 15 /* DIMENSION_TOKEN */) {
switch (value.unit) {
case DEG:
return (Math.PI * value.number) / 180;
case GRAD:
return (Math.PI / 200) * value.number;
case RAD:
return value.number;
case TURN:
return Math.PI * 2 * value.number;
}
}
throw new Error("Unsupported angle type");
}
};
var isAngle = function (value) {
if (value.type === 15 /* DIMENSION_TOKEN */) {
if (value.unit === DEG || value.unit === GRAD || value.unit === RAD || value.unit === TURN) {
return true;
}
}
return false;
};
var parseNamedSide = function (tokens) {
var sideOrCorner = tokens
.filter(isIdentToken)
.map(function (ident) { return ident.value; })
.join(' ');
switch (sideOrCorner) {
case 'to bottom right':
case 'to right bottom':
case 'left top':
case 'top left':
return [ZERO_LENGTH, ZERO_LENGTH];
case 'to top':
case 'bottom':
return deg(0);
case 'to bottom left':
case 'to left bottom':
case 'right top':
case 'top right':
return [ZERO_LENGTH, HUNDRED_PERCENT];
case 'to right':
case 'left':
return deg(90);
case 'to top left':
case 'to left top':
case 'right bottom':
case 'bottom right':
return [HUNDRED_PERCENT, HUNDRED_PERCENT];
case 'to bottom':
case 'top':
return deg(180);
case 'to top right':
case 'to right top':
case 'left bottom':
case 'bottom left':
return [HUNDRED_PERCENT, ZERO_LENGTH];
case 'to left':
case 'right':
return deg(270);
}
return 0;
};
var deg = function (deg) { return (Math.PI * deg) / 180; };
var color$1 = {
name: 'color',
parse: function (context, value) {
if (value.type === 18 /* FUNCTION */) {
var colorFunction = SUPPORTED_COLOR_FUNCTIONS[value.name];
if (typeof colorFunction === 'undefined') {
throw new Error("Attempting to parse an unsupported color function \"" + value.name + "\"");
}
return colorFunction(context, value.values);
}
if (value.type === 5 /* HASH_TOKEN */) {
if (value.value.length === 3) {
var r = value.value.substring(0, 1);
var g = value.value.substring(1, 2);
var b = value.value.substring(2, 3);
return pack(parseInt(r + r, 16), parseInt(g + g, 16), parseInt(b + b, 16), 1);
}
if (value.value.length === 4) {
var r = value.value.substring(0, 1);
var g = value.value.substring(1, 2);
var b = value.value.substring(2, 3);
var a = value.value.substring(3, 4);
return pack(parseInt(r + r, 16), parseInt(g + g, 16), parseInt(b + b, 16), parseInt(a + a, 16) / 255);
}
if (value.value.length === 6) {
var r = value.value.substring(0, 2);
var g = value.value.substring(2, 4);
var b = value.value.substring(4, 6);
return pack(parseInt(r, 16), parseInt(g, 16), parseInt(b, 16), 1);
}
if (value.value.length === 8) {
var r = value.value.substring(0, 2);
var g = value.value.substring(2, 4);
var b = value.value.substring(4, 6);
var a = value.value.substring(6, 8);
return pack(parseInt(r, 16), parseInt(g, 16), parseInt(b, 16), parseInt(a, 16) / 255);
}
}
if (value.type === 20 /* IDENT_TOKEN */) {
var namedColor = COLORS[value.value.toUpperCase()];
if (typeof namedColor !== 'undefined') {
return namedColor;
}
}
return COLORS.TRANSPARENT;
}
};
var isTransparent = function (color) { return (0xff & color) === 0; };
var asString = function (color) {
var alpha = 0xff & color;
var blue = 0xff & (color >> 8);
var green = 0xff & (color >> 16);
var red = 0xff & (color >> 24);
return alpha < 255 ? "rgba(" + red + "," + green + "," + blue + "," + alpha / 255 + ")" : "rgb(" + red + "," + green + "," + blue + ")";
};
var pack = function (r, g, b, a) {
return ((r << 24) | (g << 16) | (b << 8) | (Math.round(a * 255) << 0)) >>> 0;
};
var getTokenColorValue = function (token, i) {
if (token.type === 17 /* NUMBER_TOKEN */) {
return token.number;
}
if (token.type === 16 /* PERCENTAGE_TOKEN */) {
var max = i === 3 ? 1 : 255;
return i === 3 ? (token.number / 100) * max : Math.round((token.number / 100) * max);
}
return 0;
};
var rgb = function (_context, args) {
var tokens = args.filter(nonFunctionArgSeparator);
if (tokens.length === 3) {
var _a = tokens.map(getTokenColorValue), r = _a[0], g = _a[1], b = _a[2];
return pack(r, g, b, 1);
}
if (tokens.length === 4) {
var _b = tokens.map(getTokenColorValue), r = _b[0], g = _b[1], b = _b[2], a = _b[3];
return pack(r, g, b, a);
}
return 0;
};
function hue2rgb(t1, t2, hue) {
if (hue < 0) {
hue += 1;
}
if (hue >= 1) {
hue -= 1;
}
if (hue < 1 / 6) {
return (t2 - t1) * hue * 6 + t1;
}
else if (hue < 1 / 2) {
return t2;
}
else if (hue < 2 / 3) {
return (t2 - t1) * 6 * (2 / 3 - hue) + t1;
}
else {
return t1;
}
}
var hsl = function (context, args) {
var tokens = args.filter(nonFunctionArgSeparator);
var hue = tokens[0], saturation = tokens[1], lightness = tokens[2], alpha = tokens[3];
var h = (hue.type === 17 /* NUMBER_TOKEN */ ? deg(hue.number) : angle.parse(context, hue)) / (Math.PI * 2);
var s = isLengthPercentage(saturation) ? saturation.number / 100 : 0;
var l = isLengthPercentage(lightness) ? lightness.number / 100 : 0;
var a = typeof alpha !== 'undefined' && isLengthPercentage(alpha) ? getAbsoluteValue(alpha, 1) : 1;
if (s === 0) {
return pack(l * 255, l * 255, l * 255, 1);
}
var t2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
var t1 = l * 2 - t2;
var r = hue2rgb(t1, t2, h + 1 / 3);
var g = hue2rgb(t1, t2, h);
var b = hue2rgb(t1, t2, h - 1 / 3);
return pack(r * 255, g * 255, b * 255, a);
};
var SUPPORTED_COLOR_FUNCTIONS = {
hsl: hsl,
hsla: hsl,
rgb: rgb,
rgba: rgb
};
var parseColor = function (context, value) {
return color$1.parse(context, Parser.create(value).parseComponentValue());
};
var COLORS = {
ALICEBLUE: 0xf0f8ffff,
ANTIQUEWHITE: 0xfaebd7ff,
AQUA: 0x00ffffff,
AQUAMARINE: 0x7fffd4ff,
AZURE: 0xf0ffffff,
BEIGE: 0xf5f5dcff,
BISQUE: 0xffe4c4ff,
BLACK: 0x000000ff,
BLANCHEDALMOND: 0xffebcdff,
BLUE: 0x0000ffff,
BLUEVIOLET: 0x8a2be2ff,
BROWN: 0xa52a2aff,
BURLYWOOD: 0xdeb887ff,
CADETBLUE: 0x5f9ea0ff,
CHARTREUSE: 0x7fff00ff,
CHOCOLATE: 0xd2691eff,
CORAL: 0xff7f50ff,
CORNFLOWERBLUE: 0x6495edff,
CORNSILK: 0xfff8dcff,
CRIMSON: 0xdc143cff,
CYAN: 0x00ffffff,
DARKBLUE: 0x00008bff,
DARKCYAN: 0x008b8bff,
DARKGOLDENROD: 0xb886bbff,
DARKGRAY: 0xa9a9a9ff,
DARKGREEN: 0x006400ff,
DARKGREY: 0xa9a9a9ff,
DARKKHAKI: 0xbdb76bff,
DARKMAGENTA: 0x8b008bff,
DARKOLIVEGREEN: 0x556b2fff,
DARKORANGE: 0xff8c00ff,
DARKORCHID: 0x9932ccff,
DARKRED: 0x8b0000ff,
DARKSALMON: 0xe9967aff,
DARKSEAGREEN: 0x8fbc8fff,
DARKSLATEBLUE: 0x483d8bff,
DARKSLATEGRAY: 0x2f4f4fff,
DARKSLATEGREY: 0x2f4f4fff,
DARKTURQUOISE: 0x00ced1ff,
DARKVIOLET: 0x9400d3ff,
DEEPPINK: 0xff1493ff,
DEEPSKYBLUE: 0x00bfffff,
DIMGRAY: 0x696969ff,
DIMGREY: 0x696969ff,
DODGERBLUE: 0x1e90ffff,
FIREBRICK: 0xb22222ff,
FLORALWHITE: 0xfffaf0ff,
FORESTGREEN: 0x228b22ff,
FUCHSIA: 0xff00ffff,
GAINSBORO: 0xdcdcdcff,
GHOSTWHITE: 0xf8f8ffff,
GOLD: 0xffd700ff,
GOLDENROD: 0xdaa520ff,
GRAY: 0x808080ff,
GREEN: 0x008000ff,
GREENYELLOW: 0xadff2fff,
GREY: 0x808080ff,
HONEYDEW: 0xf0fff0ff,
HOTPINK: 0xff69b4ff,
INDIANRED: 0xcd5c5cff,
INDIGO: 0x4b0082ff,
IVORY: 0xfffff0ff,
KHAKI: 0xf0e68cff,
LAVENDER: 0xe6e6faff,
LAVENDERBLUSH: 0xfff0f5ff,
LAWNGREEN: 0x7cfc00ff,
LEMONCHIFFON: 0xfffacdff,
LIGHTBLUE: 0xadd8e6ff,
LIGHTCORAL: 0xf08080ff,
LIGHTCYAN: 0xe0ffffff,
LIGHTGOLDENRODYELLOW: 0xfafad2ff,
LIGHTGRAY: 0xd3d3d3ff,
LIGHTGREEN: 0x90ee90ff,
LIGHTGREY: 0xd3d3d3ff,
LIGHTPINK: 0xffb6c1ff,
LIGHTSALMON: 0xffa07aff,
LIGHTSEAGREEN: 0x20b2aaff,
LIGHTSKYBLUE: 0x87cefaff,
LIGHTSLATEGRAY: 0x778899ff,
LIGHTSLATEGREY: 0x778899ff,
LIGHTSTEELBLUE: 0xb0c4deff,
LIGHTYELLOW: 0xffffe0ff,
LIME: 0x00ff00ff,
LIMEGREEN: 0x32cd32ff,
LINEN: 0xfaf0e6ff,
MAGENTA: 0xff00ffff,
MAROON: 0x800000ff,
MEDIUMAQUAMARINE: 0x66cdaaff,
MEDIUMBLUE: 0x0000cdff,
MEDIUMORCHID: 0xba55d3ff,
MEDIUMPURPLE: 0x9370dbff,
MEDIUMSEAGREEN: 0x3cb371ff,
MEDIUMSLATEBLUE: 0x7b68eeff,
MEDIUMSPRINGGREEN: 0x00fa9aff,
MEDIUMTURQUOISE: 0x48d1ccff,
MEDIUMVIOLETRED: 0xc71585ff,
MIDNIGHTBLUE: 0x191970ff,
MINTCREAM: 0xf5fffaff,
MISTYROSE: 0xffe4e1ff,
MOCCASIN: 0xffe4b5ff,
NAVAJOWHITE: 0xffdeadff,
NAVY: 0x000080ff,
OLDLACE: 0xfdf5e6ff,
OLIVE: 0x808000ff,
OLIVEDRAB: 0x6b8e23ff,
ORANGE: 0xffa500ff,
ORANGERED: 0xff4500ff,
ORCHID: 0xda70d6ff,
PALEGOLDENROD: 0xeee8aaff,
PALEGREEN: 0x98fb98ff,
PALETURQUOISE: 0xafeeeeff,
PALEVIOLETRED: 0xdb7093ff,
PAPAYAWHIP: 0xffefd5ff,
PEACHPUFF: 0xffdab9ff,
PERU: 0xcd853fff,
PINK: 0xffc0cbff,
PLUM: 0xdda0ddff,
POWDERBLUE: 0xb0e0e6ff,
PURPLE: 0x800080ff,
REBECCAPURPLE: 0x663399ff,
RED: 0xff0000ff,
ROSYBROWN: 0xbc8f8fff,
ROYALBLUE: 0x4169e1ff,
SADDLEBROWN: 0x8b4513ff,
SALMON: 0xfa8072ff,
SANDYBROWN: 0xf4a460ff,
SEAGREEN: 0x2e8b57ff,
SEASHELL: 0xfff5eeff,
SIENNA: 0xa0522dff,
SILVER: 0xc0c0c0ff,
SKYBLUE: 0x87ceebff,
SLATEBLUE: 0x6a5acdff,
SLATEGRAY: 0x708090ff,
SLATEGREY: 0x708090ff,
SNOW: 0xfffafaff,
SPRINGGREEN: 0x00ff7fff,
STEELBLUE: 0x4682b4ff,
TAN: 0xd2b48cff,
TEAL: 0x008080ff,
THISTLE: 0xd8bfd8ff,
TOMATO: 0xff6347ff,
TRANSPARENT: 0x00000000,
TURQUOISE: 0x40e0d0ff,
VIOLET: 0xee82eeff,
WHEAT: 0xf5deb3ff,
WHITE: 0xffffffff,
WHITESMOKE: 0xf5f5f5ff,
YELLOW: 0xffff00ff,
YELLOWGREEN: 0x9acd32ff
};
var backgroundClip = {
name: 'background-clip',
initialValue: 'border-box',
prefix: false,
type: 1 /* LIST */,
parse: function (_context, tokens) {
return tokens.map(function (token) {
if (isIdentToken(token)) {
switch (token.value) {
case 'padding-box':
return 1 /* PADDING_BOX */;
case 'content-box':
return 2 /* CONTENT_BOX */;
}
}
return 0 /* BORDER_BOX */;
});
}
};
var backgroundColor = {
name: "background-color",
initialValue: 'transparent',
prefix: false,
type: 3 /* TYPE_VALUE */,
format: 'color'
};
var parseColorStop = function (context, args) {
var color = color$1.parse(context, args[0]);
var stop = args[1];
return stop && isLengthPercentage(stop) ? { color: color, stop: stop } : { color: color, stop: null };
};
var processColorStops = function (stops, lineLength) {
var first = stops[0];
var last = stops[stops.length - 1];
if (first.stop === null) {
first.stop = ZERO_LENGTH;
}
if (last.stop === null) {
last.stop = HUNDRED_PERCENT;
}
var processStops = [];
var previous = 0;
for (var i = 0; i < stops.length; i++) {
var stop_1 = stops[i].stop;
if (stop_1 !== null) {
var absoluteValue = getAbsoluteValue(stop_1, lineLength);
if (absoluteValue > previous) {
processStops.push(absoluteValue);
}
else {
processStops.push(previous);
}
previous = absoluteValue;
}
else {
processStops.push(null);
}
}
var gapBegin = null;
for (var i = 0; i < processStops.length; i++) {
var stop_2 = processStops[i];
if (stop_2 === null) {
if (gapBegin === null) {
gapBegin = i;
}
}
else if (gapBegin !== null) {
var gapLength = i - gapBegin;
var beforeGap = processStops[gapBegin - 1];
var gapValue = (stop_2 - beforeGap) / (gapLength + 1);
for (var g = 1; g <= gapLength; g++) {
processStops[gapBegin + g - 1] = gapValue * g;
}
gapBegin = null;
}
}
return stops.map(function (_a, i) {
var color = _a.color;
return { color: color, stop: Math.max(Math.min(1, processStops[i] / lineLength), 0) };
});
};
var getAngleFromCorner = function (corner, width, height) {
var centerX = width / 2;
var centerY = height / 2;
var x = getAbsoluteValue(corner[0], width) - centerX;
var y = centerY - getAbsoluteValue(corner[1], height);
return (Math.atan2(y, x) + Math.PI * 2) % (Math.PI * 2);
};
var calculateGradientDirection = function (angle, width, height) {
var radian = typeof angle === 'number' ? angle : getAngleFromCorner(angle, width, height);
var lineLength = Math.abs(width * Math.sin(radian)) + Math.abs(height * Math.cos(radian));
var halfWidth = width / 2;
var halfHeight = height / 2;
var halfLineLength = lineLength / 2;
var yDiff = Math.sin(radian - Math.PI / 2) * halfLineLength;
var xDiff = Math.cos(radian - Math.PI / 2) * halfLineLength;
return [lineLength, halfWidth - xDiff, halfWidth + xDiff, halfHeight - yDiff, halfHeight + yDiff];
};
var distance = function (a, b) { return Math.sqrt(a * a + b * b); };
var findCorner = function (width, height, x, y, closest) {
var corners = [
[0, 0],
[0, height],
[width, 0],
[width, height]
];
return corners.reduce(function (stat, corner) {
var cx = corner[0], cy = corner[1];
var d = distance(x - cx, y - cy);
if (closest ? d < stat.optimumDistance : d > stat.optimumDistance) {
return {
optimumCorner: corner,
optimumDistance: d
};
}
return stat;
}, {
optimumDistance: closest ? Infinity : -Infinity,
optimumCorner: null
}).optimumCorner;
};
var calculateRadius = function (gradient, x, y, width, height) {
var rx = 0;
var ry = 0;
switch (gradient.size) {
case 0 /* CLOSEST_SIDE */:
// The ending shape is sized so that that it exactly meets the side of the gradient box closest to the gradients center.
// If the shape is an ellipse, it exactly meets the closest side in each dimension.
if (gradient.shape === 0 /* CIRCLE */) {
rx = ry = Math.min(Math.abs(x), Math.abs(x - width), Math.abs(y), Math.abs(y - height));
}
else if (gradient.shape === 1 /* ELLIPSE */) {
rx = Math.min(Math.abs(x), Math.abs(x - width));
ry = Math.min(Math.abs(y), Math.abs(y - height));
}
break;
case 2 /* CLOSEST_CORNER */:
// The ending shape is sized so that that it passes through the corner of the gradient box closest to the gradients center.
// If the shape is an ellipse, the ending shape is given the same aspect-ratio it would have if closest-side were specified.
if (gradient.shape === 0 /* CIRCLE */) {
rx = ry = Math.min(distance(x, y), distance(x, y - height), distance(x - width, y), distance(x - width, y - height));
}
else if (gradient.shape === 1 /* ELLIPSE */) {
// Compute the ratio ry/rx (which is to be the same as for "closest-side")
var c = Math.min(Math.abs(y), Math.abs(y - height)) / Math.min(Math.abs(x), Math.abs(x - width));
var _a = findCorner(width, height, x, y, true), cx = _a[0], cy = _a[1];
rx = distance(cx - x, (cy - y) / c);
ry = c * rx;
}
break;
case 1 /* FARTHEST_SIDE */:
// Same as closest-side, except the ending shape is sized based on the farthest side(s)
if (gradient.shape === 0 /* CIRCLE */) {
rx = ry = Math.max(Math.abs(x), Math.abs(x - width), Math.abs(y), Math.abs(y - height));
}
else if (gradient.shape === 1 /* ELLIPSE */) {
rx = Math.max(Math.abs(x), Math.abs(x - width));
ry = Math.max(Math.abs(y), Math.abs(y - height));
}
break;
case 3 /* FARTHEST_CORNER */:
// Same as closest-corner, except the ending shape is sized based on the farthest corner.
// If the shape is an ellipse, the ending shape is given the same aspect ratio it would have if farthest-side were specified.
if (gradient.shape === 0 /* CIRCLE */) {
rx = ry = Math.max(distance(x, y), distance(x, y - height), distance(x - width, y), distance(x - width, y - height));
}
else if (gradient.shape === 1 /* ELLIPSE */) {
// Compute the ratio ry/rx (which is to be the same as for "farthest-side")
var c = Math.max(Math.abs(y), Math.abs(y - height)) / Math.max(Math.abs(x), Math.abs(x - width));
var _b = findCorner(width, height, x, y, false), cx = _b[0], cy = _b[1];
rx = distance(cx - x, (cy - y) / c);
ry = c * rx;
}
break;
}
if (Array.isArray(gradient.size)) {
rx = getAbsoluteValue(gradient.size[0], width);
ry = gradient.size.length === 2 ? getAbsoluteValue(gradient.size[1], height) : rx;
}
return [rx, ry];
};
var linearGradient = function (context, tokens) {
var angle$1 = deg(180);
var stops = [];
parseFunctionArgs(tokens).forEach(function (arg, i) {
if (i === 0) {
var firstToken = arg[0];
if (firstToken.type === 20 /* IDENT_TOKEN */ && firstToken.value === 'to') {
angle$1 = parseNamedSide(arg);
return;
}
else if (isAngle(firstToken)) {
angle$1 = angle.parse(context, firstToken);
return;
}
}
var colorStop = parseColorStop(context, arg);
stops.push(colorStop);
});
return { angle: angle$1, stops: stops, type: 1 /* LINEAR_GRADIENT */ };
};
var prefixLinearGradient = function (context, tokens) {
var angle$1 = deg(180);
var stops = [];
parseFunctionArgs(tokens).forEach(function (arg, i) {
if (i === 0) {
var firstToken = arg[0];
if (firstToken.type === 20 /* IDENT_TOKEN */ &&
['top', 'left', 'right', 'bottom'].indexOf(firstToken.value) !== -1) {
angle$1 = parseNamedSide(arg);
return;
}
else if (isAngle(firstToken)) {
angle$1 = (angle.parse(context, firstToken) + deg(270)) % deg(360);
return;
}
}
var colorStop = parseColorStop(context, arg);
stops.push(colorStop);
});
return {
angle: angle$1,
stops: stops,
type: 1 /* LINEAR_GRADIENT */
};
};
var webkitGradient = function (context, tokens) {
var angle = deg(180);
var stops = [];
var type = 1 /* LINEAR_GRADIENT */;
var shape = 0 /* CIRCLE */;
var size = 3 /* FARTHEST_CORNER */;
var position = [];
parseFunctionArgs(tokens).forEach(function (arg, i) {
var firstToken = arg[0];
if (i === 0) {
if (isIdentToken(firstToken) && firstToken.value === 'linear') {
type = 1 /* LINEAR_GRADIENT */;
return;
}
else if (isIdentToken(firstToken) && firstToken.value === 'radial') {
type = 2 /* RADIAL_GRADIENT */;
return;
}
}
if (firstToken.type === 18 /* FUNCTION */) {
if (firstToken.name === 'from') {
var color = color$1.parse(context, firstToken.values[0]);
stops.push({ stop: ZERO_LENGTH, color: color });
}
else if (firstToken.name === 'to') {
var color = color$1.parse(context, firstToken.values[0]);
stops.push({ stop: HUNDRED_PERCENT, color: color });
}
else if (firstToken.name === 'color-stop') {
var values = firstToken.values.filter(nonFunctionArgSeparator);
if (values.length === 2) {
var color = color$1.parse(context, values[1]);
var stop_1 = values[0];
if (isNumberToken(stop_1)) {
stops.push({
stop: { type: 16 /* PERCENTAGE_TOKEN */, number: stop_1.number * 100, flags: stop_1.flags },
color: color
});
}
}
}
}
});
return type === 1 /* LINEAR_GRADIENT */
? {
angle: (angle + deg(180)) % deg(360),
stops: stops,
type: type
}
: { size: size, shape: shape, stops: stops, position: position, type: type };
};
var CLOSEST_SIDE = 'closest-side';
var FARTHEST_SIDE = 'farthest-side';
var CLOSEST_CORNER = 'closest-corner';
var FARTHEST_CORNER = 'farthest-corner';
var CIRCLE = 'circle';
var ELLIPSE = 'ellipse';
var COVER = 'cover';
var CONTAIN = 'contain';
var radialGradient = function (context, tokens) {
var shape = 0 /* CIRCLE */;
var size = 3 /* FARTHEST_CORNER */;
var stops = [];
var position = [];
parseFunctionArgs(tokens).forEach(function (arg, i) {
var isColorStop = true;
if (i === 0) {
var isAtPosition_1 = false;
isColorStop = arg.reduce(function (acc, token) {
if (isAtPosition_1) {
if (isIdentToken(token)) {
switch (token.value) {
case 'center':
position.push(FIFTY_PERCENT);
return acc;
case 'top':
case 'left':
position.push(ZERO_LENGTH);
return acc;
case 'right':
case 'bottom':
position.push(HUNDRED_PERCENT);
return acc;
}
}
else if (isLengthPercentage(token) || isLength(token)) {
position.push(token);
}
}
else if (isIdentToken(token)) {
switch (token.value) {
case CIRCLE:
shape = 0 /* CIRCLE */;
return false;
case ELLIPSE:
shape = 1 /* ELLIPSE */;
return false;
case 'at':
isAtPosition_1 = true;
return false;
case CLOSEST_SIDE:
size = 0 /* CLOSEST_SIDE */;
return false;
case COVER:
case FARTHEST_SIDE:
size = 1 /* FARTHEST_SIDE */;
return false;
case CONTAIN:
case CLOSEST_CORNER:
size = 2 /* CLOSEST_CORNER */;
return false;
case FARTHEST_CORNER:
size = 3 /* FARTHEST_CORNER */;
return false;
}
}
else if (isLength(token) || isLengthPercentage(token)) {
if (!Array.isArray(size)) {
size = [];
}
size.push(token);
return false;
}
return acc;
}, isColorStop);
}
if (isColorStop) {
var colorStop = parseColorStop(context, arg);
stops.push(colorStop);
}
});
return { size: size, shape: shape, stops: stops, position: position, type: 2 /* RADIAL_GRADIENT */ };
};
var prefixRadialGradient = function (context, tokens) {
var shape = 0 /* CIRCLE */;
var size = 3 /* FARTHEST_CORNER */;
var stops = [];
var position = [];
parseFunctionArgs(tokens).forEach(function (arg, i) {
var isColorStop = true;
if (i === 0) {
isColorStop = arg.reduce(function (acc, token) {
if (isIdentToken(token)) {
switch (token.value) {
case 'center':
position.push(FIFTY_PERCENT);
return false;
case 'top':
case 'left':
position.push(ZERO_LENGTH);
return false;
case 'right':
case 'bottom':
position.push(HUNDRED_PERCENT);
return false;
}
}
else if (isLengthPercentage(token) || isLength(token)) {
position.push(token);
return false;
}
return acc;
}, isColorStop);
}
else if (i === 1) {
isColorStop = arg.reduce(function (acc, token) {
if (isIdentToken(token)) {
switch (token.value) {
case CIRCLE:
shape = 0 /* CIRCLE */;
return false;
case ELLIPSE:
shape = 1 /* ELLIPSE */;
return false;
case CONTAIN:
case CLOSEST_SIDE:
size = 0 /* CLOSEST_SIDE */;
return false;
case FARTHEST_SIDE:
size = 1 /* FARTHEST_SIDE */;
return false;
case CLOSEST_CORNER:
size = 2 /* CLOSEST_CORNER */;
return false;
case COVER:
case FARTHEST_CORNER:
size = 3 /* FARTHEST_CORNER */;
return false;
}
}
else if (isLength(token) || isLengthPercentage(token)) {
if (!Array.isArray(size)) {
size = [];
}
size.push(token);
return false;
}
return acc;
}, isColorStop);
}
if (isColorStop) {
var colorStop = parseColorStop(context, arg);
stops.push(colorStop);
}
});
return { size: size, shape: shape, stops: stops, position: position, type: 2 /* RADIAL_GRADIENT */ };
};
var isLinearGradient = function (background) {
return background.type === 1 /* LINEAR_GRADIENT */;
};
var isRadialGradient = function (background) {
return background.type === 2 /* RADIAL_GRADIENT */;
};
var image = {
name: 'image',
parse: function (context, value) {
if (value.type === 22 /* URL_TOKEN */) {
var image_1 = { url: value.value, type: 0 /* URL */ };
context.cache.addImage(value.value);
return image_1;
}
if (value.type === 18 /* FUNCTION */) {
var imageFunction = SUPPORTED_IMAGE_FUNCTIONS[value.name];
if (typeof imageFunction === 'undefined') {
throw new Error("Attempting to parse an unsupported image function \"" + value.name + "\"");
}
return imageFunction(context, value.values);
}
throw new Error("Unsupported image type " + value.type);
}
};
function isSupportedImage(value) {
return (!(value.type === 20 /* IDENT_TOKEN */ && value.value === 'none') &&
(value.type !== 18 /* FUNCTION */ || !!SUPPORTED_IMAGE_FUNCTIONS[value.name]));
}
var SUPPORTED_IMAGE_FUNCTIONS = {
'linear-gradient': linearGradient,
'-moz-linear-gradient': prefixLinearGradient,
'-ms-linear-gradient': prefixLinearGradient,
'-o-linear-gradient': prefixLinearGradient,
'-webkit-linear-gradient': prefixLinearGradient,
'radial-gradient': radialGradient,
'-moz-radial-gradient': prefixRadialGradient,
'-ms-radial-gradient': prefixRadialGradient,
'-o-radial-gradient': prefixRadialGradient,
'-webkit-radial-gradient': prefixRadialGradient,
'-webkit-gradient': webkitGradient
};
var backgroundImage = {
name: 'background-image',
initialValue: 'none',
type: 1 /* LIST */,
prefix: false,
parse: function (context, tokens) {
if (tokens.length === 0) {
return [];
}
var first = tokens[0];
if (first.type === 20 /* IDENT_TOKEN */ && first.value === 'none') {
return [];
}
return tokens
.filter(function (value) { return nonFunctionArgSeparator(value) && isSupportedImage(value); })
.map(function (value) { return image.parse(context, value); });
}
};
var backgroundOrigin = {
name: 'background-origin',
initialValue: 'border-box',
prefix: false,
type: 1 /* LIST */,
parse: function (_context, tokens) {
return tokens.map(function (token) {
if (isIdentToken(token)) {
switch (token.value) {
case 'padding-box':
return 1 /* PADDING_BOX */;
case 'content-box':
return 2 /* CONTENT_BOX */;
}
}
return 0 /* BORDER_BOX */;
});
}
};
var backgroundPosition = {
name: 'background-position',
initialValue: '0% 0%',
type: 1 /* LIST */,
prefix: false,
parse: function (_context, tokens) {
return parseFunctionArgs(tokens)
.map(function (values) { return values.filter(isLengthPercentage); })
.map(parseLengthPercentageTuple);
}
};
var backgroundRepeat = {
name: 'background-repeat',
initialValue: 'repeat',
prefix: false,
type: 1 /* LIST */,
parse: function (_context, tokens) {
return parseFunctionArgs(tokens)
.map(function (values) {
return values
.filter(isIdentToken)
.map(function (token) { return token.value; })
.join(' ');
})
.map(parseBackgroundRepeat);
}
};
var parseBackgroundRepeat = function (value) {
switch (value) {
case 'no-repeat':
return 1 /* NO_REPEAT */;
case 'repeat-x':
case 'repeat no-repeat':
return 2 /* REPEAT_X */;
case 'repeat-y':
case 'no-repeat repeat':
return 3 /* REPEAT_Y */;
case 'repeat':
default:
return 0 /* REPEAT */;
}
};
var BACKGROUND_SIZE;
(function (BACKGROUND_SIZE) {
BACKGROUND_SIZE["AUTO"] = "auto";
BACKGROUND_SIZE["CONTAIN"] = "contain";
BACKGROUND_SIZE["COVER"] = "cover";
})(BACKGROUND_SIZE || (BACKGROUND_SIZE = {}));
var backgroundSize = {
name: 'background-size',
initialValue: '0',
prefix: false,
type: 1 /* LIST */,
parse: function (_context, tokens) {
return parseFunctionArgs(tokens).map(function (values) { return values.filter(isBackgroundSizeInfoToken); });
}
};
var isBackgroundSizeInfoToken = function (value) {
return isIdentToken(value) || isLengthPercentage(value);
};
var borderColorForSide = function (side) { return ({
name: "border-" + side + "-color",
initialValue: 'transparent',
prefix: false,
type: 3 /* TYPE_VALUE */,
format: 'color'
}); };
var borderTopColor = borderColorForSide('top');
var borderRightColor = borderColorForSide('right');
var borderBottomColor = borderColorForSide('bottom');
var borderLeftColor = borderColorForSide('left');
var borderRadiusForSide = function (side) { return ({
name: "border-radius-" + side,
initialValue: '0 0',
prefix: false,
type: 1 /* LIST */,
parse: function (_context, tokens) {
return parseLengthPercentageTuple(tokens.filter(isLengthPercentage));
}
}); };
var borderTopLeftRadius = borderRadiusForSide('top-left');
var borderTopRightRadius = borderRadiusForSide('top-right');
var borderBottomRightRadius = borderRadiusForSide('bottom-right');
var borderBottomLeftRadius = borderRadiusForSide('bottom-left');
var borderStyleForSide = function (side) { return ({
name: "border-" + side + "-style",
initialValue: 'solid',
prefix: false,
type: 2 /* IDENT_VALUE */,
parse: function (_context, style) {
switch (style) {
case 'none':
return 0 /* NONE */;
case 'dashed':
return 2 /* DASHED */;
case 'dotted':
return 3 /* DOTTED */;
case 'double':
return 4 /* DOUBLE */;
}
return 1 /* SOLID */;
}
}); };
var borderTopStyle = borderStyleForSide('top');
var borderRightStyle = borderStyleForSide('right');
var borderBottomStyle = borderStyleForSide('bottom');
var borderLeftStyle = borderStyleForSide('left');
var borderWidthForSide = function (side) { return ({
name: "border-" + side + "-width",
initialValue: '0',
type: 0 /* VALUE */,
prefix: false,
parse: function (_context, token) {
if (isDimensionToken(token)) {
return token.number;
}
return 0;
}
}); };
var borderTopWidth = borderWidthForSide('top');
var borderRightWidth = borderWidthForSide('right');
var borderBottomWidth = borderWidthForSide('bottom');
var borderLeftWidth = borderWidthForSide('left');
var color = {
name: "color",
initialValue: 'transparent',
prefix: false,
type: 3 /* TYPE_VALUE */,
format: 'color'
};
var direction = {
name: 'direction',
initialValue: 'ltr',
prefix: false,
type: 2 /* IDENT_VALUE */,
parse: function (_context, direction) {
switch (direction) {
case 'rtl':
return 1 /* RTL */;
case 'ltr':
default:
return 0 /* LTR */;
}
}
};
var display = {
name: 'display',
initialValue: 'inline-block',
prefix: false,
type: 1 /* LIST */,
parse: function (_context, tokens) {
return tokens.filter(isIdentToken).reduce(function (bit, token) {
return bit | parseDisplayValue(token.value);
}, 0 /* NONE */);
}
};
var parseDisplayValue = function (display) {
switch (display) {
case 'block':
case '-webkit-box':
return 2 /* BLOCK */;
case 'inline':
return 4 /* INLINE */;
case 'run-in':
return 8 /* RUN_IN */;
case 'flow':
return 16 /* FLOW */;
case 'flow-root':
return 32 /* FLOW_ROOT */;
case 'table':
return 64 /* TABLE */;
case 'flex':
case '-webkit-flex':
return 128 /* FLEX */;
case 'grid':
case '-ms-grid':
return 256 /* GRID */;
case 'ruby':
return 512 /* RUBY */;
case 'subgrid':
return 1024 /* SUBGRID */;
case 'list-item':
return 2048 /* LIST_ITEM */;
case 'table-row-group':
return 4096 /* TABLE_ROW_GROUP */;
case 'table-header-group':
return 8192 /* TABLE_HEADER_GROUP */;
case 'table-footer-group':
return 16384 /* TABLE_FOOTER_GROUP */;
case 'table-row':
return 32768 /* TABLE_ROW */;
case 'table-cell':
return 65536 /* TABLE_CELL */;
case 'table-column-group':
return 131072 /* TABLE_COLUMN_GROUP */;
case 'table-column':
return 262144 /* TABLE_COLUMN */;
case 'table-caption':
return 524288 /* TABLE_CAPTION */;
case 'ruby-base':
return 1048576 /* RUBY_BASE */;
case 'ruby-text':
return 2097152 /* RUBY_TEXT */;
case 'ruby-base-container':
return 4194304 /* RUBY_BASE_CONTAINER */;
case 'ruby-text-container':
return 8388608 /* RUBY_TEXT_CONTAINER */;
case 'contents':
return 16777216 /* CONTENTS */;
case 'inline-block':
return 33554432 /* INLINE_BLOCK */;
case 'inline-list-item':
return 67108864 /* INLINE_LIST_ITEM */;
case 'inline-table':
return 134217728 /* INLINE_TABLE */;
case 'inline-flex':
return 268435456 /* INLINE_FLEX */;
case 'inline-grid':
return 536870912 /* INLINE_GRID */;
}
return 0 /* NONE */;
};
var float = {
name: 'float',
initialValue: 'none',
prefix: false,
type: 2 /* IDENT_VALUE */,
parse: function (_context, float) {
switch (float) {
case 'left':
return 1 /* LEFT */;
case 'right':
return 2 /* RIGHT */;
case 'inline-start':
return 3 /* INLINE_START */;
case 'inline-end':
return 4 /* INLINE_END */;
}
return 0 /* NONE */;
}
};
var letterSpacing = {
name: 'letter-spacing',
initialValue: '0',
prefix: false,
type: 0 /* VALUE */,
parse: function (_context, token) {
if (token.type === 20 /* IDENT_TOKEN */ && token.value === 'normal') {
return 0;
}
if (token.type === 17 /* NUMBER_TOKEN */) {
return token.number;
}
if (token.type === 15 /* DIMENSION_TOKEN */) {
return token.number;
}
return 0;
}
};
var LINE_BREAK;
(function (LINE_BREAK) {
LINE_BREAK["NORMAL"] = "normal";
LINE_BREAK["STRICT"] = "strict";
})(LINE_BREAK || (LINE_BREAK = {}));
var lineBreak = {
name: 'line-break',
initialValue: 'normal',
prefix: false,
type: 2 /* IDENT_VALUE */,
parse: function (_context, lineBreak) {
switch (lineBreak) {
case 'strict':
return LINE_BREAK.STRICT;
case 'normal':
default:
return LINE_BREAK.NORMAL;
}
}
};
var lineHeight = {
name: 'line-height',
initialValue: 'normal',
prefix: false,
type: 4 /* TOKEN_VALUE */
};
var computeLineHeight = function (token, fontSize) {
if (isIdentToken(token) && token.value === 'normal') {
return 1.2 * fontSize;
}
else if (token.type === 17 /* NUMBER_TOKEN */) {
return fontSize * token.number;
}
else if (isLengthPercentage(token)) {
return getAbsoluteValue(token, fontSize);
}
return fontSize;
};
var listStyleImage = {
name: 'list-style-image',
initialValue: 'none',
type: 0 /* VALUE */,
prefix: false,
parse: function (context, token) {
if (token.type === 20 /* IDENT_TOKEN */ && token.value === 'none') {
return null;
}
return image.parse(context, token);
}
};
var listStylePosition = {
name: 'list-style-position',
initialValue: 'outside',
prefix: false,
type: 2 /* IDENT_VALUE */,
parse: function (_context, position) {
switch (position) {
case 'inside':
return 0 /* INSIDE */;
case 'outside':
default:
return 1 /* OUTSIDE */;
}
}
};
var listStyleType = {
name: 'list-style-type',
initialValue: 'none',
prefix: false,
type: 2 /* IDENT_VALUE */,
parse: function (_context, type) {
switch (type) {
case 'disc':
return 0 /* DISC */;
case 'circle':
return 1 /* CIRCLE */;
case 'square':
return 2 /* SQUARE */;
case 'decimal':
return 3 /* DECIMAL */;
case 'cjk-decimal':
return 4 /* CJK_DECIMAL */;
case 'decimal-leading-zero':
return 5 /* DECIMAL_LEADING_ZERO */;
case 'lower-roman':
return 6 /* LOWER_ROMAN */;
case 'upper-roman':
return 7 /* UPPER_ROMAN */;
case 'lower-greek':
return 8 /* LOWER_GREEK */;
case 'lower-alpha':
return 9 /* LOWER_ALPHA */;
case 'upper-alpha':
return 10 /* UPPER_ALPHA */;
case 'arabic-indic':
return 11 /* ARABIC_INDIC */;
case 'armenian':
return 12 /* ARMENIAN */;
case 'bengali':
return 13 /* BENGALI */;
case 'cambodian':
return 14 /* CAMBODIAN */;
case 'cjk-earthly-branch':
return 15 /* CJK_EARTHLY_BRANCH */;
case 'cjk-heavenly-stem':
return 16 /* CJK_HEAVENLY_STEM */;
case 'cjk-ideographic':
return 17 /* CJK_IDEOGRAPHIC */;
case 'devanagari':
return 18 /* DEVANAGARI */;
case 'ethiopic-numeric':
return 19 /* ETHIOPIC_NUMERIC */;
case 'georgian':
return 20 /* GEORGIAN */;
case 'gujarati':
return 21 /* GUJARATI */;
case 'gurmukhi':
return 22 /* GURMUKHI */;
case 'hebrew':
return 22 /* HEBREW */;
case 'hiragana':
return 23 /* HIRAGANA */;
case 'hiragana-iroha':
return 24 /* HIRAGANA_IROHA */;
case 'japanese-formal':
return 25 /* JAPANESE_FORMAL */;
case 'japanese-informal':
return 26 /* JAPANESE_INFORMAL */;
case 'kannada':
return 27 /* KANNADA */;
case 'katakana':
return 28 /* KATAKANA */;
case 'katakana-iroha':
return 29 /* KATAKANA_IROHA */;
case 'khmer':
return 30 /* KHMER */;
case 'korean-hangul-formal':
return 31 /* KOREAN_HANGUL_FORMAL */;
case 'korean-hanja-formal':
return 32 /* KOREAN_HANJA_FORMAL */;
case 'korean-hanja-informal':
return 33 /* KOREAN_HANJA_INFORMAL */;
case 'lao':
return 34 /* LAO */;
case 'lower-armenian':
return 35 /* LOWER_ARMENIAN */;
case 'malayalam':
return 36 /* MALAYALAM */;
case 'mongolian':
return 37 /* MONGOLIAN */;
case 'myanmar':
return 38 /* MYANMAR */;
case 'oriya':
return 39 /* ORIYA */;
case 'persian':
return 40 /* PERSIAN */;
case 'simp-chinese-formal':
return 41 /* SIMP_CHINESE_FORMAL */;
case 'simp-chinese-informal':
return 42 /* SIMP_CHINESE_INFORMAL */;
case 'tamil':
return 43 /* TAMIL */;
case 'telugu':
return 44 /* TELUGU */;
case 'thai':
return 45 /* THAI */;
case 'tibetan':
return 46 /* TIBETAN */;
case 'trad-chinese-formal':
return 47 /* TRAD_CHINESE_FORMAL */;
case 'trad-chinese-informal':
return 48 /* TRAD_CHINESE_INFORMAL */;
case 'upper-armenian':
return 49 /* UPPER_ARMENIAN */;
case 'disclosure-open':
return 50 /* DISCLOSURE_OPEN */;
case 'disclosure-closed':
return 51 /* DISCLOSURE_CLOSED */;
case 'none':
default:
return -1 /* NONE */;
}
}
};
var marginForSide = function (side) { return ({
name: "margin-" + side,
initialValue: '0',
prefix: false,
type: 4 /* TOKEN_VALUE */
}); };
var marginTop = marginForSide('top');
var marginRight = marginForSide('right');
var marginBottom = marginForSide('bottom');
var marginLeft = marginForSide('left');
var overflow = {
name: 'overflow',
initialValue: 'visible',
prefix: false,
type: 1 /* LIST */,
parse: function (_context, tokens) {
return tokens.filter(isIdentToken).map(function (overflow) {
switch (overflow.value) {
case 'hidden':
return 1 /* HIDDEN */;
case 'scroll':
return 2 /* SCROLL */;
case 'clip':
return 3 /* CLIP */;
case 'auto':
return 4 /* AUTO */;
case 'visible':
default:
return 0 /* VISIBLE */;
}
});
}
};
var overflowWrap = {
name: 'overflow-wrap',
initialValue: 'normal',
prefix: false,
type: 2 /* IDENT_VALUE */,
parse: function (_context, overflow) {
switch (overflow) {
case 'break-word':
return "break-word" /* BREAK_WORD */;
case 'normal':
default:
return "normal" /* NORMAL */;
}
}
};
var paddingForSide = function (side) { return ({
name: "padding-" + side,
initialValue: '0',
prefix: false,
type: 3 /* TYPE_VALUE */,
format: 'length-percentage'
}); };
var paddingTop = paddingForSide('top');
var paddingRight = paddingForSide('right');
var paddingBottom = paddingForSide('bottom');
var paddingLeft = paddingForSide('left');
var textAlign = {
name: 'text-align',
initialValue: 'left',
prefix: false,
type: 2 /* IDENT_VALUE */,
parse: function (_context, textAlign) {
switch (textAlign) {
case 'right':
return 2 /* RIGHT */;
case 'center':
case 'justify':
return 1 /* CENTER */;
case 'left':
default:
return 0 /* LEFT */;
}
}
};
var position = {
name: 'position',
initialValue: 'static',
prefix: false,
type: 2 /* IDENT_VALUE */,
parse: function (_context, position) {
switch (position) {
case 'relative':
return 1 /* RELATIVE */;
case 'absolute':
return 2 /* ABSOLUTE */;
case 'fixed':
return 3 /* FIXED */;
case 'sticky':
return 4 /* STICKY */;
}
return 0 /* STATIC */;
}
};
var textShadow = {
name: 'text-shadow',
initialValue: 'none',
type: 1 /* LIST */,
prefix: false,
parse: function (context, tokens) {
if (tokens.length === 1 && isIdentWithValue(tokens[0], 'none')) {
return [];
}
return parseFunctionArgs(tokens).map(function (values) {
var shadow = {
color: COLORS.TRANSPARENT,
offsetX: ZERO_LENGTH,
offsetY: ZERO_LENGTH,
blur: ZERO_LENGTH
};
var c = 0;
for (var i = 0; i < values.length; i++) {
var token = values[i];
if (isLength(token)) {
if (c === 0) {
shadow.offsetX = token;
}
else if (c === 1) {
shadow.offsetY = token;
}
else {
shadow.blur = token;
}
c++;
}
else {
shadow.color = color$1.parse(context, token);
}
}
return shadow;
});
}
};
var textTransform = {
name: 'text-transform',
initialValue: 'none',
prefix: false,
type: 2 /* IDENT_VALUE */,
parse: function (_context, textTransform) {
switch (textTransform) {
case 'uppercase':
return 2 /* UPPERCASE */;
case 'lowercase':
return 1 /* LOWERCASE */;
case 'capitalize':
return 3 /* CAPITALIZE */;
}
return 0 /* NONE */;
}
};
var transform$1 = {
name: 'transform',
initialValue: 'none',
prefix: true,
type: 0 /* VALUE */,
parse: function (_context, token) {
if (token.type === 20 /* IDENT_TOKEN */ && token.value === 'none') {
return null;
}
if (token.type === 18 /* FUNCTION */) {
var transformFunction = SUPPORTED_TRANSFORM_FUNCTIONS[token.name];
if (typeof transformFunction === 'undefined') {
throw new Error("Attempting to parse an unsupported transform function \"" + token.name + "\"");
}
return transformFunction(token.values);
}
return null;
}
};
var matrix = function (args) {
var values = args.filter(function (arg) { return arg.type === 17 /* NUMBER_TOKEN */; }).map(function (arg) { return arg.number; });
return values.length === 6 ? values : null;
};
// doesn't support 3D transforms at the moment
var matrix3d = function (args) {
var values = args.filter(function (arg) { return arg.type === 17 /* NUMBER_TOKEN */; }).map(function (arg) { return arg.number; });
var a1 = values[0], b1 = values[1]; values[2]; values[3]; var a2 = values[4], b2 = values[5]; values[6]; values[7]; values[8]; values[9]; values[10]; values[11]; var a4 = values[12], b4 = values[13]; values[14]; values[15];
return values.length === 16 ? [a1, b1, a2, b2, a4, b4] : null;
};
var SUPPORTED_TRANSFORM_FUNCTIONS = {
matrix: matrix,
matrix3d: matrix3d
};
var DEFAULT_VALUE = {
type: 16 /* PERCENTAGE_TOKEN */,
number: 50,
flags: FLAG_INTEGER
};
var DEFAULT = [DEFAULT_VALUE, DEFAULT_VALUE];
var transformOrigin = {
name: 'transform-origin',
initialValue: '50% 50%',
prefix: true,
type: 1 /* LIST */,
parse: function (_context, tokens) {
var origins = tokens.filter(isLengthPercentage);
if (origins.length !== 2) {
return DEFAULT;
}
return [origins[0], origins[1]];
}
};
var visibility = {
name: 'visible',
initialValue: 'none',
prefix: false,
type: 2 /* IDENT_VALUE */,
parse: function (_context, visibility) {
switch (visibility) {
case 'hidden':
return 1 /* HIDDEN */;
case 'collapse':
return 2 /* COLLAPSE */;
case 'visible':
default:
return 0 /* VISIBLE */;
}
}
};
var WORD_BREAK;
(function (WORD_BREAK) {
WORD_BREAK["NORMAL"] = "normal";
WORD_BREAK["BREAK_ALL"] = "break-all";
WORD_BREAK["KEEP_ALL"] = "keep-all";
})(WORD_BREAK || (WORD_BREAK = {}));
var wordBreak = {
name: 'word-break',
initialValue: 'normal',
prefix: false,
type: 2 /* IDENT_VALUE */,
parse: function (_context, wordBreak) {
switch (wordBreak) {
case 'break-all':
return WORD_BREAK.BREAK_ALL;
case 'keep-all':
return WORD_BREAK.KEEP_ALL;
case 'normal':
default:
return WORD_BREAK.NORMAL;
}
}
};
var zIndex = {
name: 'z-index',
initialValue: 'auto',
prefix: false,
type: 0 /* VALUE */,
parse: function (_context, token) {
if (token.type === 20 /* IDENT_TOKEN */) {
return { auto: true, order: 0 };
}
if (isNumberToken(token)) {
return { auto: false, order: token.number };
}
throw new Error("Invalid z-index number parsed");
}
};
var time = {
name: 'time',
parse: function (_context, value) {
if (value.type === 15 /* DIMENSION_TOKEN */) {
switch (value.unit.toLowerCase()) {
case 's':
return 1000 * value.number;
case 'ms':
return value.number;
}
}
throw new Error("Unsupported time type");
}
};
var opacity = {
name: 'opacity',
initialValue: '1',
type: 0 /* VALUE */,
prefix: false,
parse: function (_context, token) {
if (isNumberToken(token)) {
return token.number;
}
return 1;
}
};
var textDecorationColor = {
name: "text-decoration-color",
initialValue: 'transparent',
prefix: false,
type: 3 /* TYPE_VALUE */,
format: 'color'
};
var textDecorationLine = {
name: 'text-decoration-line',
initialValue: 'none',
prefix: false,
type: 1 /* LIST */,
parse: function (_context, tokens) {
return tokens
.filter(isIdentToken)
.map(function (token) {
switch (token.value) {
case 'underline':
return 1 /* UNDERLINE */;
case 'overline':
return 2 /* OVERLINE */;
case 'line-through':
return 3 /* LINE_THROUGH */;
case 'none':
return 4 /* BLINK */;
}
return 0 /* NONE */;
})
.filter(function (line) { return line !== 0 /* NONE */; });
}
};
var fontFamily = {
name: "font-family",
initialValue: '',
prefix: false,
type: 1 /* LIST */,
parse: function (_context, tokens) {
var accumulator = [];
var results = [];
tokens.forEach(function (token) {
switch (token.type) {
case 20 /* IDENT_TOKEN */:
case 0 /* STRING_TOKEN */:
accumulator.push(token.value);
break;
case 17 /* NUMBER_TOKEN */:
accumulator.push(token.number.toString());
break;
case 4 /* COMMA_TOKEN */:
results.push(accumulator.join(' '));
accumulator.length = 0;
break;
}
});
if (accumulator.length) {
results.push(accumulator.join(' '));
}
return results.map(function (result) { return (result.indexOf(' ') === -1 ? result : "'" + result + "'"); });
}
};
var fontSize = {
name: "font-size",
initialValue: '0',
prefix: false,
type: 3 /* TYPE_VALUE */,
format: 'length'
};
var fontWeight = {
name: 'font-weight',
initialValue: 'normal',
type: 0 /* VALUE */,
prefix: false,
parse: function (_context, token) {
if (isNumberToken(token)) {
return token.number;
}
if (isIdentToken(token)) {
switch (token.value) {
case 'bold':
return 700;
case 'normal':
default:
return 400;
}
}
return 400;
}
};
var fontVariant = {
name: 'font-variant',
initialValue: 'none',
type: 1 /* LIST */,
prefix: false,
parse: function (_context, tokens) {
return tokens.filter(isIdentToken).map(function (token) { return token.value; });
}
};
var fontStyle = {
name: 'font-style',
initialValue: 'normal',
prefix: false,
type: 2 /* IDENT_VALUE */,
parse: function (_context, overflow) {
switch (overflow) {
case 'oblique':
return "oblique" /* OBLIQUE */;
case 'italic':
return "italic" /* ITALIC */;
case 'normal':
default:
return "normal" /* NORMAL */;
}
}
};
var contains = function (bit, value) { return (bit & value) !== 0; };
var content = {
name: 'content',
initialValue: 'none',
type: 1 /* LIST */,
prefix: false,
parse: function (_context, tokens) {
if (tokens.length === 0) {
return [];
}
var first = tokens[0];
if (first.type === 20 /* IDENT_TOKEN */ && first.value === 'none') {
return [];
}
return tokens;
}
};
var counterIncrement = {
name: 'counter-increment',
initialValue: 'none',
prefix: true,
type: 1 /* LIST */,
parse: function (_context, tokens) {
if (tokens.length === 0) {
return null;
}
var first = tokens[0];
if (first.type === 20 /* IDENT_TOKEN */ && first.value === 'none') {
return null;
}
var increments = [];
var filtered = tokens.filter(nonWhiteSpace);
for (var i = 0; i < filtered.length; i++) {
var counter = filtered[i];
var next = filtered[i + 1];
if (counter.type === 20 /* IDENT_TOKEN */) {
var increment = next && isNumberToken(next) ? next.number : 1;
increments.push({ counter: counter.value, increment: increment });
}
}
return increments;
}
};
var counterReset = {
name: 'counter-reset',
initialValue: 'none',
prefix: true,
type: 1 /* LIST */,
parse: function (_context, tokens) {
if (tokens.length === 0) {
return [];
}
var resets = [];
var filtered = tokens.filter(nonWhiteSpace);
for (var i = 0; i < filtered.length; i++) {
var counter = filtered[i];
var next = filtered[i + 1];
if (isIdentToken(counter) && counter.value !== 'none') {
var reset = next && isNumberToken(next) ? next.number : 0;
resets.push({ counter: counter.value, reset: reset });
}
}
return resets;
}
};
var duration = {
name: 'duration',
initialValue: '0s',
prefix: false,
type: 1 /* LIST */,
parse: function (context, tokens) {
return tokens.filter(isDimensionToken).map(function (token) { return time.parse(context, token); });
}
};
var quotes = {
name: 'quotes',
initialValue: 'none',
prefix: true,
type: 1 /* LIST */,
parse: function (_context, tokens) {
if (tokens.length === 0) {
return null;
}
var first = tokens[0];
if (first.type === 20 /* IDENT_TOKEN */ && first.value === 'none') {
return null;
}
var quotes = [];
var filtered = tokens.filter(isStringToken);
if (filtered.length % 2 !== 0) {
return null;
}
for (var i = 0; i < filtered.length; i += 2) {
var open_1 = filtered[i].value;
var close_1 = filtered[i + 1].value;
quotes.push({ open: open_1, close: close_1 });
}
return quotes;
}
};
var getQuote = function (quotes, depth, open) {
if (!quotes) {
return '';
}
var quote = quotes[Math.min(depth, quotes.length - 1)];
if (!quote) {
return '';
}
return open ? quote.open : quote.close;
};
var boxShadow = {
name: 'box-shadow',
initialValue: 'none',
type: 1 /* LIST */,
prefix: false,
parse: function (context, tokens) {
if (tokens.length === 1 && isIdentWithValue(tokens[0], 'none')) {
return [];
}
return parseFunctionArgs(tokens).map(function (values) {
var shadow = {
color: 0x000000ff,
offsetX: ZERO_LENGTH,
offsetY: ZERO_LENGTH,
blur: ZERO_LENGTH,
spread: ZERO_LENGTH,
inset: false
};
var c = 0;
for (var i = 0; i < values.length; i++) {
var token = values[i];
if (isIdentWithValue(token, 'inset')) {
shadow.inset = true;
}
else if (isLength(token)) {
if (c === 0) {
shadow.offsetX = token;
}
else if (c === 1) {
shadow.offsetY = token;
}
else if (c === 2) {
shadow.blur = token;
}
else {
shadow.spread = token;
}
c++;
}
else {
shadow.color = color$1.parse(context, token);
}
}
return shadow;
});
}
};
var paintOrder = {
name: 'paint-order',
initialValue: 'normal',
prefix: false,
type: 1 /* LIST */,
parse: function (_context, tokens) {
var DEFAULT_VALUE = [0 /* FILL */, 1 /* STROKE */, 2 /* MARKERS */];
var layers = [];
tokens.filter(isIdentToken).forEach(function (token) {
switch (token.value) {
case 'stroke':
layers.push(1 /* STROKE */);
break;
case 'fill':
layers.push(0 /* FILL */);
break;
case 'markers':
layers.push(2 /* MARKERS */);
break;
}
});
DEFAULT_VALUE.forEach(function (value) {
if (layers.indexOf(value) === -1) {
layers.push(value);
}
});
return layers;
}
};
var webkitTextStrokeColor = {
name: "-webkit-text-stroke-color",
initialValue: 'currentcolor',
prefix: false,
type: 3 /* TYPE_VALUE */,
format: 'color'
};
var webkitTextStrokeWidth = {
name: "-webkit-text-stroke-width",
initialValue: '0',
type: 0 /* VALUE */,
prefix: false,
parse: function (_context, token) {
if (isDimensionToken(token)) {
return token.number;
}
return 0;
}
};
var CSSParsedDeclaration = /** @class */ (function () {
function CSSParsedDeclaration(context, declaration) {
var _a, _b;
this.animationDuration = parse(context, duration, declaration.animationDuration);
this.backgroundClip = parse(context, backgroundClip, declaration.backgroundClip);
this.backgroundColor = parse(context, backgroundColor, declaration.backgroundColor);
this.backgroundImage = parse(context, backgroundImage, declaration.backgroundImage);
this.backgroundOrigin = parse(context, backgroundOrigin, declaration.backgroundOrigin);
this.backgroundPosition = parse(context, backgroundPosition, declaration.backgroundPosition);
this.backgroundRepeat = parse(context, backgroundRepeat, declaration.backgroundRepeat);
this.backgroundSize = parse(context, backgroundSize, declaration.backgroundSize);
this.borderTopColor = parse(context, borderTopColor, declaration.borderTopColor);
this.borderRightColor = parse(context, borderRightColor, declaration.borderRightColor);
this.borderBottomColor = parse(context, borderBottomColor, declaration.borderBottomColor);
this.borderLeftColor = parse(context, borderLeftColor, declaration.borderLeftColor);
this.borderTopLeftRadius = parse(context, borderTopLeftRadius, declaration.borderTopLeftRadius);
this.borderTopRightRadius = parse(context, borderTopRightRadius, declaration.borderTopRightRadius);
this.borderBottomRightRadius = parse(context, borderBottomRightRadius, declaration.borderBottomRightRadius);
this.borderBottomLeftRadius = parse(context, borderBottomLeftRadius, declaration.borderBottomLeftRadius);
this.borderTopStyle = parse(context, borderTopStyle, declaration.borderTopStyle);
this.borderRightStyle = parse(context, borderRightStyle, declaration.borderRightStyle);
this.borderBottomStyle = parse(context, borderBottomStyle, declaration.borderBottomStyle);
this.borderLeftStyle = parse(context, borderLeftStyle, declaration.borderLeftStyle);
this.borderTopWidth = parse(context, borderTopWidth, declaration.borderTopWidth);
this.borderRightWidth = parse(context, borderRightWidth, declaration.borderRightWidth);
this.borderBottomWidth = parse(context, borderBottomWidth, declaration.borderBottomWidth);
this.borderLeftWidth = parse(context, borderLeftWidth, declaration.borderLeftWidth);
this.boxShadow = parse(context, boxShadow, declaration.boxShadow);
this.color = parse(context, color, declaration.color);
this.direction = parse(context, direction, declaration.direction);
this.display = parse(context, display, declaration.display);
this.float = parse(context, float, declaration.cssFloat);
this.fontFamily = parse(context, fontFamily, declaration.fontFamily);
this.fontSize = parse(context, fontSize, declaration.fontSize);
this.fontStyle = parse(context, fontStyle, declaration.fontStyle);
this.fontVariant = parse(context, fontVariant, declaration.fontVariant);
this.fontWeight = parse(context, fontWeight, declaration.fontWeight);
this.letterSpacing = parse(context, letterSpacing, declaration.letterSpacing);
this.lineBreak = parse(context, lineBreak, declaration.lineBreak);
this.lineHeight = parse(context, lineHeight, declaration.lineHeight);
this.listStyleImage = parse(context, listStyleImage, declaration.listStyleImage);
this.listStylePosition = parse(context, listStylePosition, declaration.listStylePosition);
this.listStyleType = parse(context, listStyleType, declaration.listStyleType);
this.marginTop = parse(context, marginTop, declaration.marginTop);
this.marginRight = parse(context, marginRight, declaration.marginRight);
this.marginBottom = parse(context, marginBottom, declaration.marginBottom);
this.marginLeft = parse(context, marginLeft, declaration.marginLeft);
this.opacity = parse(context, opacity, declaration.opacity);
var overflowTuple = parse(context, overflow, declaration.overflow);
this.overflowX = overflowTuple[0];
this.overflowY = overflowTuple[overflowTuple.length > 1 ? 1 : 0];
this.overflowWrap = parse(context, overflowWrap, declaration.overflowWrap);
this.paddingTop = parse(context, paddingTop, declaration.paddingTop);
this.paddingRight = parse(context, paddingRight, declaration.paddingRight);
this.paddingBottom = parse(context, paddingBottom, declaration.paddingBottom);
this.paddingLeft = parse(context, paddingLeft, declaration.paddingLeft);
this.paintOrder = parse(context, paintOrder, declaration.paintOrder);
this.position = parse(context, position, declaration.position);
this.textAlign = parse(context, textAlign, declaration.textAlign);
this.textDecorationColor = parse(context, textDecorationColor, (_a = declaration.textDecorationColor) !== null && _a !== void 0 ? _a : declaration.color);
this.textDecorationLine = parse(context, textDecorationLine, (_b = declaration.textDecorationLine) !== null && _b !== void 0 ? _b : declaration.textDecoration);
this.textShadow = parse(context, textShadow, declaration.textShadow);
this.textTransform = parse(context, textTransform, declaration.textTransform);
this.transform = parse(context, transform$1, declaration.transform);
this.transformOrigin = parse(context, transformOrigin, declaration.transformOrigin);
this.visibility = parse(context, visibility, declaration.visibility);
this.webkitTextStrokeColor = parse(context, webkitTextStrokeColor, declaration.webkitTextStrokeColor);
this.webkitTextStrokeWidth = parse(context, webkitTextStrokeWidth, declaration.webkitTextStrokeWidth);
this.wordBreak = parse(context, wordBreak, declaration.wordBreak);
this.zIndex = parse(context, zIndex, declaration.zIndex);
}
CSSParsedDeclaration.prototype.isVisible = function () {
return this.display > 0 && this.opacity > 0 && this.visibility === 0 /* VISIBLE */;
};
CSSParsedDeclaration.prototype.isTransparent = function () {
return isTransparent(this.backgroundColor);
};
CSSParsedDeclaration.prototype.isTransformed = function () {
return this.transform !== null;
};
CSSParsedDeclaration.prototype.isPositioned = function () {
return this.position !== 0 /* STATIC */;
};
CSSParsedDeclaration.prototype.isPositionedWithZIndex = function () {
return this.isPositioned() && !this.zIndex.auto;
};
CSSParsedDeclaration.prototype.isFloating = function () {
return this.float !== 0 /* NONE */;
};
CSSParsedDeclaration.prototype.isInlineLevel = function () {
return (contains(this.display, 4 /* INLINE */) ||
contains(this.display, 33554432 /* INLINE_BLOCK */) ||
contains(this.display, 268435456 /* INLINE_FLEX */) ||
contains(this.display, 536870912 /* INLINE_GRID */) ||
contains(this.display, 67108864 /* INLINE_LIST_ITEM */) ||
contains(this.display, 134217728 /* INLINE_TABLE */));
};
return CSSParsedDeclaration;
}());
var CSSParsedPseudoDeclaration = /** @class */ (function () {
function CSSParsedPseudoDeclaration(context, declaration) {
this.content = parse(context, content, declaration.content);
this.quotes = parse(context, quotes, declaration.quotes);
}
return CSSParsedPseudoDeclaration;
}());
var CSSParsedCounterDeclaration = /** @class */ (function () {
function CSSParsedCounterDeclaration(context, declaration) {
this.counterIncrement = parse(context, counterIncrement, declaration.counterIncrement);
this.counterReset = parse(context, counterReset, declaration.counterReset);
}
return CSSParsedCounterDeclaration;
}());
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var parse = function (context, descriptor, style) {
var tokenizer = new Tokenizer();
var value = style !== null && typeof style !== 'undefined' ? style.toString() : descriptor.initialValue;
tokenizer.write(value);
var parser = new Parser(tokenizer.read());
switch (descriptor.type) {
case 2 /* IDENT_VALUE */:
var token = parser.parseComponentValue();
return descriptor.parse(context, isIdentToken(token) ? token.value : descriptor.initialValue);
case 0 /* VALUE */:
return descriptor.parse(context, parser.parseComponentValue());
case 1 /* LIST */:
return descriptor.parse(context, parser.parseComponentValues());
case 4 /* TOKEN_VALUE */:
return parser.parseComponentValue();
case 3 /* TYPE_VALUE */:
switch (descriptor.format) {
case 'angle':
return angle.parse(context, parser.parseComponentValue());
case 'color':
return color$1.parse(context, parser.parseComponentValue());
case 'image':
return image.parse(context, parser.parseComponentValue());
case 'length':
var length_1 = parser.parseComponentValue();
return isLength(length_1) ? length_1 : ZERO_LENGTH;
case 'length-percentage':
var value_1 = parser.parseComponentValue();
return isLengthPercentage(value_1) ? value_1 : ZERO_LENGTH;
case 'time':
return time.parse(context, parser.parseComponentValue());
}
break;
}
};
var elementDebuggerAttribute = 'data-html2canvas-debug';
var getElementDebugType = function (element) {
var attribute = element.getAttribute(elementDebuggerAttribute);
switch (attribute) {
case 'all':
return 1 /* ALL */;
case 'clone':
return 2 /* CLONE */;
case 'parse':
return 3 /* PARSE */;
case 'render':
return 4 /* RENDER */;
default:
return 0 /* NONE */;
}
};
var isDebugging = function (element, type) {
var elementType = getElementDebugType(element);
return elementType === 1 /* ALL */ || type === elementType;
};
var ElementContainer = /** @class */ (function () {
function ElementContainer(context, element) {
this.context = context;
this.textNodes = [];
this.elements = [];
this.flags = 0;
if (isDebugging(element, 3 /* PARSE */)) {
debugger;
}
this.styles = new CSSParsedDeclaration(context, window.getComputedStyle(element, null));
if (isHTMLElementNode(element)) {
if (this.styles.animationDuration.some(function (duration) { return duration > 0; })) {
element.style.animationDuration = '0s';
}
if (this.styles.transform !== null) {
// getBoundingClientRect takes transforms into account
element.style.transform = 'none';
}
}
this.bounds = parseBounds(this.context, element);
if (isDebugging(element, 4 /* RENDER */)) {
this.flags |= 16 /* DEBUG_RENDER */;
}
}
return ElementContainer;
}());
/*
* text-segmentation 1.0.3 <https://github.com/niklasvh/text-segmentation>
* Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
* Released under MIT License
*/
var base64 = 'AAAAAAAAAAAAEA4AGBkAAFAaAAACAAAAAAAIABAAGAAwADgACAAQAAgAEAAIABAACAAQAAgAEAAIABAACAAQAAgAEAAIABAAQABIAEQATAAIABAACAAQAAgAEAAIABAAVABcAAgAEAAIABAACAAQAGAAaABwAHgAgACIAI4AlgAIABAAmwCjAKgAsAC2AL4AvQDFAMoA0gBPAVYBWgEIAAgACACMANoAYgFkAWwBdAF8AX0BhQGNAZUBlgGeAaMBlQGWAasBswF8AbsBwwF0AcsBYwHTAQgA2wG/AOMBdAF8AekB8QF0AfkB+wHiAHQBfAEIAAMC5gQIAAsCEgIIAAgAFgIeAggAIgIpAggAMQI5AkACygEIAAgASAJQAlgCYAIIAAgACAAKBQoFCgUTBRMFGQUrBSsFCAAIAAgACAAIAAgACAAIAAgACABdAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABoAmgCrwGvAQgAbgJ2AggAHgEIAAgACADnAXsCCAAIAAgAgwIIAAgACAAIAAgACACKAggAkQKZAggAPADJAAgAoQKkAqwCsgK6AsICCADJAggA0AIIAAgACAAIANYC3gIIAAgACAAIAAgACABAAOYCCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAkASoB+QIEAAgACAA8AEMCCABCBQgACABJBVAFCAAIAAgACAAIAAgACAAIAAgACABTBVoFCAAIAFoFCABfBWUFCAAIAAgACAAIAAgAbQUIAAgACAAIAAgACABzBXsFfQWFBYoFigWKBZEFigWKBYoFmAWfBaYFrgWxBbkFCAAIAAgACAAIAAgACAAIAAgACAAIAMEFCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAMgFCADQBQgACAAIAAgACAAIAAgACAAIAAgACAAIAO4CCAAIAAgAiQAIAAgACABAAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAD0AggACAD8AggACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIANYFCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAMDvwAIAAgAJAIIAAgACAAIAAgACAAIAAgACwMTAwgACAB9BOsEGwMjAwgAKwMyAwsFYgE3A/MEPwMIAEUDTQNRAwgAWQOsAGEDCAAIAAgACAAIAAgACABpAzQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFIQUoBSwFCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABtAwgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABMAEwACAAIAAgACAAIABgACAAIAAgACAC/AAgACAAyAQgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACACAAIAAwAAgACAAIAAgACAAIAAgACAAIAAAARABIAAgACAAIABQASAAIAAgAIABwAEAAjgCIABsAqAC2AL0AigDQAtwC+IJIQqVAZUBWQqVAZUBlQGVAZUBlQGrC5UBlQGVAZUBlQGVAZUBlQGVAXsKlQGVAbAK6wsrDGUMpQzlDJUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAfAKAAuZA64AtwCJALoC6ADwAAgAuACgA/oEpgO6AqsD+AAIAAgAswMIAAgACAAIAIkAuwP5AfsBwwPLAwgACAAIAAgACADRA9kDCAAIAOED6QMIAAgACAAIAAgACADuA/YDCAAIAP4DyQAIAAgABgQIAAgAXQAOBAgACAAIAAgACAAIABMECAAIAAgACAAIAAgACAD8AAQBCAAIAAgAGgQiBCoECAExBAgAEAEIAAgACAAIAAgACAAIAAgACAAIAAgACAA4BAgACABABEYECAAIAAgATAQYAQgAVAQIAAgACAAIAAgACAAIAAgACAAIAFoECAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAOQEIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAB+BAcACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAEABhgSMBAgACAAIAAgAlAQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAwAEAAQABAADAAMAAwADAAQABAAEAAQABAAEAAQABHATAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAdQMIAAgACAAIAAgACAAIAMkACAAIAAgAfQMIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACACFA4kDCAAIAAgACAAIAOcBCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAIcDCAAIAAgACAAIAAgACAAIAAgACAAIAJEDCAAIAAgACADFAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABgBAgAZgQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAbAQCBXIECAAIAHkECAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABAAJwEQACjBKoEsgQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAC6BMIECAAIAAgACAAIAAgACABmBAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAxwQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAGYECAAIAAgAzgQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAigWKBYoFigWKBYoFigWKBd0FXwUIAOIF6gXxBYoF3gT5BQAGCAaKBYoFigWKBYoFigWKBYoFigWKBYoFigXWBIoFigWKBYoFigWKBYoFigWKBYsFEAaKBYoFigWKBYoFigWKBRQGCACKBYoFigWKBQgACAAIANEECAAIABgGigUgBggAJgYIAC4GMwaKBYoF0wQ3Bj4GigWKBYoFigWKBYoFigWKBYoFigWKBYoFigUIAAgACAAIAAgACAAIAAgAigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWLBf///////wQABAAEAAQABAAEAAQABAAEAAQAAwAEAAQAAgAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAQADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAUAAAAFAAUAAAAFAAUAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEAAQABAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUAAQAAAAUABQAFAAUABQAFAAAAAAAFAAUAAAAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAFAAUAAQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABwAFAAUABQAFAAAABwAHAAcAAAAHAAcABwAFAAEAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAFAAcABwAFAAUAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAQABAAAAAAAAAAAAAAAFAAUABQAFAAAABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAHAAcABwAHAAcAAAAHAAcAAAAAAAUABQAHAAUAAQAHAAEABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABwABAAUABQAFAAUAAAAAAAAAAAAAAAEAAQABAAEAAQABAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABwAFAAUAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUAAQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABQANAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAAEAAQABAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEAAQABAAEAAQABAAEAAQABAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAQABAAEAAQABAAEAAQABAAAAAAAAAAAAAAAAAAAAAAABQAHAAUABQAFAAAAAAAAAAcABQAFAAUABQAFAAQABAAEAAQABAAEAAQABAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUAAAAFAAUABQAFAAUAAAAFAAUABQAAAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAAAAAAAAAAAAUABQAFAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAHAAUAAAAHAAcABwAFAAUABQAFAAUABQAFAAUABwAHAAcABwAFAAcABwAAAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABwAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAUABwAHAAUABQAFAAUAAAAAAAcABwAAAAAABwAHAAUAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAABQAFAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAABwAHAAcABQAFAAAAAAAAAAAABQAFAAAAAAAFAAUABQAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAFAAUABQAFAAUAAAAFAAUABwAAAAcABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAFAAUABwAFAAUABQAFAAAAAAAHAAcAAAAAAAcABwAFAAAAAAAAAAAAAAAAAAAABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAcABwAAAAAAAAAHAAcABwAAAAcABwAHAAUAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAABQAHAAcABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABwAHAAcABwAAAAUABQAFAAAABQAFAAUABQAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAcABQAHAAcABQAHAAcAAAAFAAcABwAAAAcABwAFAAUAAAAAAAAAAAAAAAAAAAAFAAUAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAUABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAFAAcABwAFAAUABQAAAAUAAAAHAAcABwAHAAcABwAHAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAHAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAABwAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAUAAAAFAAAAAAAAAAAABwAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABwAFAAUABQAFAAUAAAAFAAUAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABwAFAAUABQAFAAUABQAAAAUABQAHAAcABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABQAFAAAAAAAAAAAABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAcABQAFAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAHAAUABQAFAAUABQAFAAUABwAHAAcABwAHAAcABwAHAAUABwAHAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABwAHAAcABwAFAAUABwAHAAcAAAAAAAAAAAAHAAcABQAHAAcABwAHAAcABwAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAcABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABQAHAAUABQAFAAUABQAFAAUAAAAFAAAABQAAAAAABQAFAAUABQAFAAUABQAFAAcABwAHAAcABwAHAAUABQAFAAUABQAFAAUABQAFAAUAAAAAAAUABQAFAAUABQAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABwAFAAcABwAHAAcABwAFAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAUABQAFAAUABwAHAAUABQAHAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAcABQAFAAcABwAHAAUABwAFAAUABQAHAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAcABwAHAAcABwAHAAUABQAFAAUABQAFAAUABQAHAAcABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAcABQAFAAUABQAFAAUABQAAAAAAAAAAAAUAAAAAAAAAAAAAAAAABQAAAAAABwAFAAUAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUAAAAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAABQAAAAAAAAAFAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAUABQAHAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAHAAcABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAHAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAcABwAFAAUABQAFAAcABwAFAAUABwAHAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAcABwAFAAUABwAHAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAFAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAFAAUABQAAAAAABQAFAAAAAAAAAAAAAAAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABQAFAAcABwAAAAAAAAAAAAAABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAFAAcABwAFAAcABwAAAAcABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAAAAAAAAAAAAAAAAAFAAUABQAAAAUABQAAAAAAAAAAAAAABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABQAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABwAFAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAcABQAFAAUABQAFAAUABQAFAAUABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAHAAcABQAHAAUABQAAAAAAAAAAAAAAAAAFAAAABwAHAAcABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABwAHAAcABwAAAAAABwAHAAAAAAAHAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAAAAAAFAAUABQAFAAUABQAFAAAAAAAAAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAFAAUABQAFAAUABwAHAAUABQAFAAcABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAHAAcABQAFAAUABQAFAAUABwAFAAcABwAFAAcABQAFAAcABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAHAAcABQAFAAUABQAAAAAABwAHAAcABwAFAAUABwAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAHAAUABQAFAAUABQAFAAUABQAHAAcABQAHAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABwAFAAcABwAFAAUABQAFAAUABQAHAAUAAAAAAAAAAAAAAAAAAAAAAAcABwAFAAUABQAFAAcABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAFAAUABQAFAAUABQAHAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAFAAAAAAAFAAUABwAHAAcABwAFAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABwAHAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABQAFAAUABQAFAAUABQAAAAUABQAFAAUABQAFAAcABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAAAHAAUABQAFAAUABQAFAAUABwAFAAUABwAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUAAAAAAAAABQAAAAUABQAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAHAAcAAAAFAAUAAAAHAAcABQAHAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABwAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAAAAAAAAAAAAAAAAAAABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAUABQAFAAAAAAAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAABQAFAAUABQAFAAUABQAAAAUABQAAAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAFAAUABQAFAAUADgAOAA4ADgAOAA4ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAAAAAAAAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAMAAwADAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAAAAAAAAAAAAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAAAAAAAAAAAAsADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwACwAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAADgAOAA4AAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAAAA4ADgAOAA4ADgAOAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAAAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAAAA4AAAAOAAAAAAAAAAAAAAAAAA4AAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAADgAAAAAAAAAAAA4AAAAOAAAAAAAAAAAADgAOAA4AAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAAAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4AAAAAAA4ADgAOAA4ADgAOAA4ADgAOAAAADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4AAAAAAAAAAAAAAAAAAAAAAA4ADgAOAA4ADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAOAA4ADgAOAA4ADgAAAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAAAAAAAAA=';
/*
* utrie 1.0.2 <https://github.com/niklasvh/utrie>
* Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
* Released under MIT License
*/
var chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// Use a lookup table to find the index.
var lookup$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
for (var i$1 = 0; i$1 < chars$1.length; i$1++) {
lookup$1[chars$1.charCodeAt(i$1)] = i$1;
}
var decode = function (base64) {
var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
if (base64[base64.length - 1] === '=') {
bufferLength--;
if (base64[base64.length - 2] === '=') {
bufferLength--;
}
}
var buffer = typeof ArrayBuffer !== 'undefined' &&
typeof Uint8Array !== 'undefined' &&
typeof Uint8Array.prototype.slice !== 'undefined'
? new ArrayBuffer(bufferLength)
: new Array(bufferLength);
var bytes = Array.isArray(buffer) ? buffer : new Uint8Array(buffer);
for (i = 0; i < len; i += 4) {
encoded1 = lookup$1[base64.charCodeAt(i)];
encoded2 = lookup$1[base64.charCodeAt(i + 1)];
encoded3 = lookup$1[base64.charCodeAt(i + 2)];
encoded4 = lookup$1[base64.charCodeAt(i + 3)];
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return buffer;
};
var polyUint16Array = function (buffer) {
var length = buffer.length;
var bytes = [];
for (var i = 0; i < length; i += 2) {
bytes.push((buffer[i + 1] << 8) | buffer[i]);
}
return bytes;
};
var polyUint32Array = function (buffer) {
var length = buffer.length;
var bytes = [];
for (var i = 0; i < length; i += 4) {
bytes.push((buffer[i + 3] << 24) | (buffer[i + 2] << 16) | (buffer[i + 1] << 8) | buffer[i]);
}
return bytes;
};
/** Shift size for getting the index-2 table offset. */
var UTRIE2_SHIFT_2 = 5;
/** Shift size for getting the index-1 table offset. */
var UTRIE2_SHIFT_1 = 6 + 5;
/**
* Shift size for shifting left the index array values.
* Increases possible data size with 16-bit index values at the cost
* of compactability.
* This requires data blocks to be aligned by UTRIE2_DATA_GRANULARITY.
*/
var UTRIE2_INDEX_SHIFT = 2;
/**
* Difference between the two shift sizes,
* for getting an index-1 offset from an index-2 offset. 6=11-5
*/
var UTRIE2_SHIFT_1_2 = UTRIE2_SHIFT_1 - UTRIE2_SHIFT_2;
/**
* The part of the index-2 table for U+D800..U+DBFF stores values for
* lead surrogate code _units_ not code _points_.
* Values for lead surrogate code _points_ are indexed with this portion of the table.
* Length=32=0x20=0x400>>UTRIE2_SHIFT_2. (There are 1024=0x400 lead surrogates.)
*/
var UTRIE2_LSCP_INDEX_2_OFFSET = 0x10000 >> UTRIE2_SHIFT_2;
/** Number of entries in a data block. 32=0x20 */
var UTRIE2_DATA_BLOCK_LENGTH = 1 << UTRIE2_SHIFT_2;
/** Mask for getting the lower bits for the in-data-block offset. */
var UTRIE2_DATA_MASK = UTRIE2_DATA_BLOCK_LENGTH - 1;
var UTRIE2_LSCP_INDEX_2_LENGTH = 0x400 >> UTRIE2_SHIFT_2;
/** Count the lengths of both BMP pieces. 2080=0x820 */
var UTRIE2_INDEX_2_BMP_LENGTH = UTRIE2_LSCP_INDEX_2_OFFSET + UTRIE2_LSCP_INDEX_2_LENGTH;
/**
* The 2-byte UTF-8 version of the index-2 table follows at offset 2080=0x820.
* Length 32=0x20 for lead bytes C0..DF, regardless of UTRIE2_SHIFT_2.
*/
var UTRIE2_UTF8_2B_INDEX_2_OFFSET = UTRIE2_INDEX_2_BMP_LENGTH;
var UTRIE2_UTF8_2B_INDEX_2_LENGTH = 0x800 >> 6; /* U+0800 is the first code point after 2-byte UTF-8 */
/**
* The index-1 table, only used for supplementary code points, at offset 2112=0x840.
* Variable length, for code points up to highStart, where the last single-value range starts.
* Maximum length 512=0x200=0x100000>>UTRIE2_SHIFT_1.
* (For 0x100000 supplementary code points U+10000..U+10ffff.)
*
* The part of the index-2 table for supplementary code points starts
* after this index-1 table.
*
* Both the index-1 table and the following part of the index-2 table
* are omitted completely if there is only BMP data.
*/
var UTRIE2_INDEX_1_OFFSET = UTRIE2_UTF8_2B_INDEX_2_OFFSET + UTRIE2_UTF8_2B_INDEX_2_LENGTH;
/**
* Number of index-1 entries for the BMP. 32=0x20
* This part of the index-1 table is omitted from the serialized form.
*/
var UTRIE2_OMITTED_BMP_INDEX_1_LENGTH = 0x10000 >> UTRIE2_SHIFT_1;
/** Number of entries in an index-2 block. 64=0x40 */
var UTRIE2_INDEX_2_BLOCK_LENGTH = 1 << UTRIE2_SHIFT_1_2;
/** Mask for getting the lower bits for the in-index-2-block offset. */
var UTRIE2_INDEX_2_MASK = UTRIE2_INDEX_2_BLOCK_LENGTH - 1;
var slice16 = function (view, start, end) {
if (view.slice) {
return view.slice(start, end);
}
return new Uint16Array(Array.prototype.slice.call(view, start, end));
};
var slice32 = function (view, start, end) {
if (view.slice) {
return view.slice(start, end);
}
return new Uint32Array(Array.prototype.slice.call(view, start, end));
};
var createTrieFromBase64 = function (base64, _byteLength) {
var buffer = decode(base64);
var view32 = Array.isArray(buffer) ? polyUint32Array(buffer) : new Uint32Array(buffer);
var view16 = Array.isArray(buffer) ? polyUint16Array(buffer) : new Uint16Array(buffer);
var headerLength = 24;
var index = slice16(view16, headerLength / 2, view32[4] / 2);
var data = view32[5] === 2
? slice16(view16, (headerLength + view32[4]) / 2)
: slice32(view32, Math.ceil((headerLength + view32[4]) / 4));
return new Trie(view32[0], view32[1], view32[2], view32[3], index, data);
};
var Trie = /** @class */ (function () {
function Trie(initialValue, errorValue, highStart, highValueIndex, index, data) {
this.initialValue = initialValue;
this.errorValue = errorValue;
this.highStart = highStart;
this.highValueIndex = highValueIndex;
this.index = index;
this.data = data;
}
/**
* Get the value for a code point as stored in the Trie.
*
* @param codePoint the code point
* @return the value
*/
Trie.prototype.get = function (codePoint) {
var ix;
if (codePoint >= 0) {
if (codePoint < 0x0d800 || (codePoint > 0x0dbff && codePoint <= 0x0ffff)) {
// Ordinary BMP code point, excluding leading surrogates.
// BMP uses a single level lookup. BMP index starts at offset 0 in the Trie2 index.
// 16 bit data is stored in the index array itself.
ix = this.index[codePoint >> UTRIE2_SHIFT_2];
ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK);
return this.data[ix];
}
if (codePoint <= 0xffff) {
// Lead Surrogate Code Point. A Separate index section is stored for
// lead surrogate code units and code points.
// The main index has the code unit data.
// For this function, we need the code point data.
// Note: this expression could be refactored for slightly improved efficiency, but
// surrogate code points will be so rare in practice that it's not worth it.
ix = this.index[UTRIE2_LSCP_INDEX_2_OFFSET + ((codePoint - 0xd800) >> UTRIE2_SHIFT_2)];
ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK);
return this.data[ix];
}
if (codePoint < this.highStart) {
// Supplemental code point, use two-level lookup.
ix = UTRIE2_INDEX_1_OFFSET - UTRIE2_OMITTED_BMP_INDEX_1_LENGTH + (codePoint >> UTRIE2_SHIFT_1);
ix = this.index[ix];
ix += (codePoint >> UTRIE2_SHIFT_2) & UTRIE2_INDEX_2_MASK;
ix = this.index[ix];
ix = (ix << UTRIE2_INDEX_SHIFT) + (codePoint & UTRIE2_DATA_MASK);
return this.data[ix];
}
if (codePoint <= 0x10ffff) {
return this.data[this.highValueIndex];
}
}
// Fall through. The code point is outside of the legal range of 0..0x10ffff.
return this.errorValue;
};
return Trie;
}());
/*
* base64-arraybuffer 1.0.2 <https://github.com/niklasvh/base64-arraybuffer>
* Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
* Released under MIT License
*/
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// Use a lookup table to find the index.
var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
for (var i = 0; i < chars.length; i++) {
lookup[chars.charCodeAt(i)] = i;
}
var Prepend = 1;
var CR = 2;
var LF = 3;
var Control = 4;
var Extend = 5;
var SpacingMark = 7;
var L = 8;
var V = 9;
var T = 10;
var LV = 11;
var LVT = 12;
var ZWJ = 13;
var Extended_Pictographic = 14;
var RI = 15;
var toCodePoints = function (str) {
var codePoints = [];
var i = 0;
var length = str.length;
while (i < length) {
var value = str.charCodeAt(i++);
if (value >= 0xd800 && value <= 0xdbff && i < length) {
var extra = str.charCodeAt(i++);
if ((extra & 0xfc00) === 0xdc00) {
codePoints.push(((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000);
}
else {
codePoints.push(value);
i--;
}
}
else {
codePoints.push(value);
}
}
return codePoints;
};
var fromCodePoint = function () {
var codePoints = [];
for (var _i = 0; _i < arguments.length; _i++) {
codePoints[_i] = arguments[_i];
}
if (String.fromCodePoint) {
return String.fromCodePoint.apply(String, codePoints);
}
var length = codePoints.length;
if (!length) {
return '';
}
var codeUnits = [];
var index = -1;
var result = '';
while (++index < length) {
var codePoint = codePoints[index];
if (codePoint <= 0xffff) {
codeUnits.push(codePoint);
}
else {
codePoint -= 0x10000;
codeUnits.push((codePoint >> 10) + 0xd800, (codePoint % 0x400) + 0xdc00);
}
if (index + 1 === length || codeUnits.length > 0x4000) {
result += String.fromCharCode.apply(String, codeUnits);
codeUnits.length = 0;
}
}
return result;
};
var UnicodeTrie = createTrieFromBase64(base64);
var BREAK_NOT_ALLOWED = '×';
var BREAK_ALLOWED = '÷';
var codePointToClass = function (codePoint) { return UnicodeTrie.get(codePoint); };
var _graphemeBreakAtIndex = function (_codePoints, classTypes, index) {
var prevIndex = index - 2;
var prev = classTypes[prevIndex];
var current = classTypes[index - 1];
var next = classTypes[index];
// GB3 Do not break between a CR and LF
if (current === CR && next === LF) {
return BREAK_NOT_ALLOWED;
}
// GB4 Otherwise, break before and after controls.
if (current === CR || current === LF || current === Control) {
return BREAK_ALLOWED;
}
// GB5
if (next === CR || next === LF || next === Control) {
return BREAK_ALLOWED;
}
// Do not break Hangul syllable sequences.
// GB6
if (current === L && [L, V, LV, LVT].indexOf(next) !== -1) {
return BREAK_NOT_ALLOWED;
}
// GB7
if ((current === LV || current === V) && (next === V || next === T)) {
return BREAK_NOT_ALLOWED;
}
// GB8
if ((current === LVT || current === T) && next === T) {
return BREAK_NOT_ALLOWED;
}
// GB9 Do not break before extending characters or ZWJ.
if (next === ZWJ || next === Extend) {
return BREAK_NOT_ALLOWED;
}
// Do not break before SpacingMarks, or after Prepend characters.
// GB9a
if (next === SpacingMark) {
return BREAK_NOT_ALLOWED;
}
// GB9a
if (current === Prepend) {
return BREAK_NOT_ALLOWED;
}
// GB11 Do not break within emoji modifier sequences or emoji zwj sequences.
if (current === ZWJ && next === Extended_Pictographic) {
while (prev === Extend) {
prev = classTypes[--prevIndex];
}
if (prev === Extended_Pictographic) {
return BREAK_NOT_ALLOWED;
}
}
// GB12 Do not break within emoji flag sequences.
// That is, do not break between regional indicator (RI) symbols
// if there is an odd number of RI characters before the break point.
if (current === RI && next === RI) {
var countRI = 0;
while (prev === RI) {
countRI++;
prev = classTypes[--prevIndex];
}
if (countRI % 2 === 0) {
return BREAK_NOT_ALLOWED;
}
}
return BREAK_ALLOWED;
};
var GraphemeBreaker = function (str) {
var codePoints = toCodePoints(str);
var length = codePoints.length;
var index = 0;
var lastEnd = 0;
var classTypes = codePoints.map(codePointToClass);
return {
next: function () {
if (index >= length) {
return { done: true, value: null };
}
var graphemeBreak = BREAK_NOT_ALLOWED;
while (index < length &&
(graphemeBreak = _graphemeBreakAtIndex(codePoints, classTypes, ++index)) === BREAK_NOT_ALLOWED) { }
if (graphemeBreak !== BREAK_NOT_ALLOWED || index === length) {
var value = fromCodePoint.apply(null, codePoints.slice(lastEnd, index));
lastEnd = index;
return { value: value, done: false };
}
return { done: true, value: null };
},
};
};
var splitGraphemes = function (str) {
var breaker = GraphemeBreaker(str);
var graphemes = [];
var bk;
while (!(bk = breaker.next()).done) {
if (bk.value) {
graphemes.push(bk.value.slice());
}
}
return graphemes;
};
var testRangeBounds = function (document) {
var TEST_HEIGHT = 123;
if (document.createRange) {
var range = document.createRange();
if (range.getBoundingClientRect) {
var testElement = document.createElement('boundtest');
testElement.style.height = TEST_HEIGHT + "px";
testElement.style.display = 'block';
document.body.appendChild(testElement);
range.selectNode(testElement);
var rangeBounds = range.getBoundingClientRect();
var rangeHeight = Math.round(rangeBounds.height);
document.body.removeChild(testElement);
if (rangeHeight === TEST_HEIGHT) {
return true;
}
}
}
return false;
};
var testIOSLineBreak = function (document) {
var testElement = document.createElement('boundtest');
testElement.style.width = '50px';
testElement.style.display = 'block';
testElement.style.fontSize = '12px';
testElement.style.letterSpacing = '0px';
testElement.style.wordSpacing = '0px';
document.body.appendChild(testElement);
var range = document.createRange();
testElement.innerHTML = typeof ''.repeat === 'function' ? '&#128104;'.repeat(10) : '';
var node = testElement.firstChild;
var textList = toCodePoints$1(node.data).map(function (i) { return fromCodePoint$1(i); });
var offset = 0;
var prev = {};
// ios 13 does not handle range getBoundingClientRect line changes correctly #2177
var supports = textList.every(function (text, i) {
range.setStart(node, offset);
range.setEnd(node, offset + text.length);
var rect = range.getBoundingClientRect();
offset += text.length;
var boundAhead = rect.x > prev.x || rect.y > prev.y;
prev = rect;
if (i === 0) {
return true;
}
return boundAhead;
});
document.body.removeChild(testElement);
return supports;
};
var testCORS = function () { return typeof new Image().crossOrigin !== 'undefined'; };
var testResponseType = function () { return typeof new XMLHttpRequest().responseType === 'string'; };
var testSVG = function (document) {
var img = new Image();
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
if (!ctx) {
return false;
}
img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";
try {
ctx.drawImage(img, 0, 0);
canvas.toDataURL();
}
catch (e) {
return false;
}
return true;
};
var isGreenPixel = function (data) {
return data[0] === 0 && data[1] === 255 && data[2] === 0 && data[3] === 255;
};
var testForeignObject = function (document) {
var canvas = document.createElement('canvas');
var size = 100;
canvas.width = size;
canvas.height = size;
var ctx = canvas.getContext('2d');
if (!ctx) {
return Promise.reject(false);
}
ctx.fillStyle = 'rgb(0, 255, 0)';
ctx.fillRect(0, 0, size, size);
var img = new Image();
var greenImageSrc = canvas.toDataURL();
img.src = greenImageSrc;
var svg = createForeignObjectSVG(size, size, 0, 0, img);
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, size, size);
return loadSerializedSVG$1(svg)
.then(function (img) {
ctx.drawImage(img, 0, 0);
var data = ctx.getImageData(0, 0, size, size).data;
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, size, size);
var node = document.createElement('div');
node.style.backgroundImage = "url(" + greenImageSrc + ")";
node.style.height = size + "px";
// Firefox 55 does not render inline <img /> tags
return isGreenPixel(data)
? loadSerializedSVG$1(createForeignObjectSVG(size, size, 0, 0, node))
: Promise.reject(false);
})
.then(function (img) {
ctx.drawImage(img, 0, 0);
// Edge does not render background-images
return isGreenPixel(ctx.getImageData(0, 0, size, size).data);
})
.catch(function () { return false; });
};
var createForeignObjectSVG = function (width, height, x, y, node) {
var xmlns = 'http://www.w3.org/2000/svg';
var svg = document.createElementNS(xmlns, 'svg');
var foreignObject = document.createElementNS(xmlns, 'foreignObject');
svg.setAttributeNS(null, 'width', width.toString());
svg.setAttributeNS(null, 'height', height.toString());
foreignObject.setAttributeNS(null, 'width', '100%');
foreignObject.setAttributeNS(null, 'height', '100%');
foreignObject.setAttributeNS(null, 'x', x.toString());
foreignObject.setAttributeNS(null, 'y', y.toString());
foreignObject.setAttributeNS(null, 'externalResourcesRequired', 'true');
svg.appendChild(foreignObject);
foreignObject.appendChild(node);
return svg;
};
var loadSerializedSVG$1 = function (svg) {
return new Promise(function (resolve, reject) {
var img = new Image();
img.onload = function () { return resolve(img); };
img.onerror = reject;
img.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(new XMLSerializer().serializeToString(svg));
});
};
var FEATURES = {
get SUPPORT_RANGE_BOUNDS() {
var value = testRangeBounds(document);
Object.defineProperty(FEATURES, 'SUPPORT_RANGE_BOUNDS', { value: value });
return value;
},
get SUPPORT_WORD_BREAKING() {
var value = FEATURES.SUPPORT_RANGE_BOUNDS && testIOSLineBreak(document);
Object.defineProperty(FEATURES, 'SUPPORT_WORD_BREAKING', { value: value });
return value;
},
get SUPPORT_SVG_DRAWING() {
var value = testSVG(document);
Object.defineProperty(FEATURES, 'SUPPORT_SVG_DRAWING', { value: value });
return value;
},
get SUPPORT_FOREIGNOBJECT_DRAWING() {
var value = typeof Array.from === 'function' && typeof window.fetch === 'function'
? testForeignObject(document)
: Promise.resolve(false);
Object.defineProperty(FEATURES, 'SUPPORT_FOREIGNOBJECT_DRAWING', { value: value });
return value;
},
get SUPPORT_CORS_IMAGES() {
var value = testCORS();
Object.defineProperty(FEATURES, 'SUPPORT_CORS_IMAGES', { value: value });
return value;
},
get SUPPORT_RESPONSE_TYPE() {
var value = testResponseType();
Object.defineProperty(FEATURES, 'SUPPORT_RESPONSE_TYPE', { value: value });
return value;
},
get SUPPORT_CORS_XHR() {
var value = 'withCredentials' in new XMLHttpRequest();
Object.defineProperty(FEATURES, 'SUPPORT_CORS_XHR', { value: value });
return value;
},
get SUPPORT_NATIVE_TEXT_SEGMENTATION() {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var value = !!(typeof Intl !== 'undefined' && Intl.Segmenter);
Object.defineProperty(FEATURES, 'SUPPORT_NATIVE_TEXT_SEGMENTATION', { value: value });
return value;
}
};
var TextBounds = /** @class */ (function () {
function TextBounds(text, bounds) {
this.text = text;
this.bounds = bounds;
}
return TextBounds;
}());
var parseTextBounds = function (context, value, styles, node) {
var textList = breakText(value, styles);
var textBounds = [];
var offset = 0;
textList.forEach(function (text) {
if (styles.textDecorationLine.length || text.trim().length > 0) {
if (FEATURES.SUPPORT_RANGE_BOUNDS) {
var clientRects = createRange(node, offset, text.length).getClientRects();
if (clientRects.length > 1) {
var subSegments = segmentGraphemes(text);
var subOffset_1 = 0;
subSegments.forEach(function (subSegment) {
textBounds.push(new TextBounds(subSegment, Bounds.fromDOMRectList(context, createRange(node, subOffset_1 + offset, subSegment.length).getClientRects())));
subOffset_1 += subSegment.length;
});
}
else {
textBounds.push(new TextBounds(text, Bounds.fromDOMRectList(context, clientRects)));
}
}
else {
var replacementNode = node.splitText(text.length);
textBounds.push(new TextBounds(text, getWrapperBounds(context, node)));
node = replacementNode;
}
}
else if (!FEATURES.SUPPORT_RANGE_BOUNDS) {
node = node.splitText(text.length);
}
offset += text.length;
});
return textBounds;
};
var getWrapperBounds = function (context, node) {
var ownerDocument = node.ownerDocument;
if (ownerDocument) {
var wrapper = ownerDocument.createElement('html2canvaswrapper');
wrapper.appendChild(node.cloneNode(true));
var parentNode = node.parentNode;
if (parentNode) {
parentNode.replaceChild(wrapper, node);
var bounds = parseBounds(context, wrapper);
if (wrapper.firstChild) {
parentNode.replaceChild(wrapper.firstChild, wrapper);
}
return bounds;
}
}
return Bounds.EMPTY;
};
var createRange = function (node, offset, length) {
var ownerDocument = node.ownerDocument;
if (!ownerDocument) {
throw new Error('Node has no owner document');
}
var range = ownerDocument.createRange();
range.setStart(node, offset);
range.setEnd(node, offset + length);
return range;
};
var segmentGraphemes = function (value) {
if (FEATURES.SUPPORT_NATIVE_TEXT_SEGMENTATION) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var segmenter = new Intl.Segmenter(void 0, { granularity: 'grapheme' });
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return Array.from(segmenter.segment(value)).map(function (segment) { return segment.segment; });
}
return splitGraphemes(value);
};
var segmentWords = function (value, styles) {
if (FEATURES.SUPPORT_NATIVE_TEXT_SEGMENTATION) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var segmenter = new Intl.Segmenter(void 0, {
granularity: 'word'
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return Array.from(segmenter.segment(value)).map(function (segment) { return segment.segment; });
}
return breakWords(value, styles);
};
var breakText = function (value, styles) {
return styles.letterSpacing !== 0 ? segmentGraphemes(value) : segmentWords(value, styles);
};
// https://drafts.csswg.org/css-text/#word-separator
var wordSeparators = [0x0020, 0x00a0, 0x1361, 0x10100, 0x10101, 0x1039, 0x1091];
var breakWords = function (str, styles) {
var breaker = LineBreaker(str, {
lineBreak: styles.lineBreak,
wordBreak: styles.overflowWrap === "break-word" /* BREAK_WORD */ ? 'break-word' : styles.wordBreak
});
var words = [];
var bk;
var _loop_1 = function () {
if (bk.value) {
var value = bk.value.slice();
var codePoints = toCodePoints$1(value);
var word_1 = '';
codePoints.forEach(function (codePoint) {
if (wordSeparators.indexOf(codePoint) === -1) {
word_1 += fromCodePoint$1(codePoint);
}
else {
if (word_1.length) {
words.push(word_1);
}
words.push(fromCodePoint$1(codePoint));
word_1 = '';
}
});
if (word_1.length) {
words.push(word_1);
}
}
};
while (!(bk = breaker.next()).done) {
_loop_1();
}
return words;
};
var TextContainer = /** @class */ (function () {
function TextContainer(context, node, styles) {
this.text = transform(node.data, styles.textTransform);
this.textBounds = parseTextBounds(context, this.text, styles, node);
}
return TextContainer;
}());
var transform = function (text, transform) {
switch (transform) {
case 1 /* LOWERCASE */:
return text.toLowerCase();
case 3 /* CAPITALIZE */:
return text.replace(CAPITALIZE, capitalize);
case 2 /* UPPERCASE */:
return text.toUpperCase();
default:
return text;
}
};
var CAPITALIZE = /(^|\s|:|-|\(|\))([a-z])/g;
var capitalize = function (m, p1, p2) {
if (m.length > 0) {
return p1 + p2.toUpperCase();
}
return m;
};
var ImageElementContainer = /** @class */ (function (_super) {
__extends(ImageElementContainer, _super);
function ImageElementContainer(context, img) {
var _this = _super.call(this, context, img) || this;
_this.src = img.currentSrc || img.src;
_this.intrinsicWidth = img.naturalWidth;
_this.intrinsicHeight = img.naturalHeight;
_this.context.cache.addImage(_this.src);
return _this;
}
return ImageElementContainer;
}(ElementContainer));
var CanvasElementContainer = /** @class */ (function (_super) {
__extends(CanvasElementContainer, _super);
function CanvasElementContainer(context, canvas) {
var _this = _super.call(this, context, canvas) || this;
_this.canvas = canvas;
_this.intrinsicWidth = canvas.width;
_this.intrinsicHeight = canvas.height;
return _this;
}
return CanvasElementContainer;
}(ElementContainer));
var SVGElementContainer = /** @class */ (function (_super) {
__extends(SVGElementContainer, _super);
function SVGElementContainer(context, img) {
var _this = _super.call(this, context, img) || this;
var s = new XMLSerializer();
var bounds = parseBounds(context, img);
img.setAttribute('width', bounds.width + "px");
img.setAttribute('height', bounds.height + "px");
_this.svg = "data:image/svg+xml," + encodeURIComponent(s.serializeToString(img));
_this.intrinsicWidth = img.width.baseVal.value;
_this.intrinsicHeight = img.height.baseVal.value;
_this.context.cache.addImage(_this.svg);
return _this;
}
return SVGElementContainer;
}(ElementContainer));
var LIElementContainer = /** @class */ (function (_super) {
__extends(LIElementContainer, _super);
function LIElementContainer(context, element) {
var _this = _super.call(this, context, element) || this;
_this.value = element.value;
return _this;
}
return LIElementContainer;
}(ElementContainer));
var OLElementContainer = /** @class */ (function (_super) {
__extends(OLElementContainer, _super);
function OLElementContainer(context, element) {
var _this = _super.call(this, context, element) || this;
_this.start = element.start;
_this.reversed = typeof element.reversed === 'boolean' && element.reversed === true;
return _this;
}
return OLElementContainer;
}(ElementContainer));
var CHECKBOX_BORDER_RADIUS = [
{
type: 15 /* DIMENSION_TOKEN */,
flags: 0,
unit: 'px',
number: 3
}
];
var RADIO_BORDER_RADIUS = [
{
type: 16 /* PERCENTAGE_TOKEN */,
flags: 0,
number: 50
}
];
var reformatInputBounds = function (bounds) {
if (bounds.width > bounds.height) {
return new Bounds(bounds.left + (bounds.width - bounds.height) / 2, bounds.top, bounds.height, bounds.height);
}
else if (bounds.width < bounds.height) {
return new Bounds(bounds.left, bounds.top + (bounds.height - bounds.width) / 2, bounds.width, bounds.width);
}
return bounds;
};
var getInputValue = function (node) {
var value = node.type === PASSWORD ? new Array(node.value.length + 1).join('\u2022') : node.value;
return value.length === 0 ? node.placeholder || '' : value;
};
var CHECKBOX = 'checkbox';
var RADIO = 'radio';
var PASSWORD = 'password';
var INPUT_COLOR = 0x2a2a2aff;
var InputElementContainer = /** @class */ (function (_super) {
__extends(InputElementContainer, _super);
function InputElementContainer(context, input) {
var _this = _super.call(this, context, input) || this;
_this.type = input.type.toLowerCase();
_this.checked = input.checked;
_this.value = getInputValue(input);
if (_this.type === CHECKBOX || _this.type === RADIO) {
_this.styles.backgroundColor = 0xdededeff;
_this.styles.borderTopColor =
_this.styles.borderRightColor =
_this.styles.borderBottomColor =
_this.styles.borderLeftColor =
0xa5a5a5ff;
_this.styles.borderTopWidth =
_this.styles.borderRightWidth =
_this.styles.borderBottomWidth =
_this.styles.borderLeftWidth =
1;
_this.styles.borderTopStyle =
_this.styles.borderRightStyle =
_this.styles.borderBottomStyle =
_this.styles.borderLeftStyle =
1 /* SOLID */;
_this.styles.backgroundClip = [0 /* BORDER_BOX */];
_this.styles.backgroundOrigin = [0 /* BORDER_BOX */];
_this.bounds = reformatInputBounds(_this.bounds);
}
switch (_this.type) {
case CHECKBOX:
_this.styles.borderTopRightRadius =
_this.styles.borderTopLeftRadius =
_this.styles.borderBottomRightRadius =
_this.styles.borderBottomLeftRadius =
CHECKBOX_BORDER_RADIUS;
break;
case RADIO:
_this.styles.borderTopRightRadius =
_this.styles.borderTopLeftRadius =
_this.styles.borderBottomRightRadius =
_this.styles.borderBottomLeftRadius =
RADIO_BORDER_RADIUS;
break;
}
return _this;
}
return InputElementContainer;
}(ElementContainer));
var SelectElementContainer = /** @class */ (function (_super) {
__extends(SelectElementContainer, _super);
function SelectElementContainer(context, element) {
var _this = _super.call(this, context, element) || this;
var option = element.options[element.selectedIndex || 0];
_this.value = option ? option.text || '' : '';
return _this;
}
return SelectElementContainer;
}(ElementContainer));
var TextareaElementContainer = /** @class */ (function (_super) {
__extends(TextareaElementContainer, _super);
function TextareaElementContainer(context, element) {
var _this = _super.call(this, context, element) || this;
_this.value = element.value;
return _this;
}
return TextareaElementContainer;
}(ElementContainer));
var IFrameElementContainer = /** @class */ (function (_super) {
__extends(IFrameElementContainer, _super);
function IFrameElementContainer(context, iframe) {
var _this = _super.call(this, context, iframe) || this;
_this.src = iframe.src;
_this.width = parseInt(iframe.width, 10) || 0;
_this.height = parseInt(iframe.height, 10) || 0;
_this.backgroundColor = _this.styles.backgroundColor;
try {
if (iframe.contentWindow &&
iframe.contentWindow.document &&
iframe.contentWindow.document.documentElement) {
_this.tree = parseTree(context, iframe.contentWindow.document.documentElement);
// http://www.w3.org/TR/css3-background/#special-backgrounds
var documentBackgroundColor = iframe.contentWindow.document.documentElement
? parseColor(context, getComputedStyle(iframe.contentWindow.document.documentElement).backgroundColor)
: COLORS.TRANSPARENT;
var bodyBackgroundColor = iframe.contentWindow.document.body
? parseColor(context, getComputedStyle(iframe.contentWindow.document.body).backgroundColor)
: COLORS.TRANSPARENT;
_this.backgroundColor = isTransparent(documentBackgroundColor)
? isTransparent(bodyBackgroundColor)
? _this.styles.backgroundColor
: bodyBackgroundColor
: documentBackgroundColor;
}
}
catch (e) { }
return _this;
}
return IFrameElementContainer;
}(ElementContainer));
var LIST_OWNERS = ['OL', 'UL', 'MENU'];
var parseNodeTree = function (context, node, parent, root) {
for (var childNode = node.firstChild, nextNode = void 0; childNode; childNode = nextNode) {
nextNode = childNode.nextSibling;
if (isTextNode(childNode) && childNode.data.trim().length > 0) {
parent.textNodes.push(new TextContainer(context, childNode, parent.styles));
}
else if (isElementNode(childNode)) {
if (isSlotElement(childNode) && childNode.assignedNodes) {
childNode.assignedNodes().forEach(function (childNode) { return parseNodeTree(context, childNode, parent, root); });
}
else {
var container = createContainer(context, childNode);
if (container.styles.isVisible()) {
if (createsRealStackingContext(childNode, container, root)) {
container.flags |= 4 /* CREATES_REAL_STACKING_CONTEXT */;
}
else if (createsStackingContext(container.styles)) {
container.flags |= 2 /* CREATES_STACKING_CONTEXT */;
}
if (LIST_OWNERS.indexOf(childNode.tagName) !== -1) {
container.flags |= 8 /* IS_LIST_OWNER */;
}
parent.elements.push(container);
childNode.slot;
if (childNode.shadowRoot) {
parseNodeTree(context, childNode.shadowRoot, container, root);
}
else if (!isTextareaElement(childNode) &&
!isSVGElement(childNode) &&
!isSelectElement(childNode)) {
parseNodeTree(context, childNode, container, root);
}
}
}
}
}
};
var createContainer = function (context, element) {
if (isImageElement(element)) {
return new ImageElementContainer(context, element);
}
if (isCanvasElement(element)) {
return new CanvasElementContainer(context, element);
}
if (isSVGElement(element)) {
return new SVGElementContainer(context, element);
}
if (isLIElement(element)) {
return new LIElementContainer(context, element);
}
if (isOLElement(element)) {
return new OLElementContainer(context, element);
}
if (isInputElement(element)) {
return new InputElementContainer(context, element);
}
if (isSelectElement(element)) {
return new SelectElementContainer(context, element);
}
if (isTextareaElement(element)) {
return new TextareaElementContainer(context, element);
}
if (isIFrameElement(element)) {
return new IFrameElementContainer(context, element);
}
return new ElementContainer(context, element);
};
var parseTree = function (context, element) {
var container = createContainer(context, element);
container.flags |= 4 /* CREATES_REAL_STACKING_CONTEXT */;
parseNodeTree(context, element, container, container);
return container;
};
var createsRealStackingContext = function (node, container, root) {
return (container.styles.isPositionedWithZIndex() ||
container.styles.opacity < 1 ||
container.styles.isTransformed() ||
(isBodyElement(node) && root.styles.isTransparent()));
};
var createsStackingContext = function (styles) { return styles.isPositioned() || styles.isFloating(); };
var isTextNode = function (node) { return node.nodeType === Node.TEXT_NODE; };
var isElementNode = function (node) { return node.nodeType === Node.ELEMENT_NODE; };
var isHTMLElementNode = function (node) {
return isElementNode(node) && typeof node.style !== 'undefined' && !isSVGElementNode(node);
};
var isSVGElementNode = function (element) {
return typeof element.className === 'object';
};
var isLIElement = function (node) { return node.tagName === 'LI'; };
var isOLElement = function (node) { return node.tagName === 'OL'; };
var isInputElement = function (node) { return node.tagName === 'INPUT'; };
var isHTMLElement = function (node) { return node.tagName === 'HTML'; };
var isSVGElement = function (node) { return node.tagName === 'svg'; };
var isBodyElement = function (node) { return node.tagName === 'BODY'; };
var isCanvasElement = function (node) { return node.tagName === 'CANVAS'; };
var isVideoElement = function (node) { return node.tagName === 'VIDEO'; };
var isImageElement = function (node) { return node.tagName === 'IMG'; };
var isIFrameElement = function (node) { return node.tagName === 'IFRAME'; };
var isStyleElement = function (node) { return node.tagName === 'STYLE'; };
var isScriptElement = function (node) { return node.tagName === 'SCRIPT'; };
var isTextareaElement = function (node) { return node.tagName === 'TEXTAREA'; };
var isSelectElement = function (node) { return node.tagName === 'SELECT'; };
var isSlotElement = function (node) { return node.tagName === 'SLOT'; };
// https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name
var isCustomElement = function (node) { return node.tagName.indexOf('-') > 0; };
var CounterState = /** @class */ (function () {
function CounterState() {
this.counters = {};
}
CounterState.prototype.getCounterValue = function (name) {
var counter = this.counters[name];
if (counter && counter.length) {
return counter[counter.length - 1];
}
return 1;
};
CounterState.prototype.getCounterValues = function (name) {
var counter = this.counters[name];
return counter ? counter : [];
};
CounterState.prototype.pop = function (counters) {
var _this = this;
counters.forEach(function (counter) { return _this.counters[counter].pop(); });
};
CounterState.prototype.parse = function (style) {
var _this = this;
var counterIncrement = style.counterIncrement;
var counterReset = style.counterReset;
var canReset = true;
if (counterIncrement !== null) {
counterIncrement.forEach(function (entry) {
var counter = _this.counters[entry.counter];
if (counter && entry.increment !== 0) {
canReset = false;
if (!counter.length) {
counter.push(1);
}
counter[Math.max(0, counter.length - 1)] += entry.increment;
}
});
}
var counterNames = [];
if (canReset) {
counterReset.forEach(function (entry) {
var counter = _this.counters[entry.counter];
counterNames.push(entry.counter);
if (!counter) {
counter = _this.counters[entry.counter] = [];
}
counter.push(entry.reset);
});
}
return counterNames;
};
return CounterState;
}());
var ROMAN_UPPER = {
integers: [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],
values: ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
};
var ARMENIAN = {
integers: [
9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 90, 80, 70,
60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
],
values: [
'Ք',
'Փ',
'Ւ',
'Ց',
'Ր',
'Տ',
'Վ',
'Ս',
'Ռ',
'Ջ',
'Պ',
'Չ',
'Ո',
'Շ',
'Ն',
'Յ',
'Մ',
'Ճ',
'Ղ',
'Ձ',
'Հ',
'Կ',
'Ծ',
'Խ',
'Լ',
'Ի',
'Ժ',
'Թ',
'Ը',
'Է',
'Զ',
'Ե',
'Դ',
'Գ',
'Բ',
'Ա'
]
};
var HEBREW = {
integers: [
10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 400, 300, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20,
19, 18, 17, 16, 15, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
],
values: [
'י׳',
'ט׳',
'ח׳',
'ז׳',
'ו׳',
'ה׳',
'ד׳',
'ג׳',
'ב׳',
'א׳',
'ת',
'ש',
'ר',
'ק',
'צ',
'פ',
'ע',
'ס',
'נ',
'מ',
'ל',
'כ',
'יט',
'יח',
'יז',
'טז',
'טו',
'י',
'ט',
'ח',
'ז',
'ו',
'ה',
'ד',
'ג',
'ב',
'א'
]
};
var GEORGIAN = {
integers: [
10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 90,
80, 70, 60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
],
values: [
'ჵ',
'ჰ',
'ჯ',
'ჴ',
'ხ',
'ჭ',
'წ',
'ძ',
'ც',
'ჩ',
'შ',
'',
'ღ',
'ქ',
'ფ',
'ჳ',
'ტ',
'ს',
'რ',
'ჟ',
'პ',
'ო',
'ჲ',
'ნ',
'მ',
'ლ',
'კ',
'ი',
'თ',
'ჱ',
'ზ',
'ვ',
'ე',
'დ',
'გ',
'ბ',
'ა'
]
};
var createAdditiveCounter = function (value, min, max, symbols, fallback, suffix) {
if (value < min || value > max) {
return createCounterText(value, fallback, suffix.length > 0);
}
return (symbols.integers.reduce(function (string, integer, index) {
while (value >= integer) {
value -= integer;
string += symbols.values[index];
}
return string;
}, '') + suffix);
};
var createCounterStyleWithSymbolResolver = function (value, codePointRangeLength, isNumeric, resolver) {
var string = '';
do {
if (!isNumeric) {
value--;
}
string = resolver(value) + string;
value /= codePointRangeLength;
} while (value * codePointRangeLength >= codePointRangeLength);
return string;
};
var createCounterStyleFromRange = function (value, codePointRangeStart, codePointRangeEnd, isNumeric, suffix) {
var codePointRangeLength = codePointRangeEnd - codePointRangeStart + 1;
return ((value < 0 ? '-' : '') +
(createCounterStyleWithSymbolResolver(Math.abs(value), codePointRangeLength, isNumeric, function (codePoint) {
return fromCodePoint$1(Math.floor(codePoint % codePointRangeLength) + codePointRangeStart);
}) +
suffix));
};
var createCounterStyleFromSymbols = function (value, symbols, suffix) {
if (suffix === void 0) { suffix = '. '; }
var codePointRangeLength = symbols.length;
return (createCounterStyleWithSymbolResolver(Math.abs(value), codePointRangeLength, false, function (codePoint) { return symbols[Math.floor(codePoint % codePointRangeLength)]; }) + suffix);
};
var CJK_ZEROS = 1 << 0;
var CJK_TEN_COEFFICIENTS = 1 << 1;
var CJK_TEN_HIGH_COEFFICIENTS = 1 << 2;
var CJK_HUNDRED_COEFFICIENTS = 1 << 3;
var createCJKCounter = function (value, numbers, multipliers, negativeSign, suffix, flags) {
if (value < -9999 || value > 9999) {
return createCounterText(value, 4 /* CJK_DECIMAL */, suffix.length > 0);
}
var tmp = Math.abs(value);
var string = suffix;
if (tmp === 0) {
return numbers[0] + string;
}
for (var digit = 0; tmp > 0 && digit <= 4; digit++) {
var coefficient = tmp % 10;
if (coefficient === 0 && contains(flags, CJK_ZEROS) && string !== '') {
string = numbers[coefficient] + string;
}
else if (coefficient > 1 ||
(coefficient === 1 && digit === 0) ||
(coefficient === 1 && digit === 1 && contains(flags, CJK_TEN_COEFFICIENTS)) ||
(coefficient === 1 && digit === 1 && contains(flags, CJK_TEN_HIGH_COEFFICIENTS) && value > 100) ||
(coefficient === 1 && digit > 1 && contains(flags, CJK_HUNDRED_COEFFICIENTS))) {
string = numbers[coefficient] + (digit > 0 ? multipliers[digit - 1] : '') + string;
}
else if (coefficient === 1 && digit > 0) {
string = multipliers[digit - 1] + string;
}
tmp = Math.floor(tmp / 10);
}
return (value < 0 ? negativeSign : '') + string;
};
var CHINESE_INFORMAL_MULTIPLIERS = '十百千萬';
var CHINESE_FORMAL_MULTIPLIERS = '拾佰仟萬';
var JAPANESE_NEGATIVE = 'マイナス';
var KOREAN_NEGATIVE = '마이너스';
var createCounterText = function (value, type, appendSuffix) {
var defaultSuffix = appendSuffix ? '. ' : '';
var cjkSuffix = appendSuffix ? '、' : '';
var koreanSuffix = appendSuffix ? ', ' : '';
var spaceSuffix = appendSuffix ? ' ' : '';
switch (type) {
case 0 /* DISC */:
return '•' + spaceSuffix;
case 1 /* CIRCLE */:
return '◦' + spaceSuffix;
case 2 /* SQUARE */:
return '◾' + spaceSuffix;
case 5 /* DECIMAL_LEADING_ZERO */:
var string = createCounterStyleFromRange(value, 48, 57, true, defaultSuffix);
return string.length < 4 ? "0" + string : string;
case 4 /* CJK_DECIMAL */:
return createCounterStyleFromSymbols(value, '〇一二三四五六七八九', cjkSuffix);
case 6 /* LOWER_ROMAN */:
return createAdditiveCounter(value, 1, 3999, ROMAN_UPPER, 3 /* DECIMAL */, defaultSuffix).toLowerCase();
case 7 /* UPPER_ROMAN */:
return createAdditiveCounter(value, 1, 3999, ROMAN_UPPER, 3 /* DECIMAL */, defaultSuffix);
case 8 /* LOWER_GREEK */:
return createCounterStyleFromRange(value, 945, 969, false, defaultSuffix);
case 9 /* LOWER_ALPHA */:
return createCounterStyleFromRange(value, 97, 122, false, defaultSuffix);
case 10 /* UPPER_ALPHA */:
return createCounterStyleFromRange(value, 65, 90, false, defaultSuffix);
case 11 /* ARABIC_INDIC */:
return createCounterStyleFromRange(value, 1632, 1641, true, defaultSuffix);
case 12 /* ARMENIAN */:
case 49 /* UPPER_ARMENIAN */:
return createAdditiveCounter(value, 1, 9999, ARMENIAN, 3 /* DECIMAL */, defaultSuffix);
case 35 /* LOWER_ARMENIAN */:
return createAdditiveCounter(value, 1, 9999, ARMENIAN, 3 /* DECIMAL */, defaultSuffix).toLowerCase();
case 13 /* BENGALI */:
return createCounterStyleFromRange(value, 2534, 2543, true, defaultSuffix);
case 14 /* CAMBODIAN */:
case 30 /* KHMER */:
return createCounterStyleFromRange(value, 6112, 6121, true, defaultSuffix);
case 15 /* CJK_EARTHLY_BRANCH */:
return createCounterStyleFromSymbols(value, '子丑寅卯辰巳午未申酉戌亥', cjkSuffix);
case 16 /* CJK_HEAVENLY_STEM */:
return createCounterStyleFromSymbols(value, '甲乙丙丁戊己庚辛壬癸', cjkSuffix);
case 17 /* CJK_IDEOGRAPHIC */:
case 48 /* TRAD_CHINESE_INFORMAL */:
return createCJKCounter(value, '零一二三四五六七八九', CHINESE_INFORMAL_MULTIPLIERS, '負', cjkSuffix, CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
case 47 /* TRAD_CHINESE_FORMAL */:
return createCJKCounter(value, '零壹貳參肆伍陸柒捌玖', CHINESE_FORMAL_MULTIPLIERS, '負', cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
case 42 /* SIMP_CHINESE_INFORMAL */:
return createCJKCounter(value, '零一二三四五六七八九', CHINESE_INFORMAL_MULTIPLIERS, '负', cjkSuffix, CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
case 41 /* SIMP_CHINESE_FORMAL */:
return createCJKCounter(value, '零壹贰叁肆伍陆柒捌玖', CHINESE_FORMAL_MULTIPLIERS, '负', cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS | CJK_HUNDRED_COEFFICIENTS);
case 26 /* JAPANESE_INFORMAL */:
return createCJKCounter(value, '〇一二三四五六七八九', '十百千万', JAPANESE_NEGATIVE, cjkSuffix, 0);
case 25 /* JAPANESE_FORMAL */:
return createCJKCounter(value, '零壱弐参四伍六七八九', '拾百千万', JAPANESE_NEGATIVE, cjkSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS);
case 31 /* KOREAN_HANGUL_FORMAL */:
return createCJKCounter(value, '영일이삼사오육칠팔구', '십백천만', KOREAN_NEGATIVE, koreanSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS);
case 33 /* KOREAN_HANJA_INFORMAL */:
return createCJKCounter(value, '零一二三四五六七八九', '十百千萬', KOREAN_NEGATIVE, koreanSuffix, 0);
case 32 /* KOREAN_HANJA_FORMAL */:
return createCJKCounter(value, '零壹貳參四五六七八九', '拾百千', KOREAN_NEGATIVE, koreanSuffix, CJK_ZEROS | CJK_TEN_COEFFICIENTS | CJK_TEN_HIGH_COEFFICIENTS);
case 18 /* DEVANAGARI */:
return createCounterStyleFromRange(value, 0x966, 0x96f, true, defaultSuffix);
case 20 /* GEORGIAN */:
return createAdditiveCounter(value, 1, 19999, GEORGIAN, 3 /* DECIMAL */, defaultSuffix);
case 21 /* GUJARATI */:
return createCounterStyleFromRange(value, 0xae6, 0xaef, true, defaultSuffix);
case 22 /* GURMUKHI */:
return createCounterStyleFromRange(value, 0xa66, 0xa6f, true, defaultSuffix);
case 22 /* HEBREW */:
return createAdditiveCounter(value, 1, 10999, HEBREW, 3 /* DECIMAL */, defaultSuffix);
case 23 /* HIRAGANA */:
return createCounterStyleFromSymbols(value, 'あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわゐゑをん');
case 24 /* HIRAGANA_IROHA */:
return createCounterStyleFromSymbols(value, 'いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす');
case 27 /* KANNADA */:
return createCounterStyleFromRange(value, 0xce6, 0xcef, true, defaultSuffix);
case 28 /* KATAKANA */:
return createCounterStyleFromSymbols(value, 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン', cjkSuffix);
case 29 /* KATAKANA_IROHA */:
return createCounterStyleFromSymbols(value, 'イロハニホヘトチリヌルヲワカヨタレソツネナラムウヰノオクヤマケフコエテアサキユメミシヱヒモセス', cjkSuffix);
case 34 /* LAO */:
return createCounterStyleFromRange(value, 0xed0, 0xed9, true, defaultSuffix);
case 37 /* MONGOLIAN */:
return createCounterStyleFromRange(value, 0x1810, 0x1819, true, defaultSuffix);
case 38 /* MYANMAR */:
return createCounterStyleFromRange(value, 0x1040, 0x1049, true, defaultSuffix);
case 39 /* ORIYA */:
return createCounterStyleFromRange(value, 0xb66, 0xb6f, true, defaultSuffix);
case 40 /* PERSIAN */:
return createCounterStyleFromRange(value, 0x6f0, 0x6f9, true, defaultSuffix);
case 43 /* TAMIL */:
return createCounterStyleFromRange(value, 0xbe6, 0xbef, true, defaultSuffix);
case 44 /* TELUGU */:
return createCounterStyleFromRange(value, 0xc66, 0xc6f, true, defaultSuffix);
case 45 /* THAI */:
return createCounterStyleFromRange(value, 0xe50, 0xe59, true, defaultSuffix);
case 46 /* TIBETAN */:
return createCounterStyleFromRange(value, 0xf20, 0xf29, true, defaultSuffix);
case 3 /* DECIMAL */:
default:
return createCounterStyleFromRange(value, 48, 57, true, defaultSuffix);
}
};
var IGNORE_ATTRIBUTE = 'data-html2canvas-ignore';
var DocumentCloner = /** @class */ (function () {
function DocumentCloner(context, element, options) {
this.context = context;
this.options = options;
this.scrolledElements = [];
this.referenceElement = element;
this.counters = new CounterState();
this.quoteDepth = 0;
if (!element.ownerDocument) {
throw new Error('Cloned element does not have an owner document');
}
this.documentElement = this.cloneNode(element.ownerDocument.documentElement, false);
}
DocumentCloner.prototype.toIFrame = function (ownerDocument, windowSize) {
var _this = this;
var iframe = createIFrameContainer(ownerDocument, windowSize);
if (!iframe.contentWindow) {
return Promise.reject("Unable to find iframe window");
}
var scrollX = ownerDocument.defaultView.pageXOffset;
var scrollY = ownerDocument.defaultView.pageYOffset;
var cloneWindow = iframe.contentWindow;
var documentClone = cloneWindow.document;
/* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle
if window url is about:blank, we can assign the url to current by writing onto the document
*/
var iframeLoad = iframeLoader(iframe).then(function () { return __awaiter(_this, void 0, void 0, function () {
var onclone, referenceElement;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this.scrolledElements.forEach(restoreNodeScroll);
if (cloneWindow) {
cloneWindow.scrollTo(windowSize.left, windowSize.top);
if (/(iPad|iPhone|iPod)/g.test(navigator.userAgent) &&
(cloneWindow.scrollY !== windowSize.top || cloneWindow.scrollX !== windowSize.left)) {
this.context.logger.warn('Unable to restore scroll position for cloned document');
this.context.windowBounds = this.context.windowBounds.add(cloneWindow.scrollX - windowSize.left, cloneWindow.scrollY - windowSize.top, 0, 0);
}
}
onclone = this.options.onclone;
referenceElement = this.clonedReferenceElement;
if (typeof referenceElement === 'undefined') {
return [2 /*return*/, Promise.reject("Error finding the " + this.referenceElement.nodeName + " in the cloned document")];
}
if (!(documentClone.fonts && documentClone.fonts.ready)) return [3 /*break*/, 2];
return [4 /*yield*/, documentClone.fonts.ready];
case 1:
_a.sent();
_a.label = 2;
case 2:
if (!/(AppleWebKit)/g.test(navigator.userAgent)) return [3 /*break*/, 4];
return [4 /*yield*/, imagesReady(documentClone)];
case 3:
_a.sent();
_a.label = 4;
case 4:
if (typeof onclone === 'function') {
return [2 /*return*/, Promise.resolve()
.then(function () { return onclone(documentClone, referenceElement); })
.then(function () { return iframe; })];
}
return [2 /*return*/, iframe];
}
});
}); });
documentClone.open();
documentClone.write(serializeDoctype(document.doctype) + "<html></html>");
// Chrome scrolls the parent document for some reason after the write to the cloned window???
restoreOwnerScroll(this.referenceElement.ownerDocument, scrollX, scrollY);
documentClone.replaceChild(documentClone.adoptNode(this.documentElement), documentClone.documentElement);
documentClone.close();
return iframeLoad;
};
DocumentCloner.prototype.createElementClone = function (node) {
if (isDebugging(node, 2 /* CLONE */)) {
debugger;
}
if (isCanvasElement(node)) {
return this.createCanvasClone(node);
}
if (isVideoElement(node)) {
return this.createVideoClone(node);
}
if (isStyleElement(node)) {
return this.createStyleClone(node);
}
var clone = node.cloneNode(false);
if (isImageElement(clone)) {
if (isImageElement(node) && node.currentSrc && node.currentSrc !== node.src) {
clone.src = node.currentSrc;
clone.srcset = '';
}
if (clone.loading === 'lazy') {
clone.loading = 'eager';
}
}
if (isCustomElement(clone)) {
return this.createCustomElementClone(clone);
}
return clone;
};
DocumentCloner.prototype.createCustomElementClone = function (node) {
var clone = document.createElement('html2canvascustomelement');
copyCSSStyles(node.style, clone);
return clone;
};
DocumentCloner.prototype.createStyleClone = function (node) {
try {
var sheet = node.sheet;
if (sheet && sheet.cssRules) {
var css = [].slice.call(sheet.cssRules, 0).reduce(function (css, rule) {
if (rule && typeof rule.cssText === 'string') {
return css + rule.cssText;
}
return css;
}, '');
var style = node.cloneNode(false);
style.textContent = css;
return style;
}
}
catch (e) {
// accessing node.sheet.cssRules throws a DOMException
this.context.logger.error('Unable to access cssRules property', e);
if (e.name !== 'SecurityError') {
throw e;
}
}
return node.cloneNode(false);
};
DocumentCloner.prototype.createCanvasClone = function (canvas) {
var _a;
if (this.options.inlineImages && canvas.ownerDocument) {
var img = canvas.ownerDocument.createElement('img');
try {
img.src = canvas.toDataURL();
return img;
}
catch (e) {
this.context.logger.info("Unable to inline canvas contents, canvas is tainted", canvas);
}
}
var clonedCanvas = canvas.cloneNode(false);
try {
clonedCanvas.width = canvas.width;
clonedCanvas.height = canvas.height;
var ctx = canvas.getContext('2d');
var clonedCtx = clonedCanvas.getContext('2d');
if (clonedCtx) {
if (!this.options.allowTaint && ctx) {
clonedCtx.putImageData(ctx.getImageData(0, 0, canvas.width, canvas.height), 0, 0);
}
else {
var gl = (_a = canvas.getContext('webgl2')) !== null && _a !== void 0 ? _a : canvas.getContext('webgl');
if (gl) {
var attribs = gl.getContextAttributes();
if ((attribs === null || attribs === void 0 ? void 0 : attribs.preserveDrawingBuffer) === false) {
this.context.logger.warn('Unable to clone WebGL context as it has preserveDrawingBuffer=false', canvas);
}
}
clonedCtx.drawImage(canvas, 0, 0);
}
}
return clonedCanvas;
}
catch (e) {
this.context.logger.info("Unable to clone canvas as it is tainted", canvas);
}
return clonedCanvas;
};
DocumentCloner.prototype.createVideoClone = function (video) {
var canvas = video.ownerDocument.createElement('canvas');
canvas.width = video.offsetWidth;
canvas.height = video.offsetHeight;
var ctx = canvas.getContext('2d');
try {
if (ctx) {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
if (!this.options.allowTaint) {
ctx.getImageData(0, 0, canvas.width, canvas.height);
}
}
return canvas;
}
catch (e) {
this.context.logger.info("Unable to clone video as it is tainted", video);
}
var blankCanvas = video.ownerDocument.createElement('canvas');
blankCanvas.width = video.offsetWidth;
blankCanvas.height = video.offsetHeight;
return blankCanvas;
};
DocumentCloner.prototype.appendChildNode = function (clone, child, copyStyles) {
if (!isElementNode(child) ||
(!isScriptElement(child) &&
!child.hasAttribute(IGNORE_ATTRIBUTE) &&
(typeof this.options.ignoreElements !== 'function' || !this.options.ignoreElements(child)))) {
if (!this.options.copyStyles || !isElementNode(child) || !isStyleElement(child)) {
clone.appendChild(this.cloneNode(child, copyStyles));
}
}
};
DocumentCloner.prototype.cloneChildNodes = function (node, clone, copyStyles) {
var _this = this;
for (var child = node.shadowRoot ? node.shadowRoot.firstChild : node.firstChild; child; child = child.nextSibling) {
if (isElementNode(child) && isSlotElement(child) && typeof child.assignedNodes === 'function') {
var assignedNodes = child.assignedNodes();
if (assignedNodes.length) {
assignedNodes.forEach(function (assignedNode) { return _this.appendChildNode(clone, assignedNode, copyStyles); });
}
}
else {
this.appendChildNode(clone, child, copyStyles);
}
}
};
DocumentCloner.prototype.cloneNode = function (node, copyStyles) {
if (isTextNode(node)) {
return document.createTextNode(node.data);
}
if (!node.ownerDocument) {
return node.cloneNode(false);
}
var window = node.ownerDocument.defaultView;
if (window && isElementNode(node) && (isHTMLElementNode(node) || isSVGElementNode(node))) {
var clone = this.createElementClone(node);
clone.style.transitionProperty = 'none';
var style = window.getComputedStyle(node);
var styleBefore = window.getComputedStyle(node, ':before');
var styleAfter = window.getComputedStyle(node, ':after');
if (this.referenceElement === node && isHTMLElementNode(clone)) {
this.clonedReferenceElement = clone;
}
if (isBodyElement(clone)) {
createPseudoHideStyles(clone);
}
var counters = this.counters.parse(new CSSParsedCounterDeclaration(this.context, style));
var before = this.resolvePseudoContent(node, clone, styleBefore, PseudoElementType.BEFORE);
if (isCustomElement(node)) {
copyStyles = true;
}
if (!isVideoElement(node)) {
this.cloneChildNodes(node, clone, copyStyles);
}
if (before) {
clone.insertBefore(before, clone.firstChild);
}
var after = this.resolvePseudoContent(node, clone, styleAfter, PseudoElementType.AFTER);
if (after) {
clone.appendChild(after);
}
this.counters.pop(counters);
if ((style && (this.options.copyStyles || isSVGElementNode(node)) && !isIFrameElement(node)) ||
copyStyles) {
copyCSSStyles(style, clone);
}
if (node.scrollTop !== 0 || node.scrollLeft !== 0) {
this.scrolledElements.push([clone, node.scrollLeft, node.scrollTop]);
}
if ((isTextareaElement(node) || isSelectElement(node)) &&
(isTextareaElement(clone) || isSelectElement(clone))) {
clone.value = node.value;
}
return clone;
}
return node.cloneNode(false);
};
DocumentCloner.prototype.resolvePseudoContent = function (node, clone, style, pseudoElt) {
var _this = this;
if (!style) {
return;
}
var value = style.content;
var document = clone.ownerDocument;
if (!document || !value || value === 'none' || value === '-moz-alt-content' || style.display === 'none') {
return;
}
this.counters.parse(new CSSParsedCounterDeclaration(this.context, style));
var declaration = new CSSParsedPseudoDeclaration(this.context, style);
var anonymousReplacedElement = document.createElement('html2canvaspseudoelement');
copyCSSStyles(style, anonymousReplacedElement);
declaration.content.forEach(function (token) {
if (token.type === 0 /* STRING_TOKEN */) {
anonymousReplacedElement.appendChild(document.createTextNode(token.value));
}
else if (token.type === 22 /* URL_TOKEN */) {
var img = document.createElement('img');
img.src = token.value;
img.style.opacity = '1';
anonymousReplacedElement.appendChild(img);
}
else if (token.type === 18 /* FUNCTION */) {
if (token.name === 'attr') {
var attr = token.values.filter(isIdentToken);
if (attr.length) {
anonymousReplacedElement.appendChild(document.createTextNode(node.getAttribute(attr[0].value) || ''));
}
}
else if (token.name === 'counter') {
var _a = token.values.filter(nonFunctionArgSeparator), counter = _a[0], counterStyle = _a[1];
if (counter && isIdentToken(counter)) {
var counterState = _this.counters.getCounterValue(counter.value);
var counterType = counterStyle && isIdentToken(counterStyle)
? listStyleType.parse(_this.context, counterStyle.value)
: 3 /* DECIMAL */;
anonymousReplacedElement.appendChild(document.createTextNode(createCounterText(counterState, counterType, false)));
}
}
else if (token.name === 'counters') {
var _b = token.values.filter(nonFunctionArgSeparator), counter = _b[0], delim = _b[1], counterStyle = _b[2];
if (counter && isIdentToken(counter)) {
var counterStates = _this.counters.getCounterValues(counter.value);
var counterType_1 = counterStyle && isIdentToken(counterStyle)
? listStyleType.parse(_this.context, counterStyle.value)
: 3 /* DECIMAL */;
var separator = delim && delim.type === 0 /* STRING_TOKEN */ ? delim.value : '';
var text = counterStates
.map(function (value) { return createCounterText(value, counterType_1, false); })
.join(separator);
anonymousReplacedElement.appendChild(document.createTextNode(text));
}
}
}
else if (token.type === 20 /* IDENT_TOKEN */) {
switch (token.value) {
case 'open-quote':
anonymousReplacedElement.appendChild(document.createTextNode(getQuote(declaration.quotes, _this.quoteDepth++, true)));
break;
case 'close-quote':
anonymousReplacedElement.appendChild(document.createTextNode(getQuote(declaration.quotes, --_this.quoteDepth, false)));
break;
default:
// safari doesn't parse string tokens correctly because of lack of quotes
anonymousReplacedElement.appendChild(document.createTextNode(token.value));
}
}
});
anonymousReplacedElement.className = PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
var newClassName = pseudoElt === PseudoElementType.BEFORE
? " " + PSEUDO_HIDE_ELEMENT_CLASS_BEFORE
: " " + PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
if (isSVGElementNode(clone)) {
clone.className.baseValue += newClassName;
}
else {
clone.className += newClassName;
}
return anonymousReplacedElement;
};
DocumentCloner.destroy = function (container) {
if (container.parentNode) {
container.parentNode.removeChild(container);
return true;
}
return false;
};
return DocumentCloner;
}());
var PseudoElementType;
(function (PseudoElementType) {
PseudoElementType[PseudoElementType["BEFORE"] = 0] = "BEFORE";
PseudoElementType[PseudoElementType["AFTER"] = 1] = "AFTER";
})(PseudoElementType || (PseudoElementType = {}));
var createIFrameContainer = function (ownerDocument, bounds) {
var cloneIframeContainer = ownerDocument.createElement('iframe');
cloneIframeContainer.className = 'html2canvas-container';
cloneIframeContainer.style.visibility = 'hidden';
cloneIframeContainer.style.position = 'fixed';
cloneIframeContainer.style.left = '-10000px';
cloneIframeContainer.style.top = '0px';
cloneIframeContainer.style.border = '0';
cloneIframeContainer.width = bounds.width.toString();
cloneIframeContainer.height = bounds.height.toString();
cloneIframeContainer.scrolling = 'no'; // ios won't scroll without it
cloneIframeContainer.setAttribute(IGNORE_ATTRIBUTE, 'true');
ownerDocument.body.appendChild(cloneIframeContainer);
return cloneIframeContainer;
};
var imageReady = function (img) {
return new Promise(function (resolve) {
if (img.complete) {
resolve();
return;
}
if (!img.src) {
resolve();
return;
}
img.onload = resolve;
img.onerror = resolve;
});
};
var imagesReady = function (document) {
return Promise.all([].slice.call(document.images, 0).map(imageReady));
};
var iframeLoader = function (iframe) {
return new Promise(function (resolve, reject) {
var cloneWindow = iframe.contentWindow;
if (!cloneWindow) {
return reject("No window assigned for iframe");
}
var documentClone = cloneWindow.document;
cloneWindow.onload = iframe.onload = function () {
cloneWindow.onload = iframe.onload = null;
var interval = setInterval(function () {
if (documentClone.body.childNodes.length > 0 && documentClone.readyState === 'complete') {
clearInterval(interval);
resolve(iframe);
}
}, 50);
};
});
};
var ignoredStyleProperties = [
'all',
'd',
'content' // Safari shows pseudoelements if content is set
];
var copyCSSStyles = function (style, target) {
// Edge does not provide value for cssText
for (var i = style.length - 1; i >= 0; i--) {
var property = style.item(i);
if (ignoredStyleProperties.indexOf(property) === -1) {
target.style.setProperty(property, style.getPropertyValue(property));
}
}
return target;
};
var serializeDoctype = function (doctype) {
var str = '';
if (doctype) {
str += '<!DOCTYPE ';
if (doctype.name) {
str += doctype.name;
}
if (doctype.internalSubset) {
str += doctype.internalSubset;
}
if (doctype.publicId) {
str += "\"" + doctype.publicId + "\"";
}
if (doctype.systemId) {
str += "\"" + doctype.systemId + "\"";
}
str += '>';
}
return str;
};
var restoreOwnerScroll = function (ownerDocument, x, y) {
if (ownerDocument &&
ownerDocument.defaultView &&
(x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
ownerDocument.defaultView.scrollTo(x, y);
}
};
var restoreNodeScroll = function (_a) {
var element = _a[0], x = _a[1], y = _a[2];
element.scrollLeft = x;
element.scrollTop = y;
};
var PSEUDO_BEFORE = ':before';
var PSEUDO_AFTER = ':after';
var PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = '___html2canvas___pseudoelement_before';
var PSEUDO_HIDE_ELEMENT_CLASS_AFTER = '___html2canvas___pseudoelement_after';
var PSEUDO_HIDE_ELEMENT_STYLE = "{\n content: \"\" !important;\n display: none !important;\n}";
var createPseudoHideStyles = function (body) {
createStyles(body, "." + PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + PSEUDO_BEFORE + PSEUDO_HIDE_ELEMENT_STYLE + "\n ." + PSEUDO_HIDE_ELEMENT_CLASS_AFTER + PSEUDO_AFTER + PSEUDO_HIDE_ELEMENT_STYLE);
};
var createStyles = function (body, styles) {
var document = body.ownerDocument;
if (document) {
var style = document.createElement('style');
style.textContent = styles;
body.appendChild(style);
}
};
var CacheStorage = /** @class */ (function () {
function CacheStorage() {
}
CacheStorage.getOrigin = function (url) {
var link = CacheStorage._link;
if (!link) {
return 'about:blank';
}
link.href = url;
link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/
return link.protocol + link.hostname + link.port;
};
CacheStorage.isSameOrigin = function (src) {
return CacheStorage.getOrigin(src) === CacheStorage._origin;
};
CacheStorage.setContext = function (window) {
CacheStorage._link = window.document.createElement('a');
CacheStorage._origin = CacheStorage.getOrigin(window.location.href);
};
CacheStorage._origin = 'about:blank';
return CacheStorage;
}());
var Cache = /** @class */ (function () {
function Cache(context, _options) {
this.context = context;
this._options = _options;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this._cache = {};
}
Cache.prototype.addImage = function (src) {
var result = Promise.resolve();
if (this.has(src)) {
return result;
}
if (isBlobImage(src) || isRenderable(src)) {
(this._cache[src] = this.loadImage(src)).catch(function () {
// prevent unhandled rejection
});
return result;
}
return result;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Cache.prototype.match = function (src) {
return this._cache[src];
};
Cache.prototype.loadImage = function (key) {
return __awaiter(this, void 0, void 0, function () {
var isSameOrigin, useCORS, useProxy, src;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
isSameOrigin = CacheStorage.isSameOrigin(key);
useCORS = !isInlineImage(key) && this._options.useCORS === true && FEATURES.SUPPORT_CORS_IMAGES && !isSameOrigin;
useProxy = !isInlineImage(key) &&
!isSameOrigin &&
!isBlobImage(key) &&
typeof this._options.proxy === 'string' &&
FEATURES.SUPPORT_CORS_XHR &&
!useCORS;
if (!isSameOrigin &&
this._options.allowTaint === false &&
!isInlineImage(key) &&
!isBlobImage(key) &&
!useProxy &&
!useCORS) {
return [2 /*return*/];
}
src = key;
if (!useProxy) return [3 /*break*/, 2];
return [4 /*yield*/, this.proxy(src)];
case 1:
src = _a.sent();
_a.label = 2;
case 2:
this.context.logger.debug("Added image " + key.substring(0, 256));
return [4 /*yield*/, new Promise(function (resolve, reject) {
var img = new Image();
img.onload = function () { return resolve(img); };
img.onerror = reject;
//ios safari 10.3 taints canvas with data urls unless crossOrigin is set to anonymous
if (isInlineBase64Image(src) || useCORS) {
img.crossOrigin = 'anonymous';
}
img.src = src;
if (img.complete === true) {
// Inline XML images may fail to parse, throwing an Error later on
setTimeout(function () { return resolve(img); }, 500);
}
if (_this._options.imageTimeout > 0) {
setTimeout(function () { return reject("Timed out (" + _this._options.imageTimeout + "ms) loading image"); }, _this._options.imageTimeout);
}
})];
case 3: return [2 /*return*/, _a.sent()];
}
});
});
};
Cache.prototype.has = function (key) {
return typeof this._cache[key] !== 'undefined';
};
Cache.prototype.keys = function () {
return Promise.resolve(Object.keys(this._cache));
};
Cache.prototype.proxy = function (src) {
var _this = this;
var proxy = this._options.proxy;
if (!proxy) {
throw new Error('No proxy defined');
}
var key = src.substring(0, 256);
return new Promise(function (resolve, reject) {
var responseType = FEATURES.SUPPORT_RESPONSE_TYPE ? 'blob' : 'text';
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status === 200) {
if (responseType === 'text') {
resolve(xhr.response);
}
else {
var reader_1 = new FileReader();
reader_1.addEventListener('load', function () { return resolve(reader_1.result); }, false);
reader_1.addEventListener('error', function (e) { return reject(e); }, false);
reader_1.readAsDataURL(xhr.response);
}
}
else {
reject("Failed to proxy resource " + key + " with status code " + xhr.status);
}
};
xhr.onerror = reject;
var queryString = proxy.indexOf('?') > -1 ? '&' : '?';
xhr.open('GET', "" + proxy + queryString + "url=" + encodeURIComponent(src) + "&responseType=" + responseType);
if (responseType !== 'text' && xhr instanceof XMLHttpRequest) {
xhr.responseType = responseType;
}
if (_this._options.imageTimeout) {
var timeout_1 = _this._options.imageTimeout;
xhr.timeout = timeout_1;
xhr.ontimeout = function () { return reject("Timed out (" + timeout_1 + "ms) proxying " + key); };
}
xhr.send();
});
};
return Cache;
}());
var INLINE_SVG = /^data:image\/svg\+xml/i;
var INLINE_BASE64 = /^data:image\/.*;base64,/i;
var INLINE_IMG = /^data:image\/.*/i;
var isRenderable = function (src) { return FEATURES.SUPPORT_SVG_DRAWING || !isSVG(src); };
var isInlineImage = function (src) { return INLINE_IMG.test(src); };
var isInlineBase64Image = function (src) { return INLINE_BASE64.test(src); };
var isBlobImage = function (src) { return src.substr(0, 4) === 'blob'; };
var isSVG = function (src) { return src.substr(-3).toLowerCase() === 'svg' || INLINE_SVG.test(src); };
var Vector = /** @class */ (function () {
function Vector(x, y) {
this.type = 0 /* VECTOR */;
this.x = x;
this.y = y;
}
Vector.prototype.add = function (deltaX, deltaY) {
return new Vector(this.x + deltaX, this.y + deltaY);
};
return Vector;
}());
var lerp = function (a, b, t) {
return new Vector(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t);
};
var BezierCurve = /** @class */ (function () {
function BezierCurve(start, startControl, endControl, end) {
this.type = 1 /* BEZIER_CURVE */;
this.start = start;
this.startControl = startControl;
this.endControl = endControl;
this.end = end;
}
BezierCurve.prototype.subdivide = function (t, firstHalf) {
var ab = lerp(this.start, this.startControl, t);
var bc = lerp(this.startControl, this.endControl, t);
var cd = lerp(this.endControl, this.end, t);
var abbc = lerp(ab, bc, t);
var bccd = lerp(bc, cd, t);
var dest = lerp(abbc, bccd, t);
return firstHalf ? new BezierCurve(this.start, ab, abbc, dest) : new BezierCurve(dest, bccd, cd, this.end);
};
BezierCurve.prototype.add = function (deltaX, deltaY) {
return new BezierCurve(this.start.add(deltaX, deltaY), this.startControl.add(deltaX, deltaY), this.endControl.add(deltaX, deltaY), this.end.add(deltaX, deltaY));
};
BezierCurve.prototype.reverse = function () {
return new BezierCurve(this.end, this.endControl, this.startControl, this.start);
};
return BezierCurve;
}());
var isBezierCurve = function (path) { return path.type === 1 /* BEZIER_CURVE */; };
var BoundCurves = /** @class */ (function () {
function BoundCurves(element) {
var styles = element.styles;
var bounds = element.bounds;
var _a = getAbsoluteValueForTuple(styles.borderTopLeftRadius, bounds.width, bounds.height), tlh = _a[0], tlv = _a[1];
var _b = getAbsoluteValueForTuple(styles.borderTopRightRadius, bounds.width, bounds.height), trh = _b[0], trv = _b[1];
var _c = getAbsoluteValueForTuple(styles.borderBottomRightRadius, bounds.width, bounds.height), brh = _c[0], brv = _c[1];
var _d = getAbsoluteValueForTuple(styles.borderBottomLeftRadius, bounds.width, bounds.height), blh = _d[0], blv = _d[1];
var factors = [];
factors.push((tlh + trh) / bounds.width);
factors.push((blh + brh) / bounds.width);
factors.push((tlv + blv) / bounds.height);
factors.push((trv + brv) / bounds.height);
var maxFactor = Math.max.apply(Math, factors);
if (maxFactor > 1) {
tlh /= maxFactor;
tlv /= maxFactor;
trh /= maxFactor;
trv /= maxFactor;
brh /= maxFactor;
brv /= maxFactor;
blh /= maxFactor;
blv /= maxFactor;
}
var topWidth = bounds.width - trh;
var rightHeight = bounds.height - brv;
var bottomWidth = bounds.width - brh;
var leftHeight = bounds.height - blv;
var borderTopWidth = styles.borderTopWidth;
var borderRightWidth = styles.borderRightWidth;
var borderBottomWidth = styles.borderBottomWidth;
var borderLeftWidth = styles.borderLeftWidth;
var paddingTop = getAbsoluteValue(styles.paddingTop, element.bounds.width);
var paddingRight = getAbsoluteValue(styles.paddingRight, element.bounds.width);
var paddingBottom = getAbsoluteValue(styles.paddingBottom, element.bounds.width);
var paddingLeft = getAbsoluteValue(styles.paddingLeft, element.bounds.width);
this.topLeftBorderDoubleOuterBox =
tlh > 0 || tlv > 0
? getCurvePoints(bounds.left + borderLeftWidth / 3, bounds.top + borderTopWidth / 3, tlh - borderLeftWidth / 3, tlv - borderTopWidth / 3, CORNER.TOP_LEFT)
: new Vector(bounds.left + borderLeftWidth / 3, bounds.top + borderTopWidth / 3);
this.topRightBorderDoubleOuterBox =
tlh > 0 || tlv > 0
? getCurvePoints(bounds.left + topWidth, bounds.top + borderTopWidth / 3, trh - borderRightWidth / 3, trv - borderTopWidth / 3, CORNER.TOP_RIGHT)
: new Vector(bounds.left + bounds.width - borderRightWidth / 3, bounds.top + borderTopWidth / 3);
this.bottomRightBorderDoubleOuterBox =
brh > 0 || brv > 0
? getCurvePoints(bounds.left + bottomWidth, bounds.top + rightHeight, brh - borderRightWidth / 3, brv - borderBottomWidth / 3, CORNER.BOTTOM_RIGHT)
: new Vector(bounds.left + bounds.width - borderRightWidth / 3, bounds.top + bounds.height - borderBottomWidth / 3);
this.bottomLeftBorderDoubleOuterBox =
blh > 0 || blv > 0
? getCurvePoints(bounds.left + borderLeftWidth / 3, bounds.top + leftHeight, blh - borderLeftWidth / 3, blv - borderBottomWidth / 3, CORNER.BOTTOM_LEFT)
: new Vector(bounds.left + borderLeftWidth / 3, bounds.top + bounds.height - borderBottomWidth / 3);
this.topLeftBorderDoubleInnerBox =
tlh > 0 || tlv > 0
? getCurvePoints(bounds.left + (borderLeftWidth * 2) / 3, bounds.top + (borderTopWidth * 2) / 3, tlh - (borderLeftWidth * 2) / 3, tlv - (borderTopWidth * 2) / 3, CORNER.TOP_LEFT)
: new Vector(bounds.left + (borderLeftWidth * 2) / 3, bounds.top + (borderTopWidth * 2) / 3);
this.topRightBorderDoubleInnerBox =
tlh > 0 || tlv > 0
? getCurvePoints(bounds.left + topWidth, bounds.top + (borderTopWidth * 2) / 3, trh - (borderRightWidth * 2) / 3, trv - (borderTopWidth * 2) / 3, CORNER.TOP_RIGHT)
: new Vector(bounds.left + bounds.width - (borderRightWidth * 2) / 3, bounds.top + (borderTopWidth * 2) / 3);
this.bottomRightBorderDoubleInnerBox =
brh > 0 || brv > 0
? getCurvePoints(bounds.left + bottomWidth, bounds.top + rightHeight, brh - (borderRightWidth * 2) / 3, brv - (borderBottomWidth * 2) / 3, CORNER.BOTTOM_RIGHT)
: new Vector(bounds.left + bounds.width - (borderRightWidth * 2) / 3, bounds.top + bounds.height - (borderBottomWidth * 2) / 3);
this.bottomLeftBorderDoubleInnerBox =
blh > 0 || blv > 0
? getCurvePoints(bounds.left + (borderLeftWidth * 2) / 3, bounds.top + leftHeight, blh - (borderLeftWidth * 2) / 3, blv - (borderBottomWidth * 2) / 3, CORNER.BOTTOM_LEFT)
: new Vector(bounds.left + (borderLeftWidth * 2) / 3, bounds.top + bounds.height - (borderBottomWidth * 2) / 3);
this.topLeftBorderStroke =
tlh > 0 || tlv > 0
? getCurvePoints(bounds.left + borderLeftWidth / 2, bounds.top + borderTopWidth / 2, tlh - borderLeftWidth / 2, tlv - borderTopWidth / 2, CORNER.TOP_LEFT)
: new Vector(bounds.left + borderLeftWidth / 2, bounds.top + borderTopWidth / 2);
this.topRightBorderStroke =
tlh > 0 || tlv > 0
? getCurvePoints(bounds.left + topWidth, bounds.top + borderTopWidth / 2, trh - borderRightWidth / 2, trv - borderTopWidth / 2, CORNER.TOP_RIGHT)
: new Vector(bounds.left + bounds.width - borderRightWidth / 2, bounds.top + borderTopWidth / 2);
this.bottomRightBorderStroke =
brh > 0 || brv > 0
? getCurvePoints(bounds.left + bottomWidth, bounds.top + rightHeight, brh - borderRightWidth / 2, brv - borderBottomWidth / 2, CORNER.BOTTOM_RIGHT)
: new Vector(bounds.left + bounds.width - borderRightWidth / 2, bounds.top + bounds.height - borderBottomWidth / 2);
this.bottomLeftBorderStroke =
blh > 0 || blv > 0
? getCurvePoints(bounds.left + borderLeftWidth / 2, bounds.top + leftHeight, blh - borderLeftWidth / 2, blv - borderBottomWidth / 2, CORNER.BOTTOM_LEFT)
: new Vector(bounds.left + borderLeftWidth / 2, bounds.top + bounds.height - borderBottomWidth / 2);
this.topLeftBorderBox =
tlh > 0 || tlv > 0
? getCurvePoints(bounds.left, bounds.top, tlh, tlv, CORNER.TOP_LEFT)
: new Vector(bounds.left, bounds.top);
this.topRightBorderBox =
trh > 0 || trv > 0
? getCurvePoints(bounds.left + topWidth, bounds.top, trh, trv, CORNER.TOP_RIGHT)
: new Vector(bounds.left + bounds.width, bounds.top);
this.bottomRightBorderBox =
brh > 0 || brv > 0
? getCurvePoints(bounds.left + bottomWidth, bounds.top + rightHeight, brh, brv, CORNER.BOTTOM_RIGHT)
: new Vector(bounds.left + bounds.width, bounds.top + bounds.height);
this.bottomLeftBorderBox =
blh > 0 || blv > 0
? getCurvePoints(bounds.left, bounds.top + leftHeight, blh, blv, CORNER.BOTTOM_LEFT)
: new Vector(bounds.left, bounds.top + bounds.height);
this.topLeftPaddingBox =
tlh > 0 || tlv > 0
? getCurvePoints(bounds.left + borderLeftWidth, bounds.top + borderTopWidth, Math.max(0, tlh - borderLeftWidth), Math.max(0, tlv - borderTopWidth), CORNER.TOP_LEFT)
: new Vector(bounds.left + borderLeftWidth, bounds.top + borderTopWidth);
this.topRightPaddingBox =
trh > 0 || trv > 0
? getCurvePoints(bounds.left + Math.min(topWidth, bounds.width - borderRightWidth), bounds.top + borderTopWidth, topWidth > bounds.width + borderRightWidth ? 0 : Math.max(0, trh - borderRightWidth), Math.max(0, trv - borderTopWidth), CORNER.TOP_RIGHT)
: new Vector(bounds.left + bounds.width - borderRightWidth, bounds.top + borderTopWidth);
this.bottomRightPaddingBox =
brh > 0 || brv > 0
? getCurvePoints(bounds.left + Math.min(bottomWidth, bounds.width - borderLeftWidth), bounds.top + Math.min(rightHeight, bounds.height - borderBottomWidth), Math.max(0, brh - borderRightWidth), Math.max(0, brv - borderBottomWidth), CORNER.BOTTOM_RIGHT)
: new Vector(bounds.left + bounds.width - borderRightWidth, bounds.top + bounds.height - borderBottomWidth);
this.bottomLeftPaddingBox =
blh > 0 || blv > 0
? getCurvePoints(bounds.left + borderLeftWidth, bounds.top + Math.min(leftHeight, bounds.height - borderBottomWidth), Math.max(0, blh - borderLeftWidth), Math.max(0, blv - borderBottomWidth), CORNER.BOTTOM_LEFT)
: new Vector(bounds.left + borderLeftWidth, bounds.top + bounds.height - borderBottomWidth);
this.topLeftContentBox =
tlh > 0 || tlv > 0
? getCurvePoints(bounds.left + borderLeftWidth + paddingLeft, bounds.top + borderTopWidth + paddingTop, Math.max(0, tlh - (borderLeftWidth + paddingLeft)), Math.max(0, tlv - (borderTopWidth + paddingTop)), CORNER.TOP_LEFT)
: new Vector(bounds.left + borderLeftWidth + paddingLeft, bounds.top + borderTopWidth + paddingTop);
this.topRightContentBox =
trh > 0 || trv > 0
? getCurvePoints(bounds.left + Math.min(topWidth, bounds.width + borderLeftWidth + paddingLeft), bounds.top + borderTopWidth + paddingTop, topWidth > bounds.width + borderLeftWidth + paddingLeft ? 0 : trh - borderLeftWidth + paddingLeft, trv - (borderTopWidth + paddingTop), CORNER.TOP_RIGHT)
: new Vector(bounds.left + bounds.width - (borderRightWidth + paddingRight), bounds.top + borderTopWidth + paddingTop);
this.bottomRightContentBox =
brh > 0 || brv > 0
? getCurvePoints(bounds.left + Math.min(bottomWidth, bounds.width - (borderLeftWidth + paddingLeft)), bounds.top + Math.min(rightHeight, bounds.height + borderTopWidth + paddingTop), Math.max(0, brh - (borderRightWidth + paddingRight)), brv - (borderBottomWidth + paddingBottom), CORNER.BOTTOM_RIGHT)
: new Vector(bounds.left + bounds.width - (borderRightWidth + paddingRight), bounds.top + bounds.height - (borderBottomWidth + paddingBottom));
this.bottomLeftContentBox =
blh > 0 || blv > 0
? getCurvePoints(bounds.left + borderLeftWidth + paddingLeft, bounds.top + leftHeight, Math.max(0, blh - (borderLeftWidth + paddingLeft)), blv - (borderBottomWidth + paddingBottom), CORNER.BOTTOM_LEFT)
: new Vector(bounds.left + borderLeftWidth + paddingLeft, bounds.top + bounds.height - (borderBottomWidth + paddingBottom));
}
return BoundCurves;
}());
var CORNER;
(function (CORNER) {
CORNER[CORNER["TOP_LEFT"] = 0] = "TOP_LEFT";
CORNER[CORNER["TOP_RIGHT"] = 1] = "TOP_RIGHT";
CORNER[CORNER["BOTTOM_RIGHT"] = 2] = "BOTTOM_RIGHT";
CORNER[CORNER["BOTTOM_LEFT"] = 3] = "BOTTOM_LEFT";
})(CORNER || (CORNER = {}));
var getCurvePoints = function (x, y, r1, r2, position) {
var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
var ox = r1 * kappa; // control point offset horizontal
var oy = r2 * kappa; // control point offset vertical
var xm = x + r1; // x-middle
var ym = y + r2; // y-middle
switch (position) {
case CORNER.TOP_LEFT:
return new BezierCurve(new Vector(x, ym), new Vector(x, ym - oy), new Vector(xm - ox, y), new Vector(xm, y));
case CORNER.TOP_RIGHT:
return new BezierCurve(new Vector(x, y), new Vector(x + ox, y), new Vector(xm, ym - oy), new Vector(xm, ym));
case CORNER.BOTTOM_RIGHT:
return new BezierCurve(new Vector(xm, y), new Vector(xm, y + oy), new Vector(x + ox, ym), new Vector(x, ym));
case CORNER.BOTTOM_LEFT:
default:
return new BezierCurve(new Vector(xm, ym), new Vector(xm - ox, ym), new Vector(x, y + oy), new Vector(x, y));
}
};
var calculateBorderBoxPath = function (curves) {
return [curves.topLeftBorderBox, curves.topRightBorderBox, curves.bottomRightBorderBox, curves.bottomLeftBorderBox];
};
var calculateContentBoxPath = function (curves) {
return [
curves.topLeftContentBox,
curves.topRightContentBox,
curves.bottomRightContentBox,
curves.bottomLeftContentBox
];
};
var calculatePaddingBoxPath = function (curves) {
return [
curves.topLeftPaddingBox,
curves.topRightPaddingBox,
curves.bottomRightPaddingBox,
curves.bottomLeftPaddingBox
];
};
var TransformEffect = /** @class */ (function () {
function TransformEffect(offsetX, offsetY, matrix) {
this.offsetX = offsetX;
this.offsetY = offsetY;
this.matrix = matrix;
this.type = 0 /* TRANSFORM */;
this.target = 2 /* BACKGROUND_BORDERS */ | 4 /* CONTENT */;
}
return TransformEffect;
}());
var ClipEffect = /** @class */ (function () {
function ClipEffect(path, target) {
this.path = path;
this.target = target;
this.type = 1 /* CLIP */;
}
return ClipEffect;
}());
var OpacityEffect = /** @class */ (function () {
function OpacityEffect(opacity) {
this.opacity = opacity;
this.type = 2 /* OPACITY */;
this.target = 2 /* BACKGROUND_BORDERS */ | 4 /* CONTENT */;
}
return OpacityEffect;
}());
var isTransformEffect = function (effect) {
return effect.type === 0 /* TRANSFORM */;
};
var isClipEffect = function (effect) { return effect.type === 1 /* CLIP */; };
var isOpacityEffect = function (effect) { return effect.type === 2 /* OPACITY */; };
var equalPath = function (a, b) {
if (a.length === b.length) {
return a.some(function (v, i) { return v === b[i]; });
}
return false;
};
var transformPath = function (path, deltaX, deltaY, deltaW, deltaH) {
return path.map(function (point, index) {
switch (index) {
case 0:
return point.add(deltaX, deltaY);
case 1:
return point.add(deltaX + deltaW, deltaY);
case 2:
return point.add(deltaX + deltaW, deltaY + deltaH);
case 3:
return point.add(deltaX, deltaY + deltaH);
}
return point;
});
};
var StackingContext = /** @class */ (function () {
function StackingContext(container) {
this.element = container;
this.inlineLevel = [];
this.nonInlineLevel = [];
this.negativeZIndex = [];
this.zeroOrAutoZIndexOrTransformedOrOpacity = [];
this.positiveZIndex = [];
this.nonPositionedFloats = [];
this.nonPositionedInlineLevel = [];
}
return StackingContext;
}());
var ElementPaint = /** @class */ (function () {
function ElementPaint(container, parent) {
this.container = container;
this.parent = parent;
this.effects = [];
this.curves = new BoundCurves(this.container);
if (this.container.styles.opacity < 1) {
this.effects.push(new OpacityEffect(this.container.styles.opacity));
}
if (this.container.styles.transform !== null) {
var offsetX = this.container.bounds.left + this.container.styles.transformOrigin[0].number;
var offsetY = this.container.bounds.top + this.container.styles.transformOrigin[1].number;
var matrix = this.container.styles.transform;
this.effects.push(new TransformEffect(offsetX, offsetY, matrix));
}
if (this.container.styles.overflowX !== 0 /* VISIBLE */) {
var borderBox = calculateBorderBoxPath(this.curves);
var paddingBox = calculatePaddingBoxPath(this.curves);
if (equalPath(borderBox, paddingBox)) {
this.effects.push(new ClipEffect(borderBox, 2 /* BACKGROUND_BORDERS */ | 4 /* CONTENT */));
}
else {
this.effects.push(new ClipEffect(borderBox, 2 /* BACKGROUND_BORDERS */));
this.effects.push(new ClipEffect(paddingBox, 4 /* CONTENT */));
}
}
}
ElementPaint.prototype.getEffects = function (target) {
var inFlow = [2 /* ABSOLUTE */, 3 /* FIXED */].indexOf(this.container.styles.position) === -1;
var parent = this.parent;
var effects = this.effects.slice(0);
while (parent) {
var croplessEffects = parent.effects.filter(function (effect) { return !isClipEffect(effect); });
if (inFlow || parent.container.styles.position !== 0 /* STATIC */ || !parent.parent) {
effects.unshift.apply(effects, croplessEffects);
inFlow = [2 /* ABSOLUTE */, 3 /* FIXED */].indexOf(parent.container.styles.position) === -1;
if (parent.container.styles.overflowX !== 0 /* VISIBLE */) {
var borderBox = calculateBorderBoxPath(parent.curves);
var paddingBox = calculatePaddingBoxPath(parent.curves);
if (!equalPath(borderBox, paddingBox)) {
effects.unshift(new ClipEffect(paddingBox, 2 /* BACKGROUND_BORDERS */ | 4 /* CONTENT */));
}
}
}
else {
effects.unshift.apply(effects, croplessEffects);
}
parent = parent.parent;
}
return effects.filter(function (effect) { return contains(effect.target, target); });
};
return ElementPaint;
}());
var parseStackTree = function (parent, stackingContext, realStackingContext, listItems) {
parent.container.elements.forEach(function (child) {
var treatAsRealStackingContext = contains(child.flags, 4 /* CREATES_REAL_STACKING_CONTEXT */);
var createsStackingContext = contains(child.flags, 2 /* CREATES_STACKING_CONTEXT */);
var paintContainer = new ElementPaint(child, parent);
if (contains(child.styles.display, 2048 /* LIST_ITEM */)) {
listItems.push(paintContainer);
}
var listOwnerItems = contains(child.flags, 8 /* IS_LIST_OWNER */) ? [] : listItems;
if (treatAsRealStackingContext || createsStackingContext) {
var parentStack = treatAsRealStackingContext || child.styles.isPositioned() ? realStackingContext : stackingContext;
var stack = new StackingContext(paintContainer);
if (child.styles.isPositioned() || child.styles.opacity < 1 || child.styles.isTransformed()) {
var order_1 = child.styles.zIndex.order;
if (order_1 < 0) {
var index_1 = 0;
parentStack.negativeZIndex.some(function (current, i) {
if (order_1 > current.element.container.styles.zIndex.order) {
index_1 = i;
return false;
}
else if (index_1 > 0) {
return true;
}
return false;
});
parentStack.negativeZIndex.splice(index_1, 0, stack);
}
else if (order_1 > 0) {
var index_2 = 0;
parentStack.positiveZIndex.some(function (current, i) {
if (order_1 >= current.element.container.styles.zIndex.order) {
index_2 = i + 1;
return false;
}
else if (index_2 > 0) {
return true;
}
return false;
});
parentStack.positiveZIndex.splice(index_2, 0, stack);
}
else {
parentStack.zeroOrAutoZIndexOrTransformedOrOpacity.push(stack);
}
}
else {
if (child.styles.isFloating()) {
parentStack.nonPositionedFloats.push(stack);
}
else {
parentStack.nonPositionedInlineLevel.push(stack);
}
}
parseStackTree(paintContainer, stack, treatAsRealStackingContext ? stack : realStackingContext, listOwnerItems);
}
else {
if (child.styles.isInlineLevel()) {
stackingContext.inlineLevel.push(paintContainer);
}
else {
stackingContext.nonInlineLevel.push(paintContainer);
}
parseStackTree(paintContainer, stackingContext, realStackingContext, listOwnerItems);
}
if (contains(child.flags, 8 /* IS_LIST_OWNER */)) {
processListItems(child, listOwnerItems);
}
});
};
var processListItems = function (owner, elements) {
var numbering = owner instanceof OLElementContainer ? owner.start : 1;
var reversed = owner instanceof OLElementContainer ? owner.reversed : false;
for (var i = 0; i < elements.length; i++) {
var item = elements[i];
if (item.container instanceof LIElementContainer &&
typeof item.container.value === 'number' &&
item.container.value !== 0) {
numbering = item.container.value;
}
item.listValue = createCounterText(numbering, item.container.styles.listStyleType, true);
numbering += reversed ? -1 : 1;
}
};
var parseStackingContexts = function (container) {
var paintContainer = new ElementPaint(container, null);
var root = new StackingContext(paintContainer);
var listItems = [];
parseStackTree(paintContainer, root, root, listItems);
processListItems(paintContainer.container, listItems);
return root;
};
var parsePathForBorder = function (curves, borderSide) {
switch (borderSide) {
case 0:
return createPathFromCurves(curves.topLeftBorderBox, curves.topLeftPaddingBox, curves.topRightBorderBox, curves.topRightPaddingBox);
case 1:
return createPathFromCurves(curves.topRightBorderBox, curves.topRightPaddingBox, curves.bottomRightBorderBox, curves.bottomRightPaddingBox);
case 2:
return createPathFromCurves(curves.bottomRightBorderBox, curves.bottomRightPaddingBox, curves.bottomLeftBorderBox, curves.bottomLeftPaddingBox);
case 3:
default:
return createPathFromCurves(curves.bottomLeftBorderBox, curves.bottomLeftPaddingBox, curves.topLeftBorderBox, curves.topLeftPaddingBox);
}
};
var parsePathForBorderDoubleOuter = function (curves, borderSide) {
switch (borderSide) {
case 0:
return createPathFromCurves(curves.topLeftBorderBox, curves.topLeftBorderDoubleOuterBox, curves.topRightBorderBox, curves.topRightBorderDoubleOuterBox);
case 1:
return createPathFromCurves(curves.topRightBorderBox, curves.topRightBorderDoubleOuterBox, curves.bottomRightBorderBox, curves.bottomRightBorderDoubleOuterBox);
case 2:
return createPathFromCurves(curves.bottomRightBorderBox, curves.bottomRightBorderDoubleOuterBox, curves.bottomLeftBorderBox, curves.bottomLeftBorderDoubleOuterBox);
case 3:
default:
return createPathFromCurves(curves.bottomLeftBorderBox, curves.bottomLeftBorderDoubleOuterBox, curves.topLeftBorderBox, curves.topLeftBorderDoubleOuterBox);
}
};
var parsePathForBorderDoubleInner = function (curves, borderSide) {
switch (borderSide) {
case 0:
return createPathFromCurves(curves.topLeftBorderDoubleInnerBox, curves.topLeftPaddingBox, curves.topRightBorderDoubleInnerBox, curves.topRightPaddingBox);
case 1:
return createPathFromCurves(curves.topRightBorderDoubleInnerBox, curves.topRightPaddingBox, curves.bottomRightBorderDoubleInnerBox, curves.bottomRightPaddingBox);
case 2:
return createPathFromCurves(curves.bottomRightBorderDoubleInnerBox, curves.bottomRightPaddingBox, curves.bottomLeftBorderDoubleInnerBox, curves.bottomLeftPaddingBox);
case 3:
default:
return createPathFromCurves(curves.bottomLeftBorderDoubleInnerBox, curves.bottomLeftPaddingBox, curves.topLeftBorderDoubleInnerBox, curves.topLeftPaddingBox);
}
};
var parsePathForBorderStroke = function (curves, borderSide) {
switch (borderSide) {
case 0:
return createStrokePathFromCurves(curves.topLeftBorderStroke, curves.topRightBorderStroke);
case 1:
return createStrokePathFromCurves(curves.topRightBorderStroke, curves.bottomRightBorderStroke);
case 2:
return createStrokePathFromCurves(curves.bottomRightBorderStroke, curves.bottomLeftBorderStroke);
case 3:
default:
return createStrokePathFromCurves(curves.bottomLeftBorderStroke, curves.topLeftBorderStroke);
}
};
var createStrokePathFromCurves = function (outer1, outer2) {
var path = [];
if (isBezierCurve(outer1)) {
path.push(outer1.subdivide(0.5, false));
}
else {
path.push(outer1);
}
if (isBezierCurve(outer2)) {
path.push(outer2.subdivide(0.5, true));
}
else {
path.push(outer2);
}
return path;
};
var createPathFromCurves = function (outer1, inner1, outer2, inner2) {
var path = [];
if (isBezierCurve(outer1)) {
path.push(outer1.subdivide(0.5, false));
}
else {
path.push(outer1);
}
if (isBezierCurve(outer2)) {
path.push(outer2.subdivide(0.5, true));
}
else {
path.push(outer2);
}
if (isBezierCurve(inner2)) {
path.push(inner2.subdivide(0.5, true).reverse());
}
else {
path.push(inner2);
}
if (isBezierCurve(inner1)) {
path.push(inner1.subdivide(0.5, false).reverse());
}
else {
path.push(inner1);
}
return path;
};
var paddingBox = function (element) {
var bounds = element.bounds;
var styles = element.styles;
return bounds.add(styles.borderLeftWidth, styles.borderTopWidth, -(styles.borderRightWidth + styles.borderLeftWidth), -(styles.borderTopWidth + styles.borderBottomWidth));
};
var contentBox = function (element) {
var styles = element.styles;
var bounds = element.bounds;
var paddingLeft = getAbsoluteValue(styles.paddingLeft, bounds.width);
var paddingRight = getAbsoluteValue(styles.paddingRight, bounds.width);
var paddingTop = getAbsoluteValue(styles.paddingTop, bounds.width);
var paddingBottom = getAbsoluteValue(styles.paddingBottom, bounds.width);
return bounds.add(paddingLeft + styles.borderLeftWidth, paddingTop + styles.borderTopWidth, -(styles.borderRightWidth + styles.borderLeftWidth + paddingLeft + paddingRight), -(styles.borderTopWidth + styles.borderBottomWidth + paddingTop + paddingBottom));
};
var calculateBackgroundPositioningArea = function (backgroundOrigin, element) {
if (backgroundOrigin === 0 /* BORDER_BOX */) {
return element.bounds;
}
if (backgroundOrigin === 2 /* CONTENT_BOX */) {
return contentBox(element);
}
return paddingBox(element);
};
var calculateBackgroundPaintingArea = function (backgroundClip, element) {
if (backgroundClip === 0 /* BORDER_BOX */) {
return element.bounds;
}
if (backgroundClip === 2 /* CONTENT_BOX */) {
return contentBox(element);
}
return paddingBox(element);
};
var calculateBackgroundRendering = function (container, index, intrinsicSize) {
var backgroundPositioningArea = calculateBackgroundPositioningArea(getBackgroundValueForIndex(container.styles.backgroundOrigin, index), container);
var backgroundPaintingArea = calculateBackgroundPaintingArea(getBackgroundValueForIndex(container.styles.backgroundClip, index), container);
var backgroundImageSize = calculateBackgroundSize(getBackgroundValueForIndex(container.styles.backgroundSize, index), intrinsicSize, backgroundPositioningArea);
var sizeWidth = backgroundImageSize[0], sizeHeight = backgroundImageSize[1];
var position = getAbsoluteValueForTuple(getBackgroundValueForIndex(container.styles.backgroundPosition, index), backgroundPositioningArea.width - sizeWidth, backgroundPositioningArea.height - sizeHeight);
var path = calculateBackgroundRepeatPath(getBackgroundValueForIndex(container.styles.backgroundRepeat, index), position, backgroundImageSize, backgroundPositioningArea, backgroundPaintingArea);
var offsetX = Math.round(backgroundPositioningArea.left + position[0]);
var offsetY = Math.round(backgroundPositioningArea.top + position[1]);
return [path, offsetX, offsetY, sizeWidth, sizeHeight];
};
var isAuto = function (token) { return isIdentToken(token) && token.value === BACKGROUND_SIZE.AUTO; };
var hasIntrinsicValue = function (value) { return typeof value === 'number'; };
var calculateBackgroundSize = function (size, _a, bounds) {
var intrinsicWidth = _a[0], intrinsicHeight = _a[1], intrinsicProportion = _a[2];
var first = size[0], second = size[1];
if (!first) {
return [0, 0];
}
if (isLengthPercentage(first) && second && isLengthPercentage(second)) {
return [getAbsoluteValue(first, bounds.width), getAbsoluteValue(second, bounds.height)];
}
var hasIntrinsicProportion = hasIntrinsicValue(intrinsicProportion);
if (isIdentToken(first) && (first.value === BACKGROUND_SIZE.CONTAIN || first.value === BACKGROUND_SIZE.COVER)) {
if (hasIntrinsicValue(intrinsicProportion)) {
var targetRatio = bounds.width / bounds.height;
return targetRatio < intrinsicProportion !== (first.value === BACKGROUND_SIZE.COVER)
? [bounds.width, bounds.width / intrinsicProportion]
: [bounds.height * intrinsicProportion, bounds.height];
}
return [bounds.width, bounds.height];
}
var hasIntrinsicWidth = hasIntrinsicValue(intrinsicWidth);
var hasIntrinsicHeight = hasIntrinsicValue(intrinsicHeight);
var hasIntrinsicDimensions = hasIntrinsicWidth || hasIntrinsicHeight;
// If the background-size is auto or auto auto:
if (isAuto(first) && (!second || isAuto(second))) {
// If the image has both horizontal and vertical intrinsic dimensions, it's rendered at that size.
if (hasIntrinsicWidth && hasIntrinsicHeight) {
return [intrinsicWidth, intrinsicHeight];
}
// If the image has no intrinsic dimensions and has no intrinsic proportions,
// it's rendered at the size of the background positioning area.
if (!hasIntrinsicProportion && !hasIntrinsicDimensions) {
return [bounds.width, bounds.height];
}
// TODO If the image has no intrinsic dimensions but has intrinsic proportions, it's rendered as if contain had been specified instead.
// If the image has only one intrinsic dimension and has intrinsic proportions, it's rendered at the size corresponding to that one dimension.
// The other dimension is computed using the specified dimension and the intrinsic proportions.
if (hasIntrinsicDimensions && hasIntrinsicProportion) {
var width_1 = hasIntrinsicWidth
? intrinsicWidth
: intrinsicHeight * intrinsicProportion;
var height_1 = hasIntrinsicHeight
? intrinsicHeight
: intrinsicWidth / intrinsicProportion;
return [width_1, height_1];
}
// If the image has only one intrinsic dimension but has no intrinsic proportions,
// it's rendered using the specified dimension and the other dimension of the background positioning area.
var width_2 = hasIntrinsicWidth ? intrinsicWidth : bounds.width;
var height_2 = hasIntrinsicHeight ? intrinsicHeight : bounds.height;
return [width_2, height_2];
}
// If the image has intrinsic proportions, it's stretched to the specified dimension.
// The unspecified dimension is computed using the specified dimension and the intrinsic proportions.
if (hasIntrinsicProportion) {
var width_3 = 0;
var height_3 = 0;
if (isLengthPercentage(first)) {
width_3 = getAbsoluteValue(first, bounds.width);
}
else if (isLengthPercentage(second)) {
height_3 = getAbsoluteValue(second, bounds.height);
}
if (isAuto(first)) {
width_3 = height_3 * intrinsicProportion;
}
else if (!second || isAuto(second)) {
height_3 = width_3 / intrinsicProportion;
}
return [width_3, height_3];
}
// If the image has no intrinsic proportions, it's stretched to the specified dimension.
// The unspecified dimension is computed using the image's corresponding intrinsic dimension,
// if there is one. If there is no such intrinsic dimension,
// it becomes the corresponding dimension of the background positioning area.
var width = null;
var height = null;
if (isLengthPercentage(first)) {
width = getAbsoluteValue(first, bounds.width);
}
else if (second && isLengthPercentage(second)) {
height = getAbsoluteValue(second, bounds.height);
}
if (width !== null && (!second || isAuto(second))) {
height =
hasIntrinsicWidth && hasIntrinsicHeight
? (width / intrinsicWidth) * intrinsicHeight
: bounds.height;
}
if (height !== null && isAuto(first)) {
width =
hasIntrinsicWidth && hasIntrinsicHeight
? (height / intrinsicHeight) * intrinsicWidth
: bounds.width;
}
if (width !== null && height !== null) {
return [width, height];
}
throw new Error("Unable to calculate background-size for element");
};
var getBackgroundValueForIndex = function (values, index) {
var value = values[index];
if (typeof value === 'undefined') {
return values[0];
}
return value;
};
var calculateBackgroundRepeatPath = function (repeat, _a, _b, backgroundPositioningArea, backgroundPaintingArea) {
var x = _a[0], y = _a[1];
var width = _b[0], height = _b[1];
switch (repeat) {
case 2 /* REPEAT_X */:
return [
new Vector(Math.round(backgroundPositioningArea.left), Math.round(backgroundPositioningArea.top + y)),
new Vector(Math.round(backgroundPositioningArea.left + backgroundPositioningArea.width), Math.round(backgroundPositioningArea.top + y)),
new Vector(Math.round(backgroundPositioningArea.left + backgroundPositioningArea.width), Math.round(height + backgroundPositioningArea.top + y)),
new Vector(Math.round(backgroundPositioningArea.left), Math.round(height + backgroundPositioningArea.top + y))
];
case 3 /* REPEAT_Y */:
return [
new Vector(Math.round(backgroundPositioningArea.left + x), Math.round(backgroundPositioningArea.top)),
new Vector(Math.round(backgroundPositioningArea.left + x + width), Math.round(backgroundPositioningArea.top)),
new Vector(Math.round(backgroundPositioningArea.left + x + width), Math.round(backgroundPositioningArea.height + backgroundPositioningArea.top)),
new Vector(Math.round(backgroundPositioningArea.left + x), Math.round(backgroundPositioningArea.height + backgroundPositioningArea.top))
];
case 1 /* NO_REPEAT */:
return [
new Vector(Math.round(backgroundPositioningArea.left + x), Math.round(backgroundPositioningArea.top + y)),
new Vector(Math.round(backgroundPositioningArea.left + x + width), Math.round(backgroundPositioningArea.top + y)),
new Vector(Math.round(backgroundPositioningArea.left + x + width), Math.round(backgroundPositioningArea.top + y + height)),
new Vector(Math.round(backgroundPositioningArea.left + x), Math.round(backgroundPositioningArea.top + y + height))
];
default:
return [
new Vector(Math.round(backgroundPaintingArea.left), Math.round(backgroundPaintingArea.top)),
new Vector(Math.round(backgroundPaintingArea.left + backgroundPaintingArea.width), Math.round(backgroundPaintingArea.top)),
new Vector(Math.round(backgroundPaintingArea.left + backgroundPaintingArea.width), Math.round(backgroundPaintingArea.height + backgroundPaintingArea.top)),
new Vector(Math.round(backgroundPaintingArea.left), Math.round(backgroundPaintingArea.height + backgroundPaintingArea.top))
];
}
};
var SMALL_IMAGE = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
var SAMPLE_TEXT = 'Hidden Text';
var FontMetrics = /** @class */ (function () {
function FontMetrics(document) {
this._data = {};
this._document = document;
}
FontMetrics.prototype.parseMetrics = function (fontFamily, fontSize) {
var container = this._document.createElement('div');
var img = this._document.createElement('img');
var span = this._document.createElement('span');
var body = this._document.body;
container.style.visibility = 'hidden';
container.style.fontFamily = fontFamily;
container.style.fontSize = fontSize;
container.style.margin = '0';
container.style.padding = '0';
container.style.whiteSpace = 'nowrap';
body.appendChild(container);
img.src = SMALL_IMAGE;
img.width = 1;
img.height = 1;
img.style.margin = '0';
img.style.padding = '0';
img.style.verticalAlign = 'baseline';
span.style.fontFamily = fontFamily;
span.style.fontSize = fontSize;
span.style.margin = '0';
span.style.padding = '0';
span.appendChild(this._document.createTextNode(SAMPLE_TEXT));
container.appendChild(span);
container.appendChild(img);
var baseline = img.offsetTop - span.offsetTop + 2;
container.removeChild(span);
container.appendChild(this._document.createTextNode(SAMPLE_TEXT));
container.style.lineHeight = 'normal';
img.style.verticalAlign = 'super';
var middle = img.offsetTop - container.offsetTop + 2;
body.removeChild(container);
return { baseline: baseline, middle: middle };
};
FontMetrics.prototype.getMetrics = function (fontFamily, fontSize) {
var key = fontFamily + " " + fontSize;
if (typeof this._data[key] === 'undefined') {
this._data[key] = this.parseMetrics(fontFamily, fontSize);
}
return this._data[key];
};
return FontMetrics;
}());
var Renderer = /** @class */ (function () {
function Renderer(context, options) {
this.context = context;
this.options = options;
}
return Renderer;
}());
var MASK_OFFSET = 10000;
var CanvasRenderer = /** @class */ (function (_super) {
__extends(CanvasRenderer, _super);
function CanvasRenderer(context, options) {
var _this = _super.call(this, context, options) || this;
_this._activeEffects = [];
_this.canvas = options.canvas ? options.canvas : document.createElement('canvas');
_this.ctx = _this.canvas.getContext('2d');
if (!options.canvas) {
_this.canvas.width = Math.floor(options.width * options.scale);
_this.canvas.height = Math.floor(options.height * options.scale);
_this.canvas.style.width = options.width + "px";
_this.canvas.style.height = options.height + "px";
}
_this.fontMetrics = new FontMetrics(document);
_this.ctx.scale(_this.options.scale, _this.options.scale);
_this.ctx.translate(-options.x, -options.y);
_this.ctx.textBaseline = 'bottom';
_this._activeEffects = [];
_this.context.logger.debug("Canvas renderer initialized (" + options.width + "x" + options.height + ") with scale " + options.scale);
return _this;
}
CanvasRenderer.prototype.applyEffects = function (effects) {
var _this = this;
while (this._activeEffects.length) {
this.popEffect();
}
effects.forEach(function (effect) { return _this.applyEffect(effect); });
};
CanvasRenderer.prototype.applyEffect = function (effect) {
this.ctx.save();
if (isOpacityEffect(effect)) {
this.ctx.globalAlpha = effect.opacity;
}
if (isTransformEffect(effect)) {
this.ctx.translate(effect.offsetX, effect.offsetY);
this.ctx.transform(effect.matrix[0], effect.matrix[1], effect.matrix[2], effect.matrix[3], effect.matrix[4], effect.matrix[5]);
this.ctx.translate(-effect.offsetX, -effect.offsetY);
}
if (isClipEffect(effect)) {
this.path(effect.path);
this.ctx.clip();
}
this._activeEffects.push(effect);
};
CanvasRenderer.prototype.popEffect = function () {
this._activeEffects.pop();
this.ctx.restore();
};
CanvasRenderer.prototype.renderStack = function (stack) {
return __awaiter(this, void 0, void 0, function () {
var styles;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
styles = stack.element.container.styles;
if (!styles.isVisible()) return [3 /*break*/, 2];
return [4 /*yield*/, this.renderStackContent(stack)];
case 1:
_a.sent();
_a.label = 2;
case 2: return [2 /*return*/];
}
});
});
};
CanvasRenderer.prototype.renderNode = function (paint) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (contains(paint.container.flags, 16 /* DEBUG_RENDER */)) {
debugger;
}
if (!paint.container.styles.isVisible()) return [3 /*break*/, 3];
return [4 /*yield*/, this.renderNodeBackgroundAndBorders(paint)];
case 1:
_a.sent();
return [4 /*yield*/, this.renderNodeContent(paint)];
case 2:
_a.sent();
_a.label = 3;
case 3: return [2 /*return*/];
}
});
});
};
CanvasRenderer.prototype.renderTextWithLetterSpacing = function (text, letterSpacing, baseline) {
var _this = this;
if (letterSpacing === 0) {
this.ctx.fillText(text.text, text.bounds.left, text.bounds.top + baseline);
}
else {
var letters = segmentGraphemes(text.text);
letters.reduce(function (left, letter) {
_this.ctx.fillText(letter, left, text.bounds.top + baseline);
return left + _this.ctx.measureText(letter).width;
}, text.bounds.left);
}
};
CanvasRenderer.prototype.createFontStyle = function (styles) {
var fontVariant = styles.fontVariant
.filter(function (variant) { return variant === 'normal' || variant === 'small-caps'; })
.join('');
var fontFamily = fixIOSSystemFonts(styles.fontFamily).join(', ');
var fontSize = isDimensionToken(styles.fontSize)
? "" + styles.fontSize.number + styles.fontSize.unit
: styles.fontSize.number + "px";
return [
[styles.fontStyle, fontVariant, styles.fontWeight, fontSize, fontFamily].join(' '),
fontFamily,
fontSize
];
};
CanvasRenderer.prototype.renderTextNode = function (text, styles) {
return __awaiter(this, void 0, void 0, function () {
var _a, font, fontFamily, fontSize, _b, baseline, middle, paintOrder;
var _this = this;
return __generator(this, function (_c) {
_a = this.createFontStyle(styles), font = _a[0], fontFamily = _a[1], fontSize = _a[2];
this.ctx.font = font;
this.ctx.direction = styles.direction === 1 /* RTL */ ? 'rtl' : 'ltr';
this.ctx.textAlign = 'left';
this.ctx.textBaseline = 'alphabetic';
_b = this.fontMetrics.getMetrics(fontFamily, fontSize), baseline = _b.baseline, middle = _b.middle;
paintOrder = styles.paintOrder;
text.textBounds.forEach(function (text) {
paintOrder.forEach(function (paintOrderLayer) {
switch (paintOrderLayer) {
case 0 /* FILL */:
_this.ctx.fillStyle = asString(styles.color);
_this.renderTextWithLetterSpacing(text, styles.letterSpacing, baseline);
var textShadows = styles.textShadow;
if (textShadows.length && text.text.trim().length) {
textShadows
.slice(0)
.reverse()
.forEach(function (textShadow) {
_this.ctx.shadowColor = asString(textShadow.color);
_this.ctx.shadowOffsetX = textShadow.offsetX.number * _this.options.scale;
_this.ctx.shadowOffsetY = textShadow.offsetY.number * _this.options.scale;
_this.ctx.shadowBlur = textShadow.blur.number;
_this.renderTextWithLetterSpacing(text, styles.letterSpacing, baseline);
});
_this.ctx.shadowColor = '';
_this.ctx.shadowOffsetX = 0;
_this.ctx.shadowOffsetY = 0;
_this.ctx.shadowBlur = 0;
}
if (styles.textDecorationLine.length) {
_this.ctx.fillStyle = asString(styles.textDecorationColor || styles.color);
styles.textDecorationLine.forEach(function (textDecorationLine) {
switch (textDecorationLine) {
case 1 /* UNDERLINE */:
// Draws a line at the baseline of the font
// TODO As some browsers display the line as more than 1px if the font-size is big,
// need to take that into account both in position and size
_this.ctx.fillRect(text.bounds.left, Math.round(text.bounds.top + baseline), text.bounds.width, 1);
break;
case 2 /* OVERLINE */:
_this.ctx.fillRect(text.bounds.left, Math.round(text.bounds.top), text.bounds.width, 1);
break;
case 3 /* LINE_THROUGH */:
// TODO try and find exact position for line-through
_this.ctx.fillRect(text.bounds.left, Math.ceil(text.bounds.top + middle), text.bounds.width, 1);
break;
}
});
}
break;
case 1 /* STROKE */:
if (styles.webkitTextStrokeWidth && text.text.trim().length) {
_this.ctx.strokeStyle = asString(styles.webkitTextStrokeColor);
_this.ctx.lineWidth = styles.webkitTextStrokeWidth;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
_this.ctx.lineJoin = !!window.chrome ? 'miter' : 'round';
_this.ctx.strokeText(text.text, text.bounds.left, text.bounds.top + baseline);
}
_this.ctx.strokeStyle = '';
_this.ctx.lineWidth = 0;
_this.ctx.lineJoin = 'miter';
break;
}
});
});
return [2 /*return*/];
});
});
};
CanvasRenderer.prototype.renderReplacedElement = function (container, curves, image) {
if (image && container.intrinsicWidth > 0 && container.intrinsicHeight > 0) {
var box = contentBox(container);
var path = calculatePaddingBoxPath(curves);
this.path(path);
this.ctx.save();
this.ctx.clip();
this.ctx.drawImage(image, 0, 0, container.intrinsicWidth, container.intrinsicHeight, box.left, box.top, box.width, box.height);
this.ctx.restore();
}
};
CanvasRenderer.prototype.renderNodeContent = function (paint) {
return __awaiter(this, void 0, void 0, function () {
var container, curves, styles, _i, _a, child, image, image, iframeRenderer, canvas, size, _b, fontFamily, fontSize, baseline, bounds, x, textBounds, img, image, url, fontFamily, bounds;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
this.applyEffects(paint.getEffects(4 /* CONTENT */));
container = paint.container;
curves = paint.curves;
styles = container.styles;
_i = 0, _a = container.textNodes;
_c.label = 1;
case 1:
if (!(_i < _a.length)) return [3 /*break*/, 4];
child = _a[_i];
return [4 /*yield*/, this.renderTextNode(child, styles)];
case 2:
_c.sent();
_c.label = 3;
case 3:
_i++;
return [3 /*break*/, 1];
case 4:
if (!(container instanceof ImageElementContainer)) return [3 /*break*/, 8];
_c.label = 5;
case 5:
_c.trys.push([5, 7, , 8]);
return [4 /*yield*/, this.context.cache.match(container.src)];
case 6:
image = _c.sent();
this.renderReplacedElement(container, curves, image);
return [3 /*break*/, 8];
case 7:
_c.sent();
this.context.logger.error("Error loading image " + container.src);
return [3 /*break*/, 8];
case 8:
if (container instanceof CanvasElementContainer) {
this.renderReplacedElement(container, curves, container.canvas);
}
if (!(container instanceof SVGElementContainer)) return [3 /*break*/, 12];
_c.label = 9;
case 9:
_c.trys.push([9, 11, , 12]);
return [4 /*yield*/, this.context.cache.match(container.svg)];
case 10:
image = _c.sent();
this.renderReplacedElement(container, curves, image);
return [3 /*break*/, 12];
case 11:
_c.sent();
this.context.logger.error("Error loading svg " + container.svg.substring(0, 255));
return [3 /*break*/, 12];
case 12:
if (!(container instanceof IFrameElementContainer && container.tree)) return [3 /*break*/, 14];
iframeRenderer = new CanvasRenderer(this.context, {
scale: this.options.scale,
backgroundColor: container.backgroundColor,
x: 0,
y: 0,
width: container.width,
height: container.height
});
return [4 /*yield*/, iframeRenderer.render(container.tree)];
case 13:
canvas = _c.sent();
if (container.width && container.height) {
this.ctx.drawImage(canvas, 0, 0, container.width, container.height, container.bounds.left, container.bounds.top, container.bounds.width, container.bounds.height);
}
_c.label = 14;
case 14:
if (container instanceof InputElementContainer) {
size = Math.min(container.bounds.width, container.bounds.height);
if (container.type === CHECKBOX) {
if (container.checked) {
this.ctx.save();
this.path([
new Vector(container.bounds.left + size * 0.39363, container.bounds.top + size * 0.79),
new Vector(container.bounds.left + size * 0.16, container.bounds.top + size * 0.5549),
new Vector(container.bounds.left + size * 0.27347, container.bounds.top + size * 0.44071),
new Vector(container.bounds.left + size * 0.39694, container.bounds.top + size * 0.5649),
new Vector(container.bounds.left + size * 0.72983, container.bounds.top + size * 0.23),
new Vector(container.bounds.left + size * 0.84, container.bounds.top + size * 0.34085),
new Vector(container.bounds.left + size * 0.39363, container.bounds.top + size * 0.79)
]);
this.ctx.fillStyle = asString(INPUT_COLOR);
this.ctx.fill();
this.ctx.restore();
}
}
else if (container.type === RADIO) {
if (container.checked) {
this.ctx.save();
this.ctx.beginPath();
this.ctx.arc(container.bounds.left + size / 2, container.bounds.top + size / 2, size / 4, 0, Math.PI * 2, true);
this.ctx.fillStyle = asString(INPUT_COLOR);
this.ctx.fill();
this.ctx.restore();
}
}
}
if (isTextInputElement(container) && container.value.length) {
_b = this.createFontStyle(styles), fontFamily = _b[0], fontSize = _b[1];
baseline = this.fontMetrics.getMetrics(fontFamily, fontSize).baseline;
this.ctx.font = fontFamily;
this.ctx.fillStyle = asString(styles.color);
this.ctx.textBaseline = 'alphabetic';
this.ctx.textAlign = canvasTextAlign(container.styles.textAlign);
bounds = contentBox(container);
x = 0;
switch (container.styles.textAlign) {
case 1 /* CENTER */:
x += bounds.width / 2;
break;
case 2 /* RIGHT */:
x += bounds.width;
break;
}
textBounds = bounds.add(x, 0, 0, -bounds.height / 2 + 1);
this.ctx.save();
this.path([
new Vector(bounds.left, bounds.top),
new Vector(bounds.left + bounds.width, bounds.top),
new Vector(bounds.left + bounds.width, bounds.top + bounds.height),
new Vector(bounds.left, bounds.top + bounds.height)
]);
this.ctx.clip();
this.renderTextWithLetterSpacing(new TextBounds(container.value, textBounds), styles.letterSpacing, baseline);
this.ctx.restore();
this.ctx.textBaseline = 'alphabetic';
this.ctx.textAlign = 'left';
}
if (!contains(container.styles.display, 2048 /* LIST_ITEM */)) return [3 /*break*/, 20];
if (!(container.styles.listStyleImage !== null)) return [3 /*break*/, 19];
img = container.styles.listStyleImage;
if (!(img.type === 0 /* URL */)) return [3 /*break*/, 18];
image = void 0;
url = img.url;
_c.label = 15;
case 15:
_c.trys.push([15, 17, , 18]);
return [4 /*yield*/, this.context.cache.match(url)];
case 16:
image = _c.sent();
this.ctx.drawImage(image, container.bounds.left - (image.width + 10), container.bounds.top);
return [3 /*break*/, 18];
case 17:
_c.sent();
this.context.logger.error("Error loading list-style-image " + url);
return [3 /*break*/, 18];
case 18: return [3 /*break*/, 20];
case 19:
if (paint.listValue && container.styles.listStyleType !== -1 /* NONE */) {
fontFamily = this.createFontStyle(styles)[0];
this.ctx.font = fontFamily;
this.ctx.fillStyle = asString(styles.color);
this.ctx.textBaseline = 'middle';
this.ctx.textAlign = 'right';
bounds = new Bounds(container.bounds.left, container.bounds.top + getAbsoluteValue(container.styles.paddingTop, container.bounds.width), container.bounds.width, computeLineHeight(styles.lineHeight, styles.fontSize.number) / 2 + 1);
this.renderTextWithLetterSpacing(new TextBounds(paint.listValue, bounds), styles.letterSpacing, computeLineHeight(styles.lineHeight, styles.fontSize.number) / 2 + 2);
this.ctx.textBaseline = 'bottom';
this.ctx.textAlign = 'left';
}
_c.label = 20;
case 20: return [2 /*return*/];
}
});
});
};
CanvasRenderer.prototype.renderStackContent = function (stack) {
return __awaiter(this, void 0, void 0, function () {
var _i, _a, child, _b, _c, child, _d, _e, child, _f, _g, child, _h, _j, child, _k, _l, child, _m, _o, child;
return __generator(this, function (_p) {
switch (_p.label) {
case 0:
if (contains(stack.element.container.flags, 16 /* DEBUG_RENDER */)) {
debugger;
}
// https://www.w3.org/TR/css-position-3/#painting-order
// 1. the background and borders of the element forming the stacking context.
return [4 /*yield*/, this.renderNodeBackgroundAndBorders(stack.element)];
case 1:
// https://www.w3.org/TR/css-position-3/#painting-order
// 1. the background and borders of the element forming the stacking context.
_p.sent();
_i = 0, _a = stack.negativeZIndex;
_p.label = 2;
case 2:
if (!(_i < _a.length)) return [3 /*break*/, 5];
child = _a[_i];
return [4 /*yield*/, this.renderStack(child)];
case 3:
_p.sent();
_p.label = 4;
case 4:
_i++;
return [3 /*break*/, 2];
case 5:
// 3. For all its in-flow, non-positioned, block-level descendants in tree order:
return [4 /*yield*/, this.renderNodeContent(stack.element)];
case 6:
// 3. For all its in-flow, non-positioned, block-level descendants in tree order:
_p.sent();
_b = 0, _c = stack.nonInlineLevel;
_p.label = 7;
case 7:
if (!(_b < _c.length)) return [3 /*break*/, 10];
child = _c[_b];
return [4 /*yield*/, this.renderNode(child)];
case 8:
_p.sent();
_p.label = 9;
case 9:
_b++;
return [3 /*break*/, 7];
case 10:
_d = 0, _e = stack.nonPositionedFloats;
_p.label = 11;
case 11:
if (!(_d < _e.length)) return [3 /*break*/, 14];
child = _e[_d];
return [4 /*yield*/, this.renderStack(child)];
case 12:
_p.sent();
_p.label = 13;
case 13:
_d++;
return [3 /*break*/, 11];
case 14:
_f = 0, _g = stack.nonPositionedInlineLevel;
_p.label = 15;
case 15:
if (!(_f < _g.length)) return [3 /*break*/, 18];
child = _g[_f];
return [4 /*yield*/, this.renderStack(child)];
case 16:
_p.sent();
_p.label = 17;
case 17:
_f++;
return [3 /*break*/, 15];
case 18:
_h = 0, _j = stack.inlineLevel;
_p.label = 19;
case 19:
if (!(_h < _j.length)) return [3 /*break*/, 22];
child = _j[_h];
return [4 /*yield*/, this.renderNode(child)];
case 20:
_p.sent();
_p.label = 21;
case 21:
_h++;
return [3 /*break*/, 19];
case 22:
_k = 0, _l = stack.zeroOrAutoZIndexOrTransformedOrOpacity;
_p.label = 23;
case 23:
if (!(_k < _l.length)) return [3 /*break*/, 26];
child = _l[_k];
return [4 /*yield*/, this.renderStack(child)];
case 24:
_p.sent();
_p.label = 25;
case 25:
_k++;
return [3 /*break*/, 23];
case 26:
_m = 0, _o = stack.positiveZIndex;
_p.label = 27;
case 27:
if (!(_m < _o.length)) return [3 /*break*/, 30];
child = _o[_m];
return [4 /*yield*/, this.renderStack(child)];
case 28:
_p.sent();
_p.label = 29;
case 29:
_m++;
return [3 /*break*/, 27];
case 30: return [2 /*return*/];
}
});
});
};
CanvasRenderer.prototype.mask = function (paths) {
this.ctx.beginPath();
this.ctx.moveTo(0, 0);
this.ctx.lineTo(this.canvas.width, 0);
this.ctx.lineTo(this.canvas.width, this.canvas.height);
this.ctx.lineTo(0, this.canvas.height);
this.ctx.lineTo(0, 0);
this.formatPath(paths.slice(0).reverse());
this.ctx.closePath();
};
CanvasRenderer.prototype.path = function (paths) {
this.ctx.beginPath();
this.formatPath(paths);
this.ctx.closePath();
};
CanvasRenderer.prototype.formatPath = function (paths) {
var _this = this;
paths.forEach(function (point, index) {
var start = isBezierCurve(point) ? point.start : point;
if (index === 0) {
_this.ctx.moveTo(start.x, start.y);
}
else {
_this.ctx.lineTo(start.x, start.y);
}
if (isBezierCurve(point)) {
_this.ctx.bezierCurveTo(point.startControl.x, point.startControl.y, point.endControl.x, point.endControl.y, point.end.x, point.end.y);
}
});
};
CanvasRenderer.prototype.renderRepeat = function (path, pattern, offsetX, offsetY) {
this.path(path);
this.ctx.fillStyle = pattern;
this.ctx.translate(offsetX, offsetY);
this.ctx.fill();
this.ctx.translate(-offsetX, -offsetY);
};
CanvasRenderer.prototype.resizeImage = function (image, width, height) {
var _a;
if (image.width === width && image.height === height) {
return image;
}
var ownerDocument = (_a = this.canvas.ownerDocument) !== null && _a !== void 0 ? _a : document;
var canvas = ownerDocument.createElement('canvas');
canvas.width = Math.max(1, width);
canvas.height = Math.max(1, height);
var ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, width, height);
return canvas;
};
CanvasRenderer.prototype.renderBackgroundImage = function (container) {
return __awaiter(this, void 0, void 0, function () {
var index, _loop_1, this_1, _i, _a, backgroundImage;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
index = container.styles.backgroundImage.length - 1;
_loop_1 = function (backgroundImage) {
var image, url, _c, path, x, y, width, height, pattern, _d, path, x, y, width, height, _e, lineLength, x0, x1, y0, y1, canvas, ctx, gradient_1, pattern, _f, path, left, top_1, width, height, position, x, y, _g, rx, ry, radialGradient_1, midX, midY, f, invF;
return __generator(this, function (_h) {
switch (_h.label) {
case 0:
if (!(backgroundImage.type === 0 /* URL */)) return [3 /*break*/, 5];
image = void 0;
url = backgroundImage.url;
_h.label = 1;
case 1:
_h.trys.push([1, 3, , 4]);
return [4 /*yield*/, this_1.context.cache.match(url)];
case 2:
image = _h.sent();
return [3 /*break*/, 4];
case 3:
_h.sent();
this_1.context.logger.error("Error loading background-image " + url);
return [3 /*break*/, 4];
case 4:
if (image) {
_c = calculateBackgroundRendering(container, index, [
image.width,
image.height,
image.width / image.height
]), path = _c[0], x = _c[1], y = _c[2], width = _c[3], height = _c[4];
pattern = this_1.ctx.createPattern(this_1.resizeImage(image, width, height), 'repeat');
this_1.renderRepeat(path, pattern, x, y);
}
return [3 /*break*/, 6];
case 5:
if (isLinearGradient(backgroundImage)) {
_d = calculateBackgroundRendering(container, index, [null, null, null]), path = _d[0], x = _d[1], y = _d[2], width = _d[3], height = _d[4];
_e = calculateGradientDirection(backgroundImage.angle, width, height), lineLength = _e[0], x0 = _e[1], x1 = _e[2], y0 = _e[3], y1 = _e[4];
canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext('2d');
gradient_1 = ctx.createLinearGradient(x0, y0, x1, y1);
processColorStops(backgroundImage.stops, lineLength).forEach(function (colorStop) {
return gradient_1.addColorStop(colorStop.stop, asString(colorStop.color));
});
ctx.fillStyle = gradient_1;
ctx.fillRect(0, 0, width, height);
if (width > 0 && height > 0) {
pattern = this_1.ctx.createPattern(canvas, 'repeat');
this_1.renderRepeat(path, pattern, x, y);
}
}
else if (isRadialGradient(backgroundImage)) {
_f = calculateBackgroundRendering(container, index, [
null,
null,
null
]), path = _f[0], left = _f[1], top_1 = _f[2], width = _f[3], height = _f[4];
position = backgroundImage.position.length === 0 ? [FIFTY_PERCENT] : backgroundImage.position;
x = getAbsoluteValue(position[0], width);
y = getAbsoluteValue(position[position.length - 1], height);
_g = calculateRadius(backgroundImage, x, y, width, height), rx = _g[0], ry = _g[1];
if (rx > 0 && ry > 0) {
radialGradient_1 = this_1.ctx.createRadialGradient(left + x, top_1 + y, 0, left + x, top_1 + y, rx);
processColorStops(backgroundImage.stops, rx * 2).forEach(function (colorStop) {
return radialGradient_1.addColorStop(colorStop.stop, asString(colorStop.color));
});
this_1.path(path);
this_1.ctx.fillStyle = radialGradient_1;
if (rx !== ry) {
midX = container.bounds.left + 0.5 * container.bounds.width;
midY = container.bounds.top + 0.5 * container.bounds.height;
f = ry / rx;
invF = 1 / f;
this_1.ctx.save();
this_1.ctx.translate(midX, midY);
this_1.ctx.transform(1, 0, 0, f, 0, 0);
this_1.ctx.translate(-midX, -midY);
this_1.ctx.fillRect(left, invF * (top_1 - midY) + midY, width, height * invF);
this_1.ctx.restore();
}
else {
this_1.ctx.fill();
}
}
}
_h.label = 6;
case 6:
index--;
return [2 /*return*/];
}
});
};
this_1 = this;
_i = 0, _a = container.styles.backgroundImage.slice(0).reverse();
_b.label = 1;
case 1:
if (!(_i < _a.length)) return [3 /*break*/, 4];
backgroundImage = _a[_i];
return [5 /*yield**/, _loop_1(backgroundImage)];
case 2:
_b.sent();
_b.label = 3;
case 3:
_i++;
return [3 /*break*/, 1];
case 4: return [2 /*return*/];
}
});
});
};
CanvasRenderer.prototype.renderSolidBorder = function (color, side, curvePoints) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
this.path(parsePathForBorder(curvePoints, side));
this.ctx.fillStyle = asString(color);
this.ctx.fill();
return [2 /*return*/];
});
});
};
CanvasRenderer.prototype.renderDoubleBorder = function (color, width, side, curvePoints) {
return __awaiter(this, void 0, void 0, function () {
var outerPaths, innerPaths;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(width < 3)) return [3 /*break*/, 2];
return [4 /*yield*/, this.renderSolidBorder(color, side, curvePoints)];
case 1:
_a.sent();
return [2 /*return*/];
case 2:
outerPaths = parsePathForBorderDoubleOuter(curvePoints, side);
this.path(outerPaths);
this.ctx.fillStyle = asString(color);
this.ctx.fill();
innerPaths = parsePathForBorderDoubleInner(curvePoints, side);
this.path(innerPaths);
this.ctx.fill();
return [2 /*return*/];
}
});
});
};
CanvasRenderer.prototype.renderNodeBackgroundAndBorders = function (paint) {
return __awaiter(this, void 0, void 0, function () {
var styles, hasBackground, borders, backgroundPaintingArea, side, _i, borders_1, border;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this.applyEffects(paint.getEffects(2 /* BACKGROUND_BORDERS */));
styles = paint.container.styles;
hasBackground = !isTransparent(styles.backgroundColor) || styles.backgroundImage.length;
borders = [
{ style: styles.borderTopStyle, color: styles.borderTopColor, width: styles.borderTopWidth },
{ style: styles.borderRightStyle, color: styles.borderRightColor, width: styles.borderRightWidth },
{ style: styles.borderBottomStyle, color: styles.borderBottomColor, width: styles.borderBottomWidth },
{ style: styles.borderLeftStyle, color: styles.borderLeftColor, width: styles.borderLeftWidth }
];
backgroundPaintingArea = calculateBackgroundCurvedPaintingArea(getBackgroundValueForIndex(styles.backgroundClip, 0), paint.curves);
if (!(hasBackground || styles.boxShadow.length)) return [3 /*break*/, 2];
this.ctx.save();
this.path(backgroundPaintingArea);
this.ctx.clip();
if (!isTransparent(styles.backgroundColor)) {
this.ctx.fillStyle = asString(styles.backgroundColor);
this.ctx.fill();
}
return [4 /*yield*/, this.renderBackgroundImage(paint.container)];
case 1:
_a.sent();
this.ctx.restore();
styles.boxShadow
.slice(0)
.reverse()
.forEach(function (shadow) {
_this.ctx.save();
var borderBoxArea = calculateBorderBoxPath(paint.curves);
var maskOffset = shadow.inset ? 0 : MASK_OFFSET;
var shadowPaintingArea = transformPath(borderBoxArea, -maskOffset + (shadow.inset ? 1 : -1) * shadow.spread.number, (shadow.inset ? 1 : -1) * shadow.spread.number, shadow.spread.number * (shadow.inset ? -2 : 2), shadow.spread.number * (shadow.inset ? -2 : 2));
if (shadow.inset) {
_this.path(borderBoxArea);
_this.ctx.clip();
_this.mask(shadowPaintingArea);
}
else {
_this.mask(borderBoxArea);
_this.ctx.clip();
_this.path(shadowPaintingArea);
}
_this.ctx.shadowOffsetX = shadow.offsetX.number + maskOffset;
_this.ctx.shadowOffsetY = shadow.offsetY.number;
_this.ctx.shadowColor = asString(shadow.color);
_this.ctx.shadowBlur = shadow.blur.number;
_this.ctx.fillStyle = shadow.inset ? asString(shadow.color) : 'rgba(0,0,0,1)';
_this.ctx.fill();
_this.ctx.restore();
});
_a.label = 2;
case 2:
side = 0;
_i = 0, borders_1 = borders;
_a.label = 3;
case 3:
if (!(_i < borders_1.length)) return [3 /*break*/, 13];
border = borders_1[_i];
if (!(border.style !== 0 /* NONE */ && !isTransparent(border.color) && border.width > 0)) return [3 /*break*/, 11];
if (!(border.style === 2 /* DASHED */)) return [3 /*break*/, 5];
return [4 /*yield*/, this.renderDashedDottedBorder(border.color, border.width, side, paint.curves, 2 /* DASHED */)];
case 4:
_a.sent();
return [3 /*break*/, 11];
case 5:
if (!(border.style === 3 /* DOTTED */)) return [3 /*break*/, 7];
return [4 /*yield*/, this.renderDashedDottedBorder(border.color, border.width, side, paint.curves, 3 /* DOTTED */)];
case 6:
_a.sent();
return [3 /*break*/, 11];
case 7:
if (!(border.style === 4 /* DOUBLE */)) return [3 /*break*/, 9];
return [4 /*yield*/, this.renderDoubleBorder(border.color, border.width, side, paint.curves)];
case 8:
_a.sent();
return [3 /*break*/, 11];
case 9: return [4 /*yield*/, this.renderSolidBorder(border.color, side, paint.curves)];
case 10:
_a.sent();
_a.label = 11;
case 11:
side++;
_a.label = 12;
case 12:
_i++;
return [3 /*break*/, 3];
case 13: return [2 /*return*/];
}
});
});
};
CanvasRenderer.prototype.renderDashedDottedBorder = function (color, width, side, curvePoints, style) {
return __awaiter(this, void 0, void 0, function () {
var strokePaths, boxPaths, startX, startY, endX, endY, length, dashLength, spaceLength, useLineDash, multiplier, numberOfDashes, minSpace, maxSpace, path1, path2, path1, path2;
return __generator(this, function (_a) {
this.ctx.save();
strokePaths = parsePathForBorderStroke(curvePoints, side);
boxPaths = parsePathForBorder(curvePoints, side);
if (style === 2 /* DASHED */) {
this.path(boxPaths);
this.ctx.clip();
}
if (isBezierCurve(boxPaths[0])) {
startX = boxPaths[0].start.x;
startY = boxPaths[0].start.y;
}
else {
startX = boxPaths[0].x;
startY = boxPaths[0].y;
}
if (isBezierCurve(boxPaths[1])) {
endX = boxPaths[1].end.x;
endY = boxPaths[1].end.y;
}
else {
endX = boxPaths[1].x;
endY = boxPaths[1].y;
}
if (side === 0 || side === 2) {
length = Math.abs(startX - endX);
}
else {
length = Math.abs(startY - endY);
}
this.ctx.beginPath();
if (style === 3 /* DOTTED */) {
this.formatPath(strokePaths);
}
else {
this.formatPath(boxPaths.slice(0, 2));
}
dashLength = width < 3 ? width * 3 : width * 2;
spaceLength = width < 3 ? width * 2 : width;
if (style === 3 /* DOTTED */) {
dashLength = width;
spaceLength = width;
}
useLineDash = true;
if (length <= dashLength * 2) {
useLineDash = false;
}
else if (length <= dashLength * 2 + spaceLength) {
multiplier = length / (2 * dashLength + spaceLength);
dashLength *= multiplier;
spaceLength *= multiplier;
}
else {
numberOfDashes = Math.floor((length + spaceLength) / (dashLength + spaceLength));
minSpace = (length - numberOfDashes * dashLength) / (numberOfDashes - 1);
maxSpace = (length - (numberOfDashes + 1) * dashLength) / numberOfDashes;
spaceLength =
maxSpace <= 0 || Math.abs(spaceLength - minSpace) < Math.abs(spaceLength - maxSpace)
? minSpace
: maxSpace;
}
if (useLineDash) {
if (style === 3 /* DOTTED */) {
this.ctx.setLineDash([0, dashLength + spaceLength]);
}
else {
this.ctx.setLineDash([dashLength, spaceLength]);
}
}
if (style === 3 /* DOTTED */) {
this.ctx.lineCap = 'round';
this.ctx.lineWidth = width;
}
else {
this.ctx.lineWidth = width * 2 + 1.1;
}
this.ctx.strokeStyle = asString(color);
this.ctx.stroke();
this.ctx.setLineDash([]);
// dashed round edge gap
if (style === 2 /* DASHED */) {
if (isBezierCurve(boxPaths[0])) {
path1 = boxPaths[3];
path2 = boxPaths[0];
this.ctx.beginPath();
this.formatPath([new Vector(path1.end.x, path1.end.y), new Vector(path2.start.x, path2.start.y)]);
this.ctx.stroke();
}
if (isBezierCurve(boxPaths[1])) {
path1 = boxPaths[1];
path2 = boxPaths[2];
this.ctx.beginPath();
this.formatPath([new Vector(path1.end.x, path1.end.y), new Vector(path2.start.x, path2.start.y)]);
this.ctx.stroke();
}
}
this.ctx.restore();
return [2 /*return*/];
});
});
};
CanvasRenderer.prototype.render = function (element) {
return __awaiter(this, void 0, void 0, function () {
var stack;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this.options.backgroundColor) {
this.ctx.fillStyle = asString(this.options.backgroundColor);
this.ctx.fillRect(this.options.x, this.options.y, this.options.width, this.options.height);
}
stack = parseStackingContexts(element);
return [4 /*yield*/, this.renderStack(stack)];
case 1:
_a.sent();
this.applyEffects([]);
return [2 /*return*/, this.canvas];
}
});
});
};
return CanvasRenderer;
}(Renderer));
var isTextInputElement = function (container) {
if (container instanceof TextareaElementContainer) {
return true;
}
else if (container instanceof SelectElementContainer) {
return true;
}
else if (container instanceof InputElementContainer && container.type !== RADIO && container.type !== CHECKBOX) {
return true;
}
return false;
};
var calculateBackgroundCurvedPaintingArea = function (clip, curves) {
switch (clip) {
case 0 /* BORDER_BOX */:
return calculateBorderBoxPath(curves);
case 2 /* CONTENT_BOX */:
return calculateContentBoxPath(curves);
case 1 /* PADDING_BOX */:
default:
return calculatePaddingBoxPath(curves);
}
};
var canvasTextAlign = function (textAlign) {
switch (textAlign) {
case 1 /* CENTER */:
return 'center';
case 2 /* RIGHT */:
return 'right';
case 0 /* LEFT */:
default:
return 'left';
}
};
// see https://github.com/niklasvh/html2canvas/pull/2645
var iOSBrokenFonts = ['-apple-system', 'system-ui'];
var fixIOSSystemFonts = function (fontFamilies) {
return /iPhone OS 15_(0|1)/.test(window.navigator.userAgent)
? fontFamilies.filter(function (fontFamily) { return iOSBrokenFonts.indexOf(fontFamily) === -1; })
: fontFamilies;
};
var ForeignObjectRenderer = /** @class */ (function (_super) {
__extends(ForeignObjectRenderer, _super);
function ForeignObjectRenderer(context, options) {
var _this = _super.call(this, context, options) || this;
_this.canvas = options.canvas ? options.canvas : document.createElement('canvas');
_this.ctx = _this.canvas.getContext('2d');
_this.options = options;
_this.canvas.width = Math.floor(options.width * options.scale);
_this.canvas.height = Math.floor(options.height * options.scale);
_this.canvas.style.width = options.width + "px";
_this.canvas.style.height = options.height + "px";
_this.ctx.scale(_this.options.scale, _this.options.scale);
_this.ctx.translate(-options.x, -options.y);
_this.context.logger.debug("EXPERIMENTAL ForeignObject renderer initialized (" + options.width + "x" + options.height + " at " + options.x + "," + options.y + ") with scale " + options.scale);
return _this;
}
ForeignObjectRenderer.prototype.render = function (element) {
return __awaiter(this, void 0, void 0, function () {
var svg, img;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
svg = createForeignObjectSVG(this.options.width * this.options.scale, this.options.height * this.options.scale, this.options.scale, this.options.scale, element);
return [4 /*yield*/, loadSerializedSVG(svg)];
case 1:
img = _a.sent();
if (this.options.backgroundColor) {
this.ctx.fillStyle = asString(this.options.backgroundColor);
this.ctx.fillRect(0, 0, this.options.width * this.options.scale, this.options.height * this.options.scale);
}
this.ctx.drawImage(img, -this.options.x * this.options.scale, -this.options.y * this.options.scale);
return [2 /*return*/, this.canvas];
}
});
});
};
return ForeignObjectRenderer;
}(Renderer));
var loadSerializedSVG = function (svg) {
return new Promise(function (resolve, reject) {
var img = new Image();
img.onload = function () {
resolve(img);
};
img.onerror = reject;
img.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(new XMLSerializer().serializeToString(svg));
});
};
var Logger = /** @class */ (function () {
function Logger(_a) {
var id = _a.id, enabled = _a.enabled;
this.id = id;
this.enabled = enabled;
this.start = Date.now();
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Logger.prototype.debug = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (this.enabled) {
// eslint-disable-next-line no-console
if (typeof window !== 'undefined' && window.console && typeof console.debug === 'function') {
// eslint-disable-next-line no-console
console.debug.apply(console, __spreadArray([this.id, this.getTime() + "ms"], args));
}
else {
this.info.apply(this, args);
}
}
};
Logger.prototype.getTime = function () {
return Date.now() - this.start;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Logger.prototype.info = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (this.enabled) {
// eslint-disable-next-line no-console
if (typeof window !== 'undefined' && window.console && typeof console.info === 'function') {
// eslint-disable-next-line no-console
console.info.apply(console, __spreadArray([this.id, this.getTime() + "ms"], args));
}
}
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Logger.prototype.warn = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (this.enabled) {
// eslint-disable-next-line no-console
if (typeof window !== 'undefined' && window.console && typeof console.warn === 'function') {
// eslint-disable-next-line no-console
console.warn.apply(console, __spreadArray([this.id, this.getTime() + "ms"], args));
}
else {
this.info.apply(this, args);
}
}
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Logger.prototype.error = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (this.enabled) {
// eslint-disable-next-line no-console
if (typeof window !== 'undefined' && window.console && typeof console.error === 'function') {
// eslint-disable-next-line no-console
console.error.apply(console, __spreadArray([this.id, this.getTime() + "ms"], args));
}
else {
this.info.apply(this, args);
}
}
};
Logger.instances = {};
return Logger;
}());
var Context = /** @class */ (function () {
function Context(options, windowBounds) {
var _a;
this.windowBounds = windowBounds;
this.instanceName = "#" + Context.instanceCount++;
this.logger = new Logger({ id: this.instanceName, enabled: options.logging });
this.cache = (_a = options.cache) !== null && _a !== void 0 ? _a : new Cache(this, options);
}
Context.instanceCount = 1;
return Context;
}());
var html2canvas = function (element, options) {
if (options === void 0) { options = {}; }
return renderElement(element, options);
};
if (typeof window !== 'undefined') {
CacheStorage.setContext(window);
}
var renderElement = function (element, opts) { return __awaiter(void 0, void 0, void 0, function () {
var ownerDocument, defaultView, resourceOptions, contextOptions, windowOptions, windowBounds, context, foreignObjectRendering, cloneOptions, documentCloner, clonedElement, container, _a, width, height, left, top, backgroundColor, renderOptions, canvas, renderer, root, renderer;
var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
return __generator(this, function (_u) {
switch (_u.label) {
case 0:
if (!element || typeof element !== 'object') {
return [2 /*return*/, Promise.reject('Invalid element provided as first argument')];
}
ownerDocument = element.ownerDocument;
if (!ownerDocument) {
throw new Error("Element is not attached to a Document");
}
defaultView = ownerDocument.defaultView;
if (!defaultView) {
throw new Error("Document is not attached to a Window");
}
resourceOptions = {
allowTaint: (_b = opts.allowTaint) !== null && _b !== void 0 ? _b : false,
imageTimeout: (_c = opts.imageTimeout) !== null && _c !== void 0 ? _c : 15000,
proxy: opts.proxy,
useCORS: (_d = opts.useCORS) !== null && _d !== void 0 ? _d : false
};
contextOptions = __assign({ logging: (_e = opts.logging) !== null && _e !== void 0 ? _e : true, cache: opts.cache }, resourceOptions);
windowOptions = {
windowWidth: (_f = opts.windowWidth) !== null && _f !== void 0 ? _f : defaultView.innerWidth,
windowHeight: (_g = opts.windowHeight) !== null && _g !== void 0 ? _g : defaultView.innerHeight,
scrollX: (_h = opts.scrollX) !== null && _h !== void 0 ? _h : defaultView.pageXOffset,
scrollY: (_j = opts.scrollY) !== null && _j !== void 0 ? _j : defaultView.pageYOffset
};
windowBounds = new Bounds(windowOptions.scrollX, windowOptions.scrollY, windowOptions.windowWidth, windowOptions.windowHeight);
context = new Context(contextOptions, windowBounds);
foreignObjectRendering = (_k = opts.foreignObjectRendering) !== null && _k !== void 0 ? _k : false;
cloneOptions = {
allowTaint: (_l = opts.allowTaint) !== null && _l !== void 0 ? _l : false,
onclone: opts.onclone,
ignoreElements: opts.ignoreElements,
inlineImages: foreignObjectRendering,
copyStyles: foreignObjectRendering
};
context.logger.debug("Starting document clone with size " + windowBounds.width + "x" + windowBounds.height + " scrolled to " + -windowBounds.left + "," + -windowBounds.top);
documentCloner = new DocumentCloner(context, element, cloneOptions);
clonedElement = documentCloner.clonedReferenceElement;
if (!clonedElement) {
return [2 /*return*/, Promise.reject("Unable to find element in cloned iframe")];
}
return [4 /*yield*/, documentCloner.toIFrame(ownerDocument, windowBounds)];
case 1:
container = _u.sent();
_a = isBodyElement(clonedElement) || isHTMLElement(clonedElement)
? parseDocumentSize(clonedElement.ownerDocument)
: parseBounds(context, clonedElement), width = _a.width, height = _a.height, left = _a.left, top = _a.top;
backgroundColor = parseBackgroundColor(context, clonedElement, opts.backgroundColor);
renderOptions = {
canvas: opts.canvas,
backgroundColor: backgroundColor,
scale: (_o = (_m = opts.scale) !== null && _m !== void 0 ? _m : defaultView.devicePixelRatio) !== null && _o !== void 0 ? _o : 1,
x: ((_p = opts.x) !== null && _p !== void 0 ? _p : 0) + left,
y: ((_q = opts.y) !== null && _q !== void 0 ? _q : 0) + top,
width: (_r = opts.width) !== null && _r !== void 0 ? _r : Math.ceil(width),
height: (_s = opts.height) !== null && _s !== void 0 ? _s : Math.ceil(height)
};
if (!foreignObjectRendering) return [3 /*break*/, 3];
context.logger.debug("Document cloned, using foreign object rendering");
renderer = new ForeignObjectRenderer(context, renderOptions);
return [4 /*yield*/, renderer.render(clonedElement)];
case 2:
canvas = _u.sent();
return [3 /*break*/, 5];
case 3:
context.logger.debug("Document cloned, element located at " + left + "," + top + " with size " + width + "x" + height + " using computed rendering");
context.logger.debug("Starting DOM parsing");
root = parseTree(context, clonedElement);
if (backgroundColor === root.styles.backgroundColor) {
root.styles.backgroundColor = COLORS.TRANSPARENT;
}
context.logger.debug("Starting renderer for element at " + renderOptions.x + "," + renderOptions.y + " with size " + renderOptions.width + "x" + renderOptions.height);
renderer = new CanvasRenderer(context, renderOptions);
return [4 /*yield*/, renderer.render(root)];
case 4:
canvas = _u.sent();
_u.label = 5;
case 5:
if ((_t = opts.removeContainer) !== null && _t !== void 0 ? _t : true) {
if (!DocumentCloner.destroy(container)) {
context.logger.error("Cannot detach cloned iframe as it is not in the DOM anymore");
}
}
context.logger.debug("Finished rendering");
return [2 /*return*/, canvas];
}
});
}); };
var parseBackgroundColor = function (context, element, backgroundColorOverride) {
var ownerDocument = element.ownerDocument;
// http://www.w3.org/TR/css3-background/#special-backgrounds
var documentBackgroundColor = ownerDocument.documentElement
? parseColor(context, getComputedStyle(ownerDocument.documentElement).backgroundColor)
: COLORS.TRANSPARENT;
var bodyBackgroundColor = ownerDocument.body
? parseColor(context, getComputedStyle(ownerDocument.body).backgroundColor)
: COLORS.TRANSPARENT;
var defaultBackgroundColor = typeof backgroundColorOverride === 'string'
? parseColor(context, backgroundColorOverride)
: backgroundColorOverride === null
? COLORS.TRANSPARENT
: 0xffffffff;
return element === ownerDocument.documentElement
? isTransparent(documentBackgroundColor)
? isTransparent(bodyBackgroundColor)
? defaultBackgroundColor
: bodyBackgroundColor
: documentBackgroundColor
: defaultBackgroundColor;
};
return html2canvas;
})));
});
/**
* 先把body上的内容隐藏起来
* @returns {Array} displayList 记录body子元素原始的显隐信息
*/
var hideBodyChildren = function hideBodyChildren() {
var _context;
var displayList = [];
/** @type {HTMLElement[]}*/
forEach$3(_context = from_1$2(document.body.children)).call(_context, function (dom, index) {
displayList[index] = dom.style.display;
dom.style.display = 'none';
});
return displayList;
};
/**
* 复原body上被隐藏的内容
* @param {Array} displayList 记录body子元素原始的显隐信息
*/
var undoHideBodyChildren = function undoHideBodyChildren() {
var _context2;
var displayList = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
/** @type {HTMLElement[]}*/
forEach$3(_context2 = from_1$2(document.body.children)).call(_context2, function (dom, index) {
if (typeof displayList[index] !== 'undefined') {
dom.style.display = displayList[index];
}
});
};
/**
* 将预览区域的内容放在body上准备后续导出操作
* @param {HTMLElement} previeweDom 预览区域的dom
* @param {function} cb 准备好导出后开始执行导出操作
*/
var getReadyToExport = function getReadyToExport(previeweDom, cb) {
var cherryPreviewer =
/** @type {HTMLElement}*/
previeweDom.cloneNode(true); // 强制去掉预览区的隐藏class
cherryPreviewer.className = cherryPreviewer.className.replace('cherry-previewer--hidden', '');
cherryPreviewer.style.width = '100%';
var mmls = cherryPreviewer.querySelectorAll('mjx-assistive-mml'); // a fix for html2canvas
forEach$3(mmls).call(mmls, function (e) {
if (e instanceof HTMLElement) e.style.setProperty('visibility', 'hidden');
});
var cherryWrapper = document.createElement('div');
cherryWrapper.appendChild(cherryPreviewer);
var displayList = hideBodyChildren();
document.body.appendChild(cherryWrapper);
var bodyOverflow = document.body.style.overflow;
document.body.style.overflow = 'visible';
cb(cherryPreviewer, function () {
cherryWrapper.remove();
undoHideBodyChildren(displayList);
document.body.style.overflow = bodyOverflow;
});
};
/**
* 下载文件
* @param {String} downloadUrl 图片本地地址
* @param {String} fileName 导出图片文件名
*/
var fileDownload = function fileDownload(downloadUrl, fileName) {
var aLink = document.createElement('a');
aLink.style.display = 'none';
aLink.href = downloadUrl;
aLink.download = "".concat(fileName, ".png");
document.body.appendChild(aLink);
aLink.click();
document.body.removeChild(aLink);
};
/**
* 利用window.print导出成PDF
* @param {HTMLElement} previeweDom 预览区域的dom
* @param {String} fileName 导出PDF文件名
*/
function exportPDF(previeweDom, fileName) {
var oldTitle = document.title;
document.title = fileName;
getReadyToExport(previeweDom, function (
/** @type {HTMLElement}*/
cherryPreviewer,
/** @type {function}*/
thenFinish) {
window.print();
thenFinish();
document.title = oldTitle;
});
}
/**
* 利用canvas将html内容导出成图片
* @param {HTMLElement} previeweDom 预览区域的dom
* @param {String} fileName 导出图片文件名
*/
function exportScreenShot(previeweDom, fileName) {
getReadyToExport(previeweDom, function (
/** @type {HTMLElement}*/
cherryPreviewer,
/** @type {function}*/
thenFinish) {
window.scrollTo(0, 0);
html2canvas(cherryPreviewer, {
allowTaint: true,
height: cherryPreviewer.clientHeight,
width: cherryPreviewer.clientWidth,
scrollY: 0,
scrollX: 0
}).then(function (canvas) {
var imgData = canvas.toDataURL('image/jpeg');
fileDownload(imgData, fileName);
thenFinish();
});
});
}
/**
* 导出 markdown 文件
* @param {String} markdownText markdown文本
* @param {String} fileName 导出markdown文件名
*/
function exportMarkdownFile(markdownText, fileName) {
var blob = new Blob([markdownText], {
type: 'text/markdown;charset=utf-8'
});
var aLink = document.createElement('a');
aLink.style.display = 'none';
aLink.href = url$2.createObjectURL(blob);
aLink.download = "".concat(fileName, ".md");
document.body.appendChild(aLink);
aLink.click();
document.body.removeChild(aLink);
}
/**
* 导出预览区 HTML 文件
* @param {String} HTMLText HTML文本
* @param {String} fileName 导出HTML文件名
*/
function exportHTMLFile(HTMLText, fileName) {
var blob = new Blob([HTMLText], {
type: 'text/markdown;charset=utf-8'
});
var aLink = document.createElement('a');
aLink.style.display = 'none';
aLink.href = url$2.createObjectURL(blob);
aLink.download = "".concat(fileName, ".html");
document.body.appendChild(aLink);
aLink.click();
document.body.removeChild(aLink);
}
var $propertyIsEnumerable$2 = objectPropertyIsEnumerable.f;
var propertyIsEnumerable$1 = functionUncurryThis($propertyIsEnumerable$2);
var push$9 = functionUncurryThis([].push);
// `Object.{ entries, values }` methods implementation
var createMethod$5 = function (TO_ENTRIES) {
return function (it) {
var O = toIndexedObject(it);
var keys = objectKeys(O);
var length = keys.length;
var i = 0;
var result = [];
var key;
while (length > i) {
key = keys[i++];
if (!descriptors || propertyIsEnumerable$1(O, key)) {
push$9(result, TO_ENTRIES ? [key, O[key]] : O[key]);
}
}
return result;
};
};
var objectToArray = {
// `Object.entries` method
// https://tc39.es/ecma262/#sec-object.entries
entries: createMethod$5(true),
// `Object.values` method
// https://tc39.es/ecma262/#sec-object.values
values: createMethod$5(false)
};
var $values = objectToArray.values;
// `Object.values` method
// https://tc39.es/ecma262/#sec-object.values
_export({ target: 'Object', stat: true }, {
values: function values(O) {
return $values(O);
}
});
var values$1 = path.Object.values;
var values$2 = values$1;
var values$3 = values$2;
var $entries = objectToArray.entries;
// `Object.entries` method
// https://tc39.es/ecma262/#sec-object.entries
_export({ target: 'Object', stat: true }, {
entries: function entries(O) {
return $entries(O);
}
});
var entries = path.Object.entries;
var entries$1 = entries;
var entries$2 = entries$1;
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* 用于在图片四周画出调整图片尺寸的边框
*/
var imgSizeHander = {
mouseResize: {},
getImgPosition: function getImgPosition() {
var position = this.img.getBoundingClientRect();
var editorPosition = this.previewerDom.parentNode.getBoundingClientRect();
var padding = _parseFloat$2(this.img.style.padding) || 0;
return {
bottom: position.bottom - editorPosition.bottom,
top: position.top - editorPosition.top + padding * 1.5,
height: position.height,
width: position.width,
right: position.right - editorPosition.right,
left: position.left - editorPosition.left + padding * 1.5,
x: position.x - editorPosition.x,
y: position.y - editorPosition.y
};
},
initBubbleButtons: function initBubbleButtons() {
var position = this.getImgPosition();
return {
points: {
arr: ['leftTop', 'leftBottom', 'rightTop', 'rightBottom', 'leftMiddle', 'middleBottom', 'middleTop', 'rightMiddle'],
arrInfo: {
leftTop: {
name: '20',
left: 0,
top: 0
},
leftBottom: {
name: '00',
left: 0,
top: 0
},
rightTop: {
name: '22',
left: 0,
top: 0
},
rightBottom: {
name: '02',
left: 0,
top: 0
},
leftMiddle: {
name: '10',
left: 0,
top: 0
},
middleBottom: {
name: '01',
left: 0,
top: 0
},
middleTop: {
name: '21',
left: 0,
top: 0
},
rightMiddle: {
name: '12',
left: 0,
top: 0
}
}
},
imgSrc: this.img.src,
style: {
width: this.img.width,
height: this.img.height,
left: position.left - 1,
top: position.top - 1,
marginTop: 0,
marginLeft: 0
},
scrollTop: this.previewerDom.scrollTop,
position: position
};
},
showBubble: function showBubble(img, container, previewerDom) {
if (this.$isResizing()) {
return;
}
this.img = img;
this.previewerDom = previewerDom;
this.container = container;
this.buts = this.initBubbleButtons();
this.drawBubbleButs();
},
emit: function emit(type) {
var event = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
switch (type) {
case 'mousedown':
return this.resizeBegin(event);
case 'mouseup':
return this.resizeStop(event);
case 'mousemove':
return this.resizeWorking(event);
case 'scroll':
return this.dealScroll(event);
case 'remove':
return this.remove();
case 'previewUpdate':
return this.previewUpdate(event);
}
},
previewUpdate: function previewUpdate(callback) {
if (this.$isResizing()) {
return;
}
this.remove();
callback();
},
drawBubbleButs: function drawBubbleButs() {
var _context,
_this = this;
if (this.butsLayout) {
return this.updateBubbleButs();
}
this.butsLayout = this.container;
this.butsImg = document.createElement('div');
this.butsImg.className = 'cherry-previewer-img-size-hander__background';
this.butsImg.style.backgroundImage = "url(".concat(this.buts.imgSrc, ")");
this.butsLayout.appendChild(this.butsImg);
this.butsPoints = {};
forEach$3(_context = keys$3(this.buts.points.arr)).call(_context, function (index) {
var name = _this.buts.points.arr[index];
var tmp = document.createElement('div');
tmp.className = ['cherry-previewer-img-size-hander__points', "cherry-previewer-img-size-hander__points-".concat(name)].join(' ');
tmp.dataset.name = name;
_this.butsLayout.appendChild(tmp);
_this.butsPoints["pints-".concat(name)] = tmp;
});
return this.updateBubbleButs();
},
remove: function remove() {
this.butsLayout = false;
},
updateBubbleButs: function updateBubbleButs() {
var _context2,
_this2 = this,
_context3;
this.$updatePointsInfo();
forEach$3(_context2 = keys$3(this.buts.style)).call(_context2, function (name) {
_this2.butsLayout.style[name] = "".concat(_this2.buts.style[name], "px");
});
forEach$3(_context3 = keys$3(this.buts.points.arr)).call(_context3, function (index) {
var name = _this2.buts.points.arr[index];
_this2.butsPoints["pints-".concat(name)].style.top = "".concat(_this2.buts.points.arrInfo[name].top, "px");
_this2.butsPoints["pints-".concat(name)].style.left = "".concat(_this2.buts.points.arrInfo[name].left, "px");
});
},
$updatePointsInfo: function $updatePointsInfo() {
var _context4,
_this3 = this;
var pointLeft = this.buts.style.width;
var pointTop = this.buts.style.height;
var newPointsInfo = this.$getPointsInfo(pointLeft, pointTop);
forEach$3(_context4 = keys$3(this.buts.points.arr)).call(_context4, function (index) {
var name = _this3.buts.points.arr[index];
if (_this3.buts.points.arrInfo[name].left !== newPointsInfo[name].left) {
_this3.buts.points.arrInfo[name].left = newPointsInfo[name].left;
}
if (_this3.buts.points.arrInfo[name].top !== newPointsInfo[name].top) {
_this3.buts.points.arrInfo[name].top = newPointsInfo[name].top;
}
});
},
$getPointsInfo: function $getPointsInfo(left, top) {
return {
leftTop: {
left: 0,
top: 0
},
leftBottom: {
left: 0,
top: top
},
rightTop: {
left: left,
top: 0
},
rightBottom: {
left: left,
top: top
},
leftMiddle: {
left: 0,
top: top / 2
},
middleBottom: {
left: left / 2,
top: top
},
middleTop: {
left: left / 2,
top: 0
},
rightMiddle: {
left: left,
top: top / 2
}
};
},
$isResizing: function $isResizing() {
return this.mouseResize.resize;
},
dealScroll: function dealScroll(event) {
var position = this.getImgPosition();
if (this.butsLayout.style.marginTop !== position.top - this.buts.position.top) {
this.butsLayout.style.marginTop = "".concat(position.top - this.buts.position.top, "px");
this.buts.style.marginTop = "".concat(position.top - this.buts.position.top, "px");
}
if (this.butsLayout.style.marginLeft !== position.left - this.buts.position.left) {
this.butsLayout.style.marginLeft = "".concat(position.left - this.buts.position.left, "px");
this.buts.style.marginLeft = "".concat(position.left - this.buts.position.left, "px");
}
},
initMouse: function initMouse() {
return {
left: 0,
top: 0,
resize: false,
name: ''
};
},
resizeBegin: function resizeBegin(event) {
var point = event.target;
if (!point.classList.contains('cherry-previewer-img-size-hander__points')) {
return false;
}
this.mouseResize.left = event.clientX;
this.mouseResize.top = event.clientY;
this.mouseResize.resize = true;
this.mouseResize.name = point.getAttribute('data-name');
this.previewerDom.classList.add('doing-resize-img');
},
resizeStop: function resizeStop(event, buts, editor, menu) {
if (!this.$isResizing()) {
return false;
}
this.img.style.width = "".concat(this.buts.style.width, "px");
this.img.style.height = "".concat(this.buts.style.height, "px");
this.buts.style.marginTop = 0;
this.buts.style.marginLeft = 0;
this.updateBubbleButs();
this.mouseResize.resize = false;
this.previewerDom.classList.remove('doing-resize-img');
this.change();
},
resizeWorking: function resizeWorking(event, buts) {
if (!this.$isResizing()) {
return;
}
var changeX = event.clientX - this.mouseResize.left;
var changeY = event.clientY - this.mouseResize.top;
var change = {};
switch (this.mouseResize.name) {
case 'leftTop':
case 'leftBottom':
case 'leftMiddle':
change = this.$getChange(changeX, changeY, 'x');
this.buts.style.width = this.buts.position.width - change.changeX;
if (this.mouseResize.name !== 'leftMiddle') {
this.buts.style.height = this.buts.position.height - change.changeY;
}
break;
case 'rightTop':
case 'rightBottom':
case 'rightMiddle':
change = this.$getChange(changeX, changeY, 'x');
this.buts.style.width = this.buts.position.width + change.changeX;
if (this.mouseResize.name !== 'rightMiddle') {
this.buts.style.height = this.buts.position.height + change.changeY;
}
break;
case 'middleTop':
change = this.$getChange(changeX, changeY, 'y');
this.buts.style.height = this.buts.position.height - change.changeY;
break;
case 'middleBottom':
change = this.$getChange(changeX, changeY, 'y');
this.buts.style.height = this.buts.position.height + change.changeY;
break;
}
this.updateBubbleButs();
this.change();
},
change: function change() {
this.emitChange(this.img, {
width: this.buts.style.width,
height: this.buts.style.height
});
},
bindChange: function bindChange(func) {
this.emitChange = func;
},
/**
* 根据宽x或高y来进行等比例缩放
* @param {number} x 宽度
* @param {number} y 高度
* @param {string} type 类型,以宽/高为基准做等比例缩放
* @returns
*/
$getChange: function $getChange(x, y, type) {
var ret = {
changeX: 0,
changeY: 0
};
switch (type) {
case 'y':
ret.changeY = y;
ret.changeX = y * this.buts.position.width / this.buts.position.height;
break;
default:
ret.changeX = x;
ret.changeY = x * this.buts.position.height / this.buts.position.width;
break;
}
return ret;
}
};
var $every = arrayIteration.every;
var STRICT_METHOD$4 = arrayMethodIsStrict('every');
// `Array.prototype.every` method
// https://tc39.es/ecma262/#sec-array.prototype.every
_export({ target: 'Array', proto: true, forced: !STRICT_METHOD$4 }, {
every: function every(callbackfn /* , thisArg */) {
return $every(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
var every = entryVirtual('Array').every;
var ArrayPrototype$e = Array.prototype;
var every$1 = function (it) {
var own = it.every;
return it === ArrayPrototype$e || (objectIsPrototypeOf(ArrayPrototype$e, it) && own === ArrayPrototype$e.every) ? every : own;
};
var every$2 = every$1;
var every$3 = every$2;
var TypeError$o = global_1.TypeError;
// `FlattenIntoArray` abstract operation
// https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray
var flattenIntoArray = function (target, original, source, sourceLen, start, depth, mapper, thisArg) {
var targetIndex = start;
var sourceIndex = 0;
var mapFn = mapper ? functionBindContext(mapper, thisArg) : false;
var element, elementLen;
while (sourceIndex < sourceLen) {
if (sourceIndex in source) {
element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex];
if (depth > 0 && isArray(element)) {
elementLen = lengthOfArrayLike(element);
targetIndex = flattenIntoArray(target, original, element, elementLen, targetIndex, depth - 1) - 1;
} else {
if (targetIndex >= 0x1FFFFFFFFFFFFF) throw TypeError$o('Exceed the acceptable array length');
target[targetIndex] = element;
}
targetIndex++;
}
sourceIndex++;
}
return targetIndex;
};
var flattenIntoArray_1 = flattenIntoArray;
// `Array.prototype.flat` method
// https://tc39.es/ecma262/#sec-array.prototype.flat
_export({ target: 'Array', proto: true }, {
flat: function flat(/* depthArg = 1 */) {
var depthArg = arguments.length ? arguments[0] : undefined;
var O = toObject(this);
var sourceLen = lengthOfArrayLike(O);
var A = arraySpeciesCreate(O, 0);
A.length = flattenIntoArray_1(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toIntegerOrInfinity(depthArg));
return A;
}
});
var flat = entryVirtual('Array').flat;
var ArrayPrototype$f = Array.prototype;
var flat$1 = function (it) {
var own = it.flat;
return it === ArrayPrototype$f || (objectIsPrototypeOf(ArrayPrototype$f, it) && own === ArrayPrototype$f.flat) ? flat : own;
};
var flat$2 = flat$1;
var flat$3 = flat$2;
/**
* 用于在表格上出现编辑区,并提供拖拽行列的功能
*/
var TableHandler = /*#__PURE__*/function () {
/**
* 用来存放所有的数据
*/
function TableHandler(trigger, target, container, previewerDom, codeMirror) {
_classCallCheck(this, TableHandler);
_defineProperty(this, "tableEditor", {
info: {},
// 当前点击的预览区域table的相关信息
tableCodes: [],
// 编辑器内所有的表格语法
editorDom: {} // 编辑器容器
});
// 触发方式 click / hover
this.trigger = trigger;
this.target = target;
this.previewerDom = previewerDom;
this.container = container;
this.codeMirror = codeMirror;
this.$initReg();
this.$findTableInEditor();
}
_createClass(TableHandler, [{
key: "emit",
value: function emit(type) {
var event = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var callback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {};
switch (type) {
case 'keyup':
return this.trigger === 'click' && this.$onInputChange(event);
case 'remove':
return this.$remove();
case 'scroll':
return this.$refreshPosition();
case 'previewUpdate':
return this.$refreshPosition();
case 'mouseup':
return this.trigger === 'click' && this.$tryRemoveMe(event, callback);
}
}
}, {
key: "$tryRemoveMe",
value: function $tryRemoveMe(event, callback) {
if (!/textarea/i.test(event.target.tagName)) {
this.$remove();
callback();
}
}
/**
* 获取目标dom的位置信息和尺寸信息
*/
}, {
key: "$getPosition",
value: function $getPosition() {
var node = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.tableEditor.info.tdNode;
var position = node.getBoundingClientRect();
var editorPosition = this.previewerDom.parentNode.getBoundingClientRect();
return {
top: position.top - editorPosition.top,
height: position.height,
width: position.width,
left: position.left - editorPosition.left,
maxHeight: editorPosition.height
};
}
}, {
key: "setStyle",
value: function setStyle(element, property, value) {
var info = element.getBoundingClientRect();
if (info[property] !== value) {
element.style[property] = value;
}
}
/**
* TODO: 这里是分别对文本框、操作符号和选项设置偏移,应该作为一个整体来设置
*/
}, {
key: "$setInputOffset",
value: function $setInputOffset() {
var tdInfo = this.$getPosition();
var inputDiv = this.tableEditor.editorDom.inputDiv; // 设置文本框的偏移及大小
this.setStyle(inputDiv, 'width', "".concat(tdInfo.width, "px"));
this.setStyle(inputDiv, 'height', "".concat(tdInfo.height, "px"));
this.setStyle(inputDiv, 'top', "".concat(tdInfo.top, "px"));
this.setStyle(inputDiv, 'left', "".concat(tdInfo.left, "px")); // 根据是否超出边界来显示或者隐藏元素
var isWithinBounds = tdInfo.top >= 0 && tdInfo.top + tdInfo.height <= tdInfo.maxHeight;
this.setStyle(inputDiv, 'display', isWithinBounds ? '' : 'none');
}
/**
* 刷新操作符位置
*/
}, {
key: "$setSymbolOffset",
value: function $setSymbolOffset() {
var _context2,
_this = this;
var container = this.tableEditor.editorDom.symbolContainer;
var _this$tableEditor$inf = this.tableEditor.info,
tableNode = _this$tableEditor$inf.tableNode,
trNode = _this$tableEditor$inf.trNode,
isTHead = _this$tableEditor$inf.isTHead;
var tableInfo = this.$getPosition(tableNode);
var trInfo = this.$getPosition(trNode);
var tdInfo = this.$getPosition();
var previewerRect = this.previewerDom.getBoundingClientRect(); // 设置容器宽高
this.setStyle(this.container, 'width', "".concat(tableInfo.width, "px"));
this.setStyle(this.container, 'height', "".concat(tableInfo.height, "px"));
this.setStyle(this.container, 'top', "".concat(tableInfo.top, "px"));
this.setStyle(this.container, 'left', "".concat(tableInfo.left, "px")); // 判断是否在预览区内
var isWithinBounds = function isWithinBounds(symbol) {
var _context;
var symbolRect = symbol.getBoundingClientRect();
var boundMap = {
top: [previewerRect.top, previewerRect.top + previewerRect.height - symbolRect.height],
left: [previewerRect.left, previewerRect.left + previewerRect.width - symbolRect.width]
};
return every$3(_context = entries$2(boundMap)).call(_context, function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
key = _ref2[0],
_ref2$ = _slicedToArray(_ref2[1], 2),
min = _ref2$[0],
max = _ref2$[1];
return symbolRect[key] >= min && symbolRect[key] <= max;
});
}; // 设置操作符位置与控制显隐
forEach$3(_context2 = container.childNodes).call(_context2, function (node) {
var _context3;
var _node$dataset = node.dataset,
index = _node$dataset.index,
type = _node$dataset.type,
dir = _node$dataset.dir;
var propDict = {
Row: ['left', 'right'],
Col: ['top', 'bottom']
};
var offset = {
outer: 20,
radius: 7
};
_this.setStyle(node, propDict[dir][index], "-".concat(offset.outer, "px"));
_this.setStyle(node, 'display', '');
var refreshMap = {
LastRow: function LastRow() {
return _this.setStyle(node, 'top', "".concat(trInfo.top - tableInfo.top - offset.radius, "px"));
},
NextRow: function NextRow() {
return _this.setStyle(node, 'top', "".concat(trInfo.top - tableInfo.top + trInfo.height - offset.radius, "px"));
},
LastCol: function LastCol() {
return _this.setStyle(node, 'left', "".concat(tdInfo.left - tableInfo.left - offset.radius, "px"));
},
NextCol: function NextCol() {
return _this.setStyle(node, 'left', "".concat(tdInfo.left - tableInfo.left + tdInfo.width - offset.radius, "px"));
}
};
var oper = concat$5(_context3 = "".concat(type)).call(_context3, dir);
refreshMap[oper]();
_this.setStyle(node, 'display', isWithinBounds(node) ? '' : 'none');
if (isTHead && oper === 'LastRow') {
_this.setStyle(node, 'display', 'none');
}
});
}
/**
* 刷新定位
*/
}, {
key: "$refreshPosition",
value: function $refreshPosition() {
if (this.trigger === 'click') {
this.$setInputOffset();
return;
}
this.$setSymbolOffset();
}
}, {
key: "$remove",
value: function $remove() {
this.tableEditor = {
info: {},
tableCodes: [],
editorDom: {}
};
}
/**
* 收集编辑器中的表格语法并记录表格语法的开始的offset
*/
}, {
key: "$collectTableCode",
value: function $collectTableCode() {
var tableCodes = [];
this.codeMirror.getValue().replace(this.codeBlockReg, function (whole) {
// 先把代码块里的表格语法关键字干掉
return whole.replace(/\|/g, '.');
}).replace(this.tableReg, function (whole) {
var _ref3;
var match = whole.replace(/^\n*/, '');
var offsetBegin = (_ref3 = (arguments.length <= 1 ? 0 : arguments.length - 1) - 2 + 1, _ref3 < 1 || arguments.length <= _ref3 ? undefined : arguments[_ref3]) + whole.match(/^\n*/)[0].length;
tableCodes.push({
code: match,
offset: offsetBegin
});
});
this.tableEditor.tableCodes = tableCodes;
}
/**
* 获取预览区域被点击的table对象并记录table的顺位
*/
}, {
key: "$collectTableDom",
value: function $collectTableDom() {
var _context4, _context5, _context6;
var list = from_1$2(this.previewerDom.querySelectorAll('table.cherry-table'));
var tableNode = this.$getClosestNode(this.target, 'TABLE');
if (tableNode === false) {
return false;
}
var columns = filter$3(_context4 = from_1$2(this.target.parentElement.childNodes)).call(_context4, function (child) {
// 计算列数
return child.tagName.toLowerCase() === 'td';
}).length;
this.tableEditor.info = {
tableNode: tableNode,
tdNode: this.target,
trNode: this.target.parentElement,
tdIndex: indexOf$8(_context5 = from_1$2(this.target.parentElement.childNodes)).call(_context5, this.target),
trIndex: indexOf$8(_context6 = from_1$2(this.target.parentElement.parentElement.childNodes)).call(_context6, this.target.parentElement),
isTHead: this.target.parentElement.parentElement.tagName !== 'TBODY',
totalTables: list.length,
tableIndex: indexOf$8(list).call(list, tableNode),
tableText: tableNode.textContent.replace(/[\s]/g, ''),
columns: columns
};
}
/**
* 选中对应单元格、所在行、所在列的内容
* @param {Number} index
* @param {String} type 'td': 当前单元格, 'table': 当前表格
* @param {Boolean} select 是否选中编辑器中的代码
*/
}, {
key: "$setSelection",
value: function $setSelection(index) {
var _whole$slice$match$le, _whole$slice$match, _this$codeMirror;
var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'table';
var select = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var tableCode = this.tableEditor.tableCodes[index];
var whole = this.codeMirror.getValue();
var selectTdInfo = this.tableEditor.info;
var beginLine = (_whole$slice$match$le = (_whole$slice$match = slice$7(whole).call(whole, 0, tableCode.offset).match(/\n/g)) === null || _whole$slice$match === void 0 ? void 0 : _whole$slice$match.length) !== null && _whole$slice$match$le !== void 0 ? _whole$slice$match$le : 0;
var _this$$getTdOffset = this.$getTdOffset(tableCode.code, selectTdInfo.isTHead, selectTdInfo.trIndex, selectTdInfo.tdIndex),
preLine = _this$$getTdOffset.preLine,
preCh = _this$$getTdOffset.preCh,
plusCh = _this$$getTdOffset.plusCh,
currentTd = _this$$getTdOffset.currentTd;
if (type === 'table') {
var endLine = beginLine + tableCode.code.match(/\n/g).length;
var endCh = tableCode.code.match(/[^\n]+\n*$/)[0].length;
this.tableEditor.info.selection = [{
line: beginLine,
ch: 0
}, {
line: endLine,
ch: endCh
}];
} else {
this.tableEditor.info.selection = [{
line: beginLine + preLine,
ch: preCh
}, {
line: beginLine + preLine,
ch: preCh + plusCh
}];
}
select && (_this$codeMirror = this.codeMirror).setSelection.apply(_this$codeMirror, _toConsumableArray(this.tableEditor.info.selection));
this.tableEditor.info.code = currentTd;
}
/**
* 获取对应单元格的偏移量
* @param {String} tableCode
* @param {Boolean} isTHead
* @param {Number} trIndex
* @param {Number} tdIndex
*/
}, {
key: "$getTdOffset",
value: function $getTdOffset(tableCode, isTHead, trIndex, tdIndex) {
var codes = tableCode.split(/\n/);
var targetTr = isTHead ? 0 : trIndex + 2;
var tds = codes[targetTr].split(/\|/);
var needPlus1 = /^\s*$/.test(tds[0]);
var targetTd = needPlus1 ? tdIndex + 1 : tdIndex;
var current = tds[targetTd];
var pre = [];
for (var i = 0; i < targetTd; i++) {
pre.push(tds[i]);
}
return {
preLine: targetTr,
preCh: needPlus1 ? pre.join('|').length + 1 : pre.join('|').length,
plusCh: current.length,
currentTd: current
};
}
/**
* 在编辑器里找到对应的表格源码,并让编辑器选中
*/
}, {
key: "$findTableInEditor",
value: function $findTableInEditor() {
this.$collectTableDom();
this.$collectTableCode(); // 暂时不考虑代码块中包含表格、人为输入表格html语法、tapd特色表格语法的情况
// 也就是说,出现上述情况时,表格的所见即所得编辑功能失效
if (this.tableEditor.info.totalTables !== this.tableEditor.tableCodes.length) {
return false;
}
this.$setSelection(this.tableEditor.info.tableIndex, 'td', this.trigger === 'click');
}
}, {
key: "$initReg",
value: function $initReg() {
this.tableReg = this.tableReg ? this.tableReg : getTableRule(true);
this.codeBlockReg = this.codeBlockReg ? this.codeBlockReg : getCodeBlockRule().reg;
}
}, {
key: "showBubble",
value: function showBubble() {
if (this.trigger === 'click') {
this.$drawEditor();
return;
}
this.$drawSymbol();
}
/**
* 判断是否处于编辑状态
* @returns {boolean}
*/
}, {
key: "$isEditing",
value: function $isEditing() {
return this.tableEditor.editing;
}
/**
* 把表格上的input单行文本框和操作符号画出来
*/
}, {
key: "$drawEditor",
value: function $drawEditor() {
var dom = document.createElement('div');
dom.className = 'cherry-previewer-table-content-hander__input';
var input = document.createElement('textarea');
dom.appendChild(input);
this.tableEditor.editorDom.inputDiv = dom;
this.tableEditor.editorDom.inputDom = input;
this.$updateEditorPosition();
this.container.appendChild(this.tableEditor.editorDom.inputDiv);
this.tableEditor.editorDom.inputDom.value = this.tableEditor.info.code.replace(/<br>/g, '\n');
this.tableEditor.editorDom.inputDom.focus();
}
}, {
key: "$onInputChange",
value: function $onInputChange(e) {
if (e.target.tagName !== 'TEXTAREA') {
return;
}
this.codeMirror.replaceSelection(e.target.value.replace(/\n/g, '<br>'), 'around');
}
/**
* 更新编辑器的位置(尺寸和位置)
*/
}, {
key: "$updateEditorPosition",
value: function $updateEditorPosition() {
this.$setInputOffset();
var tdStyle = getComputedStyle(this.tableEditor.info.tdNode);
this.tableEditor.editorDom.inputDom.style.textAlign = tdStyle.textAlign || 'left';
this.tableEditor.editorDom.inputDom.style.fontSize = tdStyle.fontSize || '16px';
this.tableEditor.editorDom.inputDom.style.fontFamily = tdStyle.fontFamily;
this.tableEditor.editorDom.inputDom.style.lineHeight = tdStyle.lineHeight;
this.tableEditor.editorDom.inputDom.style.padding = tdStyle.padding; // 左对齐的时候paddingRight设置成0反之paddingLeft设置成0
if (/left/.test(tdStyle.textAlign)) {
this.tableEditor.editorDom.inputDom.style.paddingRight = '0px';
}
if (/right/.test(tdStyle.textAlign)) {
this.tableEditor.editorDom.inputDom.style.paddingLeft = '0px';
}
if (/center/.test(tdStyle.textAlign)) {
this.tableEditor.editorDom.inputDom.style.paddingLeft = '0px';
this.tableEditor.editorDom.inputDom.style.paddingRight = '0px';
}
this.tableEditor.editorDom.inputDom.style.paddingBottom = '0px';
}
}, {
key: "$getClosestNode",
value: function $getClosestNode(node, targetNodeName) {
if (node.tagName === targetNodeName) {
return node;
}
if (node.parentNode.tagName === 'BODY') {
return false;
}
return this.$getClosestNode(node.parentNode, targetNodeName);
}
/**
* 绘制操作符号
*/
}, {
key: "$drawSymbol",
value: function $drawSymbol() {
var _context7,
_this2 = this;
var types = ['Last', 'Next'];
var dirs = ['Row', 'Col'];
var textDict = {
Row: '行',
Col: '列'
};
var symbols = flat$3(_context7 = map$3(dirs).call(dirs, function (_, index) {
return map$3(types).call(types, function (type) {
return map$3(dirs).call(dirs, function (dir) {
return ["".concat(index), type, dir];
});
});
})).call(_context7, 2);
var container = document.createElement('ul');
container.className = 'cherry-previewer-table-hover-handler-container';
forEach$3(symbols).call(symbols, function (_ref4) {
var _ref5 = _slicedToArray(_ref4, 3),
index = _ref5[0],
type = _ref5[1],
dir = _ref5[2];
var li = document.createElement('li');
li.setAttribute('data-index', index);
li.setAttribute('data-type', type);
li.setAttribute('data-dir', dir);
li.className = 'cherry-previewer-table-hover-handler__symbol';
li.title = "\u6DFB\u52A0".concat(textDict[dir]);
li.innerHTML = '+';
li.addEventListener('click', function (e) {
var _context8;
var target = e.target;
if (!(target instanceof HTMLElement)) {
return;
}
var _target$dataset = target.dataset,
type = _target$dataset.type,
dir = _target$dataset.dir;
_this2[concat$5(_context8 = "$add".concat(type)).call(_context8, dir)]();
});
container.appendChild(li);
}, true);
this.tableEditor.editorDom.symbolContainer = container;
this.container.appendChild(this.tableEditor.editorDom.symbolContainer);
this.$setSymbolOffset();
}
/**
* 添加上一行
*/
}, {
key: "$addLastRow",
value: function $addLastRow() {
var _context9;
var _this$tableEditor$inf2 = _slicedToArray(this.tableEditor.info.selection, 1),
line = _this$tableEditor$inf2[0].line;
var newRow = "".concat(repeat$3(_context9 = '|').call(_context9, this.tableEditor.info.columns), "\n");
this.codeMirror.replaceRange(newRow, {
line: line,
ch: 0
});
this.$findTableInEditor();
this.$setSelection(this.tableEditor.info.tableIndex, 'td');
}
/**
* 添加下一行
*/
}, {
key: "$addNextRow",
value: function $addNextRow() {
var _context10;
var _this$tableEditor$inf3 = _slicedToArray(this.tableEditor.info.selection, 2),
line = _this$tableEditor$inf3[1].line;
var newRow = "".concat(repeat$3(_context10 = '|').call(_context10, this.tableEditor.info.columns), "\n");
this.codeMirror.replaceRange(newRow, {
line: line + 1,
ch: 0
});
this.$findTableInEditor();
this.$setSelection(this.tableEditor.info.tableIndex, 'td');
}
/**
* 添加上一列
*/
}, {
key: "$addLastCol",
value: function $addLastCol() {
var _this3 = this;
this.$setSelection(this.tableEditor.info.tableIndex, 'table');
var selection = this.codeMirror.getSelection();
var lines = selection.split('\n');
var newLines = map$3(lines).call(lines, function (line, index) {
var cells = line.split('|');
var replaceItem = 1 === index ? ':-:' : '';
splice$4(cells).call(cells, _this3.tableEditor.info.tdIndex + 1, 0, replaceItem);
return cells.join('|');
});
var newText = newLines.join('\n');
this.codeMirror.replaceSelection(newText);
this.$findTableInEditor();
this.$setSelection(this.tableEditor.info.tableIndex, 'table');
}
/**
* 添加下一列
*/
}, {
key: "$addNextCol",
value: function $addNextCol() {
var _this4 = this;
this.$setSelection(this.tableEditor.info.tableIndex, 'table');
var selection = this.codeMirror.getSelection();
var lines = selection.split('\n');
var newLines = map$3(lines).call(lines, function (line, index) {
var cells = line.split('|');
var replaceItem = 1 === index ? ':-:' : '';
splice$4(cells).call(cells, _this4.tableEditor.info.tdIndex + 2, 0, replaceItem);
return cells.join('|');
});
var newText = newLines.join('\n');
this.codeMirror.replaceSelection(newText);
this.$findTableInEditor();
this.$setSelection(this.tableEditor.info.tableIndex, 'table');
}
}]);
return TableHandler;
}();
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* 对话框基操集合
*/
var dialog = {
open: function open() {
this.dom.style.display = 'block';
this.postMessage('ready?');
},
close: function close() {
this.dom.style.display = 'none';
},
postMessage: function postMessage(messageName) {
var _this$iframeDom, _this$iframeDom$conte;
var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
(_this$iframeDom = this.iframeDom) === null || _this$iframeDom === void 0 ? void 0 : (_this$iframeDom$conte = _this$iframeDom.contentWindow) === null || _this$iframeDom$conte === void 0 ? void 0 : _this$iframeDom$conte.postMessage({
eventName: messageName,
value: value
}, '*');
},
draw: function draw(params, onReady, onSubmit) {
var _this = this;
var iframeSrc = params.iframeSrc,
title = params.title;
this.onSubmit = onSubmit;
this.onReady = onReady;
if (this.dom) {
var test = new RegExp("".concat(iframeSrc, "$"), 'i');
if (!test.test(this.iframeDom.src)) {
this.iframeDom.src = iframeSrc;
}
this.open();
return;
} // 添加通信事件
window.addEventListener('message', function (event) {
// @ts-ignore
if (!event.data || !event.data.eventName) {
return;
} // @ts-ignore
switch (event.data.eventName) {
case 'getData:success':
// @ts-ignore
_this.onSubmit(event.data.value);
_this.close();
case 'ready':
_this.onReady();
}
}); // 构造页面元素
this.iframeDom = createElement('iframe', 'cherry-dialog-iframe', {
src: iframeSrc,
style: 'border: none;'
});
this.dom = createElement('div', 'cherry-dialog', {
style: ['z-index:9999', 'display: block', 'position: absolute', 'top: 10%;left: 10%;bottom: 10%;right: 10%', 'background-color: #FFF', 'box-shadow: 0px 50px 100px -12px rgba(0,0,0,.05),0px 30px 60px -30px rgba(0,0,0,.1)', 'border-radius: 6px', 'border: 1px solid #ddd;'].join(';')
});
this.head = createElement('div', 'cherry-dialog--head', {
style: ['height: 30px', 'line-height: 30px', 'padding-left: 10px', 'padding-right: 10px'].join(';')
});
this.body = createElement('div', 'cherry-dialog--body', {
style: ['position: absolute', 'bottom: 30px', 'top: 30px', 'left: 0', 'right: 0', 'overflow: hidden'].join(';')
});
this.foot = createElement('div', 'cherry-dialog--foot', {
style: ['height: 30px', 'line-height: 18px', 'padding-left: 10px', 'padding-right: 10px', 'position: absolute', 'bottom: 0', 'left: 0', 'right: 0'].join(';')
});
this.headTitle = createElement('span', 'cherry-dialog--title', {
style: 'user-select:none;'
});
this.headCloseButton = createElement('i', 'cherry-dialog--close ch-icon ch-icon-close', {
style: 'float: right;font-size: 12px;cursor: pointer;'
});
this.footSureButton = createElement('button', 'cherry-dialog--sure', {
style: ['float: right', 'cursor: pointer', 'margin: 3px', 'background-color: #4d90fe', 'color: #FFF', 'border: 1px solid #4d90fe', 'border-radius: 2px', 'padding: 2px 15px', 'user-select:none'].join(';')
});
this.headCloseButton.title = '关闭';
this.footSureButton.textContent = '确定';
this.headTitle.textContent = title;
this.head.appendChild(this.headTitle);
this.head.appendChild(this.headCloseButton);
this.foot.appendChild(this.footSureButton);
this.body.appendChild(this.iframeDom);
this.dom.appendChild(this.head);
this.dom.appendChild(this.body);
this.dom.appendChild(this.foot);
this.headCloseButton.addEventListener('click', function () {
_this.close();
});
this.footSureButton.addEventListener('click', function () {
_this.postMessage('getData');
});
document.body.appendChild(this.dom);
}
};
/**
* draw.io的对话框
* @param {string} xml draw.io的xml格式的字符串数据
* @param {*} callback 回调
*/
function drawioDialog() {
var iframeSrc = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var xml = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var callback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var dialogParam = {
iframeSrc: iframeSrc,
title: 'draw.io'
};
dialog.draw(dialogParam, function () {
dialog.postMessage('setData', xml);
}, function (data) {
callback(data);
});
}
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* 复制内容到剪贴板
* @returns null
*/
function copyToClip(str) {
function listener(e) {
e.clipboardData.setData('text/html', str);
e.clipboardData.setData('text/plain', str);
e.preventDefault();
}
document.addEventListener('copy', listener);
document.execCommand('copy');
document.removeEventListener('copy', listener);
}
/**
* Gets the timestamp of the number of milliseconds that have elapsed since
* the Unix epoch (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Date
* @returns {number} Returns the timestamp.
* @example
*
* _.defer(function(stamp) {
* console.log(_.now() - stamp);
* }, _.now());
* // => Logs the number of milliseconds it took for the deferred invocation.
*/
var now = function() {
return _root.Date.now();
};
var now_1 = now;
/** Used to match a single whitespace character. */
var reWhitespace = /\s/;
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
* character of `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the index of the last non-whitespace character.
*/
function trimmedEndIndex(string) {
var index = string.length;
while (index-- && reWhitespace.test(string.charAt(index))) {}
return index;
}
var _trimmedEndIndex = trimmedEndIndex;
/** Used to match leading whitespace. */
var reTrimStart = /^\s+/;
/**
* The base implementation of `_.trim`.
*
* @private
* @param {string} string The string to trim.
* @returns {string} Returns the trimmed string.
*/
function baseTrim(string) {
return string
? string.slice(0, _trimmedEndIndex(string) + 1).replace(reTrimStart, '')
: string;
}
var _baseTrim = baseTrim;
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol_1(value)) {
return NAN;
}
if (isObject_1(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject_1(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = _baseTrim(value);
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
var toNumber_1 = toNumber;
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax$1 = Math.max,
nativeMin = Math.min;
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed `func` invocations and a `flush` method to immediately invoke them.
* Provide `options` to indicate whether `func` should be invoked on the
* leading and/or trailing edge of the `wait` timeout. The `func` is invoked
* with the last arguments provided to the debounced function. Subsequent
* calls to the debounced function return the result of the last `func`
* invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the debounced function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=false]
* Specify invoking on the leading edge of the timeout.
* @param {number} [options.maxWait]
* The maximum time `func` is allowed to be delayed before it's invoked.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // Avoid costly calculations while the window size is in flux.
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // Invoke `sendMail` when clicked, debouncing subsequent calls.
* jQuery(element).on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // Ensure `batchLog` is invoked once after 1 second of debounced calls.
* var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
* var source = new EventSource('/stream');
* jQuery(source).on('message', debounced);
*
* // Cancel the trailing debounced invocation.
* jQuery(window).on('popstate', debounced.cancel);
*/
function debounce(func, wait, options) {
var lastArgs,
lastThis,
maxWait,
result,
timerId,
lastCallTime,
lastInvokeTime = 0,
leading = false,
maxing = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = toNumber_1(wait) || 0;
if (isObject_1(options)) {
leading = !!options.leading;
maxing = 'maxWait' in options;
maxWait = maxing ? nativeMax$1(toNumber_1(options.maxWait) || 0, wait) : maxWait;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
var args = lastArgs,
thisArg = lastThis;
lastArgs = lastThis = undefined;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function leadingEdge(time) {
// Reset any `maxWait` timer.
lastInvokeTime = time;
// Start the timer for the trailing edge.
timerId = setTimeout(timerExpired, wait);
// Invoke the leading edge.
return leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime,
timeWaiting = wait - timeSinceLastCall;
return maxing
? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
: timeWaiting;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime;
// Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
(timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
}
function timerExpired() {
var time = now_1();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
// Restart the timer.
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
timerId = undefined;
// Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = undefined;
return result;
}
function cancel() {
if (timerId !== undefined) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = undefined;
}
function flush() {
return timerId === undefined ? result : trailingEdge(now_1());
}
function debounced() {
var time = now_1(),
isInvoking = shouldInvoke(time);
lastArgs = arguments;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime);
}
if (maxing) {
// Handle invocations in a tight loop.
clearTimeout(timerId);
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
var debounce_1 = debounce;
/**
* 预览区域的响应式工具栏
*/
var PreviewerBubble = /*#__PURE__*/function () {
/**
*
* @param {import('../Previewer').default} previewer
*/
function PreviewerBubble(previewer) {
_classCallCheck(this, PreviewerBubble);
/**
* @property
* @type {import('../Previewer').default}
*/
this.previewer = previewer;
/**
* @property
* @type {import('../Editor').default}
*/
this.editor = previewer.editor;
this.previewerDom = this.previewer.getDom();
this.enablePreviewerBubble = this.previewer.options.enablePreviewerBubble;
/**
* @property
* @type {{ [key: string]: HTMLDivElement}}
*/
this.bubble = {};
/**
* @property
* @type {{ [key: string]: { emit: (...args: any[]) => any, [key:string]: any }}}
*/
this.bubbleHandler = {};
this.init();
}
_createClass(PreviewerBubble, [{
key: "init",
value: function init() {
var _context,
_context2,
_context3,
_this = this,
_context10;
this.previewerDom.addEventListener('click', bind$5(_context = this.$onClick).call(_context, this));
this.previewerDom.addEventListener('mouseover', bind$5(_context2 = this.$onMouseOver).call(_context2, this));
this.previewerDom.addEventListener('mouseout', bind$5(_context3 = this.$onMouseOut).call(_context3, this));
document.addEventListener('mousedown', function (event) {
var _context4;
forEach$3(_context4 = values$3(_this.bubbleHandler)).call(_context4, function (handler) {
return handler.emit('mousedown', event);
});
});
document.addEventListener('mouseup', function (event) {
var _context5;
forEach$3(_context5 = values$3(_this.bubbleHandler)).call(_context5, function (handler) {
return handler.emit('mouseup', event, function () {
return _this.$removeAllPreviewerBubbles('click');
});
});
});
document.addEventListener('mousemove', function (event) {
var _context6;
forEach$3(_context6 = values$3(_this.bubbleHandler)).call(_context6, function (handler) {
return handler.emit('mousemove', event);
});
});
document.addEventListener('keyup', function (event) {
var _context7;
forEach$3(_context7 = values$3(_this.bubbleHandler)).call(_context7, function (handler) {
return handler.emit('keyup', event);
});
});
this.previewerDom.addEventListener('scroll', function (event) {
var _context8;
forEach$3(_context8 = values$3(_this.bubbleHandler)).call(_context8, function (handler) {
return handler.emit('scroll', event);
});
}, true);
Event$1.on(this.previewer.instanceId, Event$1.Events.previewerClose, function () {
return _this.$removeAllPreviewerBubbles();
});
this.previewer.options.afterUpdateCallBack.push(function () {
var _context9;
forEach$3(_context9 = values$3(_this.bubbleHandler)).call(_context9, function (handler) {
return handler.emit('previewUpdate', function () {
return _this.$removeAllPreviewerBubbles();
});
});
});
this.previewerDom.addEventListener('change', bind$5(_context10 = this.$onChange).call(_context10, this));
this.removeHoverBubble = debounce_1(function () {
return _this.$removeAllPreviewerBubbles('hover');
}, 400);
}
/**
* 是否为由cherry生成的表格且不是简单表格
* @param {HTMLElement} element
* @returns {boolean}
*/
}, {
key: "isCherryTable",
value: function isCherryTable(element) {
var container = this.$getClosestNode(element, 'DIV');
if (container === false) {
return false;
}
if (/simple-table/.test(container.className) || !/cherry-table-container/.test(container.className)) {
return false;
}
return true;
}
}, {
key: "$onMouseOver",
value: function $onMouseOver(e) {
if (!this.enablePreviewerBubble) {
return;
}
var cherryStatus = this.previewer.$cherry.getStatus(); // 左侧编辑器被隐藏时不再提供后续功能
if (cherryStatus.editor === 'hide') {
return;
}
var target = e.target;
if (typeof target.tagName === 'undefined') {
return;
}
switch (target.tagName) {
case 'TD':
case 'TH':
if (!this.isCherryTable(e.target)) {
return;
}
this.removeHoverBubble.cancel();
this.$removeAllPreviewerBubbles('hover');
this.$showTablePreviewerBubbles('hover', e.target);
return;
}
}
}, {
key: "$onMouseOut",
value: function $onMouseOut() {
if (!this.enablePreviewerBubble) {
return;
}
var cherryStatus = this.previewer.$cherry.getStatus(); // 左侧编辑器被隐藏时不再提供后续功能
if (cherryStatus.editor === 'hide') {
return;
}
this.removeHoverBubble();
}
}, {
key: "$dealCheckboxClick",
value: function $dealCheckboxClick(e) {
var _this2 = this;
var target = e.target; // 先计算是previewer中第几个checkbox
var list = from_1$2(this.previewerDom.querySelectorAll('.ch-icon-square, .ch-icon-check'));
this.checkboxIdx = indexOf$8(list).call(list, target); // 然后找到Editor中对应的`- []`或者`- [ ]`进行修改
var contents = this.getValueWithoutCode().split('\n');
var editorCheckboxCount = 0; // [ ]中的空格,或者[x]中的x的位置
var targetLine = -1;
var targetCh = -1;
forEach$3(contents).call(contents, function (lineContent, lineIdx) {
var tmp = trim$3(lineContent).call(lineContent); // 去掉句首的空格和制表符
if (startsWith$3(tmp).call(tmp, '- [ ]') || startsWith$3(tmp).call(tmp, '- [x]')) {
// 如果是个checkbox
if (editorCheckboxCount === _this2.checkboxIdx) {
targetLine = lineIdx;
targetCh = indexOf$8(lineContent).call(lineContent, '- [') + 3;
}
editorCheckboxCount += 1;
}
});
if (targetLine === -1) {
// 无法找到对应的checkbox
return;
}
this.editor.editor.setSelection({
line: targetLine,
ch: targetCh
}, {
line: targetLine,
ch: targetCh + 1
});
this.editor.editor.replaceSelection(this.editor.editor.getSelection() === ' ' ? 'x' : ' ', 'around');
}
}, {
key: "$onClick",
value: function $onClick(e) {
var _this3 = this;
var target = e.target; // 复制代码块操作不关心编辑器的状态
this.$dealCopyCodeBlock(e);
var cherryStatus = this.previewer.$cherry.getStatus(); // 纯预览模式下,支持点击放大图片功能(以回调的形式实现,需要业务侧实现图片放大功能)
if (cherryStatus.editor === 'hide') {
if (cherryStatus.previewer === 'show') {
this.previewer.$cherry.options.callback.onClickPreview && this.previewer.$cherry.options.callback.onClickPreview(e);
}
return;
} // 编辑draw.io不受enablePreviewerBubble配置的影响
if (target.tagName === 'IMG' && target.getAttribute('data-type') === 'drawio') {
if (!this.beginChangeDrawioImg(target)) {
return;
}
var xmlData = decodeURI(target.getAttribute('data-xml'));
drawioDialog(this.previewer.$cherry.options.drawioIframeUrl, xmlData, function (newData) {
var _context11;
var xmlData = newData.xmlData,
base64 = newData.base64;
_this3.editor.editor.replaceSelection(concat$5(_context11 = "(".concat(base64, "){data-type=drawio data-xml=")).call(_context11, encodeURI(xmlData), "}"), 'around');
});
return;
}
if (!this.enablePreviewerBubble) {
return;
} // 只有双栏编辑模式才出现下面的功能
// checkbox所见即所得编辑操作
if (target.className === 'ch-icon ch-icon-square' || target.className === 'ch-icon ch-icon-check') {
this.$dealCheckboxClick(e);
}
this.$removeAllPreviewerBubbles();
if (typeof target.tagName === 'undefined') {
return;
}
switch (target.tagName) {
case 'IMG':
this.$showImgPreviewerBubbles(target);
break;
case 'TD':
case 'TH':
if (!this.isCherryTable(e.target)) {
return;
}
this.$showTablePreviewerBubbles('click', e.target);
break;
}
}
}, {
key: "$onChange",
value: function $onChange(e) {
var target = e.target; // code预览区域修改语言设置项事件处理
if (target.className === CODE_PREVIEWER_LANG_SELECT_CLASS_NAME) {
this.$codePreviewLangSelectEventHandler(e);
}
}
}, {
key: "$getClosestNode",
value: function $getClosestNode(node, targetNodeName) {
if (node.tagName === targetNodeName) {
return node;
}
if (node.parentNode.tagName === 'BODY') {
return false;
}
return this.$getClosestNode(node.parentNode, targetNodeName);
}
/**
* 处理复制代码块的操作
*/
}, {
key: "$dealCopyCodeBlock",
value: function $dealCopyCodeBlock(e) {
var _target$parentNode;
var target = e.target;
if (target.className === 'cherry-copy-code-block' || ((_target$parentNode = target.parentNode) === null || _target$parentNode === void 0 ? void 0 : _target$parentNode.className) === 'cherry-copy-code-block') {
var parentNode = target.className === 'cherry-copy-code-block' ? target.parentNode : target.parentNode.parentNode;
var codeContent = parentNode.innerText;
var _final = this.previewer.$cherry.options.callback.onCopyCode(e, codeContent);
if (_final === false) {
return false;
}
var iconNode = parentNode.querySelector('i.ch-icon-copy');
if (iconNode) {
iconNode.className = iconNode.className.replace('copy', 'ok');
setTimeout$3(function () {
iconNode.className = iconNode.className.replace('ok', 'copy');
}, 1500);
}
copyToClip(_final);
}
}
/**
* 隐藏预览区域已经激活的工具栏
* @param {string} trigger 移除指定的触发方式,不传默认全部移除
*/
}, {
key: "$removeAllPreviewerBubbles",
value: function $removeAllPreviewerBubbles() {
var _context12,
_context13,
_this4 = this,
_context14,
_context15;
var trigger = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
forEach$3(_context12 = filter$3(_context13 = entries$2(this.bubble)).call(_context13, function (_ref) {
var _ref2 = _slicedToArray(_ref, 1),
key = _ref2[0];
return !trigger || trigger === key;
})).call(_context12, function (_ref3) {
var _ref4 = _slicedToArray(_ref3, 2),
key = _ref4[0],
value = _ref4[1];
value.remove();
delete _this4.bubble[key];
});
forEach$3(_context14 = filter$3(_context15 = entries$2(this.bubbleHandler)).call(_context15, function (_ref5) {
var _ref6 = _slicedToArray(_ref5, 1),
key = _ref6[0];
return !trigger || trigger === key;
})).call(_context14, function (_ref7) {
var _ref8 = _slicedToArray(_ref7, 2),
key = _ref8[0],
value = _ref8[1];
value.emit('remove');
delete _this4.bubbleHandler[key];
});
}
/**
* 为触发的table增加操作工具栏
* @param {string} trigger 触发方式
* @param {HTMLElement} htmlElement 用户触发的table dom
*/
}, {
key: "$showTablePreviewerBubbles",
value: function $showTablePreviewerBubbles(trigger, htmlElement) {
this.$createPreviewerBubbles(trigger, trigger === 'click' ? 'table-content-hander' : 'table-hover-handler');
var handler = new TableHandler(trigger, htmlElement, this.bubble[trigger], this.previewerDom, this.editor.editor);
handler.showBubble();
this.bubbleHandler[trigger] = handler;
}
/**
* 为选中的图片增加操作工具栏
* @param {HTMLImageElement} htmlElement 用户点击的图片dom
*/
}, {
key: "$showImgPreviewerBubbles",
value: function $showImgPreviewerBubbles(htmlElement) {
var _context16;
this.$createPreviewerBubbles();
var list = from_1$2(this.previewerDom.querySelectorAll('img'));
this.totalImgs = list.length;
this.imgIndex = indexOf$8(list).call(list, htmlElement);
if (!this.beginChangeImgValue(htmlElement)) {
return {
emit: function emit() {}
};
}
imgSizeHander.showBubble(htmlElement, this.bubble.click, this.previewerDom);
imgSizeHander.bindChange(bind$5(_context16 = this.changeImgValue).call(_context16, this));
this.bubbleHandler.click = imgSizeHander;
}
}, {
key: "getValueWithoutCode",
value: function getValueWithoutCode() {
return this.editor.editor.getValue().replace(getCodeBlockRule().reg, function (whole) {
// 把代码块里的内容干掉
return whole.replace(/^.*$/gm, '/n');
}).replace(/(`+)(.+?(?:\n.+?)*?)\1/g, function (whole) {
// 把行内代码的符号去掉
return whole.replace(/[![\]()]/g, '.');
});
}
/**
* TODO: beginChangeDrawioImg 和 beginChangeImgValue 代码高度重合,后面有时间重构下,抽成一个可以复用的,可以避开代码块、行内代码影响的通用方法
* 修改draw.io图片时选中编辑区域的对应文本
* @param {*} htmlElement 图片node
*/
}, {
key: "beginChangeDrawioImg",
value: function beginChangeDrawioImg(htmlElement) {
var _context17;
var allDrawioImgs = from_1$2(this.previewerDom.querySelectorAll('img[data-type="drawio"]'));
var totalDrawioImgs = allDrawioImgs.length;
var drawioImgIndex = indexOf$8(allDrawioImgs).call(allDrawioImgs, htmlElement);
var content = this.getValueWithoutCode();
var drawioImgsCode = content.match(imgDrawioReg);
var testSrc = drawioImgsCode[drawioImgIndex] ? trim$3(_context17 = drawioImgsCode[drawioImgIndex].replace(/^!\[.*?\]\((.*?)\)/, '$1')).call(_context17) : '';
if (drawioImgsCode.length === totalDrawioImgs || htmlElement.getAttribute('src') === testSrc) {
// 如果drawio语法数量和预览区域的一样多
var totalValue = content.split(imgDrawioReg);
var line = 0;
var beginCh = 0;
var endCh = 0;
var testIndex = 0;
for (var i = 0; i < totalValue.length; i++) {
var targetString = totalValue[i];
if (targetString === drawioImgsCode[testIndex]) {
// 如果找到目标代码
if (testIndex === drawioImgIndex) {
endCh = beginCh + targetString.length;
beginCh += targetString.replace(/^(!\[[^\]]*])[^\n]*$/, '$1').length;
this.editor.editor.setSelection({
line: line,
ch: beginCh
}, {
line: line,
ch: endCh
}); // 更新后需要再调用一次markText机制
this.editor.dealBigData();
return true;
}
testIndex += 1;
} else {
var _targetString$match$l, _targetString$match;
line += (_targetString$match$l = (_targetString$match = targetString.match(/\n/g)) === null || _targetString$match === void 0 ? void 0 : _targetString$match.length) !== null && _targetString$match$l !== void 0 ? _targetString$match$l : 0;
if (/\n/.test(targetString)) {
// 如果有换行,则开始位置的字符计数从最后一个换行开始计数
beginCh = targetString.replace(/^[\w\W]*\n([^\n]*)$/, '$1').length;
} else {
// 如果没有换行则继续按上次的beginCh为起始开始计数
beginCh += targetString.length;
}
}
}
}
return false;
}
/**
* 选中图片对应的MD语法
* @param {*} htmlElement 图片node
* @returns {boolean}
*/
}, {
key: "beginChangeImgValue",
value: function beginChangeImgValue(htmlElement) {
var _context18;
var content = this.getValueWithoutCode();
var src = htmlElement.getAttribute('src');
var imgReg = /(!\[[^\n]*?\]\([^)]+\))/g;
var contentImgs = content.match(imgReg);
var testSrc = contentImgs[this.imgIndex] ? trim$3(_context18 = contentImgs[this.imgIndex].replace(/^!\[.*?\]\((.*?)\)/, '$1')).call(_context18) : '';
if (contentImgs.length === this.totalImgs || src === testSrc) {
// 如果图片语法数量和预览区域的一样多
// 暂时不需要考虑手动输入img标签的场景 和 引用图片的场景
var totalValue = content.split(imgReg);
var imgAppendReg = /^!\[.*?((?:#center|#right|#left|#float-right|#float-left|#border|#B|#shadow|#S|#radius|#R)+).*?\].*$/;
var line = 0;
var beginCh = 0;
var endCh = 0;
var testIndex = 0;
for (var i = 0; i < totalValue.length; i++) {
var _targetString$match$l2, _targetString$match2;
var targetString = totalValue[i];
if (targetString === contentImgs[testIndex]) {
// 如果找到目标代码
if (testIndex === this.imgIndex) {
this.imgAppend = imgAppendReg.test(targetString) ? targetString.replace(imgAppendReg, '$1') : false;
beginCh += targetString.replace(/^(!\[[^#\]]*).*$/, '$1').length;
endCh = beginCh + targetString.replace(/^(!\[[^#\]]*)([^\]]*?)\].*$/, '$2').length;
this.editor.editor.setSelection({
line: line,
ch: beginCh
}, {
line: line,
ch: endCh
});
return true;
}
testIndex += 1;
}
line += (_targetString$match$l2 = (_targetString$match2 = targetString.match(/\n/g)) === null || _targetString$match2 === void 0 ? void 0 : _targetString$match2.length) !== null && _targetString$match$l2 !== void 0 ? _targetString$match$l2 : 0;
if (/\n/.test(targetString)) {
// 如果有换行,则开始位置的字符计数从最后一个换行开始计数
beginCh = targetString.replace(/^[\w\W]*\n([^\n]*)$/, '$1').length;
} else {
// 如果没有换行则继续按上次的beginCh为起始开始计数
beginCh += targetString.length;
}
}
}
return false;
}
/**
* 修改图片尺寸时的回调
* @param {HTMLElement} htmlElement 被拖拽的图片标签
* @param {Object} style 图片的属性(宽高、对齐方式)
*/
}, {
key: "changeImgValue",
value: function changeImgValue(htmlElement, style) {
var _context19, _context20;
var append = this.imgAppend ? " ".concat(this.imgAppend) : '';
this.editor.editor.replaceSelection(concat$5(_context19 = concat$5(_context20 = "#".concat(Math.round(style.width), "px #")).call(_context20, Math.round(style.height), "px")).call(_context19, append), 'around');
}
/**
* 预览区域编辑器的容器
* @param {string} trigger 触发方式
* @param {string} type 容器类型用作样式名cherry-previewer-{type}
*/
}, {
key: "$createPreviewerBubbles",
value: function $createPreviewerBubbles() {
var trigger = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'click';
var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'img-size-hander';
if (!this.bubble[trigger]) {
this.bubble[trigger] = document.createElement('div');
this.bubble[trigger].className = "cherry-previewer-".concat(type);
this.previewerDom.after(this.bubble[trigger]);
if (trigger === 'hover') {
this.bubble[trigger].addEventListener('mouseover', this.removeHoverBubble.cancel);
this.bubble[trigger].addEventListener('mouseout', this.removeHoverBubble);
}
}
}
}, {
key: "$showBorderBubbles",
value: function $showBorderBubbles() {}
}, {
key: "$showBtnBubbles",
value: function $showBtnBubbles() {}
/**
* 修改预览区域代码语言设置的回调
*/
}, {
key: "$codePreviewLangSelectEventHandler",
value: function $codePreviewLangSelectEventHandler(event) {
var list = from_1$2(this.previewerDom.querySelectorAll(".".concat(CODE_PREVIEWER_LANG_SELECT_CLASS_NAME)));
var codePreviewIndex = indexOf$8(list).call(list, event.target);
var contentList = this.editor.editor.getValue().split('\n');
var targetCodePreviewSelectLine = -1;
var findCodeArea = -1; // 相互匹配的`的数量
var matchedSignalNum = 0; // 查找选择设置的代码块在哪一行:
var left = 0;
while (left < contentList.length) {
if (findCodeArea >= codePreviewIndex) {
break;
}
var right = left + 1;
if (/^`{3,}[\s\S]*$/.test(contentList[left])) {
var _contentList$left$mat, _contentList$left$mat2;
// 起始的`的数量
var topSignalNum = (_contentList$left$mat = (_contentList$left$mat2 = contentList[left].match(/^(`*)/g)) === null || _contentList$left$mat2 === void 0 ? void 0 : _contentList$left$mat2[0].length) !== null && _contentList$left$mat !== void 0 ? _contentList$left$mat : 0;
while (right < contentList.length) {
var _contentList$right$ma, _contentList$right$ma2;
var isMatched = false;
var bottomSignalNum = (_contentList$right$ma = (_contentList$right$ma2 = contentList[right].match(/^(`*)/g)) === null || _contentList$right$ma2 === void 0 ? void 0 : _contentList$right$ma2[0].length) !== null && _contentList$right$ma !== void 0 ? _contentList$right$ma : 0; // 支持: 3个及以上的`的相互匹配
if (/^`{3,}$/.test(contentList[right]) && bottomSignalNum === topSignalNum) {
isMatched = true;
findCodeArea = findCodeArea + 1;
if (findCodeArea === codePreviewIndex) {
targetCodePreviewSelectLine = left;
matchedSignalNum = topSignalNum;
}
}
right = right + 1;
if (isMatched) {
break;
}
}
}
left = right;
} // 只有匹配了代码块才进行替换
if (matchedSignalNum) {
this.editor.editor.setSelection({
line: targetCodePreviewSelectLine,
ch: matchedSignalNum
}, {
line: targetCodePreviewSelectLine,
ch: contentList[targetCodePreviewSelectLine].length
});
this.editor.editor.replaceSelection(event.target.value || '');
}
}
}]);
return PreviewerBubble;
}();
var setInterval$2 = path.setInterval;
var setInterval$3 = setInterval$2;
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* 懒加载图片
*
* - 只缓存图片的src的原因
* - 1、因为浏览器的图片缓存机制相同的src第二次请求时会浏览器会直接返回缓存的图片
* - 2、编辑状态时预览区域dom结构不稳定并不能准确的缓存到img dom对象
*
* - 当浏览器**禁用**了图片缓存时,本机制效果有限
* - 依然还是可以实现懒加载的效果
* - 但是会把图片请求次数翻倍
*/
var LazyLoadImg = /*#__PURE__*/function () {
function LazyLoadImg(options, previewer) {
_classCallCheck(this, LazyLoadImg);
_defineProperty(this, "options", {
// 加载图片时如果需要展示loading图则配置loading图的地址
loadingImgPath: '',
// 同一时间最多有几个图片请求最大同时加载6张图片
maxNumPerTime: 2,
// 不进行懒加载处理的图片数量如果为0即所有图片都进行懒加载处理 如果设置为-1则所有图片都不进行懒加载处理
noLoadImgNum: 5,
// 首次自动加载几张图片不论图片是否滚动到视野内autoLoadImgNum = -1 表示会自动加载完所有图片
autoLoadImgNum: 5,
// 针对加载失败的图片 或 beforeLoadOneImgCallback 返回false 的图片最多尝试加载几次为了防止死循环最多5次。以图片的src为纬度统计重试次数
maxTryTimesPerSrc: 2,
// 加载一张图片之前的回调函数函数return false 会终止加载操作
beforeLoadOneImgCallback: function beforeLoadOneImgCallback(img) {},
// 加载一张图片失败之后的回调函数
failLoadOneImgCallback: function failLoadOneImgCallback(img) {},
// 加载一张图片之后的回调函数,如果图片加载失败,则不会回调该函数
afterLoadOneImgCallback: function afterLoadOneImgCallback(img) {},
// 加载完所有图片后调用的回调函数,只表示某一个时刻所有图片都加在完时的回调,如果预览区域又有了新图片,当新图片加载完后还会产生这个回调
afterLoadAllImgCallback: function afterLoadAllImgCallback() {}
});
assign$2(this.options, options);
this.previewer = previewer; // 记录已经加载过的图片src
this.srcLoadedList = []; // 记录加载失败的图片srckey是srcvalue是失败次数
this.srcFailLoadedList = {}; // 记录正在加载的图片src
this.srcLoadingList = []; // 记录所有懒加载的图片src
this.srcList = []; // 记录当前时刻有多少图片正在加载
this.loadingImgNum = 0; // 记录上次加载完所有图片的个数
this.lastLoadAllNum = 0;
this.previewerDom = this.previewer.getDomContainer();
}
/**
* 判断图片的src是否加载过
* @param {String} src
* @return {Boolean}
*/
_createClass(LazyLoadImg, [{
key: "isLoaded",
value: function isLoaded(src) {
var _context;
return includes$4(_context = this.srcLoadedList).call(_context, src);
}
/**
* 判断图片是否正在加载
* @param {String} src
* @return {Boolean}
*/
}, {
key: "isLoading",
value: function isLoading(src) {
var _context2;
return includes$4(_context2 = this.srcLoadingList).call(_context2, src);
}
/**
* 加载失败时把src加入到失败队列中并记录失败次数
* @param {*} src
*/
}, {
key: "loadFailed",
value: function loadFailed(src) {
this.srcFailLoadedList[src] = this.srcFailLoadedList[src] ? this.srcFailLoadedList[src] + 1 : 1;
}
/**
* 判断图片失败次数是否超过最大次数
* @param {*} src
* @return {Boolean}
*/
}, {
key: "isFailLoadedMax",
value: function isFailLoadedMax(src) {
return this.srcFailLoadedList[src] && this.srcFailLoadedList[src] > this.options.maxTryTimesPerSrc;
}
/**
* 判断当前时刻所有图片是否都完成过加载
* 当出现新图片后完成加载后当前函数还是会再次触发加载完的回调函数afterLoadAllImgCallback
* 该函数并不是实时返回的最大有1s的延时
*/
}, {
key: "isLoadedAllDone",
value: function isLoadedAllDone() {
var imgs = this.previewerDom.querySelectorAll('img[data-src]');
var allLoadedNum = this.srcLoadedList.length; // const dataSrcRemain = allLoadNum - this.srcLoadedList.length;
if (imgs.length <= 0 && this.lastLoadAllNum < allLoadedNum) {
this.lastLoadAllNum = allLoadedNum;
this.options.afterLoadAllImgCallback();
return true;
}
return false;
}
/**
* 当向下滚动时提前100px加载图片
* 当向上滚动时不提前加载图片一定要图片完全进入可视区域top > 0再加载图片否则当锚点定位时会由于上面的图片加载出现定位不准的情况
*
*/
}, {
key: "loadOneImg",
value: function loadOneImg() {
var _window$innerHeight,
_window,
_this = this;
var imgs = this.previewerDom.querySelectorAll('img[data-src]');
var _this$previewerDom$ge = this.previewerDom.getBoundingClientRect(),
height = _this$previewerDom$ge.height,
top = _this$previewerDom$ge.top;
var previewerHeight = height + top + 100; // 冗余一定高度用于提前加载
var windowsHeight = (_window$innerHeight = (_window = window) === null || _window === void 0 ? void 0 : _window.innerHeight) !== null && _window$innerHeight !== void 0 ? _window$innerHeight : 0 + 100; // 浏览器的视口高度
var maxHeight = Math.min(previewerHeight, windowsHeight); // 目标视区高度一定是小于浏览器视口高度的,也一定是小于预览区高度的
var minHeight = top - 30; // 计算顶部高度时,需要预加载一行高
var autoLoadImgNum = this.options.autoLoadImgNum;
var _loop = function _loop(i) {
var img = imgs[i];
var position = img.getBoundingClientRect(); // 判断是否在视区内
var testPosition = position.top >= minHeight && position.top <= maxHeight; // 判断是否需要自动加载
var testAutoLoad = _this.srcList.length < autoLoadImgNum;
if (!testPosition && !testAutoLoad) {
return "continue";
}
var originSrc = img.getAttribute('data-src');
if (!originSrc) {
return "continue";
}
if (_this.isLoaded(originSrc) || _this.isFailLoadedMax(originSrc)) {
// 如果已经加载过相同的图片,或者已经超过失败最大重试次数,则直接加载
img.setAttribute('src', originSrc);
img.removeAttribute('data-src');
} // 如果当前src正在加载则忽略这个src继续找下个符合条件的src
if (_this.isLoading(originSrc)) {
return "continue";
} // 超过最大并发量时停止加载
if (_this.loadingImgNum >= _this.options.maxNumPerTime) {
return {
v: false
};
}
var test = _this.options.beforeLoadOneImgCallback(img);
if (typeof test === 'undefined' || test) {
var _img$getAttribute;
originSrc = (_img$getAttribute = img.getAttribute('data-src')) !== null && _img$getAttribute !== void 0 ? _img$getAttribute : originSrc;
} else {
_this.loadFailed(originSrc);
return "continue";
}
_this.loadingImgNum += 1;
_this.srcList.push(originSrc);
_this.srcLoadingList.push(originSrc);
_this.tryLoadOneImg(originSrc, function () {
var _context3, _context4;
img.setAttribute('src', originSrc);
img.removeAttribute('data-src');
_this.srcLoadedList.push(originSrc);
_this.loadingImgNum -= 1;
splice$4(_context3 = _this.srcLoadingList).call(_context3, indexOf$8(_context4 = _this.srcLoadingList).call(_context4, originSrc), 1);
_this.options.afterLoadOneImgCallback(img);
_this.loadOneImg();
}, function () {
var _context5, _context6;
_this.loadFailed(originSrc);
_this.loadingImgNum -= 1;
splice$4(_context5 = _this.srcLoadingList).call(_context5, indexOf$8(_context6 = _this.srcLoadingList).call(_context6, originSrc), 1);
_this.options.failLoadOneImgCallback(img);
_this.loadOneImg();
});
};
for (var i = 0; i < imgs.length; i++) {
var _ret = _loop(i);
if (_ret === "continue") continue;
if (_typeof(_ret) === "object") return _ret.v;
}
return false;
}
/**
* 尝试加载src
* @param {String} src
*/
}, {
key: "tryLoadOneImg",
value: function tryLoadOneImg(src, successCallback, failCallback) {
var img = document.createElement('img');
img.onload = function () {
successCallback();
img.remove();
};
img.onerror = function () {
failCallback();
img.remove();
};
img.setAttribute('src', src);
}
/**
* 开始进行懒加载
*
* **关于实现方式的思考**
* 实现图片懒加载一般有三种方式:
* 1、监听滚动事件滚动到视野内的图片开始加载
* 2、定时检测当前视窗内是否有图片需要加载
* 3、当前一张图片加载完成后自动加载下一张图片
*
* 方式1监听滚动事件的弊端
* 1、需要限频率
* 2、不能实现自动加载所有图片的功能autoLoadImgNum = -1
* 3、如果业务方对预览区域做了个性化加工有可能导致监听不到滚动事件
* 4、在自动滚动到锚点的场景会在页面滚动时加载图片图片的加载会导致锚点上方的元素高度发生变化最终导致锚点定位失败
* (所以在这个场景下,需要特殊处理图片加载的时机,但并不好判断是否锚点引发的滚动)
* 5、浏览器尺寸发生变化或者浏览器缩放比例发生变化的场景当然还有横屏竖屏切换、系统分辨率改变等不好监听和响应
*
* 方式2轮询的弊端
* 1、需要额外的逻辑来控制并发
* 2、消耗计算资源所以需要尽量优化单次计算量并尽量避免在轮询里进行大范围dom操作
* 3、两次图片加载中间可能有最大轮询间隔的空闲时间浪费
*
* 方式3依次加载的弊端
* 1、没办法实现滚动到视野内再加载图片
*
* 综合考虑决定用方式2轮询+方式3依次加载的组合方式并且每次只做一次dom写操作
* 轮询带来的性能开销就让受摩尔定律加持的硬件和每月都会更新版本的浏览器们愁去吧
*/
}, {
key: "doLazyLoad",
value: function doLazyLoad() {
var _this2 = this;
// 防止重复调用
if (this.isRunning) {
return;
}
this.isRunning = true;
var maxNumPerTime = this.options.maxNumPerTime;
var polling = function polling() {
// 保证至少有一次自动加载
_this2.loadOneImg();
for (var i = 1; i < maxNumPerTime; i++) {
_this2.loadOneImg();
}
setTimeout$3(polling, 200);
};
polling(); // setTimeout(polling, 200);
setInterval$3(function () {
_this2.isLoadedAllDone();
}, 1000);
}
/**
* 把图片里的data-src替换为src
* @param {*} content
* @returns {String}
*/
}, {
key: "changeDataSrc2Src",
value: function changeDataSrc2Src(content) {
var _this3 = this;
return content.replace(/<img ([^>]*?)data-src="([^"]+)"([^>]*?)>/g, function (match, m1, src, m3) {
var _context7, _context8;
return concat$5(_context7 = concat$5(_context8 = "<img ".concat(_this3.$removeSrc(m1), " src=\"")).call(_context8, src, "\" ")).call(_context7, _this3.$removeSrc(m3), ">").replace(/ {2,}/g, ' ');
});
}
/**
* 把已经加载的图片里的data-src替换为src
* @param {*} content
* @returns {String}
*/
}, {
key: "changeLoadedDataSrc2Src",
value: function changeLoadedDataSrc2Src(content) {
var _this4 = this;
return content.replace(/<img ([^>]*?)data-src="([^"]+)"([^>]*?)>/g, function (match, m1, src, m3) {
var _context9, _context10;
if (!_this4.isLoaded(src)) {
return match;
}
return concat$5(_context9 = concat$5(_context10 = "<img ".concat(_this4.$removeSrc(m1), " src=\"")).call(_context10, src, "\" ")).call(_context9, _this4.$removeSrc(m3), ">").replace(/ {2,}/g, ' ');
});
}
/**
* 移除图片的src属性
* @param {String} img
* @returns {String}
*/
}, {
key: "$removeSrc",
value: function $removeSrc(img) {
return " ".concat(img).replace(/^(.*?) src=".*?"(.*?$)/, '$1$2');
}
/**
* 把图片里的src替换为data-src如果src已经加载过则不替换
* @param {String} content
* @param {Boolean} focus 强制替换
* @returns {String}
*/
}, {
key: "changeSrc2DataSrc",
value: function changeSrc2DataSrc(content) {
var _this5 = this;
var focus = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var loadingImgPath = this.options.loadingImgPath;
var noLoadImgNum = this.options.noLoadImgNum;
var currentNoLoadImgNum = 0;
return content.replace(/<img ([^>]*?)src="([^"]+)"([^>]*?)>/g, function (match, m1, src, m3) {
var _context14, _context15;
// 如果已经替换过data-src了或者没有src属性或者关闭了懒加载功能则不替换
if (/data-src="/.test(match) || !/ src="/.test(match) || noLoadImgNum < 0) {
return match;
}
if (focus === false) {
// 前noLoadImgNum张图片不替换
if (currentNoLoadImgNum < noLoadImgNum) {
currentNoLoadImgNum += 1;
return match;
} // 如果src已经加载过则不替换
if (_this5.isLoaded(src)) {
return match;
}
} // 如果配置了loadingImgPath则替换src为loadingImgPath
if (loadingImgPath) {
var _context11, _context12, _context13;
return concat$5(_context11 = concat$5(_context12 = concat$5(_context13 = "<img ".concat(m1, "src=\"")).call(_context13, loadingImgPath, "\" data-src=\"")).call(_context12, src, "\"")).call(_context11, m3, ">");
}
return concat$5(_context14 = concat$5(_context15 = "<img ".concat(m1, "data-src=\"")).call(_context15, src, "\"")).call(_context14, m3, ">");
});
}
}]);
return LazyLoadImg;
}();
var onScroll = function onScroll() {}; // store in memory for remove event
/**
* 解析第一个节点
* @param {Node} node 经过DOMParser转换的HTML
* @returns {String | null}
*/
var findNonEmptyNode = function findNonEmptyNode(node) {
var _context;
// 如果节点是文本节点且内容不为空,则返回该节点
if (node.nodeType === Node.TEXT_NODE && trim$3(_context = node.textContent).call(_context) !== '') {
var _context2;
return trim$3(_context2 = node.textContent).call(_context2);
}
for (var i = 0; i < node.childNodes.length; i++) {
var childNode = node.childNodes[i];
var result = findNonEmptyNode(childNode);
if (result) {
return result;
}
}
return null;
};
/**
* 作用:
* dom更新
* 局部加载(分片)
* 与左侧输入区域滚动同步
*/
var Previewer = /*#__PURE__*/function () {
/**
* @property
* @private
* @type {boolean} 等待预览区域更新。预览区域更新时,预览区的滚动不会引起编辑器滚动,避免因插入的元素高度变化导致编辑区域跳动
*/
/**
* @property
* @private
* @type {number} 释放同步滚动锁定的定时器ID
*/
/**
* @property
* @public
* @type {boolean} 是否为移动端预览模式
*/
/**
*
* @param {Partial<import('~types/previewer').PreviewerOptions>} options 预览区域设置
*/
function Previewer(options) {
_classCallCheck(this, Previewer);
_defineProperty(this, "applyingDomChanges", false);
_defineProperty(this, "syncScrollLockTimer", 0);
_defineProperty(this, "isMobilePreview", false);
/**
* @property
* @type {import('~types/previewer').PreviewerOptions}
*/
this.options = {
previewerDom: document.createElement('div'),
virtualDragLineDom: document.createElement('div'),
editorMaskDom: document.createElement('div'),
previewerMaskDom: document.createElement('div'),
minBlockPercentage: 0.2,
// editor或previewer所占宽度比例的最小值
value: '',
enablePreviewerBubble: true,
afterUpdateCallBack: [],
isPreviewOnly: false,
previewerCache: {
// 关闭/开启预览区时缓存的previewer数据
html: '',
htmlChanged: false,
layout: {}
},
/**
* 配置图片懒加载的逻辑
* 如果不希望图片懒加载,可配置成 lazyLoadImg = {maxNumPerTime: 6, autoLoadImgNum: -1}
*/
lazyLoadImg: {
// 加载图片时如果需要展示loading图则配置loading图的地址
loadingImgPath: '',
// 同一时间最多有几个图片请求最大同时加载6张图片
maxNumPerTime: 2,
// 不进行懒加载处理的图片数量如果为0即所有图片都进行懒加载处理 如果设置为-1则所有图片都不进行懒加载处理
noLoadImgNum: 5,
// 首次自动加载几张图片不论图片是否滚动到视野内autoLoadImgNum = -1 表示会自动加载完所有图片
autoLoadImgNum: 5,
// 针对加载失败的图片 或 beforeLoadOneImgCallback 返回false 的图片最多尝试加载几次为了防止死循环最多5次。以图片的src为纬度统计重试次数
maxTryTimesPerSrc: 2,
// 加载一张图片之前的回调函数函数return false 会终止加载操作
beforeLoadOneImgCallback: function beforeLoadOneImgCallback(img) {},
// 加载一张图片失败之后的回调函数
failLoadOneImgCallback: function failLoadOneImgCallback(img) {},
// 加载一张图片之后的回调函数,如果图片加载失败,则不会回调该函数
afterLoadOneImgCallback: function afterLoadOneImgCallback(img) {},
// 加载完所有图片后调用的回调函数
afterLoadAllImgCallback: function afterLoadAllImgCallback() {}
}
};
assign$2(this.options, options);
this.$cherry = this.options.$cherry;
this.instanceId = this.$cherry.getInstanceId();
/**
* @property
* @private
* @type {{ timer?: number; destinationTop?: number }}
*/
this.animation = {};
}
_createClass(Previewer, [{
key: "init",
value: function init(editor) {
/**
* @property
* @private
* @type {boolean} 禁用滚动事件监听
*/
this.disableScrollListener = false;
this.bindScroll();
this.editor = editor;
this.bindDrag();
this.$initPreviewerBubble();
this.lazyLoadImg = new LazyLoadImg(this.options.lazyLoadImg, this);
this.lazyLoadImg.doLazyLoad();
this.onMouseDown();
}
}, {
key: "$initPreviewerBubble",
value: function $initPreviewerBubble() {
this.previewerBubble = new PreviewerBubble(this);
}
/**
* @returns {HTMLElement}
*/
}, {
key: "getDomContainer",
value: function getDomContainer() {
return this.isMobilePreview ? this.options.previewerDom.querySelector('.cherry-mobile-previewer-content') : this.options.previewerDom;
}
}, {
key: "getDom",
value: function getDom() {
return this.options.previewerDom;
}
/**
* 获取预览区内的html内容
* @param {boolean} wrapTheme 是否在外层包裹主题class
* @returns html内容
*/
}, {
key: "getValue",
value: function getValue() {
var _context3, _context4;
var wrapTheme = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
var html = '';
if (this.isPreviewerHidden()) {
html = this.options.previewerCache.html;
} else {
html = this.getDomContainer().innerHTML;
} // 需要未加载的图片替换成原始图片
html = this.lazyLoadImg.changeDataSrc2Src(html);
if (!wrapTheme || !this.$cherry.wrapperDom) {
return html;
}
var inlineCodeTheme = this.$cherry.wrapperDom.getAttribute('data-inline-code-theme');
var codeBlockTheme = this.$cherry.wrapperDom.getAttribute('data-code-block-theme');
return concat$5(_context3 = concat$5(_context4 = "<div data-inline-code-theme=\"".concat(inlineCodeTheme, "\" data-code-block-theme=\"")).call(_context4, codeBlockTheme, "\">")).call(_context3, html, "</div>");
}
}, {
key: "isPreviewerHidden",
value: function isPreviewerHidden() {
return this.options.previewerDom.classList.contains('cherry-previewer--hidden');
}
}, {
key: "calculateRealLayout",
value: function calculateRealLayout(editorWidth) {
// 根据editor的绝对宽度计算editor和previewer的百分比宽度
var editorDomWidth = this.editor.options.editorDom.getBoundingClientRect().width;
var previewerDomWidth = this.options.previewerDom.getBoundingClientRect().width;
var totalWidth = editorDomWidth + previewerDomWidth;
var editorPercentage = +(editorWidth / totalWidth).toFixed(3);
if (editorPercentage < this.options.minBlockPercentage) {
editorPercentage = +this.options.minBlockPercentage.toFixed(3);
} else if (editorPercentage > 1 - this.options.minBlockPercentage) {
editorPercentage = +(1 - this.options.minBlockPercentage).toFixed(3);
}
var previewerPercentage = +(1 - editorPercentage).toFixed(3);
var res = {
editorPercentage: "".concat(editorPercentage * 100, "%"),
previewerPercentage: "".concat(previewerPercentage * 100, "%")
};
return res;
}
}, {
key: "setRealLayout",
value: function setRealLayout(editorPercentage, previewerPercentage) {
// 主动设置editor,previewer宽度,按百分比计算
var $editorPercentage = editorPercentage;
var $previewerPercentage = previewerPercentage;
if (!$editorPercentage || !$previewerPercentage) {
$editorPercentage = '50%';
$previewerPercentage = '50%';
}
this.editor.options.editorDom.style.width = $editorPercentage;
this.options.previewerDom.style.width = $previewerPercentage;
this.syncVirtualLayoutFromReal();
}
}, {
key: "syncVirtualLayoutFromReal",
value: function syncVirtualLayoutFromReal() {
// 通过editor和previewer的百分比宽度,同步更新mask和dragLine的px宽度及位置
var editorPos = this.editor.options.editorDom.getBoundingClientRect();
var previewerPos = this.options.previewerDom.getBoundingClientRect();
var editorHeight = editorPos.height;
var editorTop = this.editor.options.editorDom.offsetTop;
var editorLeft = editorPos.left;
var editorWidth = editorPos.width;
var previewerLeft = previewerPos.left ? previewerPos.left - editorLeft : 0;
var previewerWidth = previewerPos.width || 0;
var _this$options = this.options,
editorMaskDom = _this$options.editorMaskDom,
previewerMaskDom = _this$options.previewerMaskDom,
virtualLineDom = _this$options.virtualDragLineDom;
virtualLineDom.style.top = "".concat(editorTop, "px");
virtualLineDom.style.left = "".concat(previewerLeft, "px");
virtualLineDom.style.bottom = '0px';
editorMaskDom.style.height = "".concat(editorHeight, "px");
editorMaskDom.style.top = "".concat(editorTop, "px");
editorMaskDom.style.left = '0px';
editorMaskDom.style.width = "".concat(editorWidth, "px");
previewerMaskDom.style.height = "".concat(editorHeight, "px");
previewerMaskDom.style.top = "".concat(editorTop, "px");
previewerMaskDom.style.left = "".concat(previewerLeft, "px");
previewerMaskDom.style.width = "".concat(previewerWidth, "px");
}
}, {
key: "calculateVirtualLayout",
value: function calculateVirtualLayout(editorLeft, editorRight) {
// 计算mask和dragline应处在的位置,按px计算
var editorDomWidth = this.editor.options.editorDom.getBoundingClientRect().width;
var previewerDomWidth = this.options.previewerDom.getBoundingClientRect().width;
var totalWidth = editorDomWidth + previewerDomWidth;
var startWidth = editorLeft.toFixed(0);
var leftWidth = editorRight - editorLeft;
if (leftWidth < totalWidth * this.options.minBlockPercentage) {
leftWidth = +(totalWidth * this.options.minBlockPercentage).toFixed(0);
} else if (leftWidth > totalWidth * (1 - this.options.minBlockPercentage)) {
leftWidth = +(totalWidth * (1 - this.options.minBlockPercentage)).toFixed(0);
}
var rightWidth = totalWidth - leftWidth;
var ret = {
startWidth: _parseInt$2(startWidth, 10),
// 起始位置(左侧留白)
leftWidth: leftWidth,
// 左侧mask宽度
rightWidth: rightWidth // 右侧mask宽度
};
return ret;
}
}, {
key: "setVirtualLayout",
value: function setVirtualLayout(startWidth, leftWidth, rightWidth) {
// 主动设置mask和dragLine位置,按px计算
var _this$options2 = this.options,
editorMaskDom = _this$options2.editorMaskDom,
previewerMaskDom = _this$options2.previewerMaskDom,
virtualLineDom = _this$options2.virtualDragLineDom;
var $startWidth = 0; // =startWidth
editorMaskDom.style.left = "".concat($startWidth, "px");
editorMaskDom.style.width = "".concat(leftWidth, "px");
virtualLineDom.style.left = "".concat($startWidth + leftWidth, "px");
previewerMaskDom.style.left = "".concat($startWidth + leftWidth, "px");
previewerMaskDom.style.width = "".concat(rightWidth, "px");
}
}, {
key: "bindDrag",
value: function bindDrag() {
var _this = this,
_context5;
var dragLineMouseMove = function dragLineMouseMove(mouseMoveEvent) {
// 阻止事件冒泡
if (mouseMoveEvent && mouseMoveEvent.stopPropagation) {
mouseMoveEvent.stopPropagation();
} else {
mouseMoveEvent.cancelBubble = true;
} // 取消默认事件
if (mouseMoveEvent.preventDefault) {
mouseMoveEvent.preventDefault();
} else {
window.event.returnValue = false;
}
var editorLeft = _this.editor.options.editorDom.getBoundingClientRect().left;
var editorRight = mouseMoveEvent.clientX;
var virtualLayout = _this.calculateVirtualLayout(editorLeft, editorRight);
_this.setVirtualLayout(virtualLayout.startWidth, virtualLayout.leftWidth, virtualLayout.rightWidth);
return false;
};
var dragLineMouseUp = function dragLineMouseUp(mouseUpEvent) {
// 阻止事件冒泡
if (mouseUpEvent && mouseUpEvent.stopPropagation) {
mouseUpEvent.stopPropagation();
} else {
mouseUpEvent.cancelBubble = true;
} // 取消默认事件
if (mouseUpEvent.preventDefault) {
mouseUpEvent.preventDefault();
} else {
window.event.returnValue = false;
} // 重新设置editor和previewer宽度占比
var editorLeft = _this.editor.options.editorDom.getBoundingClientRect().left;
var editorRight = mouseUpEvent.clientX;
var layout = _this.calculateRealLayout(editorRight - editorLeft);
_this.setRealLayout(layout.editorPercentage, layout.previewerPercentage); // 去掉蒙层和虚拟拖动条
_this.editor.options.editorDom.classList.remove('no-select');
_this.options.previewerDom.classList.remove('no-select');
_this.options.editorMaskDom.classList.remove('cherry-editor-mask--show');
_this.options.previewerMaskDom.classList.remove('cherry-previewer-mask--show');
_this.options.virtualDragLineDom.classList.remove('cherry-drag--show'); // 刷新codemirror宽度
_this.editor.editor.refresh(); // 取消事件绑定
removeEvent(document, 'mousemove', dragLineMouseMove, false);
removeEvent(document, 'mouseup', dragLineMouseUp, false);
return false;
};
var dragLineMouseDown = function dragLineMouseDown(mouseDownEvent) {
// 阻止事件冒泡
if (mouseDownEvent && mouseDownEvent.stopPropagation) {
mouseDownEvent.stopPropagation();
} else {
mouseDownEvent.cancelBubble = true;
} // 取消默认事件
if (mouseDownEvent.preventDefault) {
mouseDownEvent.preventDefault();
} else {
window.event.returnValue = false;
}
_this.syncVirtualLayoutFromReal();
var editorLeft = _this.editor.options.editorDom.getBoundingClientRect().left;
var editorRight = mouseDownEvent.clientX;
var virtualLayout = _this.calculateVirtualLayout(editorLeft, editorRight);
_this.setVirtualLayout(virtualLayout.startWidth, virtualLayout.leftWidth, virtualLayout.rightWidth);
if (!_this.options.virtualDragLineDom.classList.contains('cherry-drag--show')) {
// 增加蒙层防止选中editor或previewer内容
_this.options.virtualDragLineDom.classList.add('cherry-drag--show');
_this.options.editorMaskDom.classList.add('cherry-editor-mask--show');
_this.options.previewerMaskDom.classList.add('cherry-previewer-mask--show');
_this.options.previewerDom.classList.add('no-select');
_this.editor.options.editorDom.classList.add('no-select'); // 绑定事件
addEvent(document, 'mousemove', dragLineMouseMove, false);
addEvent(document, 'mouseup', dragLineMouseUp, false);
}
return false;
};
addEvent(this.options.virtualDragLineDom, 'mousedown', dragLineMouseDown, false);
addEvent(window, 'resize', bind$5(_context5 = this.syncVirtualLayoutFromReal).call(_context5, this), false);
this.setRealLayout();
}
}, {
key: "bindScroll",
value: function bindScroll() {
var _this2 = this;
var domContainer = this.getDomContainer();
onScroll = function onScroll() {
if (_this2.applyingDomChanges) {
// Logger.log(new Date(), 'sync scroll locked');
return;
}
if (_this2.disableScrollListener) {
_this2.disableScrollListener = false;
return;
}
if (domContainer.scrollTop <= 0) {
_this2.editor.scrollToLineNum(0, 0, 1);
return;
} // 判定预览区域是否滚动到底部的逻辑增加10px的冗余
if (domContainer.scrollTop + domContainer.offsetHeight + 10 > domContainer.scrollHeight) {
_this2.editor.scrollToLineNum(null);
return;
} // 获取预览容器基准坐标
var basePoint = domContainer.getBoundingClientRect(); // 观察点坐标,取容器中轴线
var watchPoint = {
x: basePoint.left + basePoint.width / 2,
y: basePoint.top + 1
}; // 获取观察点处的DOM
var targetElements = elementsFromPoint(watchPoint.x, watchPoint.y);
var targetElement;
for (var i = 0; i < targetElements.length; i++) {
if (domContainer.contains(targetElements[i])) {
targetElement = targetElements[i];
break;
}
}
if (!targetElement || targetElement === domContainer) {
return;
} // 获取观察点处最近的markdown元素
var mdElement = targetElement.closest('[data-sign]'); // 由于新增脚注内部容器也有可能存在data-sign所以需要循环往父级找
while (mdElement && mdElement.parentElement && mdElement.parentElement !== domContainer) {
mdElement = mdElement.parentElement.closest('[data-sign]');
}
if (!mdElement) {
return;
} // 计算当前焦点容器的所在行数
var lines = 0;
var element = mdElement;
while (element) {
lines += +element.getAttribute('data-lines');
element = element.previousElementSibling; // 取上一个兄弟节点直到为null
} // markdown元素存在margingetBoundingRect不能获取到margin
var mdElementStyle = getComputedStyle(mdElement);
var marginTop = _parseFloat$2(mdElementStyle.marginTop);
var marginBottom = _parseFloat$2(mdElementStyle.marginBottom); // markdown元素基于当前页面的矩形模型
var mdRect = mdElement.getBoundingClientRect();
var mdActualHeight = mdRect.height + marginTop + marginBottom; // (mdRect.y - marginTop)为顶部触达区域basePoint.y为预览区域的顶部故可视范围应减去预览区域的偏移
var mdOffsetTop = mdRect.y - marginTop - basePoint.y;
var lineNum = +mdElement.getAttribute('data-lines'); // 当前markdown元素所占行数
var percent = 100 * Math.abs(mdOffsetTop) / mdActualHeight / 100; // console.log('destLine:', lines, percent,
// mdRect.height + marginTop + marginBottom, mdOffsetTop, mdElement);
// if(mdOffsetTop < 0) {
return _this2.editor.scrollToLineNum(lines - lineNum, lineNum, percent); // }
// return this.editor.scrollToLineNum(lines - lineNum, 0, 0);
};
addEvent(domContainer, 'scroll', onScroll, false);
addEvent(domContainer, 'wheel', function () {
// 鼠标滚轮滚动时,强制监听滚动事件
_this2.disableScrollListener = false; // 打断滚动动画
cancelAnimationFrame(_this2.animation.timer);
_this2.animation.timer = 0;
}, false);
}
}, {
key: "removeScroll",
value: function removeScroll() {
var domContainer = this.getDomContainer();
removeEvent(domContainer, 'scroll', onScroll, false);
}
}, {
key: "$html2H",
value: function $html2H(dom) {
if (typeof dom === 'undefined') {
return h_1('span', {}, []);
}
if (!dom.tagName) {
return dom.textContent;
}
var tagName = dom.tagName; // skip all children if data-cm-atomic attribute is set
var isAtomic = 'true' === dom.getAttribute('data-cm-atomic');
var myAttrs = this.$getAttrsForH(dom.attributes);
var children = [];
if (!isAtomic && dom.childNodes && dom.childNodes.length > 0) {
for (var i = 0; i < dom.childNodes.length; i++) {
children.push(this.$html2H(dom.childNodes[i]));
}
}
return h_1(tagName, myAttrs, children);
}
}, {
key: "$getAttrsForH",
value: function $getAttrsForH(obj) {
if (!obj) {
return {};
}
var ret = {
dataset: {}
};
for (var i = 0; i < obj.length; i++) {
var name = obj[i].name;
var value = obj[i].value;
if (/^(width|height)$/i.test(name)) {
if (isNaN(value)) {
var _context6;
ret.style = ret.style ? ret.style : [];
ret.style.push(concat$5(_context6 = "".concat(name, ":")).call(_context6, value));
continue;
}
}
if (/^(class|id|href|rel|target|src|title|controls|align|width|height|style|open)$/i.test(name)) {
name = name === 'class' ? 'className' : name;
if (name === 'style') {
ret.style = ret.style ? ret.style : [];
ret.style.push(value);
} else if (name === 'open') {
// 只要有open这个属性就一定是true
ret[name] = true;
} else {
ret[name] = value;
}
} else {
// jsDom属性里面rowspan的S要大写,否则应用到html的dom节点会变成data-rowspan
// https://stackoverflow.com/q/29774686
if ('colspan' === name) {
name = 'colSpan';
} else if ('rowspan' === name) {
name = 'rowSpan';
}
if (/^data-/i.test(name)) {
name = name.replace(/^data-/i, '');
} else {
ret[name] = value;
}
ret.dataset[name] = value;
}
}
if (ret.style) {
ret.style = {
cssText: ret.style.join(';')
}; // see virtual-dom implementation
}
return ret;
}
}, {
key: "$updateDom",
value: function $updateDom(newDom, oldDom) {
var diff = diff_1$1(this.$html2H(oldDom), this.$html2H(newDom));
return patch_1$1(oldDom, diff);
}
}, {
key: "$testChild",
value: function $testChild(dom) {
if (!dom.parentNode) {
return true;
}
if (dom.parentNode.classList.contains('cherry-previewer')) {
return true;
}
if (dom.parentNode.getAttribute('data-sign')) {
return false;
}
return this.$testChild(dom.parentNode);
}
}, {
key: "_testMaxIndex",
value: function _testMaxIndex(index, arr) {
if (!arr) {
return false;
}
for (var i = 0; i < arr.length; i++) {
if (index <= arr[i]) {
return true;
}
}
return false;
}
}, {
key: "$getSignData",
value: function $getSignData(dom) {
var list = dom.querySelectorAll('[data-sign]');
var ret = {
list: [],
signs: {}
};
for (var i = 0; i < list.length; i++) {
if (!this.$testChild(list[i])) {
continue;
}
var sign = list[i].getAttribute('data-sign');
ret.list.push({
sign: sign,
dom: list[i]
});
if (!ret.signs[sign]) {
ret.signs[sign] = [];
}
ret.signs[sign].push(i);
}
return ret;
}
}, {
key: "_hasNewSign",
value: function _hasNewSign(list, sign, signIndex) {
if (list.length > 0) {
var resSign;
forEach$3(list).call(list, function (listItem, i) {
var _context7;
// hash精度校准
if (slice$7(_context7 = listItem.sign).call(_context7, 0, 12) === slice$7(sign).call(sign, 0, 12) && i > signIndex) {
resSign = {
index: i > signIndex ? i : signIndex,
sign: sign
};
}
});
return resSign;
}
return false;
}
}, {
key: "$dealWithMyersDiffResult",
value: function $dealWithMyersDiffResult(result, oldContent, newContent, domContainer) {
var _this3 = this;
forEach$3(result).call(result, function (change) {
if (newContent[change.newIndex].dom) {
// 把已经加载过的图片的data-src变成src
newContent[change.newIndex].dom.innerHTML = _this3.lazyLoadImg.changeLoadedDataSrc2Src(newContent[change.newIndex].dom.innerHTML);
}
switch (change.type) {
case 'delete':
domContainer.removeChild(oldContent[change.oldIndex].dom);
break;
case 'insert':
if (oldContent[change.oldIndex]) {
domContainer.insertBefore(newContent[change.newIndex].dom, oldContent[change.oldIndex].dom);
} else {
domContainer.appendChild(newContent[change.newIndex].dom);
}
break;
case 'update':
try {
if (newContent[change.newIndex].dom.querySelector('svg')) {
throw new Error(); // SVG暂不使用patch更新
}
_this3.$updateDom(newContent[change.newIndex].dom, oldContent[change.oldIndex].dom);
} catch (e) {
domContainer.insertBefore(newContent[change.newIndex].dom, oldContent[change.oldIndex].dom);
domContainer.removeChild(oldContent[change.oldIndex].dom);
}
}
});
}
}, {
key: "$dealUpdate",
value: function $dealUpdate(domContainer, oldHtmlList, newHtmlList) {
if (newHtmlList.list !== oldHtmlList.list) {
if (newHtmlList.list.length && oldHtmlList.list.length) {
var myersDiff = new MyersDiff(newHtmlList.list, oldHtmlList.list, function (obj, index) {
return obj[index].sign;
});
var res = myersDiff.doDiff();
// Logger.log(res);
this.$dealWithMyersDiffResult(res, oldHtmlList.list, newHtmlList.list, domContainer);
} else if (newHtmlList.list.length && !oldHtmlList.list.length) {
var _context8;
// 全新增
// Logger.log('add all');
forEach$3(_context8 = newHtmlList.list).call(_context8, function (piece) {
domContainer.appendChild(piece.dom);
});
} else if (!newHtmlList.list.length && oldHtmlList.list.length) {
var _context9;
// 全删除
// Logger.log('delete all');
forEach$3(_context9 = oldHtmlList.list).call(_context9, function (piece) {
domContainer.removeChild(piece.dom);
});
}
}
}
/**
* 强制重新渲染预览区域
*/
}, {
key: "refresh",
value: function refresh(html) {
var domContainer = this.getDomContainer();
domContainer.innerHTML = html;
}
}, {
key: "update",
value: function update(html) {
var _this4 = this;
// 更新时保留图片懒加载逻辑
var newHtml = this.lazyLoadImg.changeSrc2DataSrc(html);
if (!this.isPreviewerHidden()) {
// 标记当前正在更新预览区域,锁定同步滚动功能
window.clearTimeout(this.syncScrollLockTimer);
this.applyingDomChanges = true; // 预览区未隐藏时,直接更新
var tmpDiv = document.createElement('div');
var domContainer = this.getDomContainer();
tmpDiv.innerHTML = newHtml;
var newHtmlList = this.$getSignData(tmpDiv);
var oldHtmlList = this.$getSignData(domContainer);
try {
this.$dealUpdate(domContainer, oldHtmlList, newHtmlList);
this.afterUpdate();
} finally {
// 延时释放同步滚动功能在DOM更新完成后执行
this.syncScrollLockTimer = setTimeout$3(function () {
_this4.applyingDomChanges = false;
}, 50);
}
} else {
// 预览区隐藏时,先缓存起来,等到预览区打开再一次性更新
this.doHtmlCache(newHtml);
}
}
}, {
key: "$dealEditAndPreviewOnly",
value: function $dealEditAndPreviewOnly() {
var _this5 = this;
var isEditOnly = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
var fullEditorLayout = {
editorPercentage: '0%',
previewerPercentage: '100%'
};
if (isEditOnly) {
fullEditorLayout = {
editorPercentage: '100%',
previewerPercentage: '0%'
};
}
var editorWidth = this.editor.options.editorDom.getBoundingClientRect().width;
var layout = this.calculateRealLayout(editorWidth);
this.options.previewerCache.layout = layout;
this.setRealLayout(fullEditorLayout.editorPercentage, fullEditorLayout.previewerPercentage);
this.options.virtualDragLineDom.classList.add('cherry-drag--hidden');
var previewerDom = this.options.previewerDom;
var editorDom = this.editor.options.editorDom;
if (isEditOnly) {
previewerDom.classList.add('cherry-previewer--hidden');
editorDom.classList.add('cherry-editor--full');
previewerDom.classList.remove('cherry-preview--full');
editorDom.classList.remove('cherry-editor--hidden');
} else {
previewerDom.classList.add('cherry-preview--full');
editorDom.classList.add('cherry-editor--hidden');
previewerDom.classList.remove('cherry-previewer--hidden');
editorDom.classList.remove('cherry-editor--full');
}
setTimeout$3(function () {
return _this5.editor.editor.refresh();
}, 0);
}
}, {
key: "previewOnly",
value: function previewOnly() {
this.$dealEditAndPreviewOnly(false);
if (this.options.previewerCache.htmlChanged) {
this.update(this.options.previewerCache.html);
}
this.cleanHtmlCache();
Event$1.emit(this.instanceId, Event$1.Events.previewerOpen);
Event$1.emit(this.instanceId, Event$1.Events.editorClose);
}
}, {
key: "editOnly",
value: function editOnly() {
this.$dealEditAndPreviewOnly(true);
this.cleanHtmlCache();
Event$1.emit(this.instanceId, Event$1.Events.previewerClose);
Event$1.emit(this.instanceId, Event$1.Events.editorOpen);
}
}, {
key: "recoverPreviewer",
value: function recoverPreviewer() {
var _this6 = this;
this.options.previewerDom.classList.remove('cherry-previewer--hidden');
this.options.virtualDragLineDom.classList.remove('cherry-drag--hidden');
this.editor.options.editorDom.classList.remove('cherry-editor--full'); // 恢复现场
if (this.options.previewerCache.layout !== {}) {
var layout = this.options.previewerCache.layout;
this.setRealLayout(layout.editorPercentage, layout.previewerPercentage);
}
if (this.options.previewerCache.htmlChanged) {
this.update(this.options.previewerCache.html);
}
this.cleanHtmlCache();
Event$1.emit(this.instanceId, Event$1.Events.previewerOpen);
Event$1.emit(this.instanceId, Event$1.Events.editorOpen);
setTimeout$3(function () {
return _this6.editor.editor.refresh();
}, 0);
}
}, {
key: "doHtmlCache",
value: function doHtmlCache(html) {
this.options.previewerCache.html = html;
this.options.previewerCache.htmlChanged = true;
}
}, {
key: "cleanHtmlCache",
value: function cleanHtmlCache() {
this.options.previewerCache.html = '';
this.options.previewerCache.htmlChanged = false;
this.options.previewerCache.layout = {};
}
}, {
key: "afterUpdate",
value: function afterUpdate() {
var _context10;
map$3(_context10 = this.options.afterUpdateCallBack).call(_context10, function (fn) {
return fn();
});
if (this.highlightLineNum === undefined) {
this.highlightLineNum = 0;
}
this.highlightLine(this.highlightLineNum);
}
}, {
key: "registerAfterUpdate",
value: function registerAfterUpdate(fn) {
if (isArray$8(fn)) {
var _context11;
this.options.afterUpdateCallBack = concat$5(_context11 = this.options.afterUpdateCallBack).call(_context11, fn);
} else if (!fn) {
throw new Error('[markdown error]: Previewer registerAfterUpdate params are undefined');
} else {
this.options.afterUpdateCallBack.push(fn);
}
}
/**
* 根据行号计算出top值
* @param {Number} lineNum
* @param {Number} linePercent
* @return {Number} top
*/
}, {
key: "$getTopByLineNum",
value: function $getTopByLineNum(lineNum) {
var linePercent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var domContainer = this.getDomContainer();
if (lineNum === null) {
return domContainer.scrollHeight;
}
var $lineNum = typeof lineNum === 'number' ? lineNum : _parseInt$2(lineNum, 10);
var doms =
/** @type {NodeListOf<HTMLElement>}*/
domContainer.querySelectorAll('[data-sign]');
var lines = 0;
var containerY = domContainer.offsetTop;
for (var index = 0; index < doms.length; index++) {
if (doms[index].parentNode !== domContainer) {
continue;
}
var blockLines = _parseInt$2(doms[index].getAttribute('data-lines'), 10);
if (lines + blockLines < $lineNum) {
lines += blockLines;
continue;
} else {
// 基础定位区块高度及offsetTop会受到block margin合并的影响
var _getBlockTopAndHeight = getBlockTopAndHeightWithMargin(doms[index]),
blockHeight = _getBlockTopAndHeight.height,
offsetTop = _getBlockTopAndHeight.offsetTop;
var blockY = offsetTop - containerY;
var scrollTo = blockY + blockHeight * linePercent; // 区块多于1行
if (blockLines > 1) {
// 高度百分比计算
// 该区块已经滚动过的行,不包括当前行,减一
var overScrolledLines = blockLines - Math.abs($lineNum - (lines + blockLines)) - 1;
var overScrolledHeight = overScrolledLines / blockLines * blockHeight; // 已经滚过的高度
var blockLineHeight = blockHeight / blockLines; // 该区块每一行的高度
// 应该滚动到的位置
scrollTo = blockY + overScrolledHeight + blockLineHeight * linePercent; // console.log('overscrolled:', overScrolledHeight, blockLineHeight, linePercent);
} // console.log('滚动编辑区域左侧应scroll to ', lineNum, '::',scrollTo);
return scrollTo;
}
} // 如果计算完预览区域所有的行号依然<左侧光标所在的行号,则预览区域直接滚到最低部
return domContainer.scrollHeight;
}
/**
* 高亮预览区域对应的行
* @param {Number} lineNum
*/
}, {
key: "highlightLine",
value: function highlightLine(lineNum) {
var _context12, _this$$cherry, _this$$cherry$status, _this$$cherry2, _this$$cherry2$status;
var domContainer = this.getDomContainer(); // 先取消所有行的高亮效果
forEach$3(_context12 = domContainer.querySelectorAll('.cherry-highlight-line')).call(_context12, function (element) {
element.classList.remove('cherry-highlight-line');
}); // 只有双栏模式下才需要高亮光标对应的预览区域
if (((_this$$cherry = this.$cherry) === null || _this$$cherry === void 0 ? void 0 : (_this$$cherry$status = _this$$cherry.status) === null || _this$$cherry$status === void 0 ? void 0 : _this$$cherry$status.previewer) !== 'show' || ((_this$$cherry2 = this.$cherry) === null || _this$$cherry2 === void 0 ? void 0 : (_this$$cherry2$status = _this$$cherry2.status) === null || _this$$cherry2$status === void 0 ? void 0 : _this$$cherry2$status.editor) !== 'show') {
return;
}
var doms =
/** @type {NodeListOf<HTMLElement>}*/
domContainer.querySelectorAll('[data-sign]');
var lines = 0;
for (var index = 0; index < doms.length; index++) {
if (doms[index].parentNode !== domContainer) {
continue;
}
var blockLines = _parseInt$2(doms[index].getAttribute('data-lines'), 10);
if (lines + blockLines < lineNum) {
lines += blockLines;
continue;
} else {
this.highlightLineNum = lineNum;
doms[index].classList.add('cherry-highlight-line');
return;
}
}
}
/**
* 滚动到对应行号位置并加上偏移量
* @param {Number} lineNum
* @param {Number} offset
*/
}, {
key: "scrollToLineNumWithOffset",
value: function scrollToLineNumWithOffset(lineNum, offset) {
var top = this.$getTopByLineNum(lineNum) - offset;
this.$scrollAnimation(top);
this.highlightLine(lineNum);
}
/**
* 实现滚动动画
* @param { Number } targetY 目标位置
*/
}, {
key: "$scrollAnimation",
value: function $scrollAnimation(targetY) {
var _this7 = this;
this.animation.destinationTop = targetY;
if (this.animation.timer) {
return;
}
var animationHandler = function animationHandler() {
var dom = _this7.getDomContainer();
var currentTop = dom.scrollTop;
var delta = _this7.animation.destinationTop - currentTop; // 100毫秒内完成动画
var move = Math.ceil(Math.min(Math.abs(delta), Math.max(1, Math.abs(delta) / (100 / 16.7))));
if (delta === 0 || currentTop >= dom.scrollHeight || move > Math.abs(delta)) {
cancelAnimationFrame(_this7.animation.timer);
_this7.animation.timer = 0;
return;
}
_this7.disableScrollListener = true;
_this7.getDomContainer().scrollTo(null, currentTop + delta / Math.abs(delta) * move);
_this7.animation.timer = requestAnimationFrame(animationHandler);
};
this.animation.timer = requestAnimationFrame(animationHandler);
}
}, {
key: "scrollToLineNum",
value: function scrollToLineNum(lineNum, linePercent) {
var top = this.$getTopByLineNum(lineNum, linePercent);
this.$scrollAnimation(top);
}
}, {
key: "onMouseDown",
value: function onMouseDown() {
var _this8 = this;
addEvent(this.getDomContainer(), 'mousedown', function () {
setTimeout$3(function () {
Event$1.emit(_this8.instanceId, Event$1.Events.cleanAllSubMenus);
});
});
}
/**
* 导出预览区域内容
* @public
* @param {String} type 'pdf'导出成pdf文件; 'img':导出成图片
* @param {String |Function} fileName 导出文件名
*/
}, {
key: "export",
value: function _export() {
var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'pdf';
var fileName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
// console.log(this.options);
var name;
if (!fileName) {
var parser = new DOMParser();
var domTree = parser.parseFromString(this.getValue(), 'text/html');
var firstNodeText = findNonEmptyNode(domTree);
firstNodeText ? name = firstNodeText : name = 'cherry';
} // if (typeof fileName === 'function') {
// name = fileName();
// } else {
// name = fileName;
// }
if (type === 'pdf') {
exportPDF(this.getDomContainer(), name);
} else if (type === 'screenShot') {
exportScreenShot(this.getDomContainer(), name);
} else if (type === 'markdown') {
exportMarkdownFile(this.$cherry.getMarkdown(), name);
} else if (type === 'html') {
exportHTMLFile(this.getValue(), name);
}
}
}]);
return Previewer;
}();
// Kludges for bugs and behavior differences that can't be feature
// detected are enabled based on userAgent etc sniffing.
var userAgent = navigator.userAgent;
var platform = navigator.platform;
var gecko = /gecko\/\d/i.test(userAgent);
var ie_upto10 = /MSIE \d/.test(userAgent);
var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
var edge = /Edge\/(\d+)/.exec(userAgent);
var ie = ie_upto10 || ie_11up || edge;
var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
var webkit = !edge && /WebKit\//.test(userAgent);
var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
var chrome = !edge && /Chrome\//.test(userAgent);
var presto = /Opera\//.test(userAgent);
var safari = /Apple Computer/.test(navigator.vendor);
var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
var phantom = /PhantomJS/.test(userAgent);
var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
var android = /Android/.test(userAgent); // This is woefully incomplete. Suggestions for alternative methods welcome.
var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
var mac = ios || /Mac/.test(platform);
var chromeOS = /\bCrOS\b/.test(userAgent);
var windows = /win/i.test(platform);
var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
if (presto_version) presto_version = Number(presto_version[1]);
if (presto_version && presto_version >= 15) {
presto = false;
webkit = true;
} // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
/**
* @typedef {Object} SubMenuConfigItem
* @property {string} name - 子菜单项名称
* @property {string=} iconName - 子菜单项图标名称
* @property {function} onclick - 子菜单项点击事件
*/
/**
*
* @param {HTMLElement} targetDom
* @param {'absolute' | 'fixed' | 'sidebar'} [positionModel = 'absolute']
* @returns {Pick<DOMRect, 'left' | 'top' | 'width' | 'height'>}
*/
function getPosition(targetDom) {
var positionModel = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'absolute';
var pos = targetDom.getBoundingClientRect();
if (positionModel === 'fixed') {
return pos;
} // 侧边栏按钮做个特殊处理
if (positionModel === 'sidebar') {
var parent = MenuBase.getTargetParentByButton(targetDom);
return {
left: parent.offsetLeft - 130 + pos.width,
top: targetDom.offsetTop + pos.height / 2,
width: pos.width,
height: pos.height
};
}
return {
left: targetDom.offsetLeft,
top: targetDom.offsetTop,
width: pos.width,
height: pos.height
};
}
/**
* @typedef {import('@/Editor').default} Editor
*/
/**
* @class MenuBase
*/
var MenuBase = /*#__PURE__*/function () {
/**
* @deprecated
* @type {MenuBase['fire']}
*/
/**
*
* @param {*} $cherry
*/
function MenuBase($cherry) {
_classCallCheck(this, MenuBase);
_defineProperty(this, "_onClick", void 0);
this.$cherry = $cherry;
this.bubbleMenu = false;
this.subMenu = null; // 子菜单实例
this.name = ''; // 菜单项Name
this.editor = $cherry.editor; // markdown实例
this.locale = $cherry.locale;
this.dom = null;
this.updateMarkdown = true; // 是否更新markdown原文
/** @type {SubMenuConfigItem[]} */
this.subMenuConfig = []; // 子菜单配置
this.noIcon = false; // 是否不显示图标
this.cacheOnce = false; // 是否保存一次点击事件生成的内容
/**
* 子菜单的定位方式
* @property
* @type {'absolute' | 'fixed' | 'sidebar'}
*/
this.positionModel = 'absolute'; // eslint-disable-next-line no-underscore-dangle
if (typeof this._onClick === 'function') {
Logger.warn('`MenuBase._onClick` is deprecated. Override `fire` instead'); // eslint-disable-next-line no-underscore-dangle
this.fire = this._onClick;
}
}
_createClass(MenuBase, [{
key: "getSubMenuConfig",
value: function getSubMenuConfig() {
return this.subMenuConfig;
}
/**
* 设置菜单
* @param {string} name 菜单名称
* @param {string} [iconName] 菜单图标名
*/
}, {
key: "setName",
value: function setName(name, iconName) {
this.name = name;
this.iconName = iconName;
}
}, {
key: "setId",
value: function setId(id) {
this.id = id;
}
/**
* 设置一个一次性缓存
* 使用场景:
* 当需要异步操作是,比如上传视频、选择字体颜色、通过棋盘插入表格等
* 实现原理:
* 1、第一次点击按钮时触发fire()方法触发选择文件、选择颜色、选择棋盘格的操作。此时onClick()不返回任何数据。
* 2、当异步操作完成后如提交了文件、选择了颜色等调用本方法setCacheOnce实现缓存最后调用fire()方法
* 3、当fire()方法再次调用onClick()方法时onClick()方法会返回缓存的数据getAndCleanCacheOnce
*
* 这么设计的原因:
* 1、可以复用MenuBase的相关方法
* 2、避免异步操作直接与codemirror交互
* @param {*} info
*/
}, {
key: "setCacheOnce",
value: function setCacheOnce(info) {
this.cacheOnce = info;
}
}, {
key: "getAndCleanCacheOnce",
value: function getAndCleanCacheOnce() {
this.updateMarkdown = true;
var ret = this.cacheOnce;
this.cacheOnce = false;
return ret;
}
}, {
key: "hasCacheOnce",
value: function hasCacheOnce() {
return this.cacheOnce !== false;
}
/**
* 创建一个一级菜单
* @param {boolean} asSubMenu 是否以子菜单的形式创建
*/
}, {
key: "createBtn",
value: function createBtn() {
var asSubMenu = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var classNames = asSubMenu ? 'cherry-dropdown-item' : "cherry-toolbar-button cherry-toolbar-".concat(this.iconName ? this.iconName : this.name);
var span = createElement('span', classNames, {
title: this.locale[this.name] || escapeHTMLSpecialCharOnce(this.name)
}); // 如果有图标,则添加图标
if (this.iconName && !this.noIcon) {
var icon = createElement('i', "ch-icon ch-icon-".concat(this.iconName));
span.appendChild(icon);
} // 二级菜单强制显示文字,没有图标的按钮也显示文字
if (this.id) {
span.id = this.id;
}
if (asSubMenu || this.noIcon) {
span.innerHTML += this.locale[this.name] || escapeHTMLSpecialCharOnce(this.name);
} // 只有一级菜单才保存dom且只保存一次
if (!asSubMenu && !this.dom) {
this.dom = span;
}
return span;
}
}, {
key: "createSubBtnByConfig",
value: function createSubBtnByConfig(config) {
var name = config.name,
iconName = config.iconName,
id = config.id,
onclick = config.onclick;
var span = createElement('span', 'cherry-dropdown-item', {
title: this.locale[name] || escapeHTMLSpecialCharOnce(name)
});
if (iconName) {
var icon = createElement('i', "ch-icon ch-icon-".concat(iconName));
span.appendChild(icon);
}
if (id) {
span.id = id;
}
span.innerHTML += this.locale[name] || escapeHTMLSpecialCharOnce(name);
span.addEventListener('click', onclick, false);
return span;
}
/**
* 处理菜单项点击事件
* @param {MouseEvent | KeyboardEvent | undefined} [event] 点击事件
* @returns {void}
*/
}, {
key: "fire",
value: function fire(event) {
var _this = this;
var shortKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
event === null || event === void 0 ? void 0 : event.stopPropagation();
if (typeof this.onClick === 'function') {
var selections = this.editor.editor.getSelections(); // 判断是不是多选
this.isSelections = selections.length > 1; // 当onClick返回null、undefined、false时维持原样
var ret = map$3(selections).call(selections, function (selection, index, srcArray) {
return _this.onClick(selection, shortKey, event) || srcArray[index];
});
if (!this.bubbleMenu && this.updateMarkdown) {
// 非下拉菜单按钮保留selection
this.editor.editor.replaceSelections(ret, 'around');
this.editor.editor.focus();
this.$afterClick();
}
}
}
/**
* 获取当前选择区域的range
*/
}, {
key: "$getSelectionRange",
value: function $getSelectionRange() {
var _this$editor$editor$l = this.editor.editor.listSelections()[0],
anchor = _this$editor$editor$l.anchor,
head = _this$editor$editor$l.head; // 如果begin在end的后面
if (anchor.line === head.line && anchor.ch > head.ch || anchor.line > head.line) {
return {
begin: head,
end: anchor
};
}
return {
begin: anchor,
end: head
};
}
/**
* 注册点击事件渲染后的回调函数
* @param {function} cb
*/
}, {
key: "registerAfterClickCb",
value: function registerAfterClickCb(cb) {
this.afterClickCb = cb;
}
/**
* 点击事件渲染后的回调函数
*/
}, {
key: "$afterClick",
value: function $afterClick() {
if (typeof this.afterClickCb === 'function' && !this.isSelections) {
this.afterClickCb();
this.afterClickCb = null;
}
}
/**
* 选中除了前后语法后的内容
* @param {String} lessBefore
* @param {String} lessAfter
*/
}, {
key: "setLessSelection",
value: function setLessSelection(lessBefore, lessAfter) {
var _lessBefore$match, _lessBefore$match2, _lessAfter$match, _lessAfter$match2;
var cm = this.editor.editor;
var _this$$getSelectionRa = this.$getSelectionRange(),
begin = _this$$getSelectionRa.begin,
end = _this$$getSelectionRa.end;
var newBeginLine = ((_lessBefore$match = lessBefore.match(/\n/g)) === null || _lessBefore$match === void 0 ? void 0 : _lessBefore$match.length) > 0 ? begin.line + lessBefore.match(/\n/g).length : begin.line;
var newBeginCh = ((_lessBefore$match2 = lessBefore.match(/\n/g)) === null || _lessBefore$match2 === void 0 ? void 0 : _lessBefore$match2.length) > 0 ? lessBefore.replace(/^[\s\S]*?\n([^\n]*)$/, '$1').length : begin.ch + lessBefore.length;
var newBegin = {
line: newBeginLine,
ch: newBeginCh
};
var newEndLine = ((_lessAfter$match = lessAfter.match(/\n/g)) === null || _lessAfter$match === void 0 ? void 0 : _lessAfter$match.length) > 0 ? end.line - lessAfter.match(/\n/g).length : end.line;
var newEndCh = ((_lessAfter$match2 = lessAfter.match(/\n/g)) === null || _lessAfter$match2 === void 0 ? void 0 : _lessAfter$match2.length) > 0 ? cm.getLine(newEndLine).length : end.ch - lessAfter.length;
var newEnd = {
line: newEndLine,
ch: newEndCh
};
cm.setSelection(newBegin, newEnd);
}
/**
* 基于当前已选择区域,获取更多的选择区
* @param {string} [appendBefore] 选择区前面追加的内容
* @param {string} [appendAfter] 选择区后面追加的内容
* @param {function} [cb] 回调函数如果返回false则恢复原来的选取
*/
}, {
key: "getMoreSelection",
value: function getMoreSelection(appendBefore, appendAfter, cb) {
var cm = this.editor.editor;
var _this$$getSelectionRa2 = this.$getSelectionRange(),
begin = _this$$getSelectionRa2.begin,
end = _this$$getSelectionRa2.end;
var newBeginCh = // 如果只包含换行则起始位置一定是0
/\n/.test(appendBefore) ? 0 : begin.ch - appendBefore.length;
newBeginCh = newBeginCh < 0 ? 0 : newBeginCh;
var newBeginLine = /\n/.test(appendBefore) ? begin.line - appendBefore.match(/\n/g).length : begin.line;
newBeginLine = newBeginLine < 0 ? 0 : newBeginLine;
var newBegin = {
line: newBeginLine,
ch: newBeginCh
};
var newEndLine = end.line;
var newEndCh = end.ch;
if (/\n/.test(appendAfter)) {
var _cm$getLine;
newEndLine = end.line + appendAfter.match(/\n/g).length;
newEndCh = (_cm$getLine = cm.getLine(newEndLine)) === null || _cm$getLine === void 0 ? void 0 : _cm$getLine.length;
} else {
newEndCh = cm.getLine(end.line).length < end.ch + appendAfter.length ? cm.getLine(end.line).length : end.ch + appendAfter.length;
}
var newEnd = {
line: newEndLine,
ch: newEndCh
};
cm.setSelection(newBegin, newEnd);
if (cb() === false) {
cm.setSelection(begin, end);
}
}
/**
* 获取用户选中的文本内容,如果没有选中文本,则返回光标所在的位置的内容
* @param {string} selection 当前选中的文本内容
* @param {string} type 'line': 当没有选择文本时,获取光标所在行的内容; 'word': 当没有选择文本时,获取光标所在单词的内容
* @param {boolean} focus true强行选中光标处的内容否则只获取选中的内容
* @returns {string}
*/
}, {
key: "getSelection",
value: function getSelection(selection) {
var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'word';
var focus = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var cm = this.editor.editor; // 多光标模式下不做处理
if (this.isSelections) {
return selection;
}
if (selection && !focus) {
return selection;
} // 获取光标所在行的内容,同时选中所在行
if (type === 'line') {
var _this$$getSelectionRa3 = this.$getSelectionRange(),
begin = _this$$getSelectionRa3.begin,
end = _this$$getSelectionRa3.end;
cm.setSelection({
line: begin.line,
ch: 0
}, {
line: end.line,
ch: cm.getLine(end.line).length
});
return cm.getSelection();
} // 获取光标所在单词的内容,同时选中所在单词
if (type === 'word') {
var _cm$findWordAt = cm.findWordAt(cm.getCursor()),
_begin = _cm$findWordAt.anchor,
_end = _cm$findWordAt.head;
cm.setSelection(_begin, _end);
return cm.getSelection();
}
}
/**
* 反转子菜单点击事件参数顺序
* @deprecated
*/
}, {
key: "bindSubClick",
value: function bindSubClick(shortcut, selection) {
return this.fire(null, shortcut);
}
}, {
key: "onClick",
value: function onClick(selection, shortcut, callback) {
return selection;
}
}, {
key: "shortcutKeys",
get: function get() {
return [];
}
/**
* 获取当前菜单的位置
*/
}, {
key: "getMenuPosition",
value: function getMenuPosition() {
var parent = MenuBase.getTargetParentByButton(this.dom);
var isFromSidebar = /cherry-sidebar/.test(parent.className);
if (/cherry-bubble/.test(parent.className) || /cherry-floatmenu/.test(parent.className)) {
this.positionModel = 'fixed';
} else if (isFromSidebar) {
this.positionModel = 'sidebar';
} else {
this.positionModel = 'absolute';
}
return getPosition(this.dom, this.positionModel);
}
/**
* 根据按钮获取按钮的父元素这里父元素要绕过toolbar-(left|right)那一层
* @param {HTMLElement} dom 按钮元素
* @returns {HTMLElement} 父元素
*/
}], [{
key: "getTargetParentByButton",
value: function getTargetParentByButton(dom) {
var parent = dom.parentElement;
if (/toolbar-(left|right)/.test(parent.className)) {
parent = parent.parentElement;
}
return parent;
}
}]);
return MenuBase;
}();
function _createSuper$z(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$z(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$z() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 加粗按钮
*/
var Bold = /*#__PURE__*/function (_MenuBase) {
_inherits(Bold, _MenuBase);
var _super = _createSuper$z(Bold);
function Bold($cherry) {
var _this;
_classCallCheck(this, Bold);
_this = _super.call(this, $cherry);
_this.setName('bold', 'bold');
return _this;
}
/**
* 是不是包含加粗语法
* @param {String} selection
* @returns {Boolean}
*/
_createClass(Bold, [{
key: "$testIsBold",
value: function $testIsBold(selection) {
return /^\s*(\*\*|__)[\s\S]+(\1)/.test(selection);
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @param {string} shortKey 快捷键参数,本函数不处理这个参数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
}, {
key: "onClick",
value: function onClick(selection) {
var _this2 = this;
var $selection = this.getSelection(selection) || this.locale.bold; // 如果是单选,并且选中内容的开始结束内没有加粗语法,则扩大选中范围
if (!this.isSelections && !this.$testIsBold($selection)) {
this.getMoreSelection('**', '**', function () {
var newSelection = _this2.editor.editor.getSelection();
var isBold = _this2.$testIsBold(newSelection);
if (isBold) {
$selection = newSelection;
}
return isBold;
});
} // 如果选中的文本中已经有加粗语法了,则去掉加粗语法
if (this.$testIsBold($selection)) {
return $selection.replace(/(^)(\s*)(\*\*|__)([^\n]+)(\3)(\s*)($)/gm, '$1$4$7');
}
this.registerAfterClickCb(function () {
_this2.setLessSelection('**', '**');
});
return $selection.replace(/(^)([^\n]+)($)/gm, '$1**$2**$3');
}
/**
* 声明绑定的快捷键快捷键触发onClick
*/
}, {
key: "shortcutKeys",
get: function get() {
return ['Ctrl-b'];
}
}]);
return Bold;
}(MenuBase);
function _createSuper$A(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$A(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$A() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入斜体的按钮
*/
var Italic = /*#__PURE__*/function (_MenuBase) {
_inherits(Italic, _MenuBase);
var _super = _createSuper$A(Italic);
function Italic($cherry) {
var _this;
_classCallCheck(this, Italic);
_this = _super.call(this, $cherry);
_this.setName('italic', 'italic');
return _this;
}
/**
* 是不是包含加粗语法
* @param {String} selection
* @returns {Boolean}
*/
_createClass(Italic, [{
key: "$testIsItalic",
value: function $testIsItalic(selection) {
return /^\s*(\*|_)[\s\S]+(\1)/.test(selection);
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @param {string} shortKey 快捷键参数,本函数不处理这个参数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
}, {
key: "onClick",
value: function onClick(selection) {
var _this2 = this;
var $selection = this.getSelection(selection) || this.locale.italic; // 如果是单选,并且选中内容的开始结束内没有加粗语法,则扩大选中范围
if (!this.isSelections && !this.$testIsItalic($selection)) {
this.getMoreSelection('*', '*', function () {
var newSelection = _this2.editor.editor.getSelection();
var isItalic = _this2.$testIsItalic(newSelection);
if (isItalic) {
$selection = newSelection;
}
return isItalic;
});
}
if (this.$testIsItalic($selection)) {
return $selection.replace(/(^)(\s*)(\*|_)([^\n]+)(\3)(\s*)($)/gm, '$1$4$7');
}
this.registerAfterClickCb(function () {
_this2.setLessSelection('*', '*');
});
return $selection.replace(/(^)([^\n]+)($)/gm, '$1*$2*$3');
}
/**
* 获得监听的快捷键
* 在windows下是Ctrl+i在mac下是cmd+i
*/
}, {
key: "shortcutKeys",
get: function get() {
return ['Ctrl-i'];
}
}]);
return Italic;
}(MenuBase);
function _createSuper$B(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$B(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$B() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 工具栏里的分割线,用来切分不同类型按钮的区域
* 一个实例中可以配置多个分割线
*/
var Split = /*#__PURE__*/function (_MenuBase) {
_inherits(Split, _MenuBase);
var _super = _createSuper$B(Split);
function Split($cherry) {
var _this;
_classCallCheck(this, Split);
_this = _super.call(this, $cherry);
_this.setName('split', '|');
return _this;
}
/**
* 重载创建按钮逻辑
* @returns {HTMLElement} 分割线标签
*/
_createClass(Split, [{
key: "createBtn",
value: function createBtn() {
var className = 'cherry-toolbar-button cherry-toolbar-split';
var i = document.createElement('i');
i.className = className;
return i;
}
}]);
return Split;
}(MenuBase);
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* 获取用户选中的文本内容,如果没有选中文本,则返回光标所在的位置的内容
* @param {Object} cm Codemirror实例
* @param {string} selection 当前选中的文本内容
* @param {string} type 'line': 当没有选择文本时,获取光标所在行的内容; 'word': 当没有选择文本时,获取光标所在单词的内容
* @param {boolean} focus true强行选中光标处的内容否则只获取选中的内容
* @returns {string}
*/
function getSelection(cm, selection) {
var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'word';
var focus = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
// 多光标模式下不做处理
if (cm.getSelections().length > 1) {
return selection;
}
if (selection && !focus) {
return selection;
} // 获取光标所在行的内容,同时选中所在行
if (type === 'line') {
var _cm$listSelections$ = cm.listSelections()[0],
anchor = _cm$listSelections$.anchor,
head = _cm$listSelections$.head; // 如果begin在end的后面
if (anchor.line === head.line && anchor.ch > head.ch || anchor.line > head.line) {
cm.setSelection({
line: head.line,
ch: 0
}, {
line: anchor.line,
ch: cm.getLine(anchor.line).length
});
} else {
cm.setSelection({
line: anchor.line,
ch: 0
}, {
line: head.line,
ch: cm.getLine(head.line).length
});
}
return cm.getSelection();
} // 获取光标所在单词的内容,同时选中所在单词
if (type === 'word') {
var _cm$findWordAt = cm.findWordAt(cm.getCursor()),
begin = _cm$findWordAt.anchor,
end = _cm$findWordAt.head;
cm.setSelection(begin, end);
return cm.getSelection();
}
}
function _createSuper$C(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$C(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$C() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 删除线的按钮
*/
var Strikethrough$1 = /*#__PURE__*/function (_MenuBase) {
_inherits(Strikethrough, _MenuBase);
var _super = _createSuper$C(Strikethrough);
function Strikethrough($cherry) {
var _this;
_classCallCheck(this, Strikethrough);
_this = _super.call(this, $cherry);
_this.setName('strikethrough', 'strike');
return _this;
}
_createClass(Strikethrough, [{
key: "$testIsStrike",
value: function $testIsStrike(selection) {
return /(~~)[\s\S]+(\1)/.test(selection);
}
/**
*
* @param {string} selection 被用户选中的文本内容
* @param {string} shortKey 快捷键参数,本函数不处理这个参数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
}, {
key: "onClick",
value: function onClick(selection) {
var _this$$cherry,
_this$$cherry$options,
_this$$cherry$options2,
_this$$cherry$options3,
_this$$cherry$options4,
_this2 = this,
_context;
var $selection = getSelection(this.editor.editor, selection) || this.locale.strikethrough; // @ts-ignore
var needWhitespace = (_this$$cherry = this.$cherry) === null || _this$$cherry === void 0 ? void 0 : (_this$$cherry$options = _this$$cherry.options) === null || _this$$cherry$options === void 0 ? void 0 : (_this$$cherry$options2 = _this$$cherry$options.engine) === null || _this$$cherry$options2 === void 0 ? void 0 : (_this$$cherry$options3 = _this$$cherry$options2.syntax) === null || _this$$cherry$options3 === void 0 ? void 0 : (_this$$cherry$options4 = _this$$cherry$options3.strikethrough) === null || _this$$cherry$options4 === void 0 ? void 0 : _this$$cherry$options4.needWhitespace;
var space = needWhitespace ? ' ' : ''; // 如果被选中的文本中包含删除线语法,则去掉删除线语法
if (!this.isSelections && !this.$testIsStrike($selection)) {
this.getMoreSelection("".concat(space, "~~"), "~~".concat(space), function () {
var newSelection = _this2.editor.editor.getSelection();
var isStrike = _this2.$testIsStrike(newSelection);
if (isStrike) {
$selection = newSelection;
}
return isStrike;
});
}
if (this.$testIsStrike($selection)) {
return selection.replace(/[\s]*(~~)([\s\S]+)(\1)[\s]*/g, '$2');
}
this.registerAfterClickCb(function () {
_this2.setLessSelection("".concat(space, "~~"), "~~".concat(space));
});
return $selection.replace(/(^)[\s]*([\s\S]+?)[\s]*($)/g, concat$5(_context = "$1".concat(space, "~~$2~~")).call(_context, space, "$3"));
}
}, {
key: "shortcutKeys",
get: function get() {
return ['Ctrl-d'];
}
}]);
return Strikethrough;
}(MenuBase);
function _createSuper$D(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$D(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$D() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 下标的按钮
**/
var Sub$1 = /*#__PURE__*/function (_MenuBase) {
_inherits(Sub, _MenuBase);
var _super = _createSuper$D(Sub);
function Sub($cherry) {
var _this;
_classCallCheck(this, Sub);
_this = _super.call(this, $cherry);
_this.setName('sub', 'sub');
return _this;
}
_createClass(Sub, [{
key: "$testIsSub",
value: function $testIsSub(selection) {
return /^\s*(\^\^)[\s\S]+(\1)/.test(selection);
}
/**
*
* @param {string} selection 被用户选中的文本内容
* @param {string} shortKey 快捷键参数,本函数不处理这个参数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
}, {
key: "onClick",
value: function onClick(selection) {
var _this2 = this;
var $selection = getSelection(this.editor.editor, selection) || this.locale.sub; // 如果选中的内容里有下标的语法,则认为是要去掉下标语法
if (!this.isSelections && !this.$testIsSub($selection)) {
this.getMoreSelection('^^', '^^', function () {
var newSelection = _this2.editor.editor.getSelection();
var isSub = _this2.$testIsSub(newSelection);
if (isSub) {
$selection = newSelection;
}
return isSub;
});
}
if (this.$testIsSub($selection)) {
return $selection.replace(/(^)(\s*)(\^\^)([^\n]+)(\3)(\s*)($)/gm, '$1$4$7');
}
this.registerAfterClickCb(function () {
_this2.setLessSelection('^^', '^^');
});
return $selection.replace(/(^)([^\n]+)($)/gm, '$1^^$2^^$3');
}
}]);
return Sub;
}(MenuBase);
function _createSuper$E(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$E(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$E() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 上标的按钮
**/
var Sup$1 = /*#__PURE__*/function (_MenuBase) {
_inherits(Sup, _MenuBase);
var _super = _createSuper$E(Sup);
function Sup($cherry) {
var _this;
_classCallCheck(this, Sup);
_this = _super.call(this, $cherry);
_this.setName('sup', 'sup');
return _this;
}
_createClass(Sup, [{
key: "$testIsSup",
value: function $testIsSup(selection) {
return /^\s*(\^)[\s\S]+(\1)/.test(selection);
}
/**
*
* @param {string} selection 被用户选中的文本内容
* @param {string} shortKey 快捷键参数,本函数不处理这个参数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
}, {
key: "onClick",
value: function onClick(selection) {
var _this2 = this;
var $selection = getSelection(this.editor.editor, selection) || this.locale.sup; // 如果选中的内容里有上标的语法,则认为是要去掉上标语法
if (!this.isSelections && !this.$testIsSup($selection)) {
this.getMoreSelection('^', '^', function () {
var newSelection = _this2.editor.editor.getSelection();
var isSup = _this2.$testIsSup(newSelection);
if (isSup) {
$selection = newSelection;
}
return isSup;
});
}
if (this.$testIsSup($selection)) {
return selection.replace(/(^)(\s*)(\^)([^\n]+)(\3)(\s*)($)/gm, '$1$4$7');
}
this.registerAfterClickCb(function () {
_this2.setLessSelection('^', '^');
});
return $selection.replace(/(^)([^\n]+)($)/gm, '$1^$2^$3');
}
}]);
return Sup;
}(MenuBase);
function _createSuper$F(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$F(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$F() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入字体颜色或者字体背景颜色的按钮
*/
var Color$1 = /*#__PURE__*/function (_MenuBase) {
_inherits(Color, _MenuBase);
var _super = _createSuper$F(Color);
function Color($cherry) {
var _this;
_classCallCheck(this, Color);
_this = _super.call(this, $cherry);
_this.setName('color', 'color'); // this.bubbleMenu = true;
_this.bubbleColor = new BubbleColor($cherry);
return _this;
}
_createClass(Color, [{
key: "$testIsColor",
value: function $testIsColor(type, selection) {
var textReg = /^\s*!![^\s]+ [\s\S]+!!\s*$/;
var bgReg = /^\s*!!![^\s]+ [\s\S]+!!!\s*$/;
if (type === 'text') {
return textReg.test(selection) && !bgReg.test(selection);
}
return bgReg.test(selection);
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @param {string} shortKey 快捷键参数,本函数不处理这个参数
* @param {Event & {target:HTMLElement}} event 点击事件,用来从被点击的调色盘中获得对应的颜色
* @returns 回填到编辑器光标位置/选中文本区域的内容
*/
}, {
key: "onClick",
value: function onClick(selection) {
var _this2 = this;
var event = arguments.length > 2 ? arguments[2] : undefined;
var $selection = getSelection(this.editor.editor, selection) || this.locale.color;
if (this.hasCacheOnce()) {
var _context4, _context5;
// @ts-ignore
var _this$getAndCleanCach = this.getAndCleanCacheOnce(),
type = _this$getAndCleanCach.type,
color = _this$getAndCleanCach.color;
var begin = type === 'text' ? "!!".concat(color, " ") : "!!!".concat(color, " ");
var end = type === 'text' ? '!!' : '!!!';
if (!this.isSelections && !this.$testIsColor(type, $selection)) {
this.getMoreSelection(begin, end, function () {
var newSelection = _this2.editor.editor.getSelection();
if (_this2.$testIsColor(type, newSelection)) {
$selection = newSelection;
return true;
}
return false;
});
}
if (this.$testIsColor(type, $selection)) {
var _context;
var reg = new RegExp(concat$5(_context = "(^\\s*".concat(end, ")([^\\s]+) ([\\s\\S]+")).call(_context, end, "\\s*$)"), 'gm');
var needClean = true;
var tmp = $selection.replace(reg, function (w, m1, m2, m3) {
var _context2, _context3;
needClean = needClean ? m2 === color : false;
return concat$5(_context2 = concat$5(_context3 = "".concat(m1)).call(_context3, color, " ")).call(_context2, m3);
});
if (needClean) {
return $selection.replace(reg, '$3').replace(/!+\s*$/gm, '');
}
this.registerAfterClickCb(function () {
_this2.setLessSelection(begin, end);
});
return tmp;
}
this.registerAfterClickCb(function () {
_this2.setLessSelection(begin, end);
});
return concat$5(_context4 = concat$5(_context5 = "".concat(begin)).call(_context5, $selection)).call(_context4, end);
} // 定位调色盘应该出现的位置
// 该按钮可能出现在顶部工具栏,
// 也可能出现在选中文字时出现的bubble工具栏
// 也可能出现在新行出现的float工具栏
var top = 0;
var left = 0;
if (event.target.closest('.cherry-bubble')) {
var $colorDom =
/** @type {HTMLElement}*/
event.target.closest('.cherry-bubble');
var clientRect = $colorDom.getBoundingClientRect();
top = clientRect.top + $colorDom.offsetHeight;
left =
/** @type {HTMLElement}*/
event.target.closest('.cherry-toolbar-color').offsetLeft + clientRect.left;
} else {
var _$colorDom =
/** @type {HTMLElement}*/
event.target.closest('.cherry-toolbar-color');
var _clientRect = _$colorDom.getBoundingClientRect();
top = _clientRect.top + _$colorDom.offsetHeight;
left = _clientRect.left;
}
this.updateMarkdown = false; // 【TODO】需要增加getMoreSelection的逻辑
this.bubbleColor.show({
left: left,
top: top,
$color: this
});
}
}]);
return Color;
}(MenuBase);
var BubbleColor = /*#__PURE__*/function () {
function BubbleColor($cherry) {
_classCallCheck(this, BubbleColor);
_defineProperty(this, "colorStack", ['#000000', '#444444', '#666666', '#999999', '#cccccc', '#eeeeee', '#f3f3f3', '#ffffff', '#ff0000', '#ff9900', '#ffff00', '#00ff00', '#00ffff', '#0000ff', '#9900ff', '#ff00ff', '#f4cccc', '#fce5cd', '#fff2cc', '#d9ead3', '#d0e0e3', '#cfe2f3', '#d9d2e9', '#ead1dc', '#ea9999', '#f9cb9c', '#ffe599', '#b6d7a8', '#a2c4c9', '#9fc5e8', '#b4a7d6', '#d5a6bd', '#e06666', '#f6b26b', '#ffd966', '#93c47d', '#76a5af', '#6fa8dc', '#8e7cc3', '#c27ba0', '#cc0000', '#e69138', '#f1c232', '#6aa84f', '#45818e', '#3d85c6', '#674ea7', '#a64d79', '#990000', '#b45f06', '#bf9000', '#38761d', '#134f5c', '#0b5394', '#351c75', '#741b47', '#660000', '#783f04', '#7f6000', '#274e13', '#0c343d', '#073763', '#20124d', '#4c1130']);
this.editor = $cherry.editor;
this.init();
this.initAction();
}
/**
* 定义调色盘每个色块的颜色值
*/
_createClass(BubbleColor, [{
key: "setSelection",
value:
/**
* 用来暂存选中的内容
* @param {string} selection 编辑区选中的文本内容
*/
function setSelection(selection) {
this.selection = selection;
}
}, {
key: "getFontColorDom",
value: function getFontColorDom(title) {
var _context6, _context9;
var colorStackDOM = map$3(_context6 = this.colorStack).call(_context6, function (color) {
var _context7, _context8;
return concat$5(_context7 = concat$5(_context8 = "<span class=\"cherry-color-item cherry-color-item__".concat(color.replace('#', ''), "\" unselectable=\"on\" data-val=\"")).call(_context8, color, "\"\n style=\"background-color:")).call(_context7, color, "\"></span>");
}).join('');
return concat$5(_context9 = "<h3>".concat(title, "</h3>")).call(_context9, colorStackDOM);
}
}, {
key: "getDom",
value: function getDom() {
var $colorWrap = document.createElement('div');
$colorWrap.classList.add('cherry-color-wrap');
$colorWrap.classList.add('cherry-dropdown');
var $textWrap = document.createElement('div');
$textWrap.classList.add('cherry-color-text');
$textWrap.innerHTML = this.getFontColorDom('文本颜色');
$colorWrap.appendChild($textWrap);
var $bgWrap = document.createElement('div');
$bgWrap.classList.add('cherry-color-bg');
$bgWrap.innerHTML = this.getFontColorDom('背景颜色');
$colorWrap.appendChild($bgWrap);
return $colorWrap;
}
}, {
key: "init",
value: function init() {
this.dom = this.getDom();
this.editor.options.wrapperDom.appendChild(this.dom);
}
}, {
key: "onClick",
value: function onClick() {
var _context11;
if (this.type === 'text') {
var _context10;
if (/^!!#\S+ [\s\S]+?!!/.test(this.selection)) {
return this.selection.replace(/^!!#\S+ ([\s\S]+?)!!/, "!!".concat(this.colorValue, " $1!!"));
}
return concat$5(_context10 = "!!".concat(this.colorValue, " ")).call(_context10, this.selection, "!!");
}
if (/^!!!#\S+ [\s\S]+?!!!/.test(this.selection)) {
return this.selection.replace(/^!!!#\S+ ([\s\S]+?)!!!/, "!!!".concat(this.colorValue, " $1!!!"));
}
return concat$5(_context11 = "!!!".concat(this.colorValue, " ")).call(_context11, this.selection, "!!!");
}
}, {
key: "initAction",
value: function initAction() {
var _this3 = this;
// const self = this;
this.dom.addEventListener('click', function (evt) {
var target =
/** @type {MouseEvent & {target:HTMLElement}}*/
evt.target;
_this3.colorValue = target.getAttribute('data-val');
if (!_this3.colorValue) {
return false;
}
_this3.type = target.closest('.cherry-color-text') ? 'text' : 'bg';
_this3.$color.setCacheOnce({
type: _this3.type,
color: _this3.colorValue
});
_this3.$color.fire(null);
}, false);
this.dom.addEventListener('EditorHideToolbarSubMenu', function () {
if (_this3.dom.style.display !== 'none') {
_this3.dom.style.display = 'none';
}
});
}
/**
* 在对应的坐标展示调色盘
* @param {Object} 坐标
*/
}, {
key: "show",
value: function show(_ref) {
var left = _ref.left,
top = _ref.top,
$color = _ref.$color;
this.dom.style.left = "".concat(left, "px");
this.dom.style.top = "".concat(top, "px");
this.dom.style.display = 'block';
this.$color = $color;
}
}]);
return BubbleColor;
}();
function _createSuper$G(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$G(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$G() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入1级~5级标题
*/
var Header$1 = /*#__PURE__*/function (_MenuBase) {
_inherits(Header, _MenuBase);
var _super = _createSuper$G(Header);
function Header($cherry) {
var _context, _context2, _context3, _context4, _context5;
var _this;
_classCallCheck(this, Header);
_this = _super.call(this, $cherry);
_this.setName('header', 'header');
_this.subMenuConfig = [{
iconName: 'h1',
name: 'h1',
onclick: bind$5(_context = _this.bindSubClick).call(_context, _assertThisInitialized(_this), '1')
}, {
iconName: 'h2',
name: 'h2',
onclick: bind$5(_context2 = _this.bindSubClick).call(_context2, _assertThisInitialized(_this), '2')
}, {
iconName: 'h3',
name: 'h3',
onclick: bind$5(_context3 = _this.bindSubClick).call(_context3, _assertThisInitialized(_this), '3')
}, {
iconName: 'h4',
name: 'h4',
onclick: bind$5(_context4 = _this.bindSubClick).call(_context4, _assertThisInitialized(_this), '4')
}, {
iconName: 'h5',
name: 'h5',
onclick: bind$5(_context5 = _this.bindSubClick).call(_context5, _assertThisInitialized(_this), '5')
}];
return _this;
}
_createClass(Header, [{
key: "getSubMenuConfig",
value: function getSubMenuConfig() {
return this.subMenuConfig;
}
/**
* 解析快捷键,判断插入的标题级别
* @param {string} shortKey 快捷键
* @returns
*/
}, {
key: "$getFlagStr",
value: function $getFlagStr(shortKey) {
var _context6;
var test = +(typeof shortKey === 'string' ? shortKey.replace(/[^0-9]+([0-9])/g, '$1') : shortKey);
return repeat$3(_context6 = '#').call(_context6, test ? test : 1);
}
}, {
key: "$testIsHead",
value: function $testIsHead(selection) {
return /^\s*(#+)\s*.+/.test(selection);
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @param {string} shortKey 快捷键参数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
}, {
key: "onClick",
value: function onClick(selection) {
var _this2 = this;
var shortKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var $selection = getSelection(this.editor.editor, selection, 'line', true) || this.locale.header;
var header = this.$getFlagStr(shortKey);
if (!this.isSelections && !this.$testIsHead($selection)) {
this.getMoreSelection('\n', '', function () {
var newSelection = _this2.editor.editor.getSelection();
var isHead = _this2.$testIsHead(newSelection);
if (isHead) {
$selection = newSelection;
}
return isHead;
});
}
if (this.$testIsHead($selection)) {
// 如果选中的内容里有标题语法,并且标记级别与目标一致,则去掉标题语法
// 反之,修改标题级别与目标一致
var needClean = true;
var tmp = $selection.replace(/(^\s*)(#+)(\s*)(.+$)/gm, function (w, m1, m2, m3, m4) {
var _context7, _context8, _context9;
needClean = needClean ? m2.length === header.length : false;
return concat$5(_context7 = concat$5(_context8 = concat$5(_context9 = "".concat(m1)).call(_context9, header)).call(_context8, m3)).call(_context7, m4);
});
if (needClean) {
return $selection.replace(/(^\s*)(#+)(\s*)(.+$)/gm, '$1$4');
}
this.registerAfterClickCb(function () {
_this2.setLessSelection("".concat(header, " "), '');
});
return tmp;
}
this.registerAfterClickCb(function () {
_this2.setLessSelection("".concat(header, " "), '');
});
return $selection.replace(/(^)([\s]*)([^\n]+)($)/gm, "$1".concat(header, " $3$4"));
}
/**
* 获得监听的快捷键
* 在windows下是Ctrl+1在mac下是cmd+1
*/
}, {
key: "shortcutKeys",
get: function get() {
return ['Ctrl-1', 'Ctrl-2', 'Ctrl-3', 'Ctrl-4', 'Ctrl-5', 'Ctrl-6'];
}
}]);
return Header;
}(MenuBase);
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var createTableItem = function createTableItem(dataset, className) {
var _context;
var dom = document.createElement('td');
dom.className = className || 'table-item';
forEach$3(_context = keys$3(dataset)).call(_context, function (prop) {
dom.dataset[prop] = dataset[prop];
});
return dom;
};
/**
* 插入表格的辅助面板
*/
var BubbleTableMenu = /*#__PURE__*/function () {
function BubbleTableMenu(_ref, className) {
var row = _ref.row,
col = _ref.col;
_classCallCheck(this, BubbleTableMenu);
this.init(row, col, className);
this.initEventListeners();
this.afterClick = function () {};
}
_createClass(BubbleTableMenu, [{
key: "init",
value: function init(row, col, className) {
var _this = this;
var container = document.createElement('table');
var cellArr = [];
var classNames = ['cherry-insert-table-menu', 'cherry-dropdown'];
container.className = classNames.join(' ');
for (var r = 1; r <= row; r++) {
var rowContainer = document.createElement('tr');
rowContainer.className = 'cherry-insert-table-menu-row';
cellArr[r - 1] = [];
for (var c = 1; c <= col; c++) {
var cell = createTableItem({
row: r,
col: c
}, 'cherry-insert-table-menu-item');
rowContainer.appendChild(cell);
cellArr[r - 1][c - 1] = cell;
}
container.appendChild(rowContainer);
}
container.style.display = 'none';
container.addEventListener('EditorHideToolbarSubMenu', function () {
_this.hide();
});
this.dom = container;
this.cell = cellArr;
this.maxRow = row;
this.maxCol = col;
this.activeRow = 0;
this.activeCol = 0;
return this.dom;
}
}, {
key: "initEventListeners",
value: function initEventListeners() {
var _context2, _context3;
this.dom.addEventListener('mousemove', bind$5(_context2 = this.handleMouseMove).call(_context2, this), false); // 不能用click
this.dom.addEventListener('mouseup', bind$5(_context3 = this.handleMouseUp).call(_context3, this));
}
}, {
key: "setActiveCell",
value: function setActiveCell(row, col) {
if (this.activeRow === row && this.activeCol === col) {
return;
}
var minRow = Math.min(this.activeRow, row);
var maxRow = Math.max(this.activeRow, row);
if (minRow !== maxRow) {
// 先清空或按照历史列数增减active类
for (var r = maxRow; r > minRow; r--) {
for (var c = 1; c <= this.activeCol; c++) {
this.cell[r - 1][c - 1].classList.toggle('active');
}
}
}
var minCol = Math.min(this.activeCol, col);
var maxCol = Math.max(this.activeCol, col);
if (minCol !== maxCol) {
for (var _c = maxCol; _c > minCol; _c--) {
for (var _r = 1; _r <= row; _r++) {
this.cell[_r - 1][_c - 1].classList.toggle('active');
}
}
}
this.activeRow = row;
this.activeCol = col;
}
}, {
key: "handleMouseMove",
value: function handleMouseMove(event) {
var target = event.target;
if (target === this.dom) {
return;
}
if (!target.classList.contains('cherry-insert-table-menu-item')) {
target = target.querySelector('.cherry-insert-table-menu-item');
}
if (!target) {
return;
}
this.setActiveCell(target.dataset.row, target.dataset.col);
}
}, {
key: "handleMouseUp",
value: function handleMouseUp(event) {
var target = event.target;
if (target === this.dom) {
this.afterClick(this.activeRow, this.activeCol);
this.hide();
return;
}
if (!target.classList.contains('cherry-insert-table-menu-item')) {
target = target.querySelector('.cherry-insert-table-menu-item');
}
if (!target) {
this.afterClick(this.activeRow, this.activeCol);
this.hide();
return;
} // 正中单元格时才使用target的dataset
this.afterClick(this.activeRow, this.activeCol);
this.hide();
}
}, {
key: "show",
value: function show(callback) {
this.dom.style.display = 'block';
this.afterClick = callback;
}
}, {
key: "hide",
value: function hide() {
this.dom.style.display = 'none'; // reset active status
for (var r = 0; r < this.maxRow; r++) {
for (var c = 0; c < this.maxCol; c++) {
this.cell[r][c].classList.remove('active');
}
}
this.activeRow = 0;
this.activeCol = 0;
}
}]);
return BubbleTableMenu;
}();
function _createSuper$H(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$H(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$H() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* "插入"按钮
*/
var Insert = /*#__PURE__*/function (_MenuBase) {
_inherits(Insert, _MenuBase);
var _super = _createSuper$H(Insert);
// TODO: 需要优化参数传入方式
function Insert($cherry) {
var _this;
_classCallCheck(this, Insert);
_this = _super.call(this, $cherry);
_this.setName('insert', 'insert');
_this.noIcon = true;
_this.subBubbleTableMenu = new BubbleTableMenu({
row: 9,
col: 9
});
$cherry.editor.options.wrapperDom.appendChild(_this.subBubbleTableMenu.dom);
return _this;
}
/**
* 上传文件的逻辑
* @param {string} type 上传文件的类型
*/
_createClass(Insert, [{
key: "handleUpload",
value: function handleUpload() {
var _this2 = this;
var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'image';
// type为上传文件类型 image|video|audio|pdf|word
var input = document.createElement('input');
input.type = 'file';
input.id = 'fileUpload';
input.value = '';
input.style.display = 'none'; // document.body.appendChild(input);
input.addEventListener('change', function (event) {
// @ts-ignore
var _event$target$files = _slicedToArray(event.target.files, 1),
file = _event$target$files[0]; // 文件上传后的回调函数可以由调用方自己实现
_this2.$cherry.options.fileUpload(file, function (url) {
// 文件上传的默认回调行数,调用方可以完全不使用该函数
if (typeof url !== 'string' || !url) {
return;
}
var code = '';
if (type === 'image') {
var _context;
// 如果是图片则返回固定的图片markdown源码
code = concat$5(_context = "![".concat(file.name, "](")).call(_context, url, ")");
} else if (type === 'video') {
var _context2;
// 如果是视频则返回固定的视频markdown源码
code = concat$5(_context2 = "!video[".concat(file.name, "](")).call(_context2, url, ")");
} else if (type === 'audio') {
var _context3;
// 如果是音频则返回固定的音频markdown源码
code = concat$5(_context3 = "!audio[".concat(file.name, "](")).call(_context3, url, ")");
} else {
var _context4;
// 默认返回超链接
code = concat$5(_context4 = "[".concat(file.name, "](")).call(_context4, url, ")");
} // 替换选中区域
// @ts-ignore
_this2.$cherry.$cherry.doc.replaceSelection(code);
});
});
input.click();
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @param {string} shortKey 快捷键参数
* @param {Function} [callback] 回调函数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
}, {
key: "onClick",
value: function onClick(selection) {
var _context11, _context18, _context19, _context25, _context26;
var shortKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var callback = arguments.length > 2 ? arguments[2] : undefined;
if (/normal-table/.test(shortKey)) {
var _context5, _context6, _context7, _context8, _context9, _context10;
// 如果是插入markdown标准表格
// 根据shortKey获取想插入表格的行号和列号
// shortKey形如`normal-table-2*4`表示插入2行(包含表头是3行)4列的表格
var rowAndCol = shortKey.match(/([0-9]+)[^0-9]([0-9]+)/);
var row = rowAndCol ? +rowAndCol[1] : 3;
var col = rowAndCol ? +rowAndCol[2] : 5;
var headerText = repeat$3(_context5 = ' Header |').call(_context5, col);
var controlText = repeat$3(_context6 = ' ------ |').call(_context6, col);
var rowText = "\n|".concat(repeat$3(_context7 = ' Sample |').call(_context7, col));
var text = concat$5(_context8 = concat$5(_context9 = concat$5(_context10 = "".concat(selection, "\n\n|")).call(_context10, headerText, "\n|")).call(_context9, controlText)).call(_context8, repeat$3(rowText).call(rowText, row), "\n\n");
return text;
}
var $selection = getSelection(this.editor.editor, selection);
switch (shortKey) {
case 'hr':
// 插入分割线
return "".concat(selection, "\n\n---\n");
case 'br':
// 插入换行在cherry里约定一个回车是一个换行两个连续回车是一个空行三个及以上连续回车是两个空行
return "".concat(selection, "<br>");
case 'code':
// 插入代码块
return "\n``` \n".concat(selection ? selection : 'code...', "\n```\n");
case 'formula':
// 插入行内公式
return "".concat(selection, "\n\n$ e=mc^2 $\n\n");
case 'checklist':
// 插入检查项
return "".concat(selection, "\n\n- [x] Item 1\n- [ ] Item 2\n- [ ] Item 3\n");
case 'toc':
// 插入目录
return "".concat(selection, "\n\n[[toc]]\n");
case 'link':
// 插入超链接
return concat$5(_context11 = "".concat(selection, "[")).call(_context11, this.locale.link, "](http://url.com) ");
case 'image':
// 插入图片,调用上传文件逻辑
this.handleUpload('image');
return selection;
case 'video':
// 插入视频,调用上传文件逻辑
this.handleUpload('video');
return selection;
case 'audio':
// 插入音频,调用上传文件逻辑
this.handleUpload('audio');
return selection;
case 'table':
// 插入表格,会出现一个二维面板,用户可以通过点击决定插入表格的行号和列号
// TODO: 菜单定位方式调整,空行判断
this.subBubbleTableMenu.dom.style.left = this.subMenu.dom.style.left;
this.subBubbleTableMenu.dom.style.top = this.subMenu.dom.style.top;
this.subBubbleTableMenu.show(function (row, col) {
var _context12, _context13, _context14, _context15, _context16, _context17;
var headerText = repeat$3(_context12 = ' Header |').call(_context12, col);
var controlText = repeat$3(_context13 = ' ------ |').call(_context13, col);
var rowText = "\n|".concat(repeat$3(_context14 = ' Sample |').call(_context14, col));
var text = concat$5(_context15 = concat$5(_context16 = concat$5(_context17 = "".concat(selection, "\n\n|")).call(_context17, headerText, "\n|")).call(_context16, controlText)).call(_context15, repeat$3(rowText).call(rowText, row), "\n\n");
callback(text);
});
return;
case 'line-table':
// 插入带折线图的表格
return concat$5(_context18 = "".concat(selection, "\n\n")).call(_context18, ['| :line: {x,y} | a | b | c |', '| :-: | :-: | :-: | :-: |', '| x | 1 | 2 | 3 |', '| y | 2 | 4 | 6 |', '| z | 7 | 5 | 3 |'].join('\n'), "\n\n");
case 'bar-table':
// 插入带柱状图的表格
return concat$5(_context19 = "".concat(selection, "\n\n")).call(_context19, ['| :bar: {x,y} | a | b | c |', '| :-: | :-: | :-: | :-: |', '| x | 1 | 2 | 3 |', '| y | 2 | 4 | 6 |', '| z | 7 | 5 | 3 |'].join('\n'), "\n\n");
case 'headlessTable':
// 插入没有表头的表格
// 该表格语法是源于[TAPD](https://tapd.cn) wiki应用里的一种表格语法
// 该表格语法不是markdown通用语法请慎用
// TODO: 菜单定位方式调整, 空行判断
this.subBubbleTableMenu.dom.style.left = this.subMenu.dom.style.left;
this.subBubbleTableMenu.dom.style.top = this.subMenu.dom.style.top;
this.subBubbleTableMenu.show(function (row, col) {
var _context20, _context21, _context22, _context23, _context24;
var text = concat$5(_context20 = concat$5(_context21 = "".concat(selection, "\n\n||")).call(_context21, repeat$3(_context22 = ' ~Header ||').call(_context22, col))).call(_context20, repeat$3(_context23 = "\n||".concat(repeat$3(_context24 = ' SampleT ||').call(_context24, col))).call(_context23, row - 1), "\n\n");
callback(text);
});
return;
case 'pdf':
// 插入pdf文件调用上传文件逻辑
this.handleUpload('pdf');
return selection;
case 'word':
// 插入word调用上传文件逻辑
// 可以在文件上传逻辑里做处理word上传后通过后台服务转成html再返回前端接受后进行处理并回填
this.handleUpload('word');
return selection;
case 'ruby':
// 如果选中的文本中已经有ruby语法了则去掉该语法
if (/^\s*\{[\s\S]+\|[\s\S]+\}/.test($selection)) {
return $selection.replace(/^\s*\{\s*([\s\S]+?)\s*\|[\s\S]+\}\s*/gm, '$1');
}
return concat$5(_context25 = " { ".concat($selection, " | ")).call(_context25, trim$3(_context26 = this.editor.$cherry.options.callback.changeString2Pinyin($selection)).call(_context26), " } ");
}
}
}]);
return Insert;
}(MenuBase);
function _createSuper$I(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$I(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$I() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入有序/无序/checklist列表的按钮
*/
var List$1 = /*#__PURE__*/function (_MenuBase) {
_inherits(List, _MenuBase);
var _super = _createSuper$I(List);
function List($cherry) {
var _context, _context2, _context3;
var _this;
_classCallCheck(this, List);
_this = _super.call(this, $cherry);
_this.setName('list', 'list');
_this.subMenuConfig = [{
iconName: 'ol',
name: 'ol',
onclick: bind$5(_context = _this.bindSubClick).call(_context, _assertThisInitialized(_this), '1')
}, {
iconName: 'ul',
name: 'ul',
onclick: bind$5(_context2 = _this.bindSubClick).call(_context2, _assertThisInitialized(_this), '2')
}, {
iconName: 'checklist',
name: 'checklist',
onclick: bind$5(_context3 = _this.bindSubClick).call(_context3, _assertThisInitialized(_this), '3')
}];
return _this;
}
_createClass(List, [{
key: "getSubMenuConfig",
value: function getSubMenuConfig() {
return this.subMenuConfig;
}
/**
* 响应点击事件
* @param {string} selection 编辑区选中的文本内容
* @param {string} shortKey 快捷键ol 有序列表ul 无序列表checklist 检查项
* @returns 对应markdown的源码
*/
}, {
key: "onClick",
value: function onClick(selection) {
var shortKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var listType = [null, 'ol', 'ul', 'checklist']; // 下标1, 2, 3生效
var $selection = getSelection(this.editor.editor, selection, 'line', true);
var _$selection$match = $selection.match(/^\n*/),
_$selection$match2 = _slicedToArray(_$selection$match, 1),
before = _$selection$match2[0];
var _$selection$match3 = $selection.match(/\n*$/),
_$selection$match4 = _slicedToArray(_$selection$match3, 1),
after = _$selection$match4[0];
if (listType[shortKey] !== null) {
var _context4, _context5;
return concat$5(_context4 = concat$5(_context5 = "".concat(before)).call(_context5, getListFromStr($selection, listType[shortKey]))).call(_context4, after);
}
return $selection;
}
}]);
return List;
}(MenuBase);
function _createSuper$J(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$J(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$J() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 下标的按钮
**/
var Ol = /*#__PURE__*/function (_MenuBase) {
_inherits(Ol, _MenuBase);
var _super = _createSuper$J(Ol);
function Ol($cherry) {
var _this;
_classCallCheck(this, Ol);
_this = _super.call(this, $cherry);
_this.setName('ol', 'ol');
return _this;
}
/**
*
* @param {string} selection 被用户选中的文本内容
* @param {string} shortKey 快捷键参数,本函数不处理这个参数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(Ol, [{
key: "onClick",
value: function onClick(selection) {
var _context, _context2;
var $selection = getSelection(this.editor.editor, selection, 'line', true) || 'Item 1\n Item 1.1\nItem 2';
var _$selection$match = $selection.match(/^\n*/),
_$selection$match2 = _slicedToArray(_$selection$match, 1),
before = _$selection$match2[0];
var _$selection$match3 = $selection.match(/\n*$/),
_$selection$match4 = _slicedToArray(_$selection$match3, 1),
after = _$selection$match4[0];
return concat$5(_context = concat$5(_context2 = "".concat(before)).call(_context2, getListFromStr($selection, 'ol'))).call(_context, after);
}
}]);
return Ol;
}(MenuBase);
function _createSuper$K(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$K(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$K() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 下标的按钮
**/
var Ul = /*#__PURE__*/function (_MenuBase) {
_inherits(Ul, _MenuBase);
var _super = _createSuper$K(Ul);
function Ul($cherry) {
var _this;
_classCallCheck(this, Ul);
_this = _super.call(this, $cherry);
_this.setName('ul', 'ul');
return _this;
}
/**
*
* @param {string} selection 被用户选中的文本内容
* @param {string} shortKey 快捷键参数,本函数不处理这个参数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(Ul, [{
key: "onClick",
value: function onClick(selection) {
var _context, _context2;
var $selection = getSelection(this.editor.editor, selection, 'line', true) || 'Item 1\n Item 1.1\nItem 2';
var _$selection$match = $selection.match(/^\n*/),
_$selection$match2 = _slicedToArray(_$selection$match, 1),
before = _$selection$match2[0];
var _$selection$match3 = $selection.match(/\n*$/),
_$selection$match4 = _slicedToArray(_$selection$match3, 1),
after = _$selection$match4[0];
return concat$5(_context = concat$5(_context2 = "".concat(before)).call(_context2, getListFromStr($selection, 'ul'))).call(_context, after);
}
}]);
return Ul;
}(MenuBase);
function _createSuper$L(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$L(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$L() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 下标的按钮
**/
var Checklist = /*#__PURE__*/function (_MenuBase) {
_inherits(Checklist, _MenuBase);
var _super = _createSuper$L(Checklist);
function Checklist($cherry) {
var _this;
_classCallCheck(this, Checklist);
_this = _super.call(this, $cherry);
_this.setName('checklist', 'checklist');
return _this;
}
/**
*
* @param {string} selection 被用户选中的文本内容
* @param {string} shortKey 快捷键参数,本函数不处理这个参数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(Checklist, [{
key: "onClick",
value: function onClick(selection) {
var _context, _context2;
var $selection = getSelection(this.editor.editor, selection, 'line', true) || 'Item 1\n Item 1.1\nItem 2';
var _$selection$match = $selection.match(/^\n*/),
_$selection$match2 = _slicedToArray(_$selection$match, 1),
before = _$selection$match2[0];
var _$selection$match3 = $selection.match(/\n*$/),
_$selection$match4 = _slicedToArray(_$selection$match3, 1),
after = _$selection$match4[0];
return concat$5(_context = concat$5(_context2 = "".concat(before)).call(_context2, getListFromStr($selection, 'checklist'))).call(_context, after);
}
}]);
return Checklist;
}(MenuBase);
function _createSuper$M(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$M(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$M() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function generateExample(title, mermaidCode) {
return [title, '```mermaid', mermaidCode, '```'].join('\n');
}
var flowChartContent = ['\tA[公司] -->| 下 班 | B(菜市场)', '\tB --> C{看见<br>卖西瓜的}', '\tC -->|Yes| D[买一个包子]', '\tC -->|No| E[买一斤包子]'].join('\n');
var sample = {
flow: ['FlowChart', generateExample('左右结构', "graph LR\n".concat(flowChartContent)), generateExample('上下结构', "graph TD\n".concat(flowChartContent))].join('\n'),
sequence: generateExample('SequenceDiagram', ['sequenceDiagram', 'autonumber', 'A-->A: 文本1', 'A->>B: 文本2', 'loop 循环1', 'loop 循环2', 'A->B: 文本3', 'end', 'loop 循环3', 'B -->>A: 文本4', 'end', 'B -->> B: 文本5', 'end'].join('\n')),
state: generateExample('StateDiagram', ['stateDiagram-v2', '[*] --> A', 'A --> B', 'A --> C', 'state A {', ' \t[*] --> D', ' \tD --> [*]', '}', 'B --> [*]', 'C --> [*]'].join('\n')),
"class": generateExample('ClassDiagram', ['classDiagram', 'Base <|-- One', 'Base <|-- Two', 'Base : +String name', 'Base: +getName()', 'Base: +setName(String name)', 'class One{', ' \t+String newName', ' \t+getNewName()', '}', 'class Two{', ' \t-int id', ' \t-getId()', '}'].join('\n')),
pie: generateExample('PieChart', ['pie', 'title 饼图', '"A" : 100', '"B" : 80', '"C" : 40', '"D" : 30'].join('\n')),
gantt: generateExample('GanttChart', ['gantt', '\ttitle 敏捷研发流程', '\tsection 迭代前', '\t\t交互设计 :a1, 2020-03-01, 4d', '\t\tUI设计 :after a1, 5d', '\t\t需求评审 : 1d', '\tsection 迭代中', '\t\t详细设计 :a2, 2020-03-11, 2d', '\t\t开发 :2020-03-15, 7d', '\t\t测试 :2020-03-22, 5d', '\tsection 迭代后', '\t\t发布: 1d', '\t\t验收: 2d', '\t\t回顾: 1d'].join('\n'))
};
/**
* 插入“画图”的按钮
* 本功能依赖[Mermaid.js](https://mermaid-js.github.io)组件请保证调用CherryMarkdown前已加载mermaid.js组件
*/
var Graph = /*#__PURE__*/function (_MenuBase) {
_inherits(Graph, _MenuBase);
var _super = _createSuper$M(Graph);
function Graph($cherry) {
var _context, _context2, _context3, _context4, _context5, _context6;
var _this;
_classCallCheck(this, Graph);
_this = _super.call(this, $cherry);
_this.setName('graph', 'insertChart');
_this.noIcon = true;
_this.subMenuConfig = [// 流程图
// 访问[Mermaid 流程图](https://mermaid-js.github.io/mermaid/#/flowchart)参考具体使用方法。
{
iconName: 'insertFlow',
name: 'insertFlow',
onclick: bind$5(_context = _this.bindSubClick).call(_context, _assertThisInitialized(_this), '1')
}, // 时序图
// 访问[Mermaid 时序图](https://mermaid-js.github.io/mermaid/#/sequenceDiagram)参考具体使用方法
{
iconName: 'insertSeq',
name: 'insertSeq',
onclick: bind$5(_context2 = _this.bindSubClick).call(_context2, _assertThisInitialized(_this), '2')
}, // 状态图
// 访问[Mermaid 状态图](https://mermaid-js.github.io/mermaid/#/stateDiagram)参考具体使用方法
{
iconName: 'insertState',
name: 'insertState',
onclick: bind$5(_context3 = _this.bindSubClick).call(_context3, _assertThisInitialized(_this), '3')
}, // 类图
// 访问[Mermaid UML图](https://mermaid-js.github.io/mermaid/#/classDiagram)参考具体使用方法
{
iconName: 'insertClass',
name: 'insertClass',
onclick: bind$5(_context4 = _this.bindSubClick).call(_context4, _assertThisInitialized(_this), '4')
}, // 饼图
// 访问[Mermaid 饼图](https://mermaid-js.github.io/mermaid/#/pie)参考具体使用方法
{
iconName: 'insertPie',
name: 'insertPie',
onclick: bind$5(_context5 = _this.bindSubClick).call(_context5, _assertThisInitialized(_this), '5')
}, // 甘特图
{
iconName: 'insertGantt',
name: 'insertGantt',
onclick: bind$5(_context6 = _this.bindSubClick).call(_context6, _assertThisInitialized(_this), '6')
}];
return _this;
}
_createClass(Graph, [{
key: "getSubMenuConfig",
value: function getSubMenuConfig() {
return this.subMenuConfig;
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容,本函数不处理选中的内容,会直接清空用户选中的内容
* @param {string} shortKey 快捷键参数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
}, {
key: "onClick",
value: function onClick(selection) {
var _this2 = this;
var shortKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var shortcut = "".concat(shortKey);
var shortcutKeyMap = [, 'flow', 'sequence', 'state', 'class', 'pie', 'gantt'];
var selectedExample = shortcutKeyMap[+shortcut];
if (!shortcutKeyMap[+shortcut]) {
return;
}
this.registerAfterClickCb(function () {
_this2.setLessSelection('\n\n\n\n\n', '\n\n');
});
return "\n\n".concat(this.$getSampleCode(selectedExample), "\n");
}
/**
* 画图的markdown源码模版
* @param {string} type 画图的类型
* @returns
*/
}, {
key: "$getSampleCode",
value: function $getSampleCode(type) {
return sample[type].replace(/\t/g, ' ');
}
}]);
return Graph;
}(MenuBase);
function _createSuper$N(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$N(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$N() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Size$1 = /*#__PURE__*/function (_MenuBase) {
_inherits(Size, _MenuBase);
var _super = _createSuper$N(Size);
function Size($cherry) {
var _context, _context2, _context3, _context4;
var _this;
_classCallCheck(this, Size);
_this = _super.call(this, $cherry);
_this.setName('size', 'size');
_this.subMenuConfig = [{
name: '小',
noIcon: true,
onclick: bind$5(_context = _this.bindSubClick).call(_context, _assertThisInitialized(_this), '12')
}, {
name: '中',
noIcon: true,
onclick: bind$5(_context2 = _this.bindSubClick).call(_context2, _assertThisInitialized(_this), '17')
}, {
name: '大',
noIcon: true,
onclick: bind$5(_context3 = _this.bindSubClick).call(_context3, _assertThisInitialized(_this), '24')
}, {
name: '特大',
noIcon: true,
onclick: bind$5(_context4 = _this.bindSubClick).call(_context4, _assertThisInitialized(_this), '32')
}];
_this.shortKeyMap = {
'Alt-1': '12',
'Alt-2': '17',
'Alt-3': '24',
'Alt-4': '32'
};
return _this;
}
_createClass(Size, [{
key: "getSubMenuConfig",
value: function getSubMenuConfig() {
return this.subMenuConfig;
}
}, {
key: "_getFlagStr",
value: function _getFlagStr(shortKey) {
var test = shortKey.replace(/[^0-9]+([0-9])/g, '$1');
var header = '#';
for (var i = 1; i < test; i++) {
header += '#';
}
return header;
}
}, {
key: "$testIsSize",
value: function $testIsSize(selection) {
return /^\s*(![0-9]+) [\s\S]+!/.test(selection);
}
}, {
key: "$getSizeByShortKey",
value: function $getSizeByShortKey(shortKey) {
if (/^[0-9]+$/.test(shortKey)) {
return shortKey;
}
return this.shortKeyMap[shortKey] || '17';
}
}, {
key: "onClick",
value: function onClick(selection) {
var _this2 = this;
var shortKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '17';
var size = this.$getSizeByShortKey(shortKey);
var $selection = getSelection(this.editor.editor, selection) || '字号'; // 如果选中的内容里有字号语法,则直接去掉该语法
if (!this.isSelections && !this.$testIsSize($selection)) {
this.getMoreSelection('!32 ', '!', function () {
var newSelection = _this2.editor.editor.getSelection();
if (_this2.$testIsSize(newSelection)) {
$selection = newSelection;
return true;
}
return false;
});
}
if (this.$testIsSize($selection)) {
// 如果选中的内容里有字号语法,并且字号与目标一致,则去掉字号语法
// 反之,修改字号与目标一致
var needClean = true;
var tmp = $selection.replace(/(^)(\s*)(![0-9]+)([^\n]+)(!)(\s*)($)/gm, function (w, m1, m2, m3, m4, m5, m6, m7) {
var _context5, _context6, _context7, _context8, _context9, _context10;
needClean = needClean ? m3 === "!".concat(size) : false;
return concat$5(_context5 = concat$5(_context6 = concat$5(_context7 = concat$5(_context8 = concat$5(_context9 = concat$5(_context10 = "".concat(m1)).call(_context10, m2, "!")).call(_context9, size)).call(_context8, m4)).call(_context7, m5)).call(_context6, m6)).call(_context5, m7);
});
if (needClean) {
return $selection.replace(/(^)(\s*)(![0-9]+\s*)([^\n]+)(!)(\s*)($)/gm, '$1$4$7');
}
this.registerAfterClickCb(function () {
_this2.setLessSelection("!".concat(size, " "), '!');
});
return tmp;
}
this.registerAfterClickCb(function () {
_this2.setLessSelection("!".concat(size, " "), '!');
});
return $selection.replace(/(^)([^\n]+)($)/gm, "$1!".concat(size, " $2!$3"));
}
}, {
key: "shortcutKeys",
get: function get() {
return ['Alt-1', 'Alt-2', 'Alt-3', 'Alt-4'];
}
}]);
return Size;
}(MenuBase);
function _createSuper$O(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$O(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$O() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入1级标题
*/
var H1 = /*#__PURE__*/function (_MenuBase) {
_inherits(H1, _MenuBase);
var _super = _createSuper$O(H1);
function H1($cherry) {
var _this;
_classCallCheck(this, H1);
_this = _super.call(this, $cherry);
_this.setName('h1', 'h1');
return _this;
}
_createClass(H1, [{
key: "$testIsHead",
value: function $testIsHead(selection) {
return /^\s*(#+)\s*.+/.test(selection);
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @param {string} shortKey 快捷键参数,本函数不处理这个参数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
}, {
key: "onClick",
value: function onClick(selection) {
var _this2 = this;
var $selection = getSelection(this.editor.editor, selection, 'line', true) || this.locale.h1;
var header = '#';
if (!this.isSelections && !this.$testIsHead($selection)) {
this.getMoreSelection('\n', '', function () {
var newSelection = _this2.editor.editor.getSelection();
var isHead = _this2.$testIsHead(newSelection);
if (isHead) {
$selection = newSelection;
}
return isHead;
});
}
if (this.$testIsHead($selection)) {
// 如果选中的内容里有标题语法,并且标记级别与目标一致,则去掉标题语法
// 反之,修改标题级别与目标一致
var needClean = true;
var tmp = $selection.replace(/(^\s*)(#+)(\s*)(.+$)/gm, function (w, m1, m2, m3, m4) {
var _context, _context2, _context3;
needClean = needClean ? m2.length === header.length : false;
return concat$5(_context = concat$5(_context2 = concat$5(_context3 = "".concat(m1)).call(_context3, header)).call(_context2, m3)).call(_context, m4);
});
if (needClean) {
return $selection.replace(/(^\s*)(#+)(\s*)(.+$)/gm, '$1$4');
}
this.registerAfterClickCb(function () {
_this2.setLessSelection("".concat(header, " "), '');
});
return tmp;
}
this.registerAfterClickCb(function () {
_this2.setLessSelection("".concat(header, " "), '');
});
return $selection.replace(/(^)([\s]*)([^\n]+)($)/gm, "$1".concat(header, " $3$4"));
}
}]);
return H1;
}(MenuBase);
function _createSuper$P(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$P(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$P() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入2级标题
*/
var H2 = /*#__PURE__*/function (_MenuBase) {
_inherits(H2, _MenuBase);
var _super = _createSuper$P(H2);
function H2($cherry) {
var _this;
_classCallCheck(this, H2);
_this = _super.call(this, $cherry);
_this.setName('h2', 'h2');
return _this;
}
_createClass(H2, [{
key: "$testIsHead",
value: function $testIsHead(selection) {
return /^\s*(#+)\s*.+/.test(selection);
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @param {string} shortKey 快捷键参数,本函数不处理这个参数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
}, {
key: "onClick",
value: function onClick(selection) {
var _this2 = this;
var $selection = getSelection(this.editor.editor, selection, 'line', true) || this.locale.h2;
var header = '##';
if (!this.isSelections && !this.$testIsHead($selection)) {
this.getMoreSelection('\n', '', function () {
var newSelection = _this2.editor.editor.getSelection();
var isHead = _this2.$testIsHead(newSelection);
if (isHead) {
$selection = newSelection;
}
return isHead;
});
}
if (this.$testIsHead($selection)) {
// 如果选中的内容里有标题语法,并且标记级别与目标一致,则去掉标题语法
// 反之,修改标题级别与目标一致
var needClean = true;
var tmp = $selection.replace(/(^\s*)(#+)(\s*)(.+$)/gm, function (w, m1, m2, m3, m4) {
var _context, _context2, _context3;
needClean = needClean ? m2.length === header.length : false;
return concat$5(_context = concat$5(_context2 = concat$5(_context3 = "".concat(m1)).call(_context3, header)).call(_context2, m3)).call(_context, m4);
});
if (needClean) {
return $selection.replace(/(^\s*)(#+)(\s*)(.+$)/gm, '$1$4');
}
this.registerAfterClickCb(function () {
_this2.setLessSelection("".concat(header, " "), '');
});
return tmp;
}
this.registerAfterClickCb(function () {
_this2.setLessSelection("".concat(header, " "), '');
});
return $selection.replace(/(^)([\s]*)([^\n]+)($)/gm, "$1".concat(header, " $3$4"));
}
}]);
return H2;
}(MenuBase);
function _createSuper$Q(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$Q(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$Q() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入3级标题
*/
var H3 = /*#__PURE__*/function (_MenuBase) {
_inherits(H3, _MenuBase);
var _super = _createSuper$Q(H3);
function H3($cherry) {
var _this;
_classCallCheck(this, H3);
_this = _super.call(this, $cherry);
_this.setName('h3', 'h3');
return _this;
}
_createClass(H3, [{
key: "$testIsHead",
value: function $testIsHead(selection) {
return /^\s*(#+)\s*.+/.test(selection);
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @param {string} shortKey 快捷键参数,本函数不处理这个参数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
}, {
key: "onClick",
value: function onClick(selection) {
var _this2 = this;
var $selection = getSelection(this.editor.editor, selection, 'line', true) || this.locale.h3;
var header = '###';
if (!this.isSelections && !this.$testIsHead($selection)) {
this.getMoreSelection('\n', '', function () {
var newSelection = _this2.editor.editor.getSelection();
var isHead = _this2.$testIsHead(newSelection);
if (isHead) {
$selection = newSelection;
}
return isHead;
});
}
if (this.$testIsHead($selection)) {
// 如果选中的内容里有标题语法,并且标记级别与目标一致,则去掉标题语法
// 反之,修改标题级别与目标一致
var needClean = true;
var tmp = $selection.replace(/(^\s*)(#+)(\s*)(.+$)/gm, function (w, m1, m2, m3, m4) {
var _context, _context2, _context3;
needClean = needClean ? m2.length === header.length : false;
return concat$5(_context = concat$5(_context2 = concat$5(_context3 = "".concat(m1)).call(_context3, header)).call(_context2, m3)).call(_context, m4);
});
if (needClean) {
return $selection.replace(/(^\s*)(#+)(\s*)(.+$)/gm, '$1$4');
}
this.registerAfterClickCb(function () {
_this2.setLessSelection("".concat(header, " "), '');
});
return tmp;
}
this.registerAfterClickCb(function () {
_this2.setLessSelection("".concat(header, " "), '');
});
return $selection.replace(/(^)([\s]*)([^\n]+)($)/gm, "$1".concat(header, " $3$4"));
}
}]);
return H3;
}(MenuBase);
function _createSuper$R(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$R(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$R() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入“引用”的按钮
*/
var Quote = /*#__PURE__*/function (_MenuBase) {
_inherits(Quote, _MenuBase);
var _super = _createSuper$R(Quote);
function Quote($cherry) {
var _this;
_classCallCheck(this, Quote);
_this = _super.call(this, $cherry);
_this.setName('quote', 'blockquote');
return _this;
}
/**
* click handler
* @param {string} selection selection in editor
* @returns
*/
_createClass(Quote, [{
key: "onClick",
value: function onClick(selection) {
var _context,
_this2 = this;
var $selection = getSelection(this.editor.editor, selection, 'line', true) || this.locale.quote;
var isWrapped = every$3(_context = $selection.split('\n')).call(_context, function (text) {
return /^\s*>[^\n]+$/.exec(text);
});
if (isWrapped) {
// 去掉>号
return $selection.replace(/(^\s*)>\s*([^\n]+)($)/gm, '$1$2$3').replace(/\n+$/, '\n\n');
}
this.registerAfterClickCb(function () {
_this2.setLessSelection('> ', '');
}); // 给每一行增加>号
return $selection.replace(/(^)([^\n]+)($)/gm, '$1> $2$3').replace(/\n+$/, '\n\n');
}
}]);
return Quote;
}(MenuBase);
function _createSuper$S(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$S(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$S() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入“简单表格”的按钮
* 所谓简单表格,是源于[TAPD](https://tapd.cn) wiki应用里的一种表格语法
* 该表格语法不是markdown通用语法请慎用
*/
var QuickTable = /*#__PURE__*/function (_MenuBase) {
_inherits(QuickTable, _MenuBase);
var _super = _createSuper$S(QuickTable);
function QuickTable($cherry) {
var _this;
_classCallCheck(this, QuickTable);
_this = _super.call(this, $cherry);
_this.setName('quickTable', 'table');
return _this;
}
/**
* 响应点击事件
* @param {string} selection 编辑器里选中的内容
* @param {string} shortKey 本函数不处理快捷键
* @returns
*/
_createClass(QuickTable, [{
key: "onClick",
value: function onClick(selection) {
// TODO可以尝试解析下selection里的内容按\s、\t区分列按\n区分行
return "".concat(selection, "| LeftAlignedCol | CenterAlignedCol | RightAlignedCol |\n") + '| :--- | :---: | ---: |\n' + '| sampleText | sampleText | sampleText |\n' + '| **left**Text | centered Text | *right*Text |\n';
}
}]);
return QuickTable;
}(MenuBase);
function _createSuper$T(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$T(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$T() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 关闭/展示预览区域的按钮
*/
var TogglePreview = /*#__PURE__*/function (_MenuBase) {
_inherits(TogglePreview, _MenuBase);
var _super = _createSuper$T(TogglePreview);
/** @type {boolean} 当前预览状态 */
function TogglePreview($cherry) {
var _this;
_classCallCheck(this, TogglePreview);
_this = _super.call(this, $cherry);
_defineProperty(_assertThisInitialized(_this), "$previewerHidden", false);
_this.setName('previewClose', 'previewClose');
_this.instanceId = $cherry.instanceId;
_this.updateMarkdown = false;
_this.attachEventListeners();
return _this;
}
/**
* 绑定预览事件
*/
_createClass(TogglePreview, [{
key: "attachEventListeners",
value: function attachEventListeners() {
var _this2 = this;
Event$1.on(this.instanceId, Event$1.Events.previewerClose, function () {
_this2.isHidden = true;
});
Event$1.on(this.instanceId, Event$1.Events.previewerOpen, function () {
_this2.isHidden = false;
});
}
}, {
key: "isHidden",
get: function get() {
return this.$previewerHidden;
},
set: function set(state) {
// 节流
if (state === this.$previewerHidden) {
return;
}
var icon = this.dom.querySelector('i'); // 隐藏预览,按钮状态为打开预览
if (state) {
icon.classList.toggle('ch-icon-previewClose', false);
icon.classList.toggle('ch-icon-preview', true);
icon.title = this.locale.togglePreview;
} else {
icon.classList.toggle('ch-icon-previewClose', true);
icon.classList.toggle('ch-icon-preview', false);
icon.title = this.locale.previewClose;
}
this.$previewerHidden = state;
}
/**
* 响应点击事件
*/
}, {
key: "onClick",
value: function onClick() {
if (this.editor.previewer.isPreviewerHidden()) {
this.editor.previewer.recoverPreviewer(true);
this.isHidden = false;
} else {
this.editor.previewer.editOnly(true);
this.isHidden = true;
}
}
}]);
return TogglePreview;
}(MenuBase);
function _createSuper$U(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$U(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$U() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 全屏按钮
*/
var FullScreen = /*#__PURE__*/function (_MenuBase) {
_inherits(FullScreen, _MenuBase);
var _super = _createSuper$U(FullScreen);
function FullScreen($cherry) {
var _this;
_classCallCheck(this, FullScreen);
_this = _super.call(this, $cherry);
_this.updateMarkdown = false;
_this.setName('fullScreen', 'fullscreen');
return _this;
}
/**
* 响应点击事件
*/
_createClass(FullScreen, [{
key: "onClick",
value: function onClick() {
var cherryClass = this.editor.options.editorDom.parentElement.classList;
var cherryToolbarFullscreen = document.querySelector('.cherry-toolbar-fullscreen');
while (cherryToolbarFullscreen.firstChild) {
// 循环删除父元素下的第一个子元素,直到父元素下没有子元素
cherryToolbarFullscreen.removeChild(cherryToolbarFullscreen.firstChild);
}
if (cherryClass.contains('fullscreen')) {
var fullScreen = createElement('i', 'ch-icon ch-icon-fullscreen');
cherryToolbarFullscreen.appendChild(fullScreen);
cherryClass.remove('fullscreen');
} else {
var minScreen = createElement('i', 'ch-icon ch-icon-minscreen');
cherryToolbarFullscreen.appendChild(minScreen);
cherryClass.add('fullscreen');
}
this.editor.editor.refresh();
}
}]);
return FullScreen;
}(MenuBase);
function _createSuper$V(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$V(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$V() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 撤销回退按钮点击后触发编辑器的undo操作
* 依赖codemirror的undo接口
**/
var Undo = /*#__PURE__*/function (_MenuBase) {
_inherits(Undo, _MenuBase);
var _super = _createSuper$V(Undo);
function Undo($cherry) {
var _this;
_classCallCheck(this, Undo);
_this = _super.call(this, $cherry);
_this.setName('undo', 'undo');
return _this;
}
_createClass(Undo, [{
key: "onClick",
value: function onClick() {
this.editor.editor.undo();
}
}]);
return Undo;
}(MenuBase);
function _createSuper$W(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$W(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$W() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 撤销/重做 里的“重做”按键
* 依赖codemirror的undo接口
*/
var Redo = /*#__PURE__*/function (_MenuBase) {
_inherits(Redo, _MenuBase);
var _super = _createSuper$W(Redo);
function Redo($cherry) {
var _this;
_classCallCheck(this, Redo);
_this = _super.call(this, $cherry);
_this.setName('redo', 'redo');
return _this;
}
/**
* 直接调用codemirror的redo方法就好了
*/
_createClass(Redo, [{
key: "onClick",
value: function onClick() {
this.editor.editor.redo();
}
}]);
return Redo;
}(MenuBase);
function _createSuper$X(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$X(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$X() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入代码块的按钮
*/
var Code = /*#__PURE__*/function (_MenuBase) {
_inherits(Code, _MenuBase);
var _super = _createSuper$X(Code);
function Code($cherry) {
var _this;
_classCallCheck(this, Code);
_this = _super.call(this, $cherry);
_this.setName('code', 'code');
return _this;
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @param {string} shortKey 快捷键参数,本函数不处理这个参数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(Code, [{
key: "onClick",
value: function onClick(selection) {
var _this2 = this;
var code = selection ? selection : 'code...';
this.registerAfterClickCb(function () {
_this2.setLessSelection("\n``` \n", "\n```\n");
});
return "\n``` \n".concat(code, "\n```\n");
}
/**
* 声明绑定的快捷键快捷键触发onClick
*/
}, {
key: "shortcutKeys",
get: function get() {
return ['Ctrl-k'];
}
}]);
return Code;
}(MenuBase);
function _createSuper$Y(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$Y(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$Y() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 设置代码块的主题
* 本功能依赖[prism组件](https://github.com/PrismJS/prism)
*/
var CodeTheme = /*#__PURE__*/function (_MenuBase) {
_inherits(CodeTheme, _MenuBase);
var _super = _createSuper$Y(CodeTheme);
function CodeTheme($cherry) {
var _context, _context2, _context3, _context4, _context5, _context6, _context7, _context8;
var _this;
_classCallCheck(this, CodeTheme);
_this = _super.call(this, $cherry);
_this.setName('codeTheme');
_this.iconName = "code-theme";
_this.updateMarkdown = false;
_this.subMenuConfig = [{
noIcon: true,
name: 'default',
onclick: bind$5(_context = _this.bindSubClick).call(_context, _assertThisInitialized(_this), 'default')
}, {
noIcon: true,
name: 'dark',
onclick: bind$5(_context2 = _this.bindSubClick).call(_context2, _assertThisInitialized(_this), 'dark')
}, {
noIcon: true,
name: 'funky',
onclick: bind$5(_context3 = _this.bindSubClick).call(_context3, _assertThisInitialized(_this), 'funky')
}, {
noIcon: true,
name: 'okaidia',
onclick: bind$5(_context4 = _this.bindSubClick).call(_context4, _assertThisInitialized(_this), 'okaidia')
}, {
noIcon: true,
name: 'twilight',
onclick: bind$5(_context5 = _this.bindSubClick).call(_context5, _assertThisInitialized(_this), 'twilight')
}, {
noIcon: true,
name: 'coy',
onclick: bind$5(_context6 = _this.bindSubClick).call(_context6, _assertThisInitialized(_this), 'coy')
}, {
noIcon: true,
name: 'solarized light',
onclick: bind$5(_context7 = _this.bindSubClick).call(_context7, _assertThisInitialized(_this), 'solarized-light')
}, {
noIcon: true,
name: 'tomorrow night',
onclick: bind$5(_context8 = _this.bindSubClick).call(_context8, _assertThisInitialized(_this), 'tomorrow-night')
}];
return _this;
}
/**
* 响应点击事件
* @param {string} shortKey 快捷键参数,本函数不处理这个参数
* @param {string} theme 具体的代码块主题
* @returns 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(CodeTheme, [{
key: "onClick",
value: function onClick() {
var theme = arguments.length > 1 ? arguments[1] : undefined;
document.querySelector('.cherry').setAttribute('data-code-block-theme', theme);
}
}]);
return CodeTheme;
}(MenuBase);
function _createSuper$Z(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$Z(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$Z() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Export = /*#__PURE__*/function (_MenuBase) {
_inherits(Export, _MenuBase);
var _super = _createSuper$Z(Export);
function Export($cherry) {
var _context, _context2, _context3, _context4;
var _this;
_classCallCheck(this, Export);
_this = _super.call(this, $cherry);
_this.setName('export');
_this.iconName = "export";
_this.updateMarkdown = false;
_this.subMenuConfig = [{
noIcon: true,
name: 'exportToPdf',
onclick: bind$5(_context = _this.bindSubClick).call(_context, _assertThisInitialized(_this), 'pdf')
}, {
noIcon: true,
name: 'exportScreenshot',
onclick: bind$5(_context2 = _this.bindSubClick).call(_context2, _assertThisInitialized(_this), 'screenShot')
}, {
noIcon: true,
name: 'exportMarkdownFile',
onclick: bind$5(_context3 = _this.bindSubClick).call(_context3, _assertThisInitialized(_this), 'markdown')
}, {
noIcon: true,
name: 'exportHTMLFile',
onclick: bind$5(_context4 = _this.bindSubClick).call(_context4, _assertThisInitialized(_this), 'html')
}];
return _this;
}
_createClass(Export, [{
key: "onClick",
value: function onClick() {
var type = arguments.length > 1 ? arguments[1] : undefined;
if (document.querySelector('.cherry-dropdown[name=export]')) {
/** @type {HTMLElement}*/
document.querySelector('.cherry-dropdown[name=export]').style.display = 'none';
} // 强制刷新一下预览区域的内容
var previewer = this.$cherry.previewer;
var html = '';
if (previewer.isPreviewerHidden()) {
html = previewer.options.previewerCache.html;
} else {
html = previewer.getDomContainer().innerHTML;
} // 需要未加载的图片替换成原始图片
html = previewer.lazyLoadImg.changeDataSrc2Src(html);
previewer.refresh(html);
previewer["export"](type);
}
}]);
return Export;
}(MenuBase);
function _createSuper$_(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$_(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$_() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 设置按钮
*/
var Settings = /*#__PURE__*/function (_MenuBase) {
_inherits(Settings, _MenuBase);
var _super = _createSuper$_(Settings);
/**
* TODO: 需要优化参数传入方式
*/
function Settings($cherry) {
var _this$engine$$cherry$, _context, _context2, _context3;
var _this;
_classCallCheck(this, Settings);
_this = _super.call(this, $cherry);
_this.setName('settings', 'settings');
_this.updateMarkdown = false;
_this.engine = $cherry.engine;
var classicBr = testKeyInLocal('classicBr') ? getIsClassicBrFromLocal() : (_this$engine$$cherry$ = _this.engine.$cherry.options.engine.global) === null || _this$engine$$cherry$ === void 0 ? void 0 : _this$engine$$cherry$.classicBr;
var defaultModel = $cherry.editor.options.defaultModel;
var classicBrIconName = classicBr ? 'br' : 'normal';
var classicBrName = classicBr ? 'classicBr' : 'normalBr';
var previewIcon = defaultModel === 'editOnly' ? 'preview' : 'previewClose';
var previewName = defaultModel === 'editOnly' ? 'togglePreview' : 'previewClose';
_this.instanceId = $cherry.instanceId;
_this.subMenuConfig = [{
iconName: classicBrIconName,
name: classicBrName,
onclick: bind$5(_context = _this.bindSubClick).call(_context, _assertThisInitialized(_this), 'classicBr')
}, {
iconName: previewIcon,
name: previewName,
onclick: bind$5(_context2 = _this.bindSubClick).call(_context2, _assertThisInitialized(_this), 'previewClose')
}, {
iconName: '',
name: 'hide',
onclick: bind$5(_context3 = _this.bindSubClick).call(_context3, _assertThisInitialized(_this), 'toggleToolbar')
}];
_this.attachEventListeners();
_this.shortcutKeyMaps = [{
shortKey: 'toggleToolbar',
shortcutKey: 'Ctrl-0'
}];
return _this;
}
/**
* 获取子菜单数组
* @returns {Array} 返回子菜单
*/
_createClass(Settings, [{
key: "getSubMenuConfig",
value: function getSubMenuConfig() {
return this.subMenuConfig;
}
/**
* 监听快捷键,并触发回调
* @param {string} shortCut 快捷键
* @param {string} selection 编辑区选中的内容
* @param {boolean} [async] 是否异步
* @param {Function} [callback] 回调函数
* @returns
*/
}, {
key: "bindSubClick",
value: function bindSubClick(shortCut, selection, async, callback) {
if (async) {
return this.onClick(selection, shortCut, callback);
}
return this.onClick(selection, shortCut);
}
/**
* 切换预览按钮
* @param {boolean} isOpen 预览模式是否打开
*/
}, {
key: "togglePreviewBtn",
value: function togglePreviewBtn(isOpen) {
var _this2 = this;
var previewIcon = isOpen ? 'previewClose' : 'preview';
var previewName = isOpen ? 'previewClose' : 'togglePreview';
if (this.subMenu) {
var dropdown = document.querySelector('.cherry-dropdown[name="settings"]');
if (dropdown) {
var icon =
/** @type {HTMLElement} */
dropdown.querySelector('.ch-icon-previewClose,.ch-icon-preview');
icon.classList.toggle('ch-icon-previewClose');
icon.classList.toggle('ch-icon-preview');
icon.title = this.locale[previewName];
icon.parentElement.innerHTML = icon.parentElement.innerHTML.replace(/<\/i>.+$/, "</i>".concat(this.locale[previewName]));
}
} else {
var _context4;
this.subMenuConfig = map$3(_context4 = this.subMenuConfig).call(_context4, function (item) {
if (item.iconName === 'previewClose' || item.iconName === 'preview') {
var _context5;
return {
iconName: previewIcon,
name: previewName,
onclick: bind$5(_context5 = _this2.bindSubClick).call(_context5, _this2, 'previewClose')
};
}
return item;
});
}
}
/**
* 绑定预览事件
*/
}, {
key: "attachEventListeners",
value: function attachEventListeners() {
var _this3 = this;
Event$1.on(this.instanceId, Event$1.Events.previewerClose, function () {
_this3.togglePreviewBtn(false);
});
Event$1.on(this.instanceId, Event$1.Events.previewerOpen, function () {
_this3.togglePreviewBtn(true);
});
}
/**
* 响应点击事件
* @param {string} selection 编辑区选中的内容
* @param {string} shortKey 快捷键
* @param {Function} [callback] 回调函数
* @returns
*/
}, {
key: "onClick",
value: function onClick(selection) {
var shortKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
// eslint-disable-next-line no-param-reassign
shortKey = this.matchShortcutKey(shortKey);
if (shortKey === 'classicBr') {
var _context6;
var targetIsClassicBr = !getIsClassicBrFromLocal();
saveIsClassicBrToLocal(targetIsClassicBr);
this.engine.$cherry.options.engine.global.classicBr = targetIsClassicBr;
forEach$3(_context6 = this.engine.hookCenter.hookList.paragraph).call(_context6, function (item) {
item.classicBr = targetIsClassicBr;
});
var i = this.$cherry.wrapperDom.querySelector('.cherry-dropdown .ch-icon-normal');
i = i ? i : this.$cherry.wrapperDom.querySelector('.cherry-dropdown .ch-icon-br');
if (targetIsClassicBr) {
i.classList.replace('ch-icon-normal', 'ch-icon-br');
i.parentElement.childNodes[1].textContent = this.locale.classicBr;
} else {
i.classList.replace('ch-icon-br', 'ch-icon-normal');
i.parentElement.childNodes[1].textContent = this.locale.normalBr;
}
this.engine.$cherry.previewer.update('');
this.engine.$cherry.initText(this.engine.$cherry.editor.editor);
} else if (shortKey === 'previewClose') {
if (this.editor.previewer.isPreviewerHidden()) {
this.editor.previewer.recoverPreviewer(true);
} else {
this.editor.previewer.editOnly(true);
}
} else if (shortKey === 'toggleToolbar') {
this.toggleToolbar();
}
return selection;
}
/**
* 解析快捷键
* @param {string} shortcutKey 快捷键
* @returns
*/
}, {
key: "matchShortcutKey",
value: function matchShortcutKey(shortcutKey) {
var _context7;
var shortcutKeyMap = find$3(_context7 = this.shortcutKeyMaps).call(_context7, function (item) {
return item.shortcutKey === shortcutKey;
});
return shortcutKeyMap !== undefined ? shortcutKeyMap.shortKey : shortcutKey;
}
/**
* 切换Toolbar显示状态
*/
}, {
key: "toggleToolbar",
value: function toggleToolbar() {
var wrapperDom = this.engine.$cherry.wrapperDom;
if (wrapperDom instanceof HTMLDivElement) {
var _context8;
var toolbarInstanceId = this.engine.$cherry.toolbar.instanceId;
if (indexOf$8(_context8 = wrapperDom.className).call(_context8, 'cherry--no-toolbar') > -1) {
wrapperDom.classList.remove('cherry--no-toolbar');
Event$1.emit(toolbarInstanceId, Event$1.Events.toolbarShow);
} else {
wrapperDom.classList.add('cherry--no-toolbar');
Event$1.emit(toolbarInstanceId, Event$1.Events.toolbarHide);
}
}
}
}, {
key: "shortcutKeys",
get: function get() {
var _context9;
return map$3(_context9 = this.shortcutKeyMaps).call(_context9, function (item) {
return item.shortcutKey;
});
}
}]);
return Settings;
}(MenuBase);
function _createSuper$$(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$$(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$$() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 下划线按钮
**/
var Underline$1 = /*#__PURE__*/function (_MenuBase) {
_inherits(Underline, _MenuBase);
var _super = _createSuper$$(Underline);
function Underline($cherry) {
var _this;
_classCallCheck(this, Underline);
_this = _super.call(this, $cherry);
_this.setName('underline', 'underline');
return _this;
}
_createClass(Underline, [{
key: "$testIsUnderline",
value: function $testIsUnderline(selection) {
return /^\s*(\/)[\s\S]+(\1)/.test(selection);
}
/**
*
* @param {string} selection 被用户选中的文本内容
* @param {string} shortKey 快捷键参数,本函数不处理这个参数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
}, {
key: "onClick",
value: function onClick(selection) {
var _this2 = this;
var $selection = selection ? selection : this.locale.underline; // 如果选中的内容里有下划线语法,则认为是要去掉下划线语法
if (!this.isSelections && !this.$testIsUnderline($selection)) {
this.getMoreSelection(' /', '/ ', function () {
var newSelection = _this2.editor.editor.getSelection();
var isUnderline = _this2.$testIsUnderline(newSelection);
if (isUnderline) {
$selection = newSelection;
}
return isUnderline;
});
}
if (this.$testIsUnderline($selection)) {
return $selection.replace(/(^)(\s*)(\/)([^\n]+)(\3)(\s*)($)/gm, '$1$4$7');
}
this.registerAfterClickCb(function () {
_this2.setLessSelection(' /', '/ ');
}); // 如果选中的内容里没有下划线语法,则加上下划线
return $selection.replace(/(^)([^\n]+)($)/gm, '$1 /$2/ $3');
}
/**
* 声明绑定的快捷键快捷键触发onClick
*/
}, {
key: "shortcutKeys",
get: function get() {
return ['Ctrl-u'];
}
}]);
return Underline;
}(MenuBase);
function _createSuper$10(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$10(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$10() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 切换预览/编辑模式的按钮
* 该按钮不支持切换到双栏编辑模式
* 只能切换成纯编辑模式和纯预览模式
**/
var SwitchModel = /*#__PURE__*/function (_MenuBase) {
_inherits(SwitchModel, _MenuBase);
var _super = _createSuper$10(SwitchModel);
function SwitchModel($cherry) {
var _this;
_classCallCheck(this, SwitchModel);
_this = _super.call(this, $cherry);
_this.setName('switchPreview');
_this.instanceId = $cherry.instanceId;
_this.attachEventListeners();
return _this;
}
_createClass(SwitchModel, [{
key: "attachEventListeners",
value: function attachEventListeners() {
var _this2 = this;
Event$1.on(this.instanceId, Event$1.Events.toolbarHide, function () {
// 当收到工具栏隐藏事件后,修改工具栏的内容为切换到编辑模式的内容
_this2.dom.textContent = _this2.locale.switchEdit;
});
Event$1.on(this.instanceId, Event$1.Events.toolbarShow, function () {
// 当收到工具栏显示事件后,修改工具栏的内容为切换到预览模式的内容
_this2.dom.textContent = _this2.locale.switchPreview;
});
}
}, {
key: "onClick",
value: function onClick() {
if (this.editor.previewer.isPreviewerHidden()) {
// 从编辑模式切换到预览模式
this.editor.previewer.previewOnly();
var toolbar = this.dom.parentElement.parentElement;
toolbar.classList.add('preview-only');
this.dom.textContent = this.locale.switchEdit;
} else {
// 从预览模式切换到编辑模式
this.editor.previewer.editOnly(true);
var _toolbar = this.dom.parentElement.parentElement;
_toolbar.classList.remove('preview-only');
this.dom.textContent = this.locale.switchPreview;
}
}
}]);
return SwitchModel;
}(MenuBase);
function _createSuper$11(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$11(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$11() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入图片
*/
var Image$2 = /*#__PURE__*/function (_MenuBase) {
_inherits(Image, _MenuBase);
var _super = _createSuper$11(Image);
function Image($cherry) {
var _this;
_classCallCheck(this, Image);
_this = _super.call(this, $cherry);
_this.setName('image', 'image');
return _this;
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(Image, [{
key: "onClick",
value: function onClick(selection) {
var _this2 = this,
_this$$cherry$options,
_this$$cherry$options2,
_this$$cherry$options3;
if (this.hasCacheOnce()) {
var _context, _context2;
// @ts-ignore
var _this$getAndCleanCach = this.getAndCleanCacheOnce(),
name = _this$getAndCleanCach.name,
url = _this$getAndCleanCach.url,
params = _this$getAndCleanCach.params;
var begin = '![';
var end = "](".concat(url, ")");
this.registerAfterClickCb(function () {
_this2.setLessSelection(begin, end);
});
var finalName = params.name ? params.name : name;
return concat$5(_context = concat$5(_context2 = "".concat(begin).concat(finalName)).call(_context2, handelParams(params))).call(_context, end);
}
var accept = (_this$$cherry$options = (_this$$cherry$options2 = this.$cherry.options) === null || _this$$cherry$options2 === void 0 ? void 0 : (_this$$cherry$options3 = _this$$cherry$options2.fileTypeLimitMap) === null || _this$$cherry$options3 === void 0 ? void 0 : _this$$cherry$options3.image) !== null && _this$$cherry$options !== void 0 ? _this$$cherry$options : '*'; // 插入图片,调用上传文件逻辑
handleUpload(this.editor, 'image', accept, function (name, url, params) {
_this2.setCacheOnce({
name: name,
url: url,
params: params
});
_this2.fire(null);
});
this.updateMarkdown = false;
return selection;
}
/**
* 声明绑定的快捷键快捷键触发onClick
*/
}, {
key: "shortcutKeys",
get: function get() {
return ['Ctrl-g'];
}
}]);
return Image;
}(MenuBase);
function _createSuper$12(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$12(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$12() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入音频
*/
var Audio = /*#__PURE__*/function (_MenuBase) {
_inherits(Audio, _MenuBase);
var _super = _createSuper$12(Audio);
function Audio($cherry) {
var _this;
_classCallCheck(this, Audio);
_this = _super.call(this, $cherry);
_this.setName('audio', 'video');
return _this;
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(Audio, [{
key: "onClick",
value: function onClick(selection) {
var _this2 = this,
_this$$cherry$options,
_this$$cherry$options2,
_this$$cherry$options3;
if (this.hasCacheOnce()) {
var _context, _context2;
// @ts-ignore
var _this$getAndCleanCach = this.getAndCleanCacheOnce(),
name = _this$getAndCleanCach.name,
url = _this$getAndCleanCach.url,
params = _this$getAndCleanCach.params;
var begin = '!audio[';
var end = "](".concat(url, ")");
this.registerAfterClickCb(function () {
_this2.setLessSelection(begin, end);
});
var finalName = params.name ? params.name : name;
return concat$5(_context = concat$5(_context2 = "".concat(begin).concat(finalName)).call(_context2, handelParams(params))).call(_context, end);
}
var accept = (_this$$cherry$options = (_this$$cherry$options2 = this.$cherry.options) === null || _this$$cherry$options2 === void 0 ? void 0 : (_this$$cherry$options3 = _this$$cherry$options2.fileTypeLimitMap) === null || _this$$cherry$options3 === void 0 ? void 0 : _this$$cherry$options3.audio) !== null && _this$$cherry$options !== void 0 ? _this$$cherry$options : '*'; // 插入图片,调用上传文件逻辑
handleUpload(this.editor, 'audio', accept, function (name, url, params) {
_this2.setCacheOnce({
name: name,
url: url,
params: params
});
_this2.fire(null);
});
this.updateMarkdown = false;
return selection;
}
}]);
return Audio;
}(MenuBase);
function _createSuper$13(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$13(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$13() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入视频
*/
var Video = /*#__PURE__*/function (_MenuBase) {
_inherits(Video, _MenuBase);
var _super = _createSuper$13(Video);
function Video($cherry) {
var _this;
_classCallCheck(this, Video);
_this = _super.call(this, $cherry);
_this.setName('video', 'video');
return _this;
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(Video, [{
key: "onClick",
value: function onClick(selection) {
var _this2 = this,
_this$$cherry$options,
_this$$cherry$options2,
_this$$cherry$options3;
if (this.hasCacheOnce()) {
var _context, _context2, _context3;
// @ts-ignore
var _this$getAndCleanCach = this.getAndCleanCacheOnce(),
name = _this$getAndCleanCach.name,
url = _this$getAndCleanCach.url,
params = _this$getAndCleanCach.params;
var begin = '!video[';
var end = params.poster ? concat$5(_context = "](".concat(url, "){poster=")).call(_context, params.poster, "}") : "](".concat(url, ")");
this.registerAfterClickCb(function () {
_this2.setLessSelection(begin, end);
});
var finalName = params.name ? params.name : name;
return concat$5(_context2 = concat$5(_context3 = "".concat(begin).concat(finalName)).call(_context3, handelParams(params))).call(_context2, end);
}
var accept = (_this$$cherry$options = (_this$$cherry$options2 = this.$cherry.options) === null || _this$$cherry$options2 === void 0 ? void 0 : (_this$$cherry$options3 = _this$$cherry$options2.fileTypeLimitMap) === null || _this$$cherry$options3 === void 0 ? void 0 : _this$$cherry$options3.video) !== null && _this$$cherry$options !== void 0 ? _this$$cherry$options : '*'; // 插入图片,调用上传文件逻辑
handleUpload(this.editor, 'video', accept, function (name, url, params) {
_this2.setCacheOnce({
name: name,
url: url,
params: params
});
_this2.fire(null);
});
this.updateMarkdown = false;
return selection;
}
}]);
return Video;
}(MenuBase);
function _createSuper$14(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$14(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$14() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入换行
*/
var Br$1 = /*#__PURE__*/function (_MenuBase) {
_inherits(Br, _MenuBase);
var _super = _createSuper$14(Br);
function Br($cherry) {
var _this;
_classCallCheck(this, Br);
_this = _super.call(this, $cherry);
_this.setName('br', 'br');
return _this;
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(Br, [{
key: "onClick",
value: function onClick(selection) {
return "".concat(selection, "<br>");
}
}]);
return Br;
}(MenuBase);
function _createSuper$15(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$15(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$15() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入分割线
*/
var Hr$1 = /*#__PURE__*/function (_MenuBase) {
_inherits(Hr, _MenuBase);
var _super = _createSuper$15(Hr);
function Hr($cherry) {
var _this;
_classCallCheck(this, Hr);
_this = _super.call(this, $cherry);
_this.setName('hr', 'line');
return _this;
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(Hr, [{
key: "onClick",
value: function onClick(selection) {
// 插入分割线
return "".concat(selection, "\n\n---\n");
}
}]);
return Hr;
}(MenuBase);
function _createSuper$16(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$16(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$16() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入行内公式
*/
var Formula = /*#__PURE__*/function (_MenuBase) {
_inherits(Formula, _MenuBase);
var _super = _createSuper$16(Formula);
function Formula($cherry) {
var _this;
_classCallCheck(this, Formula);
_this = _super.call(this, $cherry);
_this.setName('formula', 'insertFormula');
return _this;
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(Formula, [{
key: "onClick",
value: function onClick(selection) {
var _this2 = this,
_context;
var before = "".concat(selection, " $ ");
var after = ' $ ';
this.registerAfterClickCb(function () {
_this2.setLessSelection(before, after);
}); // 插入行内公式
return concat$5(_context = "".concat(before, "e=mc^2")).call(_context, after);
}
/**
* 声明绑定的快捷键快捷键触发onClick
*/
}, {
key: "shortcutKeys",
get: function get() {
return ['Ctrl-m'];
}
}]);
return Formula;
}(MenuBase);
function _createSuper$17(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$17(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$17() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入超链接
*/
var Link$1 = /*#__PURE__*/function (_MenuBase) {
_inherits(Link, _MenuBase);
var _super = _createSuper$17(Link);
function Link($cherry) {
var _this;
_classCallCheck(this, Link);
_this = _super.call(this, $cherry);
_this.setName('link', 'link');
return _this;
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(Link, [{
key: "onClick",
value: function onClick(selection) {
// 插入图片,调用上传文件逻辑
if (/^http/.test(selection)) {
var _context;
return concat$5(_context = "[".concat(this.locale.link, "](")).call(_context, selection, ")");
}
var title = selection ? selection : this.locale.link;
return "[".concat(title, "](http://url.com) ");
}
/**
* 声明绑定的快捷键快捷键触发onClick
*/
}, {
key: "shortcutKeys",
get: function get() {
return ['Ctrl-l'];
}
}]);
return Link;
}(MenuBase);
function _createSuper$18(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$18(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$18() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入普通表格
*/
var Table$1 = /*#__PURE__*/function (_MenuBase) {
_inherits(Table, _MenuBase);
var _super = _createSuper$18(Table);
function Table($cherry) {
var _this;
_classCallCheck(this, Table);
_this = _super.call(this, $cherry);
_this.setName('table', 'table');
_this.subBubbleTableMenu = new BubbleTableMenu({
row: 9,
col: 9
});
$cherry.editor.options.wrapperDom.appendChild(_this.subBubbleTableMenu.dom);
_this.catchOnce = '';
return _this;
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @returns {*} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(Table, [{
key: "onClick",
value: function onClick(selection) {
var _this2 = this;
// 如果二维面板处于隐藏状态,说明是第一次点击
if (this.subBubbleTableMenu.dom.style.display === 'none' || !this.hasCacheOnce()) {
// 插入表格,会出现一个二维面板,用户可以通过点击决定插入表格的行号和列号
var pos = this.dom.getBoundingClientRect();
this.subBubbleTableMenu.dom.style.left = "".concat(pos.left + pos.width, "px");
this.subBubbleTableMenu.dom.style.top = "".concat(pos.top + pos.height, "px");
this.subBubbleTableMenu.show(function (row, col) {
var _context, _context2, _context3, _context4, _context5, _context6;
var headerText = repeat$3(_context = ' Header |').call(_context, col);
var controlText = repeat$3(_context2 = ' ------ |').call(_context2, col);
var rowText = "\n|".concat(repeat$3(_context3 = ' Sample |').call(_context3, col));
var _final = concat$5(_context4 = concat$5(_context5 = concat$5(_context6 = "".concat(selection, "\n\n|")).call(_context6, headerText, "\n|")).call(_context5, controlText)).call(_context4, repeat$3(rowText).call(rowText, row), "\n\n");
_this2.setCacheOnce(_final);
_this2.fire(null);
});
this.updateMarkdown = false;
return false;
}
return this.getAndCleanCacheOnce();
}
}]);
return Table;
}(MenuBase);
function _createSuper$19(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$19(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$19() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入目录
*/
var Toc$1 = /*#__PURE__*/function (_MenuBase) {
_inherits(Toc, _MenuBase);
var _super = _createSuper$19(Toc);
function Toc($cherry) {
var _this;
_classCallCheck(this, Toc);
_this = _super.call(this, $cherry);
_this.setName('toc', 'toc');
return _this;
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(Toc, [{
key: "onClick",
value: function onClick(selection) {
// 插入目录
return "".concat(selection, "\n\n[[toc]]\n");
}
}]);
return Toc;
}(MenuBase);
function _createSuper$1a(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1a(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1a() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入折线图+表格
*/
var LineTable = /*#__PURE__*/function (_MenuBase) {
_inherits(LineTable, _MenuBase);
var _super = _createSuper$1a(LineTable);
function LineTable($cherry) {
var _this;
_classCallCheck(this, LineTable);
_this = _super.call(this, $cherry);
_this.setName('lineTable', 'table');
return _this;
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(LineTable, [{
key: "onClick",
value: function onClick(selection) {
var _context;
// 插入带折线图的表格
return concat$5(_context = "".concat(selection, "\n\n")).call(_context, ['| :line: {x,y} | a | b | c |', '| :-: | :-: | :-: | :-: |', '| x | 1 | 2 | 3 |', '| y | 2 | 4 | 6 |', '| z | 7 | 5 | 3 |'].join('\n'), "\n\n");
}
}]);
return LineTable;
}(MenuBase);
function _createSuper$1b(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1b(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1b() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入柱状图图+表格
*/
var BrTable = /*#__PURE__*/function (_MenuBase) {
_inherits(BrTable, _MenuBase);
var _super = _createSuper$1b(BrTable);
function BrTable($cherry) {
var _this;
_classCallCheck(this, BrTable);
_this = _super.call(this, $cherry);
_this.setName('brTable', 'table');
return _this;
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(BrTable, [{
key: "onClick",
value: function onClick(selection) {
var _context;
// 插入带折线图的表格
return concat$5(_context = "".concat(selection, "\n\n")).call(_context, ['| :bar: {x,y} | a | b | c |', '| :-: | :-: | :-: | :-: |', '| x | 1 | 2 | 3 |', '| y | 2 | 4 | 6 |', '| z | 7 | 5 | 3 |'].join('\n'), "\n\n");
}
}]);
return BrTable;
}(MenuBase);
function _createSuper$1c(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1c(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1c() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入pdf
*/
var Pdf = /*#__PURE__*/function (_MenuBase) {
_inherits(Pdf, _MenuBase);
var _super = _createSuper$1c(Pdf);
function Pdf($cherry) {
var _this;
_classCallCheck(this, Pdf);
_this = _super.call(this, $cherry);
_this.setName('pdf', 'pdf');
return _this;
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(Pdf, [{
key: "onClick",
value: function onClick(selection) {
var _this2 = this,
_this$$cherry$options,
_this$$cherry$options2,
_this$$cherry$options3;
if (this.hasCacheOnce()) {
var _context;
// @ts-ignore
var _this$getAndCleanCach = this.getAndCleanCacheOnce(),
name = _this$getAndCleanCach.name,
url = _this$getAndCleanCach.url,
params = _this$getAndCleanCach.params;
var begin = '[';
var end = "](".concat(url, ")");
this.registerAfterClickCb(function () {
_this2.setLessSelection(begin, end);
});
var finalName = params.name ? params.name : name;
return concat$5(_context = "".concat(begin).concat(finalName)).call(_context, end);
}
var accept = (_this$$cherry$options = (_this$$cherry$options2 = this.$cherry.options) === null || _this$$cherry$options2 === void 0 ? void 0 : (_this$$cherry$options3 = _this$$cherry$options2.fileTypeLimitMap) === null || _this$$cherry$options3 === void 0 ? void 0 : _this$$cherry$options3.pdf) !== null && _this$$cherry$options !== void 0 ? _this$$cherry$options : '*'; // 插入图片,调用上传文件逻辑
handleUpload(this.editor, 'pdf', accept, function (name, url, params) {
_this2.setCacheOnce({
name: name,
url: url,
params: params
});
_this2.fire(null);
});
this.updateMarkdown = false;
return selection;
}
}]);
return Pdf;
}(MenuBase);
function _createSuper$1d(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1d(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1d() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入pdf
*/
var File = /*#__PURE__*/function (_MenuBase) {
_inherits(File, _MenuBase);
var _super = _createSuper$1d(File);
function File($cherry) {
var _this;
_classCallCheck(this, File);
_this = _super.call(this, $cherry);
_this.setName('file', 'phone');
return _this;
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(File, [{
key: "onClick",
value: function onClick(selection) {
var _this2 = this,
_this$$cherry$options,
_this$$cherry$options2,
_this$$cherry$options3;
if (this.hasCacheOnce()) {
var _context;
// @ts-ignore
var _this$getAndCleanCach = this.getAndCleanCacheOnce(),
name = _this$getAndCleanCach.name,
url = _this$getAndCleanCach.url,
params = _this$getAndCleanCach.params;
var begin = '[';
var end = "](".concat(url, ")");
this.registerAfterClickCb(function () {
_this2.setLessSelection(begin, end);
});
var finalName = params.name ? params.name : name;
return concat$5(_context = "".concat(begin).concat(finalName)).call(_context, end);
}
var accept = (_this$$cherry$options = (_this$$cherry$options2 = this.$cherry.options) === null || _this$$cherry$options2 === void 0 ? void 0 : (_this$$cherry$options3 = _this$$cherry$options2.fileTypeLimitMap) === null || _this$$cherry$options3 === void 0 ? void 0 : _this$$cherry$options3.file) !== null && _this$$cherry$options !== void 0 ? _this$$cherry$options : '*'; // 插入图片,调用上传文件逻辑
handleUpload(this.editor, 'file', accept, function (name, url, params) {
_this2.setCacheOnce({
name: name,
url: url,
params: params
});
_this2.fire(null);
});
this.updateMarkdown = false;
return selection;
}
}]);
return File;
}(MenuBase);
function _createSuper$1e(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1e(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1e() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入word
*/
var Word = /*#__PURE__*/function (_MenuBase) {
_inherits(Word, _MenuBase);
var _super = _createSuper$1e(Word);
function Word($cherry) {
var _this;
_classCallCheck(this, Word);
_this = _super.call(this, $cherry);
_this.setName('word', 'word');
return _this;
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(Word, [{
key: "onClick",
value: function onClick(selection) {
var _this2 = this,
_this$$cherry$options,
_this$$cherry$options2,
_this$$cherry$options3;
if (this.hasCacheOnce()) {
var _context;
// @ts-ignore
var _this$getAndCleanCach = this.getAndCleanCacheOnce(),
name = _this$getAndCleanCach.name,
url = _this$getAndCleanCach.url,
params = _this$getAndCleanCach.params;
var begin = '[';
var end = "](".concat(url, ")");
this.registerAfterClickCb(function () {
_this2.setLessSelection(begin, end);
});
var finalName = params.name ? params.name : name;
return concat$5(_context = "".concat(begin).concat(finalName)).call(_context, end);
}
var accept = (_this$$cherry$options = (_this$$cherry$options2 = this.$cherry.options) === null || _this$$cherry$options2 === void 0 ? void 0 : (_this$$cherry$options3 = _this$$cherry$options2.fileTypeLimitMap) === null || _this$$cherry$options3 === void 0 ? void 0 : _this$$cherry$options3.word) !== null && _this$$cherry$options !== void 0 ? _this$$cherry$options : '*'; // 插入图片,调用上传文件逻辑
handleUpload(this.editor, 'word', accept, function (name, url, params) {
_this2.setCacheOnce({
name: name,
url: url,
params: params
});
_this2.fire(null);
});
this.updateMarkdown = false;
return selection;
}
}]);
return Word;
}(MenuBase);
function _createSuper$1f(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1f(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1f() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 生成ruby使用场景给中文增加拼音、给中文增加英文、给英文增加中文等等
*/
var Ruby$1 = /*#__PURE__*/function (_MenuBase) {
_inherits(Ruby, _MenuBase);
var _super = _createSuper$1f(Ruby);
function Ruby($cherry) {
var _this;
_classCallCheck(this, Ruby);
_this = _super.call(this, $cherry);
_this.setName('pinyin', 'pinyin');
return _this;
}
_createClass(Ruby, [{
key: "$testIsRuby",
value: function $testIsRuby(selection) {
return /^\s*\{[\s\S]+\|[\s\S]+\}/.test(selection);
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @param {string} shortKey 快捷键参数,本函数不处理这个参数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
}, {
key: "onClick",
value: function onClick(selection) {
var _this2 = this,
_context,
_context2;
var $selection = getSelection(this.editor.editor, selection) || '拼音'; // 如果选中的文本中已经有ruby语法了则去掉该语法
if (!this.isSelections && !this.$testIsRuby($selection)) {
this.getMoreSelection(' { ', ' } ', function () {
var newSelection = _this2.editor.editor.getSelection();
var isRuby = _this2.$testIsRuby(newSelection);
if (isRuby) {
$selection = newSelection;
}
return isRuby;
});
}
if (this.$testIsRuby($selection)) {
return $selection.replace(/^\s*\{\s*([\s\S]+?)\s*\|[\s\S]+\}\s*/gm, '$1');
}
var pinyin = trim$3(_context = this.editor.$cherry.options.callback.changeString2Pinyin($selection) || 'pin yin').call(_context);
this.registerAfterClickCb(function () {
_this2.setLessSelection(' { ', ' } ');
});
return concat$5(_context2 = " { ".concat($selection, " | ")).call(_context2, pinyin, " } ");
}
}]);
return Ruby;
}(MenuBase);
function _createSuper$1g(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1g(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1g() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 修改主题
*/
var Theme = /*#__PURE__*/function (_MenuBase) {
_inherits(Theme, _MenuBase);
var _super = _createSuper$1g(Theme);
function Theme($cherry) {
var _context;
var _this;
_classCallCheck(this, Theme);
_this = _super.call(this, $cherry);
_this.setName('theme', 'insertChart');
_this.subMenuConfig = [];
var self = _assertThisInitialized(_this);
forEach$3(_context = $cherry.options.theme).call(_context, function (one) {
var _context2;
self.subMenuConfig.push({
iconName: one.className,
name: one.label,
onclick: bind$5(_context2 = self.bindSubClick).call(_context2, self, one.className)
});
});
return _this;
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @param {string} shortKey 快捷键参数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(Theme, [{
key: "onClick",
value: function onClick(selection) {
var shortKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
changeTheme(this.$cherry, shortKey);
this.updateMarkdown = false;
return '';
}
}]);
return Theme;
}(MenuBase);
var bind$a = function bind(fn, thisArg) {
return function wrap() {
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
return fn.apply(thisArg, args);
};
};
// utils is a library of generic helper functions non-specific to axios
var toString$4 = Object.prototype.toString;
/**
* Determine if a value is an Array
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Array, otherwise false
*/
function isArray$a(val) {
return Array.isArray(val);
}
/**
* Determine if a value is undefined
*
* @param {Object} val The value to test
* @returns {boolean} True if the value is undefined, otherwise false
*/
function isUndefined(val) {
return typeof val === 'undefined';
}
/**
* Determine if a value is a Buffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Buffer, otherwise false
*/
function isBuffer$1(val) {
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
&& typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
}
/**
* Determine if a value is an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
function isArrayBuffer(val) {
return toString$4.call(val) === '[object ArrayBuffer]';
}
/**
* Determine if a value is a FormData
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an FormData, otherwise false
*/
function isFormData(val) {
return toString$4.call(val) === '[object FormData]';
}
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
var result;
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
result = ArrayBuffer.isView(val);
} else {
result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
}
return result;
}
/**
* Determine if a value is a String
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a String, otherwise false
*/
function isString(val) {
return typeof val === 'string';
}
/**
* Determine if a value is a Number
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Number, otherwise false
*/
function isNumber(val) {
return typeof val === 'number';
}
/**
* Determine if a value is an Object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Object, otherwise false
*/
function isObject$3(val) {
return val !== null && typeof val === 'object';
}
/**
* Determine if a value is a plain Object
*
* @param {Object} val The value to test
* @return {boolean} True if value is a plain Object, otherwise false
*/
function isPlainObject$1(val) {
if (toString$4.call(val) !== '[object Object]') {
return false;
}
var prototype = Object.getPrototypeOf(val);
return prototype === null || prototype === Object.prototype;
}
/**
* Determine if a value is a Date
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Date, otherwise false
*/
function isDate(val) {
return toString$4.call(val) === '[object Date]';
}
/**
* Determine if a value is a File
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a File, otherwise false
*/
function isFile(val) {
return toString$4.call(val) === '[object File]';
}
/**
* Determine if a value is a Blob
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Blob, otherwise false
*/
function isBlob(val) {
return toString$4.call(val) === '[object Blob]';
}
/**
* Determine if a value is a Function
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
function isFunction$1(val) {
return toString$4.call(val) === '[object Function]';
}
/**
* Determine if a value is a Stream
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Stream, otherwise false
*/
function isStream(val) {
return isObject$3(val) && isFunction$1(val.pipe);
}
/**
* Determine if a value is a URLSearchParams object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
function isURLSearchParams(val) {
return toString$4.call(val) === '[object URLSearchParams]';
}
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
* @returns {String} The String freed of excess whitespace
*/
function trim$6(str) {
return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
}
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* navigator.product -> 'ReactNative'
* nativescript
* navigator.product -> 'NativeScript' or 'NS'
*/
function isStandardBrowserEnv() {
if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
navigator.product === 'NativeScript' ||
navigator.product === 'NS')) {
return false;
}
return (
typeof window !== 'undefined' &&
typeof document !== 'undefined'
);
}
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*/
function forEach$5(obj, fn) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
// Force an array if not already something iterable
if (typeof obj !== 'object') {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray$a(obj)) {
// Iterate over array values
for (var i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Iterate over object keys
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(null, obj[key], key, obj);
}
}
}
}
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* var result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function merge$1(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (isPlainObject$1(result[key]) && isPlainObject$1(val)) {
result[key] = merge$1(result[key], val);
} else if (isPlainObject$1(val)) {
result[key] = merge$1({}, val);
} else if (isArray$a(val)) {
result[key] = val.slice();
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach$5(arguments[i], assignValue);
}
return result;
}
/**
* Extends object a by mutably adding to it the properties of object b.
*
* @param {Object} a The object to be extended
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
* @return {Object} The resulting value of object a
*/
function extend(a, b, thisArg) {
forEach$5(b, function assignValue(val, key) {
if (thisArg && typeof val === 'function') {
a[key] = bind$a(val, thisArg);
} else {
a[key] = val;
}
});
return a;
}
/**
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
*
* @param {string} content with BOM
* @return {string} content value without BOM
*/
function stripBOM(content) {
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1);
}
return content;
}
var utils = {
isArray: isArray$a,
isArrayBuffer: isArrayBuffer,
isBuffer: isBuffer$1,
isFormData: isFormData,
isArrayBufferView: isArrayBufferView,
isString: isString,
isNumber: isNumber,
isObject: isObject$3,
isPlainObject: isPlainObject$1,
isUndefined: isUndefined,
isDate: isDate,
isFile: isFile,
isBlob: isBlob,
isFunction: isFunction$1,
isStream: isStream,
isURLSearchParams: isURLSearchParams,
isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach$5,
merge: merge$1,
extend: extend,
trim: trim$6,
stripBOM: stripBOM
};
function encode$1(val) {
return encodeURIComponent(val).
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, '+').
replace(/%5B/gi, '[').
replace(/%5D/gi, ']');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @returns {string} The formatted url
*/
var buildURL = function buildURL(url, params, paramsSerializer) {
/*eslint no-param-reassign:0*/
if (!params) {
return url;
}
var serializedParams;
if (paramsSerializer) {
serializedParams = paramsSerializer(params);
} else if (utils.isURLSearchParams(params)) {
serializedParams = params.toString();
} else {
var parts = [];
utils.forEach(params, function serialize(val, key) {
if (val === null || typeof val === 'undefined') {
return;
}
if (utils.isArray(val)) {
key = key + '[]';
} else {
val = [val];
}
utils.forEach(val, function parseValue(v) {
if (utils.isDate(v)) {
v = v.toISOString();
} else if (utils.isObject(v)) {
v = JSON.stringify(v);
}
parts.push(encode$1(key) + '=' + encode$1(v));
});
});
serializedParams = parts.join('&');
}
if (serializedParams) {
var hashmarkIndex = url.indexOf('#');
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
};
function InterceptorManager() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null
});
return this.handlers.length - 1;
};
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*/
InterceptorManager.prototype.eject = function eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
};
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*/
InterceptorManager.prototype.forEach = function forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
};
var InterceptorManager_1 = InterceptorManager;
var normalizeHeaderName = function normalizeHeaderName(headers, normalizedName) {
utils.forEach(headers, function processHeader(value, name) {
if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
headers[normalizedName] = value;
delete headers[name];
}
});
};
/**
* Update an Error with the specified config, error code, and response.
*
* @param {Error} error The error to update.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The error.
*/
var enhanceError = function enhanceError(error, config, code, request, response) {
error.config = config;
if (code) {
error.code = code;
}
error.request = request;
error.response = response;
error.isAxiosError = true;
error.toJSON = function toJSON() {
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: this.config,
code: this.code,
status: this.response && this.response.status ? this.response.status : null
};
};
return error;
};
var transitional = {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
};
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The created error.
*/
var createError = function createError(message, config, code, request, response) {
var error = new Error(message);
return enhanceError(error, config, code, request, response);
};
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*/
var settle = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(createError(
'Request failed with status code ' + response.status,
response.config,
null,
response.request,
response
));
}
};
var cookies = (
utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})()
);
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
var isAbsoluteURL = function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
};
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
* @returns {string} The combined URL
*/
var combineURLs = function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
};
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
* @returns {string} The combined full path
*/
var buildFullPath = function buildFullPath(baseURL, requestedURL) {
if (baseURL && !isAbsoluteURL(requestedURL)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
};
// Headers whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
var ignoreDuplicateOf = [
'age', 'authorization', 'content-length', 'content-type', 'etag',
'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
'last-modified', 'location', 'max-forwards', 'proxy-authorization',
'referer', 'retry-after', 'user-agent'
];
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} headers Headers needing to be parsed
* @returns {Object} Headers parsed into an object
*/
var parseHeaders = function parseHeaders(headers) {
var parsed = {};
var key;
var val;
var i;
if (!headers) { return parsed; }
utils.forEach(headers.split('\n'), function parser(line) {
i = line.indexOf(':');
key = utils.trim(line.substr(0, i)).toLowerCase();
val = utils.trim(line.substr(i + 1));
if (key) {
if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
return;
}
if (key === 'set-cookie') {
parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
}
});
return parsed;
};
var isURLSameOrigin = (
utils.isStandardBrowserEnv() ?
// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
(function standardBrowserEnv() {
var msie = /(msie|trident)/i.test(navigator.userAgent);
var urlParsingNode = document.createElement('a');
var originURL;
/**
* Parse a URL to discover it's components
*
* @param {String} url The URL to be parsed
* @returns {Object}
*/
function resolveURL(url) {
var href = url;
if (msie) {
// IE needs attribute set twice to normalize properties
urlParsingNode.setAttribute('href', href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
urlParsingNode.pathname :
'/' + urlParsingNode.pathname
};
}
originURL = resolveURL(window.location.href);
/**
* Determine if a URL shares the same origin as the current location
*
* @param {String} requestURL The URL to test
* @returns {boolean} True if URL shares the same origin, otherwise false
*/
return function isURLSameOrigin(requestURL) {
var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
return (parsed.protocol === originURL.protocol &&
parsed.host === originURL.host);
};
})() :
// Non standard browser envs (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return function isURLSameOrigin() {
return true;
};
})()
);
/**
* A `Cancel` is an object that is thrown when an operation is canceled.
*
* @class
* @param {string=} message The message.
*/
function Cancel(message) {
this.message = message;
}
Cancel.prototype.toString = function toString() {
return 'Cancel' + (this.message ? ': ' + this.message : '');
};
Cancel.prototype.__CANCEL__ = true;
var Cancel_1 = Cancel;
var xhr = function xhrAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
var requestData = config.data;
var requestHeaders = config.headers;
var responseType = config.responseType;
var onCanceled;
function done() {
if (config.cancelToken) {
config.cancelToken.unsubscribe(onCanceled);
}
if (config.signal) {
config.signal.removeEventListener('abort', onCanceled);
}
}
if (utils.isFormData(requestData)) {
delete requestHeaders['Content-Type']; // Let the browser set it
}
var request = new XMLHttpRequest();
// HTTP basic authentication
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
}
var fullPath = buildFullPath(config.baseURL, config.url);
request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
// Set the request timeout in MS
request.timeout = config.timeout;
function onloadend() {
if (!request) {
return;
}
// Prepare the response
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
request.responseText : request.response;
var response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config: config,
request: request
};
settle(function _resolve(value) {
resolve(value);
done();
}, function _reject(err) {
reject(err);
done();
}, response);
// Clean up request
request = null;
}
if ('onloadend' in request) {
// Use onloadend if available
request.onloadend = onloadend;
} else {
// Listen for ready state to emulate onloadend
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
return;
}
// readystate handler is calling before onerror or ontimeout handlers,
// so we should call onloadend on the next 'tick'
setTimeout(onloadend);
};
}
// Handle browser request cancellation (as opposed to a manual cancellation)
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(createError('Request aborted', config, 'ECONNABORTED', request));
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(createError('Network Error', config, null, request));
// Clean up request
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
var transitional$1 = config.transitional || transitional;
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
reject(createError(
timeoutErrorMessage,
config,
transitional$1.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED',
request));
// Clean up request
request = null;
};
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) {
// Add xsrf header
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
cookies.read(config.xsrfCookieName) :
undefined;
if (xsrfValue) {
requestHeaders[config.xsrfHeaderName] = xsrfValue;
}
}
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
// Remove Content-Type if data is undefined
delete requestHeaders[key];
} else {
// Otherwise add header to the request
request.setRequestHeader(key, val);
}
});
}
// Add withCredentials to request if needed
if (!utils.isUndefined(config.withCredentials)) {
request.withCredentials = !!config.withCredentials;
}
// Add responseType to request if needed
if (responseType && responseType !== 'json') {
request.responseType = config.responseType;
}
// Handle progress if needed
if (typeof config.onDownloadProgress === 'function') {
request.addEventListener('progress', config.onDownloadProgress);
}
// Not all browsers support upload events
if (typeof config.onUploadProgress === 'function' && request.upload) {
request.upload.addEventListener('progress', config.onUploadProgress);
}
if (config.cancelToken || config.signal) {
// Handle cancellation
// eslint-disable-next-line func-names
onCanceled = function(cancel) {
if (!request) {
return;
}
reject(!cancel || (cancel && cancel.type) ? new Cancel_1('canceled') : cancel);
request.abort();
request = null;
};
config.cancelToken && config.cancelToken.subscribe(onCanceled);
if (config.signal) {
config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
}
}
if (!requestData) {
requestData = null;
}
// Send the request
request.send(requestData);
});
};
var DEFAULT_CONTENT_TYPE = {
'Content-Type': 'application/x-www-form-urlencoded'
};
function setContentTypeIfUnset(headers, value) {
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
headers['Content-Type'] = value;
}
}
function getDefaultAdapter() {
var adapter;
if (typeof XMLHttpRequest !== 'undefined') {
// For browsers use XHR adapter
adapter = xhr;
} else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
// For node use HTTP adapter
adapter = xhr;
}
return adapter;
}
function stringifySafely(rawValue, parser, encoder) {
if (utils.isString(rawValue)) {
try {
(parser || JSON.parse)(rawValue);
return utils.trim(rawValue);
} catch (e) {
if (e.name !== 'SyntaxError') {
throw e;
}
}
}
return (encoder || JSON.stringify)(rawValue);
}
var defaults = {
transitional: transitional,
adapter: getDefaultAdapter(),
transformRequest: [function transformRequest(data, headers) {
normalizeHeaderName(headers, 'Accept');
normalizeHeaderName(headers, 'Content-Type');
if (utils.isFormData(data) ||
utils.isArrayBuffer(data) ||
utils.isBuffer(data) ||
utils.isStream(data) ||
utils.isFile(data) ||
utils.isBlob(data)
) {
return data;
}
if (utils.isArrayBufferView(data)) {
return data.buffer;
}
if (utils.isURLSearchParams(data)) {
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
return data.toString();
}
if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) {
setContentTypeIfUnset(headers, 'application/json');
return stringifySafely(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
var transitional = this.transitional || defaults.transitional;
var silentJSONParsing = transitional && transitional.silentJSONParsing;
var forcedJSONParsing = transitional && transitional.forcedJSONParsing;
var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';
if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {
try {
return JSON.parse(data);
} catch (e) {
if (strictJSONParsing) {
if (e.name === 'SyntaxError') {
throw enhanceError(e, this, 'E_JSON_PARSE');
}
throw e;
}
}
}
return data;
}],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
},
headers: {
common: {
'Accept': 'application/json, text/plain, */*'
}
}
};
utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
defaults.headers[method] = {};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
});
var defaults_1 = defaults;
/**
* Transform the data for a request or a response
*
* @param {Object|String} data The data to be transformed
* @param {Array} headers The headers for the request or response
* @param {Array|Function} fns A single function or Array of functions
* @returns {*} The resulting transformed data
*/
var transformData = function transformData(data, headers, fns) {
var context = this || defaults_1;
/*eslint no-param-reassign:0*/
utils.forEach(fns, function transform(fn) {
data = fn.call(context, data, headers);
});
return data;
};
var isCancel = function isCancel(value) {
return !!(value && value.__CANCEL__);
};
/**
* Throws a `Cancel` if cancellation has been requested.
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
if (config.signal && config.signal.aborted) {
throw new Cancel_1('canceled');
}
}
/**
* Dispatch a request to the server using the configured adapter.
*
* @param {object} config The config that is to be used for the request
* @returns {Promise} The Promise to be fulfilled
*/
var dispatchRequest = function dispatchRequest(config) {
throwIfCancellationRequested(config);
// Ensure headers exist
config.headers = config.headers || {};
// Transform request data
config.data = transformData.call(
config,
config.data,
config.headers,
config.transformRequest
);
// Flatten headers
config.headers = utils.merge(
config.headers.common || {},
config.headers[config.method] || {},
config.headers
);
utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
function cleanHeaderConfig(method) {
delete config.headers[method];
}
);
var adapter = config.adapter || defaults_1.adapter;
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
// Transform response data
response.data = transformData.call(
config,
response.data,
response.headers,
config.transformResponse
);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
// Transform response data
if (reason && reason.response) {
reason.response.data = transformData.call(
config,
reason.response.data,
reason.response.headers,
config.transformResponse
);
}
}
return Promise.reject(reason);
});
};
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
* @returns {Object} New object resulting from merging config2 to config1
*/
var mergeConfig = function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config2 = config2 || {};
var config = {};
function getMergedValue(target, source) {
if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
return utils.merge(target, source);
} else if (utils.isPlainObject(source)) {
return utils.merge({}, source);
} else if (utils.isArray(source)) {
return source.slice();
}
return source;
}
// eslint-disable-next-line consistent-return
function mergeDeepProperties(prop) {
if (!utils.isUndefined(config2[prop])) {
return getMergedValue(config1[prop], config2[prop]);
} else if (!utils.isUndefined(config1[prop])) {
return getMergedValue(undefined, config1[prop]);
}
}
// eslint-disable-next-line consistent-return
function valueFromConfig2(prop) {
if (!utils.isUndefined(config2[prop])) {
return getMergedValue(undefined, config2[prop]);
}
}
// eslint-disable-next-line consistent-return
function defaultToConfig2(prop) {
if (!utils.isUndefined(config2[prop])) {
return getMergedValue(undefined, config2[prop]);
} else if (!utils.isUndefined(config1[prop])) {
return getMergedValue(undefined, config1[prop]);
}
}
// eslint-disable-next-line consistent-return
function mergeDirectKeys(prop) {
if (prop in config2) {
return getMergedValue(config1[prop], config2[prop]);
} else if (prop in config1) {
return getMergedValue(undefined, config1[prop]);
}
}
var mergeMap = {
'url': valueFromConfig2,
'method': valueFromConfig2,
'data': valueFromConfig2,
'baseURL': defaultToConfig2,
'transformRequest': defaultToConfig2,
'transformResponse': defaultToConfig2,
'paramsSerializer': defaultToConfig2,
'timeout': defaultToConfig2,
'timeoutMessage': defaultToConfig2,
'withCredentials': defaultToConfig2,
'adapter': defaultToConfig2,
'responseType': defaultToConfig2,
'xsrfCookieName': defaultToConfig2,
'xsrfHeaderName': defaultToConfig2,
'onUploadProgress': defaultToConfig2,
'onDownloadProgress': defaultToConfig2,
'decompress': defaultToConfig2,
'maxContentLength': defaultToConfig2,
'maxBodyLength': defaultToConfig2,
'transport': defaultToConfig2,
'httpAgent': defaultToConfig2,
'httpsAgent': defaultToConfig2,
'cancelToken': defaultToConfig2,
'socketPath': defaultToConfig2,
'responseEncoding': defaultToConfig2,
'validateStatus': mergeDirectKeys
};
utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
var merge = mergeMap[prop] || mergeDeepProperties;
var configValue = merge(prop);
(utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
});
return config;
};
var data$1 = {
"version": "0.26.1"
};
var VERSION = data$1.version;
var validators = {};
// eslint-disable-next-line func-names
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {
validators[type] = function validator(thing) {
return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
};
});
var deprecatedWarnings = {};
/**
* Transitional option validator
* @param {function|boolean?} validator - set to false if the transitional option has been removed
* @param {string?} version - deprecated version / removed since version
* @param {string?} message - some message with additional info
* @returns {function}
*/
validators.transitional = function transitional(validator, version, message) {
function formatMessage(opt, desc) {
return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
}
// eslint-disable-next-line func-names
return function(value, opt, opts) {
if (validator === false) {
throw new Error(formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')));
}
if (version && !deprecatedWarnings[opt]) {
deprecatedWarnings[opt] = true;
// eslint-disable-next-line no-console
console.warn(
formatMessage(
opt,
' has been deprecated since v' + version + ' and will be removed in the near future'
)
);
}
return validator ? validator(value, opt, opts) : true;
};
};
/**
* Assert object's properties type
* @param {object} options
* @param {object} schema
* @param {boolean?} allowUnknown
*/
function assertOptions(options, schema, allowUnknown) {
if (typeof options !== 'object') {
throw new TypeError('options must be an object');
}
var keys = Object.keys(options);
var i = keys.length;
while (i-- > 0) {
var opt = keys[i];
var validator = schema[opt];
if (validator) {
var value = options[opt];
var result = value === undefined || validator(value, opt, options);
if (result !== true) {
throw new TypeError('option ' + opt + ' must be ' + result);
}
continue;
}
if (allowUnknown !== true) {
throw Error('Unknown option ' + opt);
}
}
}
var validator = {
assertOptions: assertOptions,
validators: validators
};
var validators$1 = validator.validators;
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*/
function Axios(instanceConfig) {
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager_1(),
response: new InterceptorManager_1()
};
}
/**
* Dispatch a request
*
* @param {Object} config The config specific for this request (merged with this.defaults)
*/
Axios.prototype.request = function request(configOrUrl, config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof configOrUrl === 'string') {
config = config || {};
config.url = configOrUrl;
} else {
config = configOrUrl || {};
}
config = mergeConfig(this.defaults, config);
// Set config.method
if (config.method) {
config.method = config.method.toLowerCase();
} else if (this.defaults.method) {
config.method = this.defaults.method.toLowerCase();
} else {
config.method = 'get';
}
var transitional = config.transitional;
if (transitional !== undefined) {
validator.assertOptions(transitional, {
silentJSONParsing: validators$1.transitional(validators$1.boolean),
forcedJSONParsing: validators$1.transitional(validators$1.boolean),
clarifyTimeoutError: validators$1.transitional(validators$1.boolean)
}, false);
}
// filter out skipped interceptors
var requestInterceptorChain = [];
var synchronousRequestInterceptors = true;
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
return;
}
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
});
var responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
var promise;
if (!synchronousRequestInterceptors) {
var chain = [dispatchRequest, undefined];
Array.prototype.unshift.apply(chain, requestInterceptorChain);
chain = chain.concat(responseInterceptorChain);
promise = Promise.resolve(config);
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
}
var newConfig = config;
while (requestInterceptorChain.length) {
var onFulfilled = requestInterceptorChain.shift();
var onRejected = requestInterceptorChain.shift();
try {
newConfig = onFulfilled(newConfig);
} catch (error) {
onRejected(error);
break;
}
}
try {
promise = dispatchRequest(newConfig);
} catch (error) {
return Promise.reject(error);
}
while (responseInterceptorChain.length) {
promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
}
return promise;
};
Axios.prototype.getUri = function getUri(config) {
config = mergeConfig(this.defaults, config);
return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, '');
};
// Provide aliases for supported request methods
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, config) {
return this.request(mergeConfig(config || {}, {
method: method,
url: url,
data: (config || {}).data
}));
};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, data, config) {
return this.request(mergeConfig(config || {}, {
method: method,
url: url,
data: data
}));
};
});
var Axios_1 = Axios;
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @class
* @param {Function} executor The executor function.
*/
function CancelToken(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
var resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
var token = this;
// eslint-disable-next-line func-names
this.promise.then(function(cancel) {
if (!token._listeners) return;
var i;
var l = token._listeners.length;
for (i = 0; i < l; i++) {
token._listeners[i](cancel);
}
token._listeners = null;
});
// eslint-disable-next-line func-names
this.promise.then = function(onfulfilled) {
var _resolve;
// eslint-disable-next-line func-names
var promise = new Promise(function(resolve) {
token.subscribe(resolve);
_resolve = resolve;
}).then(onfulfilled);
promise.cancel = function reject() {
token.unsubscribe(_resolve);
};
return promise;
};
executor(function cancel(message) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new Cancel_1(message);
resolvePromise(token.reason);
});
}
/**
* Throws a `Cancel` if cancellation has been requested.
*/
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
if (this.reason) {
throw this.reason;
}
};
/**
* Subscribe to the cancel signal
*/
CancelToken.prototype.subscribe = function subscribe(listener) {
if (this.reason) {
listener(this.reason);
return;
}
if (this._listeners) {
this._listeners.push(listener);
} else {
this._listeners = [listener];
}
};
/**
* Unsubscribe from the cancel signal
*/
CancelToken.prototype.unsubscribe = function unsubscribe(listener) {
if (!this._listeners) {
return;
}
var index = this._listeners.indexOf(listener);
if (index !== -1) {
this._listeners.splice(index, 1);
}
};
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
CancelToken.source = function source() {
var cancel;
var token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token: token,
cancel: cancel
};
};
var CancelToken_1 = CancelToken;
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* var args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
* @returns {Function}
*/
var spread = function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
};
/**
* Determines whether the payload is an error thrown by Axios
*
* @param {*} payload The value to test
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
var isAxiosError = function isAxiosError(payload) {
return utils.isObject(payload) && (payload.isAxiosError === true);
};
/**
* Create an instance of Axios
*
* @param {Object} defaultConfig The default config for the instance
* @return {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
var context = new Axios_1(defaultConfig);
var instance = bind$a(Axios_1.prototype.request, context);
// Copy axios.prototype to instance
utils.extend(instance, Axios_1.prototype, context);
// Copy context to instance
utils.extend(instance, context);
// Factory for creating new instances
instance.create = function create(instanceConfig) {
return createInstance(mergeConfig(defaultConfig, instanceConfig));
};
return instance;
}
// Create the default instance to be exported
var axios = createInstance(defaults_1);
// Expose Axios class to allow class inheritance
axios.Axios = Axios_1;
// Expose Cancel & CancelToken
axios.Cancel = Cancel_1;
axios.CancelToken = CancelToken_1;
axios.isCancel = isCancel;
axios.VERSION = data$1.version;
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = spread;
// Expose isAxiosError
axios.isAxiosError = isAxiosError;
var axios_1 = axios;
// Allow use of default import syntax in TypeScript
var _default = axios;
axios_1.default = _default;
var axios$1 = axios_1;
var base$1 = createCommonjsModule(function (module, exports) {
/* tslint:disable */
/* eslint-disable */
/**
* OpenAI API
* APIs for sampling from and fine-tuning language models
*
* The version of the OpenAPI document: 1.3.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.RequiredError = exports.BaseAPI = exports.COLLECTION_FORMATS = exports.BASE_PATH = void 0;
exports.BASE_PATH = "https://api.openai.com/v1".replace(/\/+$/, "");
/**
*
* @export
*/
exports.COLLECTION_FORMATS = {
csv: ",",
ssv: " ",
tsv: "\t",
pipes: "|",
};
/**
*
* @export
* @class BaseAPI
*/
class BaseAPI {
constructor(configuration, basePath = exports.BASE_PATH, axios = axios$1.default) {
this.basePath = basePath;
this.axios = axios;
if (configuration) {
this.configuration = configuration;
this.basePath = configuration.basePath || this.basePath;
}
}
}
exports.BaseAPI = BaseAPI;
/**
*
* @export
* @class RequiredError
* @extends {Error}
*/
class RequiredError extends Error {
constructor(field, msg) {
super(msg);
this.field = field;
this.name = "RequiredError";
}
}
exports.RequiredError = RequiredError;
});
unwrapExports(base$1);
var base_1 = base$1.RequiredError;
var base_2 = base$1.BaseAPI;
var base_3 = base$1.COLLECTION_FORMATS;
var base_4 = base$1.BASE_PATH;
var common = createCommonjsModule(function (module, exports) {
/* tslint:disable */
/* eslint-disable */
/**
* OpenAI API
* APIs for sampling from and fine-tuning language models
*
* The version of the OpenAPI document: 1.3.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createRequestFunction = exports.toPathString = exports.serializeDataIfNeeded = exports.setSearchParams = exports.setOAuthToObject = exports.setBearerAuthToObject = exports.setBasicAuthToObject = exports.setApiKeyToObject = exports.assertParamExists = exports.DUMMY_BASE_URL = void 0;
/**
*
* @export
*/
exports.DUMMY_BASE_URL = 'https://example.com';
/**
*
* @throws {RequiredError}
* @export
*/
exports.assertParamExists = function (functionName, paramName, paramValue) {
if (paramValue === null || paramValue === undefined) {
throw new base$1.RequiredError(paramName, `Required parameter ${paramName} was null or undefined when calling ${functionName}.`);
}
};
/**
*
* @export
*/
exports.setApiKeyToObject = function (object, keyParamName, configuration) {
return __awaiter(this, void 0, void 0, function* () {
if (configuration && configuration.apiKey) {
const localVarApiKeyValue = typeof configuration.apiKey === 'function'
? yield configuration.apiKey(keyParamName)
: yield configuration.apiKey;
object[keyParamName] = localVarApiKeyValue;
}
});
};
/**
*
* @export
*/
exports.setBasicAuthToObject = function (object, configuration) {
if (configuration && (configuration.username || configuration.password)) {
object["auth"] = { username: configuration.username, password: configuration.password };
}
};
/**
*
* @export
*/
exports.setBearerAuthToObject = function (object, configuration) {
return __awaiter(this, void 0, void 0, function* () {
if (configuration && configuration.accessToken) {
const accessToken = typeof configuration.accessToken === 'function'
? yield configuration.accessToken()
: yield configuration.accessToken;
object["Authorization"] = "Bearer " + accessToken;
}
});
};
/**
*
* @export
*/
exports.setOAuthToObject = function (object, name, scopes, configuration) {
return __awaiter(this, void 0, void 0, function* () {
if (configuration && configuration.accessToken) {
const localVarAccessTokenValue = typeof configuration.accessToken === 'function'
? yield configuration.accessToken(name, scopes)
: yield configuration.accessToken;
object["Authorization"] = "Bearer " + localVarAccessTokenValue;
}
});
};
function setFlattenedQueryParams(urlSearchParams, parameter, key = "") {
if (parameter == null)
return;
if (typeof parameter === "object") {
if (Array.isArray(parameter)) {
parameter.forEach(item => setFlattenedQueryParams(urlSearchParams, item, key));
}
else {
Object.keys(parameter).forEach(currentKey => setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`));
}
}
else {
if (urlSearchParams.has(key)) {
urlSearchParams.append(key, parameter);
}
else {
urlSearchParams.set(key, parameter);
}
}
}
/**
*
* @export
*/
exports.setSearchParams = function (url, ...objects) {
const searchParams = new URLSearchParams(url.search);
setFlattenedQueryParams(searchParams, objects);
url.search = searchParams.toString();
};
/**
*
* @export
*/
exports.serializeDataIfNeeded = function (value, requestOptions, configuration) {
const nonString = typeof value !== 'string';
const needsSerialization = nonString && configuration && configuration.isJsonMime
? configuration.isJsonMime(requestOptions.headers['Content-Type'])
: nonString;
return needsSerialization
? JSON.stringify(value !== undefined ? value : {})
: (value || "");
};
/**
*
* @export
*/
exports.toPathString = function (url) {
return url.pathname + url.search + url.hash;
};
/**
*
* @export
*/
exports.createRequestFunction = function (axiosArgs, globalAxios, BASE_PATH, configuration) {
return (axios = globalAxios, basePath = BASE_PATH) => {
const axiosRequestArgs = Object.assign(Object.assign({}, axiosArgs.options), { url: ((configuration === null || configuration === void 0 ? void 0 : configuration.basePath) || basePath) + axiosArgs.url });
return axios.request(axiosRequestArgs);
};
};
});
unwrapExports(common);
var common_1 = common.createRequestFunction;
var common_2 = common.toPathString;
var common_3 = common.serializeDataIfNeeded;
var common_4 = common.setSearchParams;
var common_5 = common.setOAuthToObject;
var common_6 = common.setBearerAuthToObject;
var common_7 = common.setBasicAuthToObject;
var common_8 = common.setApiKeyToObject;
var common_9 = common.assertParamExists;
var common_10 = common.DUMMY_BASE_URL;
var api = createCommonjsModule(function (module, exports) {
/* tslint:disable */
/* eslint-disable */
/**
* OpenAI API
* APIs for sampling from and fine-tuning language models
*
* The version of the OpenAPI document: 1.3.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OpenAIApi = exports.OpenAIApiFactory = exports.OpenAIApiFp = exports.OpenAIApiAxiosParamCreator = exports.CreateImageRequestResponseFormatEnum = exports.CreateImageRequestSizeEnum = exports.ChatCompletionResponseMessageRoleEnum = exports.ChatCompletionRequestMessageRoleEnum = void 0;
// Some imports not used depending on template conditions
// @ts-ignore
// @ts-ignore
exports.ChatCompletionRequestMessageRoleEnum = {
System: 'system',
User: 'user',
Assistant: 'assistant',
Function: 'function'
};
exports.ChatCompletionResponseMessageRoleEnum = {
System: 'system',
User: 'user',
Assistant: 'assistant',
Function: 'function'
};
exports.CreateImageRequestSizeEnum = {
_256x256: '256x256',
_512x512: '512x512',
_1024x1024: '1024x1024'
};
exports.CreateImageRequestResponseFormatEnum = {
Url: 'url',
B64Json: 'b64_json'
};
/**
* OpenAIApi - axios parameter creator
* @export
*/
exports.OpenAIApiAxiosParamCreator = function (configuration) {
return {
/**
*
* @summary Immediately cancel a fine-tune job.
* @param {string} fineTuneId The ID of the fine-tune job to cancel
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
cancelFineTune: (fineTuneId, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'fineTuneId' is not null or undefined
common.assertParamExists('cancelFineTune', 'fineTuneId', fineTuneId);
const localVarPath = `/fine-tunes/{fine_tune_id}/cancel`
.replace(`{${"fine_tune_id"}}`, encodeURIComponent(String(fineTuneId)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'POST' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Answers the specified question using the provided documents and examples. The endpoint first [searches](/docs/api-reference/searches) over provided documents or files to find relevant context. The relevant context is combined with the provided examples and question to create the prompt for [completion](/docs/api-reference/completions).
* @param {CreateAnswerRequest} createAnswerRequest
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
*/
createAnswer: (createAnswerRequest, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'createAnswerRequest' is not null or undefined
common.assertParamExists('createAnswer', 'createAnswerRequest', createAnswerRequest);
const localVarPath = `/answers`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'POST' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
localVarHeaderParameter['Content-Type'] = 'application/json';
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
localVarRequestOptions.data = common.serializeDataIfNeeded(createAnswerRequest, localVarRequestOptions, configuration);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Creates a model response for the given chat conversation.
* @param {CreateChatCompletionRequest} createChatCompletionRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createChatCompletion: (createChatCompletionRequest, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'createChatCompletionRequest' is not null or undefined
common.assertParamExists('createChatCompletion', 'createChatCompletionRequest', createChatCompletionRequest);
const localVarPath = `/chat/completions`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'POST' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
localVarHeaderParameter['Content-Type'] = 'application/json';
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
localVarRequestOptions.data = common.serializeDataIfNeeded(createChatCompletionRequest, localVarRequestOptions, configuration);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Classifies the specified `query` using provided examples. The endpoint first [searches](/docs/api-reference/searches) over the labeled examples to select the ones most relevant for the particular query. Then, the relevant examples are combined with the query to construct a prompt to produce the final label via the [completions](/docs/api-reference/completions) endpoint. Labeled examples can be provided via an uploaded `file`, or explicitly listed in the request using the `examples` parameter for quick tests and small scale use cases.
* @param {CreateClassificationRequest} createClassificationRequest
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
*/
createClassification: (createClassificationRequest, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'createClassificationRequest' is not null or undefined
common.assertParamExists('createClassification', 'createClassificationRequest', createClassificationRequest);
const localVarPath = `/classifications`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'POST' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
localVarHeaderParameter['Content-Type'] = 'application/json';
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
localVarRequestOptions.data = common.serializeDataIfNeeded(createClassificationRequest, localVarRequestOptions, configuration);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Creates a completion for the provided prompt and parameters.
* @param {CreateCompletionRequest} createCompletionRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createCompletion: (createCompletionRequest, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'createCompletionRequest' is not null or undefined
common.assertParamExists('createCompletion', 'createCompletionRequest', createCompletionRequest);
const localVarPath = `/completions`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'POST' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
localVarHeaderParameter['Content-Type'] = 'application/json';
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
localVarRequestOptions.data = common.serializeDataIfNeeded(createCompletionRequest, localVarRequestOptions, configuration);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Creates a new edit for the provided input, instruction, and parameters.
* @param {CreateEditRequest} createEditRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createEdit: (createEditRequest, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'createEditRequest' is not null or undefined
common.assertParamExists('createEdit', 'createEditRequest', createEditRequest);
const localVarPath = `/edits`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'POST' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
localVarHeaderParameter['Content-Type'] = 'application/json';
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
localVarRequestOptions.data = common.serializeDataIfNeeded(createEditRequest, localVarRequestOptions, configuration);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Creates an embedding vector representing the input text.
* @param {CreateEmbeddingRequest} createEmbeddingRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createEmbedding: (createEmbeddingRequest, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'createEmbeddingRequest' is not null or undefined
common.assertParamExists('createEmbedding', 'createEmbeddingRequest', createEmbeddingRequest);
const localVarPath = `/embeddings`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'POST' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
localVarHeaderParameter['Content-Type'] = 'application/json';
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
localVarRequestOptions.data = common.serializeDataIfNeeded(createEmbeddingRequest, localVarRequestOptions, configuration);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Upload a file that contains document(s) to be used across various endpoints/features. Currently, the size of all the files uploaded by one organization can be up to 1 GB. Please contact us if you need to increase the storage limit.
* @param {File} file Name of the [JSON Lines](https://jsonlines.readthedocs.io/en/latest/) file to be uploaded. If the &#x60;purpose&#x60; is set to \\\&quot;fine-tune\\\&quot;, each line is a JSON record with \\\&quot;prompt\\\&quot; and \\\&quot;completion\\\&quot; fields representing your [training examples](/docs/guides/fine-tuning/prepare-training-data).
* @param {string} purpose The intended purpose of the uploaded documents. Use \\\&quot;fine-tune\\\&quot; for [Fine-tuning](/docs/api-reference/fine-tunes). This allows us to validate the format of the uploaded file.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createFile: (file, purpose, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'file' is not null or undefined
common.assertParamExists('createFile', 'file', file);
// verify required parameter 'purpose' is not null or undefined
common.assertParamExists('createFile', 'purpose', purpose);
const localVarPath = `/files`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'POST' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
const localVarFormParams = new ((configuration && configuration.formDataCtor) || FormData)();
if (file !== undefined) {
localVarFormParams.append('file', file);
}
if (purpose !== undefined) {
localVarFormParams.append('purpose', purpose);
}
localVarHeaderParameter['Content-Type'] = 'multipart/form-data';
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), localVarFormParams.getHeaders()), headersFromBaseOptions), options.headers);
localVarRequestOptions.data = localVarFormParams;
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Creates a job that fine-tunes a specified model from a given dataset. Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete. [Learn more about Fine-tuning](/docs/guides/fine-tuning)
* @param {CreateFineTuneRequest} createFineTuneRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createFineTune: (createFineTuneRequest, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'createFineTuneRequest' is not null or undefined
common.assertParamExists('createFineTune', 'createFineTuneRequest', createFineTuneRequest);
const localVarPath = `/fine-tunes`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'POST' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
localVarHeaderParameter['Content-Type'] = 'application/json';
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
localVarRequestOptions.data = common.serializeDataIfNeeded(createFineTuneRequest, localVarRequestOptions, configuration);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Creates an image given a prompt.
* @param {CreateImageRequest} createImageRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createImage: (createImageRequest, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'createImageRequest' is not null or undefined
common.assertParamExists('createImage', 'createImageRequest', createImageRequest);
const localVarPath = `/images/generations`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'POST' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
localVarHeaderParameter['Content-Type'] = 'application/json';
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
localVarRequestOptions.data = common.serializeDataIfNeeded(createImageRequest, localVarRequestOptions, configuration);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Creates an edited or extended image given an original image and a prompt.
* @param {File} image The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask is not provided, image must have transparency, which will be used as the mask.
* @param {string} prompt A text description of the desired image(s). The maximum length is 1000 characters.
* @param {File} [mask] An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where &#x60;image&#x60; should be edited. Must be a valid PNG file, less than 4MB, and have the same dimensions as &#x60;image&#x60;.
* @param {number} [n] The number of images to generate. Must be between 1 and 10.
* @param {string} [size] The size of the generated images. Must be one of &#x60;256x256&#x60;, &#x60;512x512&#x60;, or &#x60;1024x1024&#x60;.
* @param {string} [responseFormat] The format in which the generated images are returned. Must be one of &#x60;url&#x60; or &#x60;b64_json&#x60;.
* @param {string} [user] A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createImageEdit: (image, prompt, mask, n, size, responseFormat, user, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'image' is not null or undefined
common.assertParamExists('createImageEdit', 'image', image);
// verify required parameter 'prompt' is not null or undefined
common.assertParamExists('createImageEdit', 'prompt', prompt);
const localVarPath = `/images/edits`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'POST' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
const localVarFormParams = new ((configuration && configuration.formDataCtor) || FormData)();
if (image !== undefined) {
localVarFormParams.append('image', image);
}
if (mask !== undefined) {
localVarFormParams.append('mask', mask);
}
if (prompt !== undefined) {
localVarFormParams.append('prompt', prompt);
}
if (n !== undefined) {
localVarFormParams.append('n', n);
}
if (size !== undefined) {
localVarFormParams.append('size', size);
}
if (responseFormat !== undefined) {
localVarFormParams.append('response_format', responseFormat);
}
if (user !== undefined) {
localVarFormParams.append('user', user);
}
localVarHeaderParameter['Content-Type'] = 'multipart/form-data';
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), localVarFormParams.getHeaders()), headersFromBaseOptions), options.headers);
localVarRequestOptions.data = localVarFormParams;
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Creates a variation of a given image.
* @param {File} image The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square.
* @param {number} [n] The number of images to generate. Must be between 1 and 10.
* @param {string} [size] The size of the generated images. Must be one of &#x60;256x256&#x60;, &#x60;512x512&#x60;, or &#x60;1024x1024&#x60;.
* @param {string} [responseFormat] The format in which the generated images are returned. Must be one of &#x60;url&#x60; or &#x60;b64_json&#x60;.
* @param {string} [user] A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createImageVariation: (image, n, size, responseFormat, user, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'image' is not null or undefined
common.assertParamExists('createImageVariation', 'image', image);
const localVarPath = `/images/variations`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'POST' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
const localVarFormParams = new ((configuration && configuration.formDataCtor) || FormData)();
if (image !== undefined) {
localVarFormParams.append('image', image);
}
if (n !== undefined) {
localVarFormParams.append('n', n);
}
if (size !== undefined) {
localVarFormParams.append('size', size);
}
if (responseFormat !== undefined) {
localVarFormParams.append('response_format', responseFormat);
}
if (user !== undefined) {
localVarFormParams.append('user', user);
}
localVarHeaderParameter['Content-Type'] = 'multipart/form-data';
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), localVarFormParams.getHeaders()), headersFromBaseOptions), options.headers);
localVarRequestOptions.data = localVarFormParams;
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Classifies if text violates OpenAI\'s Content Policy
* @param {CreateModerationRequest} createModerationRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createModeration: (createModerationRequest, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'createModerationRequest' is not null or undefined
common.assertParamExists('createModeration', 'createModerationRequest', createModerationRequest);
const localVarPath = `/moderations`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'POST' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
localVarHeaderParameter['Content-Type'] = 'application/json';
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
localVarRequestOptions.data = common.serializeDataIfNeeded(createModerationRequest, localVarRequestOptions, configuration);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary The search endpoint computes similarity scores between provided query and documents. Documents can be passed directly to the API if there are no more than 200 of them. To go beyond the 200 document limit, documents can be processed offline and then used for efficient retrieval at query time. When `file` is set, the search endpoint searches over all the documents in the given file and returns up to the `max_rerank` number of documents. These documents will be returned along with their search scores. The similarity score is a positive score that usually ranges from 0 to 300 (but can sometimes go higher), where a score above 200 usually means the document is semantically similar to the query.
* @param {string} engineId The ID of the engine to use for this request. You can select one of &#x60;ada&#x60;, &#x60;babbage&#x60;, &#x60;curie&#x60;, or &#x60;davinci&#x60;.
* @param {CreateSearchRequest} createSearchRequest
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
*/
createSearch: (engineId, createSearchRequest, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'engineId' is not null or undefined
common.assertParamExists('createSearch', 'engineId', engineId);
// verify required parameter 'createSearchRequest' is not null or undefined
common.assertParamExists('createSearch', 'createSearchRequest', createSearchRequest);
const localVarPath = `/engines/{engine_id}/search`
.replace(`{${"engine_id"}}`, encodeURIComponent(String(engineId)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'POST' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
localVarHeaderParameter['Content-Type'] = 'application/json';
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
localVarRequestOptions.data = common.serializeDataIfNeeded(createSearchRequest, localVarRequestOptions, configuration);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Transcribes audio into the input language.
* @param {File} file The audio file object (not file name) to transcribe, in one of these formats: mp3, mp4, mpeg, mpga, m4a, wav, or webm.
* @param {string} model ID of the model to use. Only &#x60;whisper-1&#x60; is currently available.
* @param {string} [prompt] An optional text to guide the model\\\&#39;s style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should match the audio language.
* @param {string} [responseFormat] The format of the transcript output, in one of these options: json, text, srt, verbose_json, or vtt.
* @param {number} [temperature] The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.
* @param {string} [language] The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will improve accuracy and latency.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createTranscription: (file, model, prompt, responseFormat, temperature, language, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'file' is not null or undefined
common.assertParamExists('createTranscription', 'file', file);
// verify required parameter 'model' is not null or undefined
common.assertParamExists('createTranscription', 'model', model);
const localVarPath = `/audio/transcriptions`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'POST' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
const localVarFormParams = new ((configuration && configuration.formDataCtor) || FormData)();
if (file !== undefined) {
localVarFormParams.append('file', file);
}
if (model !== undefined) {
localVarFormParams.append('model', model);
}
if (prompt !== undefined) {
localVarFormParams.append('prompt', prompt);
}
if (responseFormat !== undefined) {
localVarFormParams.append('response_format', responseFormat);
}
if (temperature !== undefined) {
localVarFormParams.append('temperature', temperature);
}
if (language !== undefined) {
localVarFormParams.append('language', language);
}
localVarHeaderParameter['Content-Type'] = 'multipart/form-data';
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), localVarFormParams.getHeaders()), headersFromBaseOptions), options.headers);
localVarRequestOptions.data = localVarFormParams;
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Translates audio into into English.
* @param {File} file The audio file object (not file name) translate, in one of these formats: mp3, mp4, mpeg, mpga, m4a, wav, or webm.
* @param {string} model ID of the model to use. Only &#x60;whisper-1&#x60; is currently available.
* @param {string} [prompt] An optional text to guide the model\\\&#39;s style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should be in English.
* @param {string} [responseFormat] The format of the transcript output, in one of these options: json, text, srt, verbose_json, or vtt.
* @param {number} [temperature] The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createTranslation: (file, model, prompt, responseFormat, temperature, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'file' is not null or undefined
common.assertParamExists('createTranslation', 'file', file);
// verify required parameter 'model' is not null or undefined
common.assertParamExists('createTranslation', 'model', model);
const localVarPath = `/audio/translations`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'POST' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
const localVarFormParams = new ((configuration && configuration.formDataCtor) || FormData)();
if (file !== undefined) {
localVarFormParams.append('file', file);
}
if (model !== undefined) {
localVarFormParams.append('model', model);
}
if (prompt !== undefined) {
localVarFormParams.append('prompt', prompt);
}
if (responseFormat !== undefined) {
localVarFormParams.append('response_format', responseFormat);
}
if (temperature !== undefined) {
localVarFormParams.append('temperature', temperature);
}
localVarHeaderParameter['Content-Type'] = 'multipart/form-data';
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), localVarFormParams.getHeaders()), headersFromBaseOptions), options.headers);
localVarRequestOptions.data = localVarFormParams;
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Delete a file.
* @param {string} fileId The ID of the file to use for this request
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteFile: (fileId, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'fileId' is not null or undefined
common.assertParamExists('deleteFile', 'fileId', fileId);
const localVarPath = `/files/{file_id}`
.replace(`{${"file_id"}}`, encodeURIComponent(String(fileId)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'DELETE' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Delete a fine-tuned model. You must have the Owner role in your organization.
* @param {string} model The model to delete
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteModel: (model, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'model' is not null or undefined
common.assertParamExists('deleteModel', 'model', model);
const localVarPath = `/models/{model}`
.replace(`{${"model"}}`, encodeURIComponent(String(model)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'DELETE' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Returns the contents of the specified file
* @param {string} fileId The ID of the file to use for this request
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
downloadFile: (fileId, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'fileId' is not null or undefined
common.assertParamExists('downloadFile', 'fileId', fileId);
const localVarPath = `/files/{file_id}/content`
.replace(`{${"file_id"}}`, encodeURIComponent(String(fileId)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'GET' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Lists the currently available (non-finetuned) models, and provides basic information about each one such as the owner and availability.
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
*/
listEngines: (options = {}) => __awaiter(this, void 0, void 0, function* () {
const localVarPath = `/engines`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'GET' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Returns a list of files that belong to the user\'s organization.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listFiles: (options = {}) => __awaiter(this, void 0, void 0, function* () {
const localVarPath = `/files`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'GET' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Get fine-grained status updates for a fine-tune job.
* @param {string} fineTuneId The ID of the fine-tune job to get events for.
* @param {boolean} [stream] Whether to stream events for the fine-tune job. If set to true, events will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available. The stream will terminate with a &#x60;data: [DONE]&#x60; message when the job is finished (succeeded, cancelled, or failed). If set to false, only events generated so far will be returned.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listFineTuneEvents: (fineTuneId, stream, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'fineTuneId' is not null or undefined
common.assertParamExists('listFineTuneEvents', 'fineTuneId', fineTuneId);
const localVarPath = `/fine-tunes/{fine_tune_id}/events`
.replace(`{${"fine_tune_id"}}`, encodeURIComponent(String(fineTuneId)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'GET' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
if (stream !== undefined) {
localVarQueryParameter['stream'] = stream;
}
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary List your organization\'s fine-tuning jobs
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listFineTunes: (options = {}) => __awaiter(this, void 0, void 0, function* () {
const localVarPath = `/fine-tunes`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'GET' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Lists the currently available models, and provides basic information about each one such as the owner and availability.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listModels: (options = {}) => __awaiter(this, void 0, void 0, function* () {
const localVarPath = `/models`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'GET' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Retrieves a model instance, providing basic information about it such as the owner and availability.
* @param {string} engineId The ID of the engine to use for this request
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
*/
retrieveEngine: (engineId, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'engineId' is not null or undefined
common.assertParamExists('retrieveEngine', 'engineId', engineId);
const localVarPath = `/engines/{engine_id}`
.replace(`{${"engine_id"}}`, encodeURIComponent(String(engineId)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'GET' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Returns information about a specific file.
* @param {string} fileId The ID of the file to use for this request
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
retrieveFile: (fileId, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'fileId' is not null or undefined
common.assertParamExists('retrieveFile', 'fileId', fileId);
const localVarPath = `/files/{file_id}`
.replace(`{${"file_id"}}`, encodeURIComponent(String(fileId)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'GET' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Gets info about the fine-tune job. [Learn more about Fine-tuning](/docs/guides/fine-tuning)
* @param {string} fineTuneId The ID of the fine-tune job
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
retrieveFineTune: (fineTuneId, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'fineTuneId' is not null or undefined
common.assertParamExists('retrieveFineTune', 'fineTuneId', fineTuneId);
const localVarPath = `/fine-tunes/{fine_tune_id}`
.replace(`{${"fine_tune_id"}}`, encodeURIComponent(String(fineTuneId)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'GET' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
/**
*
* @summary Retrieves a model instance, providing basic information about the model such as the owner and permissioning.
* @param {string} model The ID of the model to use for this request
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
retrieveModel: (model, options = {}) => __awaiter(this, void 0, void 0, function* () {
// verify required parameter 'model' is not null or undefined
common.assertParamExists('retrieveModel', 'model', model);
const localVarPath = `/models/{model}`
.replace(`{${"model"}}`, encodeURIComponent(String(model)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, common.DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = Object.assign(Object.assign({ method: 'GET' }, baseOptions), options);
const localVarHeaderParameter = {};
const localVarQueryParameter = {};
common.setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
return {
url: common.toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
}),
};
};
/**
* OpenAIApi - functional programming interface
* @export
*/
exports.OpenAIApiFp = function (configuration) {
const localVarAxiosParamCreator = exports.OpenAIApiAxiosParamCreator(configuration);
return {
/**
*
* @summary Immediately cancel a fine-tune job.
* @param {string} fineTuneId The ID of the fine-tune job to cancel
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
cancelFineTune(fineTuneId, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.cancelFineTune(fineTuneId, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Answers the specified question using the provided documents and examples. The endpoint first [searches](/docs/api-reference/searches) over provided documents or files to find relevant context. The relevant context is combined with the provided examples and question to create the prompt for [completion](/docs/api-reference/completions).
* @param {CreateAnswerRequest} createAnswerRequest
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
*/
createAnswer(createAnswerRequest, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.createAnswer(createAnswerRequest, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Creates a model response for the given chat conversation.
* @param {CreateChatCompletionRequest} createChatCompletionRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createChatCompletion(createChatCompletionRequest, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.createChatCompletion(createChatCompletionRequest, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Classifies the specified `query` using provided examples. The endpoint first [searches](/docs/api-reference/searches) over the labeled examples to select the ones most relevant for the particular query. Then, the relevant examples are combined with the query to construct a prompt to produce the final label via the [completions](/docs/api-reference/completions) endpoint. Labeled examples can be provided via an uploaded `file`, or explicitly listed in the request using the `examples` parameter for quick tests and small scale use cases.
* @param {CreateClassificationRequest} createClassificationRequest
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
*/
createClassification(createClassificationRequest, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.createClassification(createClassificationRequest, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Creates a completion for the provided prompt and parameters.
* @param {CreateCompletionRequest} createCompletionRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createCompletion(createCompletionRequest, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.createCompletion(createCompletionRequest, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Creates a new edit for the provided input, instruction, and parameters.
* @param {CreateEditRequest} createEditRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createEdit(createEditRequest, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.createEdit(createEditRequest, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Creates an embedding vector representing the input text.
* @param {CreateEmbeddingRequest} createEmbeddingRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createEmbedding(createEmbeddingRequest, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.createEmbedding(createEmbeddingRequest, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Upload a file that contains document(s) to be used across various endpoints/features. Currently, the size of all the files uploaded by one organization can be up to 1 GB. Please contact us if you need to increase the storage limit.
* @param {File} file Name of the [JSON Lines](https://jsonlines.readthedocs.io/en/latest/) file to be uploaded. If the &#x60;purpose&#x60; is set to \\\&quot;fine-tune\\\&quot;, each line is a JSON record with \\\&quot;prompt\\\&quot; and \\\&quot;completion\\\&quot; fields representing your [training examples](/docs/guides/fine-tuning/prepare-training-data).
* @param {string} purpose The intended purpose of the uploaded documents. Use \\\&quot;fine-tune\\\&quot; for [Fine-tuning](/docs/api-reference/fine-tunes). This allows us to validate the format of the uploaded file.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createFile(file, purpose, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.createFile(file, purpose, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Creates a job that fine-tunes a specified model from a given dataset. Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete. [Learn more about Fine-tuning](/docs/guides/fine-tuning)
* @param {CreateFineTuneRequest} createFineTuneRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createFineTune(createFineTuneRequest, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.createFineTune(createFineTuneRequest, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Creates an image given a prompt.
* @param {CreateImageRequest} createImageRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createImage(createImageRequest, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.createImage(createImageRequest, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Creates an edited or extended image given an original image and a prompt.
* @param {File} image The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask is not provided, image must have transparency, which will be used as the mask.
* @param {string} prompt A text description of the desired image(s). The maximum length is 1000 characters.
* @param {File} [mask] An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where &#x60;image&#x60; should be edited. Must be a valid PNG file, less than 4MB, and have the same dimensions as &#x60;image&#x60;.
* @param {number} [n] The number of images to generate. Must be between 1 and 10.
* @param {string} [size] The size of the generated images. Must be one of &#x60;256x256&#x60;, &#x60;512x512&#x60;, or &#x60;1024x1024&#x60;.
* @param {string} [responseFormat] The format in which the generated images are returned. Must be one of &#x60;url&#x60; or &#x60;b64_json&#x60;.
* @param {string} [user] A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createImageEdit(image, prompt, mask, n, size, responseFormat, user, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.createImageEdit(image, prompt, mask, n, size, responseFormat, user, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Creates a variation of a given image.
* @param {File} image The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square.
* @param {number} [n] The number of images to generate. Must be between 1 and 10.
* @param {string} [size] The size of the generated images. Must be one of &#x60;256x256&#x60;, &#x60;512x512&#x60;, or &#x60;1024x1024&#x60;.
* @param {string} [responseFormat] The format in which the generated images are returned. Must be one of &#x60;url&#x60; or &#x60;b64_json&#x60;.
* @param {string} [user] A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createImageVariation(image, n, size, responseFormat, user, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.createImageVariation(image, n, size, responseFormat, user, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Classifies if text violates OpenAI\'s Content Policy
* @param {CreateModerationRequest} createModerationRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createModeration(createModerationRequest, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.createModeration(createModerationRequest, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary The search endpoint computes similarity scores between provided query and documents. Documents can be passed directly to the API if there are no more than 200 of them. To go beyond the 200 document limit, documents can be processed offline and then used for efficient retrieval at query time. When `file` is set, the search endpoint searches over all the documents in the given file and returns up to the `max_rerank` number of documents. These documents will be returned along with their search scores. The similarity score is a positive score that usually ranges from 0 to 300 (but can sometimes go higher), where a score above 200 usually means the document is semantically similar to the query.
* @param {string} engineId The ID of the engine to use for this request. You can select one of &#x60;ada&#x60;, &#x60;babbage&#x60;, &#x60;curie&#x60;, or &#x60;davinci&#x60;.
* @param {CreateSearchRequest} createSearchRequest
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
*/
createSearch(engineId, createSearchRequest, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.createSearch(engineId, createSearchRequest, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Transcribes audio into the input language.
* @param {File} file The audio file object (not file name) to transcribe, in one of these formats: mp3, mp4, mpeg, mpga, m4a, wav, or webm.
* @param {string} model ID of the model to use. Only &#x60;whisper-1&#x60; is currently available.
* @param {string} [prompt] An optional text to guide the model\\\&#39;s style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should match the audio language.
* @param {string} [responseFormat] The format of the transcript output, in one of these options: json, text, srt, verbose_json, or vtt.
* @param {number} [temperature] The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.
* @param {string} [language] The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will improve accuracy and latency.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createTranscription(file, model, prompt, responseFormat, temperature, language, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.createTranscription(file, model, prompt, responseFormat, temperature, language, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Translates audio into into English.
* @param {File} file The audio file object (not file name) translate, in one of these formats: mp3, mp4, mpeg, mpga, m4a, wav, or webm.
* @param {string} model ID of the model to use. Only &#x60;whisper-1&#x60; is currently available.
* @param {string} [prompt] An optional text to guide the model\\\&#39;s style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should be in English.
* @param {string} [responseFormat] The format of the transcript output, in one of these options: json, text, srt, verbose_json, or vtt.
* @param {number} [temperature] The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createTranslation(file, model, prompt, responseFormat, temperature, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.createTranslation(file, model, prompt, responseFormat, temperature, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Delete a file.
* @param {string} fileId The ID of the file to use for this request
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteFile(fileId, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.deleteFile(fileId, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Delete a fine-tuned model. You must have the Owner role in your organization.
* @param {string} model The model to delete
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteModel(model, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.deleteModel(model, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Returns the contents of the specified file
* @param {string} fileId The ID of the file to use for this request
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
downloadFile(fileId, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.downloadFile(fileId, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Lists the currently available (non-finetuned) models, and provides basic information about each one such as the owner and availability.
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
*/
listEngines(options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.listEngines(options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Returns a list of files that belong to the user\'s organization.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listFiles(options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.listFiles(options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Get fine-grained status updates for a fine-tune job.
* @param {string} fineTuneId The ID of the fine-tune job to get events for.
* @param {boolean} [stream] Whether to stream events for the fine-tune job. If set to true, events will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available. The stream will terminate with a &#x60;data: [DONE]&#x60; message when the job is finished (succeeded, cancelled, or failed). If set to false, only events generated so far will be returned.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listFineTuneEvents(fineTuneId, stream, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.listFineTuneEvents(fineTuneId, stream, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary List your organization\'s fine-tuning jobs
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listFineTunes(options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.listFineTunes(options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Lists the currently available models, and provides basic information about each one such as the owner and availability.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listModels(options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.listModels(options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Retrieves a model instance, providing basic information about it such as the owner and availability.
* @param {string} engineId The ID of the engine to use for this request
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
*/
retrieveEngine(engineId, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.retrieveEngine(engineId, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Returns information about a specific file.
* @param {string} fileId The ID of the file to use for this request
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
retrieveFile(fileId, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.retrieveFile(fileId, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Gets info about the fine-tune job. [Learn more about Fine-tuning](/docs/guides/fine-tuning)
* @param {string} fineTuneId The ID of the fine-tune job
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
retrieveFineTune(fineTuneId, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.retrieveFineTune(fineTuneId, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
/**
*
* @summary Retrieves a model instance, providing basic information about the model such as the owner and permissioning.
* @param {string} model The ID of the model to use for this request
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
retrieveModel(model, options) {
return __awaiter(this, void 0, void 0, function* () {
const localVarAxiosArgs = yield localVarAxiosParamCreator.retrieveModel(model, options);
return common.createRequestFunction(localVarAxiosArgs, axios$1.default, base$1.BASE_PATH, configuration);
});
},
};
};
/**
* OpenAIApi - factory interface
* @export
*/
exports.OpenAIApiFactory = function (configuration, basePath, axios) {
const localVarFp = exports.OpenAIApiFp(configuration);
return {
/**
*
* @summary Immediately cancel a fine-tune job.
* @param {string} fineTuneId The ID of the fine-tune job to cancel
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
cancelFineTune(fineTuneId, options) {
return localVarFp.cancelFineTune(fineTuneId, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Answers the specified question using the provided documents and examples. The endpoint first [searches](/docs/api-reference/searches) over provided documents or files to find relevant context. The relevant context is combined with the provided examples and question to create the prompt for [completion](/docs/api-reference/completions).
* @param {CreateAnswerRequest} createAnswerRequest
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
*/
createAnswer(createAnswerRequest, options) {
return localVarFp.createAnswer(createAnswerRequest, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Creates a model response for the given chat conversation.
* @param {CreateChatCompletionRequest} createChatCompletionRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createChatCompletion(createChatCompletionRequest, options) {
return localVarFp.createChatCompletion(createChatCompletionRequest, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Classifies the specified `query` using provided examples. The endpoint first [searches](/docs/api-reference/searches) over the labeled examples to select the ones most relevant for the particular query. Then, the relevant examples are combined with the query to construct a prompt to produce the final label via the [completions](/docs/api-reference/completions) endpoint. Labeled examples can be provided via an uploaded `file`, or explicitly listed in the request using the `examples` parameter for quick tests and small scale use cases.
* @param {CreateClassificationRequest} createClassificationRequest
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
*/
createClassification(createClassificationRequest, options) {
return localVarFp.createClassification(createClassificationRequest, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Creates a completion for the provided prompt and parameters.
* @param {CreateCompletionRequest} createCompletionRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createCompletion(createCompletionRequest, options) {
return localVarFp.createCompletion(createCompletionRequest, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Creates a new edit for the provided input, instruction, and parameters.
* @param {CreateEditRequest} createEditRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createEdit(createEditRequest, options) {
return localVarFp.createEdit(createEditRequest, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Creates an embedding vector representing the input text.
* @param {CreateEmbeddingRequest} createEmbeddingRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createEmbedding(createEmbeddingRequest, options) {
return localVarFp.createEmbedding(createEmbeddingRequest, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Upload a file that contains document(s) to be used across various endpoints/features. Currently, the size of all the files uploaded by one organization can be up to 1 GB. Please contact us if you need to increase the storage limit.
* @param {File} file Name of the [JSON Lines](https://jsonlines.readthedocs.io/en/latest/) file to be uploaded. If the &#x60;purpose&#x60; is set to \\\&quot;fine-tune\\\&quot;, each line is a JSON record with \\\&quot;prompt\\\&quot; and \\\&quot;completion\\\&quot; fields representing your [training examples](/docs/guides/fine-tuning/prepare-training-data).
* @param {string} purpose The intended purpose of the uploaded documents. Use \\\&quot;fine-tune\\\&quot; for [Fine-tuning](/docs/api-reference/fine-tunes). This allows us to validate the format of the uploaded file.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createFile(file, purpose, options) {
return localVarFp.createFile(file, purpose, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Creates a job that fine-tunes a specified model from a given dataset. Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete. [Learn more about Fine-tuning](/docs/guides/fine-tuning)
* @param {CreateFineTuneRequest} createFineTuneRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createFineTune(createFineTuneRequest, options) {
return localVarFp.createFineTune(createFineTuneRequest, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Creates an image given a prompt.
* @param {CreateImageRequest} createImageRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createImage(createImageRequest, options) {
return localVarFp.createImage(createImageRequest, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Creates an edited or extended image given an original image and a prompt.
* @param {File} image The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask is not provided, image must have transparency, which will be used as the mask.
* @param {string} prompt A text description of the desired image(s). The maximum length is 1000 characters.
* @param {File} [mask] An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where &#x60;image&#x60; should be edited. Must be a valid PNG file, less than 4MB, and have the same dimensions as &#x60;image&#x60;.
* @param {number} [n] The number of images to generate. Must be between 1 and 10.
* @param {string} [size] The size of the generated images. Must be one of &#x60;256x256&#x60;, &#x60;512x512&#x60;, or &#x60;1024x1024&#x60;.
* @param {string} [responseFormat] The format in which the generated images are returned. Must be one of &#x60;url&#x60; or &#x60;b64_json&#x60;.
* @param {string} [user] A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createImageEdit(image, prompt, mask, n, size, responseFormat, user, options) {
return localVarFp.createImageEdit(image, prompt, mask, n, size, responseFormat, user, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Creates a variation of a given image.
* @param {File} image The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square.
* @param {number} [n] The number of images to generate. Must be between 1 and 10.
* @param {string} [size] The size of the generated images. Must be one of &#x60;256x256&#x60;, &#x60;512x512&#x60;, or &#x60;1024x1024&#x60;.
* @param {string} [responseFormat] The format in which the generated images are returned. Must be one of &#x60;url&#x60; or &#x60;b64_json&#x60;.
* @param {string} [user] A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createImageVariation(image, n, size, responseFormat, user, options) {
return localVarFp.createImageVariation(image, n, size, responseFormat, user, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Classifies if text violates OpenAI\'s Content Policy
* @param {CreateModerationRequest} createModerationRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createModeration(createModerationRequest, options) {
return localVarFp.createModeration(createModerationRequest, options).then((request) => request(axios, basePath));
},
/**
*
* @summary The search endpoint computes similarity scores between provided query and documents. Documents can be passed directly to the API if there are no more than 200 of them. To go beyond the 200 document limit, documents can be processed offline and then used for efficient retrieval at query time. When `file` is set, the search endpoint searches over all the documents in the given file and returns up to the `max_rerank` number of documents. These documents will be returned along with their search scores. The similarity score is a positive score that usually ranges from 0 to 300 (but can sometimes go higher), where a score above 200 usually means the document is semantically similar to the query.
* @param {string} engineId The ID of the engine to use for this request. You can select one of &#x60;ada&#x60;, &#x60;babbage&#x60;, &#x60;curie&#x60;, or &#x60;davinci&#x60;.
* @param {CreateSearchRequest} createSearchRequest
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
*/
createSearch(engineId, createSearchRequest, options) {
return localVarFp.createSearch(engineId, createSearchRequest, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Transcribes audio into the input language.
* @param {File} file The audio file object (not file name) to transcribe, in one of these formats: mp3, mp4, mpeg, mpga, m4a, wav, or webm.
* @param {string} model ID of the model to use. Only &#x60;whisper-1&#x60; is currently available.
* @param {string} [prompt] An optional text to guide the model\\\&#39;s style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should match the audio language.
* @param {string} [responseFormat] The format of the transcript output, in one of these options: json, text, srt, verbose_json, or vtt.
* @param {number} [temperature] The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.
* @param {string} [language] The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will improve accuracy and latency.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createTranscription(file, model, prompt, responseFormat, temperature, language, options) {
return localVarFp.createTranscription(file, model, prompt, responseFormat, temperature, language, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Translates audio into into English.
* @param {File} file The audio file object (not file name) translate, in one of these formats: mp3, mp4, mpeg, mpga, m4a, wav, or webm.
* @param {string} model ID of the model to use. Only &#x60;whisper-1&#x60; is currently available.
* @param {string} [prompt] An optional text to guide the model\\\&#39;s style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should be in English.
* @param {string} [responseFormat] The format of the transcript output, in one of these options: json, text, srt, verbose_json, or vtt.
* @param {number} [temperature] The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createTranslation(file, model, prompt, responseFormat, temperature, options) {
return localVarFp.createTranslation(file, model, prompt, responseFormat, temperature, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Delete a file.
* @param {string} fileId The ID of the file to use for this request
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteFile(fileId, options) {
return localVarFp.deleteFile(fileId, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Delete a fine-tuned model. You must have the Owner role in your organization.
* @param {string} model The model to delete
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteModel(model, options) {
return localVarFp.deleteModel(model, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Returns the contents of the specified file
* @param {string} fileId The ID of the file to use for this request
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
downloadFile(fileId, options) {
return localVarFp.downloadFile(fileId, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Lists the currently available (non-finetuned) models, and provides basic information about each one such as the owner and availability.
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
*/
listEngines(options) {
return localVarFp.listEngines(options).then((request) => request(axios, basePath));
},
/**
*
* @summary Returns a list of files that belong to the user\'s organization.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listFiles(options) {
return localVarFp.listFiles(options).then((request) => request(axios, basePath));
},
/**
*
* @summary Get fine-grained status updates for a fine-tune job.
* @param {string} fineTuneId The ID of the fine-tune job to get events for.
* @param {boolean} [stream] Whether to stream events for the fine-tune job. If set to true, events will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available. The stream will terminate with a &#x60;data: [DONE]&#x60; message when the job is finished (succeeded, cancelled, or failed). If set to false, only events generated so far will be returned.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listFineTuneEvents(fineTuneId, stream, options) {
return localVarFp.listFineTuneEvents(fineTuneId, stream, options).then((request) => request(axios, basePath));
},
/**
*
* @summary List your organization\'s fine-tuning jobs
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listFineTunes(options) {
return localVarFp.listFineTunes(options).then((request) => request(axios, basePath));
},
/**
*
* @summary Lists the currently available models, and provides basic information about each one such as the owner and availability.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listModels(options) {
return localVarFp.listModels(options).then((request) => request(axios, basePath));
},
/**
*
* @summary Retrieves a model instance, providing basic information about it such as the owner and availability.
* @param {string} engineId The ID of the engine to use for this request
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
*/
retrieveEngine(engineId, options) {
return localVarFp.retrieveEngine(engineId, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Returns information about a specific file.
* @param {string} fileId The ID of the file to use for this request
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
retrieveFile(fileId, options) {
return localVarFp.retrieveFile(fileId, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Gets info about the fine-tune job. [Learn more about Fine-tuning](/docs/guides/fine-tuning)
* @param {string} fineTuneId The ID of the fine-tune job
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
retrieveFineTune(fineTuneId, options) {
return localVarFp.retrieveFineTune(fineTuneId, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Retrieves a model instance, providing basic information about the model such as the owner and permissioning.
* @param {string} model The ID of the model to use for this request
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
retrieveModel(model, options) {
return localVarFp.retrieveModel(model, options).then((request) => request(axios, basePath));
},
};
};
/**
* OpenAIApi - object-oriented interface
* @export
* @class OpenAIApi
* @extends {BaseAPI}
*/
class OpenAIApi extends base$1.BaseAPI {
/**
*
* @summary Immediately cancel a fine-tune job.
* @param {string} fineTuneId The ID of the fine-tune job to cancel
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
cancelFineTune(fineTuneId, options) {
return exports.OpenAIApiFp(this.configuration).cancelFineTune(fineTuneId, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Answers the specified question using the provided documents and examples. The endpoint first [searches](/docs/api-reference/searches) over provided documents or files to find relevant context. The relevant context is combined with the provided examples and question to create the prompt for [completion](/docs/api-reference/completions).
* @param {CreateAnswerRequest} createAnswerRequest
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
* @memberof OpenAIApi
*/
createAnswer(createAnswerRequest, options) {
return exports.OpenAIApiFp(this.configuration).createAnswer(createAnswerRequest, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Creates a model response for the given chat conversation.
* @param {CreateChatCompletionRequest} createChatCompletionRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
createChatCompletion(createChatCompletionRequest, options) {
return exports.OpenAIApiFp(this.configuration).createChatCompletion(createChatCompletionRequest, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Classifies the specified `query` using provided examples. The endpoint first [searches](/docs/api-reference/searches) over the labeled examples to select the ones most relevant for the particular query. Then, the relevant examples are combined with the query to construct a prompt to produce the final label via the [completions](/docs/api-reference/completions) endpoint. Labeled examples can be provided via an uploaded `file`, or explicitly listed in the request using the `examples` parameter for quick tests and small scale use cases.
* @param {CreateClassificationRequest} createClassificationRequest
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
* @memberof OpenAIApi
*/
createClassification(createClassificationRequest, options) {
return exports.OpenAIApiFp(this.configuration).createClassification(createClassificationRequest, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Creates a completion for the provided prompt and parameters.
* @param {CreateCompletionRequest} createCompletionRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
createCompletion(createCompletionRequest, options) {
return exports.OpenAIApiFp(this.configuration).createCompletion(createCompletionRequest, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Creates a new edit for the provided input, instruction, and parameters.
* @param {CreateEditRequest} createEditRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
createEdit(createEditRequest, options) {
return exports.OpenAIApiFp(this.configuration).createEdit(createEditRequest, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Creates an embedding vector representing the input text.
* @param {CreateEmbeddingRequest} createEmbeddingRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
createEmbedding(createEmbeddingRequest, options) {
return exports.OpenAIApiFp(this.configuration).createEmbedding(createEmbeddingRequest, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Upload a file that contains document(s) to be used across various endpoints/features. Currently, the size of all the files uploaded by one organization can be up to 1 GB. Please contact us if you need to increase the storage limit.
* @param {File} file Name of the [JSON Lines](https://jsonlines.readthedocs.io/en/latest/) file to be uploaded. If the &#x60;purpose&#x60; is set to \\\&quot;fine-tune\\\&quot;, each line is a JSON record with \\\&quot;prompt\\\&quot; and \\\&quot;completion\\\&quot; fields representing your [training examples](/docs/guides/fine-tuning/prepare-training-data).
* @param {string} purpose The intended purpose of the uploaded documents. Use \\\&quot;fine-tune\\\&quot; for [Fine-tuning](/docs/api-reference/fine-tunes). This allows us to validate the format of the uploaded file.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
createFile(file, purpose, options) {
return exports.OpenAIApiFp(this.configuration).createFile(file, purpose, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Creates a job that fine-tunes a specified model from a given dataset. Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete. [Learn more about Fine-tuning](/docs/guides/fine-tuning)
* @param {CreateFineTuneRequest} createFineTuneRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
createFineTune(createFineTuneRequest, options) {
return exports.OpenAIApiFp(this.configuration).createFineTune(createFineTuneRequest, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Creates an image given a prompt.
* @param {CreateImageRequest} createImageRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
createImage(createImageRequest, options) {
return exports.OpenAIApiFp(this.configuration).createImage(createImageRequest, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Creates an edited or extended image given an original image and a prompt.
* @param {File} image The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask is not provided, image must have transparency, which will be used as the mask.
* @param {string} prompt A text description of the desired image(s). The maximum length is 1000 characters.
* @param {File} [mask] An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where &#x60;image&#x60; should be edited. Must be a valid PNG file, less than 4MB, and have the same dimensions as &#x60;image&#x60;.
* @param {number} [n] The number of images to generate. Must be between 1 and 10.
* @param {string} [size] The size of the generated images. Must be one of &#x60;256x256&#x60;, &#x60;512x512&#x60;, or &#x60;1024x1024&#x60;.
* @param {string} [responseFormat] The format in which the generated images are returned. Must be one of &#x60;url&#x60; or &#x60;b64_json&#x60;.
* @param {string} [user] A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
createImageEdit(image, prompt, mask, n, size, responseFormat, user, options) {
return exports.OpenAIApiFp(this.configuration).createImageEdit(image, prompt, mask, n, size, responseFormat, user, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Creates a variation of a given image.
* @param {File} image The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square.
* @param {number} [n] The number of images to generate. Must be between 1 and 10.
* @param {string} [size] The size of the generated images. Must be one of &#x60;256x256&#x60;, &#x60;512x512&#x60;, or &#x60;1024x1024&#x60;.
* @param {string} [responseFormat] The format in which the generated images are returned. Must be one of &#x60;url&#x60; or &#x60;b64_json&#x60;.
* @param {string} [user] A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
createImageVariation(image, n, size, responseFormat, user, options) {
return exports.OpenAIApiFp(this.configuration).createImageVariation(image, n, size, responseFormat, user, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Classifies if text violates OpenAI\'s Content Policy
* @param {CreateModerationRequest} createModerationRequest
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
createModeration(createModerationRequest, options) {
return exports.OpenAIApiFp(this.configuration).createModeration(createModerationRequest, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary The search endpoint computes similarity scores between provided query and documents. Documents can be passed directly to the API if there are no more than 200 of them. To go beyond the 200 document limit, documents can be processed offline and then used for efficient retrieval at query time. When `file` is set, the search endpoint searches over all the documents in the given file and returns up to the `max_rerank` number of documents. These documents will be returned along with their search scores. The similarity score is a positive score that usually ranges from 0 to 300 (but can sometimes go higher), where a score above 200 usually means the document is semantically similar to the query.
* @param {string} engineId The ID of the engine to use for this request. You can select one of &#x60;ada&#x60;, &#x60;babbage&#x60;, &#x60;curie&#x60;, or &#x60;davinci&#x60;.
* @param {CreateSearchRequest} createSearchRequest
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
* @memberof OpenAIApi
*/
createSearch(engineId, createSearchRequest, options) {
return exports.OpenAIApiFp(this.configuration).createSearch(engineId, createSearchRequest, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Transcribes audio into the input language.
* @param {File} file The audio file object (not file name) to transcribe, in one of these formats: mp3, mp4, mpeg, mpga, m4a, wav, or webm.
* @param {string} model ID of the model to use. Only &#x60;whisper-1&#x60; is currently available.
* @param {string} [prompt] An optional text to guide the model\\\&#39;s style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should match the audio language.
* @param {string} [responseFormat] The format of the transcript output, in one of these options: json, text, srt, verbose_json, or vtt.
* @param {number} [temperature] The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.
* @param {string} [language] The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will improve accuracy and latency.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
createTranscription(file, model, prompt, responseFormat, temperature, language, options) {
return exports.OpenAIApiFp(this.configuration).createTranscription(file, model, prompt, responseFormat, temperature, language, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Translates audio into into English.
* @param {File} file The audio file object (not file name) translate, in one of these formats: mp3, mp4, mpeg, mpga, m4a, wav, or webm.
* @param {string} model ID of the model to use. Only &#x60;whisper-1&#x60; is currently available.
* @param {string} [prompt] An optional text to guide the model\\\&#39;s style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should be in English.
* @param {string} [responseFormat] The format of the transcript output, in one of these options: json, text, srt, verbose_json, or vtt.
* @param {number} [temperature] The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
createTranslation(file, model, prompt, responseFormat, temperature, options) {
return exports.OpenAIApiFp(this.configuration).createTranslation(file, model, prompt, responseFormat, temperature, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Delete a file.
* @param {string} fileId The ID of the file to use for this request
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
deleteFile(fileId, options) {
return exports.OpenAIApiFp(this.configuration).deleteFile(fileId, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Delete a fine-tuned model. You must have the Owner role in your organization.
* @param {string} model The model to delete
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
deleteModel(model, options) {
return exports.OpenAIApiFp(this.configuration).deleteModel(model, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Returns the contents of the specified file
* @param {string} fileId The ID of the file to use for this request
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
downloadFile(fileId, options) {
return exports.OpenAIApiFp(this.configuration).downloadFile(fileId, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Lists the currently available (non-finetuned) models, and provides basic information about each one such as the owner and availability.
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
* @memberof OpenAIApi
*/
listEngines(options) {
return exports.OpenAIApiFp(this.configuration).listEngines(options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Returns a list of files that belong to the user\'s organization.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
listFiles(options) {
return exports.OpenAIApiFp(this.configuration).listFiles(options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Get fine-grained status updates for a fine-tune job.
* @param {string} fineTuneId The ID of the fine-tune job to get events for.
* @param {boolean} [stream] Whether to stream events for the fine-tune job. If set to true, events will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available. The stream will terminate with a &#x60;data: [DONE]&#x60; message when the job is finished (succeeded, cancelled, or failed). If set to false, only events generated so far will be returned.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
listFineTuneEvents(fineTuneId, stream, options) {
return exports.OpenAIApiFp(this.configuration).listFineTuneEvents(fineTuneId, stream, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary List your organization\'s fine-tuning jobs
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
listFineTunes(options) {
return exports.OpenAIApiFp(this.configuration).listFineTunes(options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Lists the currently available models, and provides basic information about each one such as the owner and availability.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
listModels(options) {
return exports.OpenAIApiFp(this.configuration).listModels(options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Retrieves a model instance, providing basic information about it such as the owner and availability.
* @param {string} engineId The ID of the engine to use for this request
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
* @memberof OpenAIApi
*/
retrieveEngine(engineId, options) {
return exports.OpenAIApiFp(this.configuration).retrieveEngine(engineId, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Returns information about a specific file.
* @param {string} fileId The ID of the file to use for this request
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
retrieveFile(fileId, options) {
return exports.OpenAIApiFp(this.configuration).retrieveFile(fileId, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Gets info about the fine-tune job. [Learn more about Fine-tuning](/docs/guides/fine-tuning)
* @param {string} fineTuneId The ID of the fine-tune job
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
retrieveFineTune(fineTuneId, options) {
return exports.OpenAIApiFp(this.configuration).retrieveFineTune(fineTuneId, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Retrieves a model instance, providing basic information about the model such as the owner and permissioning.
* @param {string} model The ID of the model to use for this request
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof OpenAIApi
*/
retrieveModel(model, options) {
return exports.OpenAIApiFp(this.configuration).retrieveModel(model, options).then((request) => request(this.axios, this.basePath));
}
}
exports.OpenAIApi = OpenAIApi;
});
unwrapExports(api);
var api_1 = api.OpenAIApi;
var api_2 = api.OpenAIApiFactory;
var api_3 = api.OpenAIApiFp;
var api_4 = api.OpenAIApiAxiosParamCreator;
var api_5 = api.CreateImageRequestResponseFormatEnum;
var api_6 = api.CreateImageRequestSizeEnum;
var api_7 = api.ChatCompletionResponseMessageRoleEnum;
var api_8 = api.ChatCompletionRequestMessageRoleEnum;
var name = "openai";
var version$2 = "3.3.0";
var description = "Node.js library for the OpenAI API";
var repository = {
type: "git",
url: "git@github.com:openai/openai-node.git"
};
var keywords = [
"openai",
"open",
"ai",
"gpt-3",
"gpt3"
];
var author = "OpenAI";
var license = "MIT";
var main = "./dist/index.js";
var types = "./dist/index.d.ts";
var scripts = {
build: "tsc --outDir dist/"
};
var dependencies = {
axios: "^0.26.0",
"form-data": "^4.0.0"
};
var devDependencies = {
"@types/node": "^12.11.5",
typescript: "^3.6.4"
};
var _package = {
name: name,
version: version$2,
description: description,
repository: repository,
keywords: keywords,
author: author,
license: license,
main: main,
types: types,
scripts: scripts,
dependencies: dependencies,
devDependencies: devDependencies
};
var _package$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name,
version: version$2,
description: description,
repository: repository,
keywords: keywords,
author: author,
license: license,
main: main,
types: types,
scripts: scripts,
dependencies: dependencies,
devDependencies: devDependencies,
'default': _package
});
/* eslint-env browser */
var browser = typeof self == 'object' ? self.FormData : window.FormData;
var packageJson = getCjsExportFromNamespace(_package$1);
var configuration = createCommonjsModule(function (module, exports) {
/* tslint:disable */
/* eslint-disable */
/**
* OpenAI API
* APIs for sampling from and fine-tuning language models
*
* The version of the OpenAPI document: 1.3.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Configuration = void 0;
class Configuration {
constructor(param = {}) {
this.apiKey = param.apiKey;
this.organization = param.organization;
this.username = param.username;
this.password = param.password;
this.accessToken = param.accessToken;
this.basePath = param.basePath;
this.baseOptions = param.baseOptions;
this.formDataCtor = param.formDataCtor;
if (!this.baseOptions) {
this.baseOptions = {};
}
this.baseOptions.headers = Object.assign({ 'User-Agent': `OpenAI/NodeJS/${packageJson.version}`, 'Authorization': `Bearer ${this.apiKey}` }, this.baseOptions.headers);
if (this.organization) {
this.baseOptions.headers['OpenAI-Organization'] = this.organization;
}
if (!this.formDataCtor) {
this.formDataCtor = browser;
}
}
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
* application/vnd.company+json
* @param mime - MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise.
*/
isJsonMime(mime) {
const jsonMime = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');
return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json');
}
}
exports.Configuration = Configuration;
});
unwrapExports(configuration);
var configuration_1 = configuration.Configuration;
var dist = createCommonjsModule(function (module, exports) {
/* tslint:disable */
/* eslint-disable */
/**
* OpenAI API
* APIs for sampling from and fine-tuning language models
*
* The version of the OpenAPI document: 1.3.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(api, exports);
__exportStar(configuration, exports);
});
var openAI = unwrapExports(dist);
var _generatePromptMap, _queryMap;
function _createSuper$1h(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1h(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1h() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var FUNC_MAP = {
COMPLEMENT: 'complement',
SUMMARY: 'summary'
};
/**
* 插入“画图”的按钮
* 本功能依赖[Mermaid.js](https://mermaid-js.github.io)组件请保证调用CherryMarkdown前已加载mermaid.js组件
*/
var ChatGpt = /*#__PURE__*/function (_MenuBase) {
_inherits(ChatGpt, _MenuBase);
var _super = _createSuper$1h(ChatGpt);
function ChatGpt($cherry) {
var _context, _context2;
var _this;
_classCallCheck(this, ChatGpt);
_this = _super.call(this, $cherry);
_this.setName('chatgpt', 'chatgpt');
_this.noIcon = true;
_this.subMenuConfig = [// 续写
{
iconName: _this.locale.complement,
name: FUNC_MAP.COMPLEMENT,
onclick: bind$5(_context = _this.bindSubClick).call(_context, _assertThisInitialized(_this), FUNC_MAP.COMPLEMENT)
}, // 总结
{
iconName: _this.locale.summary,
name: FUNC_MAP.SUMMARY,
onclick: bind$5(_context2 = _this.bindSubClick).call(_context2, _assertThisInitialized(_this), FUNC_MAP.SUMMARY)
}];
var _ref = _this.$cherry.options.openai || {},
_ref$apiKey = _ref.apiKey,
apiKey = _ref$apiKey === void 0 ? '' : _ref$apiKey,
_ref$proxy = _ref.proxy;
_ref$proxy = _ref$proxy === void 0 ? {} : _ref$proxy;
var _ref$proxy$host = _ref$proxy.host,
host = _ref$proxy$host === void 0 ? '' : _ref$proxy$host,
_ref$proxy$port = _ref$proxy.port,
port = _ref$proxy$port === void 0 ? '' : _ref$proxy$port,
ignoreError = _ref.ignoreError; // 设置apiKey
if (apiKey) {
var openai = new openAI.OpenAIApi(new openAI.Configuration({
apiKey: apiKey
}));
_this.openai = openai;
} // 设置http proxy
if (host && port) {
_this.proxy = {
host: host,
port: port
};
}
_this.ignoreError = ignoreError;
return _this;
}
_createClass(ChatGpt, [{
key: "getSubMenuConfig",
value: function getSubMenuConfig() {
return this.subMenuConfig;
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容,本函数不处理选中的内容,会直接清空用户选中的内容
* @param {string} shortKey 快捷键参数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
}, {
key: "onClick",
value: function onClick(selection) {
var shortKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
if (!shortKey) {
return;
}
switch (shortKey) {
case FUNC_MAP.COMPLEMENT:
if (!this.openai) {
// 触发一个事件表示没有apiKey
return;
}
this.queryOpenAIApi(FUNC_MAP.COMPLEMENT, selection);
break;
case FUNC_MAP.SUMMARY:
this.queryOpenAIApi(FUNC_MAP.SUMMARY, selection);
break;
default:
return;
}
}
/**
* 在编辑器中添加文字
*/
}, {
key: "concatText",
value: function concatText(selection, text) {
var _this$editor, _this$editor$editor, _context3, _this$editor2, _this$editor2$editor;
this.button.className = this.button.className.replace('icon-loading loading', '');
this.button.innerText = this.button.title;
(_this$editor = this.editor) === null || _this$editor === void 0 ? void 0 : (_this$editor$editor = _this$editor.editor) === null || _this$editor$editor === void 0 ? void 0 : _this$editor$editor.replaceSelection(concat$5(_context3 = "".concat(selection || '', " \n")).call(_context3, text));
(_this$editor2 = this.editor) === null || _this$editor2 === void 0 ? void 0 : (_this$editor2$editor = _this$editor2.editor) === null || _this$editor2$editor === void 0 ? void 0 : _this$editor2$editor.focus();
}
/**
* 请求openai api成功回调&失败回调
* @param {string} name
* @param {string} selection
*/
}, {
key: "queryOpenAIApi",
value: function queryOpenAIApi(name, selection) {
var _this2 = this;
if (!this.openai) {
return;
} // 增加loading
// eslint-disable-next-line prefer-destructuring
this.button = this.$cherry.wrapperDom.getElementsByClassName('cherry-toolbar-chatgpt')[0];
if (/icon-loading loading/.test(this.button.className)) {
return;
}
this.button.className += ' icon-loading loading';
this.button.innerText = ''; // const that = this;
var inputText = selection || this.$cherry.editor.editor.getValue();
queryMap[name].apply(this, [inputText]).then(function (res) {
var _res$data, _res$data$choices, _res$data$choices$, _res$data$choices$$me;
return _this2.concatText(selection, ((_res$data = res.data) === null || _res$data === void 0 ? void 0 : (_res$data$choices = _res$data.choices) === null || _res$data$choices === void 0 ? void 0 : (_res$data$choices$ = _res$data$choices[0]) === null || _res$data$choices$ === void 0 ? void 0 : (_res$data$choices$$me = _res$data$choices$.message) === null || _res$data$choices$$me === void 0 ? void 0 : _res$data$choices$$me.content) || '');
})["catch"](function (res) {
var _res$response, _res$response$data, _res$response$data$er;
// 请求失败处理,两种方案
// 1. 抛出一个事件给第三方使用者在cherry里怎么实现
// 2. cherry处理并在编辑器中提示用户目前采取这种方式
var errMsg = (res === null || res === void 0 ? void 0 : (_res$response = res.response) === null || _res$response === void 0 ? void 0 : (_res$response$data = _res$response.data) === null || _res$response$data === void 0 ? void 0 : (_res$response$data$er = _res$response$data.error) === null || _res$response$data$er === void 0 ? void 0 : _res$response$data$er.message) || '';
if (errMsg && _this2.ignoreError === false) {
_this2.concatText(selection, errMsg);
}
});
}
}]);
return ChatGpt;
}(MenuBase);
var generatePromptMap = (_generatePromptMap = {}, _defineProperty(_generatePromptMap, FUNC_MAP.COMPLEMENT, function (text, language) {
if (language === 'zh_CN') {
return "\u8BF7\u7EED\u5199\u4EE5\u4E0B\u6587\u5B57: ".concat(text);
}
return "continue writing with the following text: ".concat(text);
}), _defineProperty(_generatePromptMap, FUNC_MAP.SUMMARY, function (text, language) {
if (language === 'zh_CN') {
return "\u8BF7\u603B\u7ED3\u4EE5\u4E0B\u6587\u5B57: ".concat(text);
}
return "summary the following text: ".concat(text);
}), _generatePromptMap);
function queryCompletion(type, input) {
return this.openai.createChatCompletion({
model: 'gpt-3.5-turbo',
messages: [{
role: 'user',
content: generatePromptMap[type](input, this.$cherry.options.locale || '')
}] // temperature: 0.6,
// max_tokens: 500,
}, {
proxy: this.proxy
});
}
var queryMap = (_queryMap = {}, _defineProperty(_queryMap, FUNC_MAP.COMPLEMENT, function (input) {
return queryCompletion.apply(this, [FUNC_MAP.COMPLEMENT, input]);
}), _defineProperty(_queryMap, FUNC_MAP.SUMMARY, function (input) {
return queryCompletion.apply(this, [FUNC_MAP.SUMMARY, input]);
}), _queryMap);
function _createSuper$1i(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1i(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1i() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 预览区域切换到“移动端视图”的按钮
*/
var MobilePreview = /*#__PURE__*/function (_MenuBase) {
_inherits(MobilePreview, _MenuBase);
var _super = _createSuper$1i(MobilePreview);
function MobilePreview($cherry) {
var _this;
_classCallCheck(this, MobilePreview);
_this = _super.call(this, $cherry);
_this.previewer = $cherry.previewer;
_this.updateMarkdown = false;
_this.setName('mobilePreview', 'phone');
return _this;
}
/**
* 响应点击事件
* 因为是预览区域的按钮,所以不用关注编辑区的选中内容
*/
_createClass(MobilePreview, [{
key: "onClick",
value: function onClick() {
this.previewer.removeScroll(); // TODO是否可以只通过修改外层class的方式来实现移动端预览效果的展示而不是增加删除dom结构的方式
var previewerDom = this.previewer.getDomContainer();
if (this.previewer.isMobilePreview) {
previewerDom.parentNode.innerHTML = previewerDom.innerHTML;
} else {
previewerDom.innerHTML = "<div class='cherry-mobile-previewer-content'>".concat(previewerDom.innerHTML, "</div>");
}
this.previewer.isMobilePreview = !this.previewer.isMobilePreview;
this.previewer.bindScroll();
}
}]);
return MobilePreview;
}(MenuBase);
var copyConstructorProperties = function (target, source, exceptions) {
var keys = ownKeys(source);
var defineProperty = objectDefineProperty.f;
var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!hasOwnProperty_1(target, key) && !(exceptions && hasOwnProperty_1(exceptions, key))) {
defineProperty(target, key, getOwnPropertyDescriptor(source, key));
}
}
};
var $Error = Error;
var replace$5 = functionUncurryThis(''.replace);
var TEST = (function (arg) { return String($Error(arg).stack); })('zxcasd');
var V8_OR_CHAKRA_STACK_ENTRY = /\n\s*at [^:]*:[^\n]*/;
var IS_V8_OR_CHAKRA_STACK = V8_OR_CHAKRA_STACK_ENTRY.test(TEST);
var clearErrorStack = function (stack, dropEntries) {
if (IS_V8_OR_CHAKRA_STACK && typeof stack == 'string' && !$Error.prepareStackTrace) {
while (dropEntries--) stack = replace$5(stack, V8_OR_CHAKRA_STACK_ENTRY, '');
} return stack;
};
// `InstallErrorCause` abstract operation
// https://tc39.es/proposal-error-cause/#sec-errorobjects-install-error-cause
var installErrorCause = function (O, options) {
if (isObject(options) && 'cause' in options) {
createNonEnumerableProperty(O, 'cause', options.cause);
}
};
var normalizeStringArgument = function (argument, $default) {
return argument === undefined ? arguments.length < 2 ? '' : $default : toString_1(argument);
};
var errorStackInstallable = !fails(function () {
var error = Error('a');
if (!('stack' in error)) return true;
// eslint-disable-next-line es-x/no-object-defineproperty -- safe
Object.defineProperty(error, 'stack', createPropertyDescriptor(1, 7));
return error.stack !== 7;
});
var TO_STRING_TAG$4 = wellKnownSymbol('toStringTag');
var Error$1 = global_1.Error;
var push$a = [].push;
var $AggregateError = function AggregateError(errors, message /* , options */) {
var options = arguments.length > 2 ? arguments[2] : undefined;
var isInstance = objectIsPrototypeOf(AggregateErrorPrototype, this);
var that;
if (objectSetPrototypeOf) {
that = objectSetPrototypeOf(new Error$1(), isInstance ? objectGetPrototypeOf(this) : AggregateErrorPrototype);
} else {
that = isInstance ? this : objectCreate(AggregateErrorPrototype);
createNonEnumerableProperty(that, TO_STRING_TAG$4, 'Error');
}
if (message !== undefined) createNonEnumerableProperty(that, 'message', normalizeStringArgument(message));
if (errorStackInstallable) createNonEnumerableProperty(that, 'stack', clearErrorStack(that.stack, 1));
installErrorCause(that, options);
var errorsArray = [];
iterate(errors, push$a, { that: errorsArray });
createNonEnumerableProperty(that, 'errors', errorsArray);
return that;
};
if (objectSetPrototypeOf) objectSetPrototypeOf($AggregateError, Error$1);
else copyConstructorProperties($AggregateError, Error$1, { name: true });
var AggregateErrorPrototype = $AggregateError.prototype = objectCreate(Error$1.prototype, {
constructor: createPropertyDescriptor(1, $AggregateError),
message: createPropertyDescriptor(1, ''),
name: createPropertyDescriptor(1, 'AggregateError')
});
// `AggregateError` constructor
// https://tc39.es/ecma262/#sec-aggregate-error-constructor
_export({ global: true, constructor: true, arity: 2 }, {
AggregateError: $AggregateError
});
var engineIsIos = /(?:ipad|iphone|ipod).*applewebkit/i.test(engineUserAgent);
var set$1 = global_1.setImmediate;
var clear = global_1.clearImmediate;
var process$2 = global_1.process;
var Dispatch = global_1.Dispatch;
var Function$3 = global_1.Function;
var MessageChannel = global_1.MessageChannel;
var String$5 = global_1.String;
var counter = 0;
var queue = {};
var ONREADYSTATECHANGE = 'onreadystatechange';
var location$1, defer, channel, port;
try {
// Deno throws a ReferenceError on `location` access without `--location` flag
location$1 = global_1.location;
} catch (error) { /* empty */ }
var run = function (id) {
if (hasOwnProperty_1(queue, id)) {
var fn = queue[id];
delete queue[id];
fn();
}
};
var runner = function (id) {
return function () {
run(id);
};
};
var listener = function (event) {
run(event.data);
};
var post = function (id) {
// old engines have not location.origin
global_1.postMessage(String$5(id), location$1.protocol + '//' + location$1.host);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if (!set$1 || !clear) {
set$1 = function setImmediate(handler) {
validateArgumentsLength(arguments.length, 1);
var fn = isCallable(handler) ? handler : Function$3(handler);
var args = arraySlice(arguments, 1);
queue[++counter] = function () {
functionApply(fn, undefined, args);
};
defer(counter);
return counter;
};
clear = function clearImmediate(id) {
delete queue[id];
};
// Node.js 0.8-
if (engineIsNode) {
defer = function (id) {
process$2.nextTick(runner(id));
};
// Sphere (JS game engine) Dispatch API
} else if (Dispatch && Dispatch.now) {
defer = function (id) {
Dispatch.now(runner(id));
};
// Browsers with MessageChannel, includes WebWorkers
// except iOS - https://github.com/zloirock/core-js/issues/624
} else if (MessageChannel && !engineIsIos) {
channel = new MessageChannel();
port = channel.port2;
channel.port1.onmessage = listener;
defer = functionBindContext(port.postMessage, port);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if (
global_1.addEventListener &&
isCallable(global_1.postMessage) &&
!global_1.importScripts &&
location$1 && location$1.protocol !== 'file:' &&
!fails(post)
) {
defer = post;
global_1.addEventListener('message', listener, false);
// IE8-
} else if (ONREADYSTATECHANGE in documentCreateElement('script')) {
defer = function (id) {
html.appendChild(documentCreateElement('script'))[ONREADYSTATECHANGE] = function () {
html.removeChild(this);
run(id);
};
};
// Rest old browsers
} else {
defer = function (id) {
setTimeout(runner(id), 0);
};
}
}
var task = {
set: set$1,
clear: clear
};
var engineIsIosPebble = /ipad|iphone|ipod/i.test(engineUserAgent) && global_1.Pebble !== undefined;
var engineIsWebosWebkit = /web0s(?!.*chrome)/i.test(engineUserAgent);
var getOwnPropertyDescriptor$9 = objectGetOwnPropertyDescriptor.f;
var macrotask = task.set;
var MutationObserver = global_1.MutationObserver || global_1.WebKitMutationObserver;
var document$2 = global_1.document;
var process$3 = global_1.process;
var Promise$1 = global_1.Promise;
// Node.js 11 shows ExperimentalWarning on getting `queueMicrotask`
var queueMicrotaskDescriptor = getOwnPropertyDescriptor$9(global_1, 'queueMicrotask');
var queueMicrotask = queueMicrotaskDescriptor && queueMicrotaskDescriptor.value;
var flush, head, last, notify, toggle, node, promise, then;
// modern engines have queueMicrotask method
if (!queueMicrotask) {
flush = function () {
var parent, fn;
if (engineIsNode && (parent = process$3.domain)) parent.exit();
while (head) {
fn = head.fn;
head = head.next;
try {
fn();
} catch (error) {
if (head) notify();
else last = undefined;
throw error;
}
} last = undefined;
if (parent) parent.enter();
};
// browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339
// also except WebOS Webkit https://github.com/zloirock/core-js/issues/898
if (!engineIsIos && !engineIsNode && !engineIsWebosWebkit && MutationObserver && document$2) {
toggle = true;
node = document$2.createTextNode('');
new MutationObserver(flush).observe(node, { characterData: true });
notify = function () {
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if (!engineIsIosPebble && Promise$1 && Promise$1.resolve) {
// Promise.resolve without an argument throws an error in LG WebOS 2
promise = Promise$1.resolve(undefined);
// workaround of WebKit ~ iOS Safari 10.1 bug
promise.constructor = Promise$1;
then = functionBindContext(promise.then, promise);
notify = function () {
then(flush);
};
// Node.js without promises
} else if (engineIsNode) {
notify = function () {
process$3.nextTick(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessage
// - onreadystatechange
// - setTimeout
} else {
// strange IE + webpack dev server bug - use .bind(global)
macrotask = functionBindContext(macrotask, global_1);
notify = function () {
macrotask(flush);
};
}
}
var microtask = queueMicrotask || function (fn) {
var task = { fn: fn, next: undefined };
if (last) last.next = task;
if (!head) {
head = task;
notify();
} last = task;
};
var hostReportErrors = function (a, b) {
var console = global_1.console;
if (console && console.error) {
arguments.length == 1 ? console.error(a) : console.error(a, b);
}
};
var perform = function (exec) {
try {
return { error: false, value: exec() };
} catch (error) {
return { error: true, value: error };
}
};
var Queue = function () {
this.head = null;
this.tail = null;
};
Queue.prototype = {
add: function (item) {
var entry = { item: item, next: null };
if (this.head) this.tail.next = entry;
else this.head = entry;
this.tail = entry;
},
get: function () {
var entry = this.head;
if (entry) {
this.head = entry.next;
if (this.tail === entry) this.tail = null;
return entry.item;
}
}
};
var queue$1 = Queue;
var promiseNativeConstructor = global_1.Promise;
var engineIsBrowser = typeof window == 'object' && typeof Deno != 'object';
var NativePromisePrototype = promiseNativeConstructor && promiseNativeConstructor.prototype;
var SPECIES$5 = wellKnownSymbol('species');
var SUBCLASSING = false;
var NATIVE_PROMISE_REJECTION_EVENT = isCallable(global_1.PromiseRejectionEvent);
var FORCED_PROMISE_CONSTRUCTOR = isForced_1('Promise', function () {
var PROMISE_CONSTRUCTOR_SOURCE = inspectSource(promiseNativeConstructor);
var GLOBAL_CORE_JS_PROMISE = PROMISE_CONSTRUCTOR_SOURCE !== String(promiseNativeConstructor);
// V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables
// https://bugs.chromium.org/p/chromium/issues/detail?id=830565
// We can't detect it synchronously, so just check versions
if (!GLOBAL_CORE_JS_PROMISE && engineV8Version === 66) return true;
// We need Promise#{ catch, finally } in the pure version for preventing prototype pollution
if ( !(NativePromisePrototype['catch'] && NativePromisePrototype['finally'])) return true;
// We can't use @@species feature detection in V8 since it causes
// deoptimization and performance degradation
// https://github.com/zloirock/core-js/issues/679
if (engineV8Version >= 51 && /native code/.test(PROMISE_CONSTRUCTOR_SOURCE)) return false;
// Detect correctness of subclassing with @@species support
var promise = new promiseNativeConstructor(function (resolve) { resolve(1); });
var FakePromise = function (exec) {
exec(function () { /* empty */ }, function () { /* empty */ });
};
var constructor = promise.constructor = {};
constructor[SPECIES$5] = FakePromise;
SUBCLASSING = promise.then(function () { /* empty */ }) instanceof FakePromise;
if (!SUBCLASSING) return true;
// Unhandled rejections tracking support, NodeJS Promise without it fails @@species test
return !GLOBAL_CORE_JS_PROMISE && engineIsBrowser && !NATIVE_PROMISE_REJECTION_EVENT;
});
var promiseConstructorDetection = {
CONSTRUCTOR: FORCED_PROMISE_CONSTRUCTOR,
REJECTION_EVENT: NATIVE_PROMISE_REJECTION_EVENT,
SUBCLASSING: SUBCLASSING
};
var PromiseCapability = function (C) {
var resolve, reject;
this.promise = new C(function ($$resolve, $$reject) {
if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aCallable(resolve);
this.reject = aCallable(reject);
};
// `NewPromiseCapability` abstract operation
// https://tc39.es/ecma262/#sec-newpromisecapability
var f$8 = function (C) {
return new PromiseCapability(C);
};
var newPromiseCapability = {
f: f$8
};
var task$1 = task.set;
var PROMISE = 'Promise';
var FORCED_PROMISE_CONSTRUCTOR$1 = promiseConstructorDetection.CONSTRUCTOR;
var NATIVE_PROMISE_REJECTION_EVENT$1 = promiseConstructorDetection.REJECTION_EVENT;
var getInternalPromiseState = internalState.getterFor(PROMISE);
var setInternalState$7 = internalState.set;
var NativePromisePrototype$1 = promiseNativeConstructor && promiseNativeConstructor.prototype;
var PromiseConstructor = promiseNativeConstructor;
var PromisePrototype = NativePromisePrototype$1;
var TypeError$p = global_1.TypeError;
var document$3 = global_1.document;
var process$4 = global_1.process;
var newPromiseCapability$1 = newPromiseCapability.f;
var newGenericPromiseCapability = newPromiseCapability$1;
var DISPATCH_EVENT = !!(document$3 && document$3.createEvent && global_1.dispatchEvent);
var UNHANDLED_REJECTION = 'unhandledrejection';
var REJECTION_HANDLED = 'rejectionhandled';
var PENDING = 0;
var FULFILLED = 1;
var REJECTED = 2;
var HANDLED = 1;
var UNHANDLED = 2;
var Internal, OwnPromiseCapability, PromiseWrapper;
// helpers
var isThenable = function (it) {
var then;
return isObject(it) && isCallable(then = it.then) ? then : false;
};
var callReaction = function (reaction, state) {
var value = state.value;
var ok = state.state == FULFILLED;
var handler = ok ? reaction.ok : reaction.fail;
var resolve = reaction.resolve;
var reject = reaction.reject;
var domain = reaction.domain;
var result, then, exited;
try {
if (handler) {
if (!ok) {
if (state.rejection === UNHANDLED) onHandleUnhandled(state);
state.rejection = HANDLED;
}
if (handler === true) result = value;
else {
if (domain) domain.enter();
result = handler(value); // can throw
if (domain) {
domain.exit();
exited = true;
}
}
if (result === reaction.promise) {
reject(TypeError$p('Promise-chain cycle'));
} else if (then = isThenable(result)) {
functionCall(then, result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch (error) {
if (domain && !exited) domain.exit();
reject(error);
}
};
var notify$1 = function (state, isReject) {
if (state.notified) return;
state.notified = true;
microtask(function () {
var reactions = state.reactions;
var reaction;
while (reaction = reactions.get()) {
callReaction(reaction, state);
}
state.notified = false;
if (isReject && !state.rejection) onUnhandled(state);
});
};
var dispatchEvent = function (name, promise, reason) {
var event, handler;
if (DISPATCH_EVENT) {
event = document$3.createEvent('Event');
event.promise = promise;
event.reason = reason;
event.initEvent(name, false, true);
global_1.dispatchEvent(event);
} else event = { promise: promise, reason: reason };
if (!NATIVE_PROMISE_REJECTION_EVENT$1 && (handler = global_1['on' + name])) handler(event);
else if (name === UNHANDLED_REJECTION) hostReportErrors('Unhandled promise rejection', reason);
};
var onUnhandled = function (state) {
functionCall(task$1, global_1, function () {
var promise = state.facade;
var value = state.value;
var IS_UNHANDLED = isUnhandled(state);
var result;
if (IS_UNHANDLED) {
result = perform(function () {
if (engineIsNode) {
process$4.emit('unhandledRejection', value, promise);
} else dispatchEvent(UNHANDLED_REJECTION, promise, value);
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
state.rejection = engineIsNode || isUnhandled(state) ? UNHANDLED : HANDLED;
if (result.error) throw result.value;
}
});
};
var isUnhandled = function (state) {
return state.rejection !== HANDLED && !state.parent;
};
var onHandleUnhandled = function (state) {
functionCall(task$1, global_1, function () {
var promise = state.facade;
if (engineIsNode) {
process$4.emit('rejectionHandled', promise);
} else dispatchEvent(REJECTION_HANDLED, promise, state.value);
});
};
var bind$b = function (fn, state, unwrap) {
return function (value) {
fn(state, value, unwrap);
};
};
var internalReject = function (state, value, unwrap) {
if (state.done) return;
state.done = true;
if (unwrap) state = unwrap;
state.value = value;
state.state = REJECTED;
notify$1(state, true);
};
var internalResolve = function (state, value, unwrap) {
if (state.done) return;
state.done = true;
if (unwrap) state = unwrap;
try {
if (state.facade === value) throw TypeError$p("Promise can't be resolved itself");
var then = isThenable(value);
if (then) {
microtask(function () {
var wrapper = { done: false };
try {
functionCall(then, value,
bind$b(internalResolve, wrapper, state),
bind$b(internalReject, wrapper, state)
);
} catch (error) {
internalReject(wrapper, error, state);
}
});
} else {
state.value = value;
state.state = FULFILLED;
notify$1(state, false);
}
} catch (error) {
internalReject({ done: false }, error, state);
}
};
// constructor polyfill
if (FORCED_PROMISE_CONSTRUCTOR$1) {
// 25.4.3.1 Promise(executor)
PromiseConstructor = function Promise(executor) {
anInstance(this, PromisePrototype);
aCallable(executor);
functionCall(Internal, this);
var state = getInternalPromiseState(this);
try {
executor(bind$b(internalResolve, state), bind$b(internalReject, state));
} catch (error) {
internalReject(state, error);
}
};
PromisePrototype = PromiseConstructor.prototype;
// eslint-disable-next-line no-unused-vars -- required for `.length`
Internal = function Promise(executor) {
setInternalState$7(this, {
type: PROMISE,
done: false,
notified: false,
parent: false,
reactions: new queue$1(),
rejection: false,
state: PENDING,
value: undefined
});
};
// `Promise.prototype.then` method
// https://tc39.es/ecma262/#sec-promise.prototype.then
Internal.prototype = defineBuiltIn(PromisePrototype, 'then', function then(onFulfilled, onRejected) {
var state = getInternalPromiseState(this);
var reaction = newPromiseCapability$1(speciesConstructor(this, PromiseConstructor));
state.parent = true;
reaction.ok = isCallable(onFulfilled) ? onFulfilled : true;
reaction.fail = isCallable(onRejected) && onRejected;
reaction.domain = engineIsNode ? process$4.domain : undefined;
if (state.state == PENDING) state.reactions.add(reaction);
else microtask(function () {
callReaction(reaction, state);
});
return reaction.promise;
});
OwnPromiseCapability = function () {
var promise = new Internal();
var state = getInternalPromiseState(promise);
this.promise = promise;
this.resolve = bind$b(internalResolve, state);
this.reject = bind$b(internalReject, state);
};
newPromiseCapability.f = newPromiseCapability$1 = function (C) {
return C === PromiseConstructor || C === PromiseWrapper
? new OwnPromiseCapability(C)
: newGenericPromiseCapability(C);
};
}
_export({ global: true, constructor: true, wrap: true, forced: FORCED_PROMISE_CONSTRUCTOR$1 }, {
Promise: PromiseConstructor
});
setToStringTag(PromiseConstructor, PROMISE, false, true);
setSpecies(PROMISE);
var FORCED_PROMISE_CONSTRUCTOR$2 = promiseConstructorDetection.CONSTRUCTOR;
var promiseStaticsIncorrectIteration = FORCED_PROMISE_CONSTRUCTOR$2 || !checkCorrectnessOfIteration(function (iterable) {
promiseNativeConstructor.all(iterable).then(undefined, function () { /* empty */ });
});
// `Promise.all` method
// https://tc39.es/ecma262/#sec-promise.all
_export({ target: 'Promise', stat: true, forced: promiseStaticsIncorrectIteration }, {
all: function all(iterable) {
var C = this;
var capability = newPromiseCapability.f(C);
var resolve = capability.resolve;
var reject = capability.reject;
var result = perform(function () {
var $promiseResolve = aCallable(C.resolve);
var values = [];
var counter = 0;
var remaining = 1;
iterate(iterable, function (promise) {
var index = counter++;
var alreadyCalled = false;
remaining++;
functionCall($promiseResolve, C, promise).then(function (value) {
if (alreadyCalled) return;
alreadyCalled = true;
values[index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if (result.error) reject(result.value);
return capability.promise;
}
});
var FORCED_PROMISE_CONSTRUCTOR$3 = promiseConstructorDetection.CONSTRUCTOR;
var NativePromisePrototype$2 = promiseNativeConstructor && promiseNativeConstructor.prototype;
// `Promise.prototype.catch` method
// https://tc39.es/ecma262/#sec-promise.prototype.catch
_export({ target: 'Promise', proto: true, forced: FORCED_PROMISE_CONSTRUCTOR$3, real: true }, {
'catch': function (onRejected) {
return this.then(undefined, onRejected);
}
});
// `Promise.race` method
// https://tc39.es/ecma262/#sec-promise.race
_export({ target: 'Promise', stat: true, forced: promiseStaticsIncorrectIteration }, {
race: function race(iterable) {
var C = this;
var capability = newPromiseCapability.f(C);
var reject = capability.reject;
var result = perform(function () {
var $promiseResolve = aCallable(C.resolve);
iterate(iterable, function (promise) {
functionCall($promiseResolve, C, promise).then(capability.resolve, reject);
});
});
if (result.error) reject(result.value);
return capability.promise;
}
});
var FORCED_PROMISE_CONSTRUCTOR$4 = promiseConstructorDetection.CONSTRUCTOR;
// `Promise.reject` method
// https://tc39.es/ecma262/#sec-promise.reject
_export({ target: 'Promise', stat: true, forced: FORCED_PROMISE_CONSTRUCTOR$4 }, {
reject: function reject(r) {
var capability = newPromiseCapability.f(this);
functionCall(capability.reject, undefined, r);
return capability.promise;
}
});
var promiseResolve = function (C, x) {
anObject(C);
if (isObject(x) && x.constructor === C) return x;
var promiseCapability = newPromiseCapability.f(C);
var resolve = promiseCapability.resolve;
resolve(x);
return promiseCapability.promise;
};
var FORCED_PROMISE_CONSTRUCTOR$5 = promiseConstructorDetection.CONSTRUCTOR;
var PromiseConstructorWrapper = getBuiltIn('Promise');
var CHECK_WRAPPER = !FORCED_PROMISE_CONSTRUCTOR$5;
// `Promise.resolve` method
// https://tc39.es/ecma262/#sec-promise.resolve
_export({ target: 'Promise', stat: true, forced: isPure }, {
resolve: function resolve(x) {
return promiseResolve(CHECK_WRAPPER && this === PromiseConstructorWrapper ? promiseNativeConstructor : this, x);
}
});
// `Promise.allSettled` method
// https://tc39.es/ecma262/#sec-promise.allsettled
_export({ target: 'Promise', stat: true }, {
allSettled: function allSettled(iterable) {
var C = this;
var capability = newPromiseCapability.f(C);
var resolve = capability.resolve;
var reject = capability.reject;
var result = perform(function () {
var promiseResolve = aCallable(C.resolve);
var values = [];
var counter = 0;
var remaining = 1;
iterate(iterable, function (promise) {
var index = counter++;
var alreadyCalled = false;
remaining++;
functionCall(promiseResolve, C, promise).then(function (value) {
if (alreadyCalled) return;
alreadyCalled = true;
values[index] = { status: 'fulfilled', value: value };
--remaining || resolve(values);
}, function (error) {
if (alreadyCalled) return;
alreadyCalled = true;
values[index] = { status: 'rejected', reason: error };
--remaining || resolve(values);
});
});
--remaining || resolve(values);
});
if (result.error) reject(result.value);
return capability.promise;
}
});
var PROMISE_ANY_ERROR = 'No one promise resolved';
// `Promise.any` method
// https://tc39.es/ecma262/#sec-promise.any
_export({ target: 'Promise', stat: true }, {
any: function any(iterable) {
var C = this;
var AggregateError = getBuiltIn('AggregateError');
var capability = newPromiseCapability.f(C);
var resolve = capability.resolve;
var reject = capability.reject;
var result = perform(function () {
var promiseResolve = aCallable(C.resolve);
var errors = [];
var counter = 0;
var remaining = 1;
var alreadyResolved = false;
iterate(iterable, function (promise) {
var index = counter++;
var alreadyRejected = false;
remaining++;
functionCall(promiseResolve, C, promise).then(function (value) {
if (alreadyRejected || alreadyResolved) return;
alreadyResolved = true;
resolve(value);
}, function (error) {
if (alreadyRejected || alreadyResolved) return;
alreadyRejected = true;
errors[index] = error;
--remaining || reject(new AggregateError(errors, PROMISE_ANY_ERROR));
});
});
--remaining || reject(new AggregateError(errors, PROMISE_ANY_ERROR));
});
if (result.error) reject(result.value);
return capability.promise;
}
});
var NativePromisePrototype$3 = promiseNativeConstructor && promiseNativeConstructor.prototype;
// Safari bug https://bugs.webkit.org/show_bug.cgi?id=200829
var NON_GENERIC = !!promiseNativeConstructor && fails(function () {
// eslint-disable-next-line unicorn/no-thenable -- required for testing
NativePromisePrototype$3['finally'].call({ then: function () { /* empty */ } }, function () { /* empty */ });
});
// `Promise.prototype.finally` method
// https://tc39.es/ecma262/#sec-promise.prototype.finally
_export({ target: 'Promise', proto: true, real: true, forced: NON_GENERIC }, {
'finally': function (onFinally) {
var C = speciesConstructor(this, getBuiltIn('Promise'));
var isFunction = isCallable(onFinally);
return this.then(
isFunction ? function (x) {
return promiseResolve(C, onFinally()).then(function () { return x; });
} : onFinally,
isFunction ? function (e) {
return promiseResolve(C, onFinally()).then(function () { throw e; });
} : onFinally
);
}
});
var promise$1 = path.Promise;
var promise$2 = promise$1;
var promise$3 = promise$2;
// TODO: Remove from `core-js@4`
// `Promise.try` method
// https://github.com/tc39/proposal-promise-try
_export({ target: 'Promise', stat: true, forced: true }, {
'try': function (callbackfn) {
var promiseCapability = newPromiseCapability.f(this);
var result = perform(callbackfn);
(result.error ? promiseCapability.reject : promiseCapability.resolve)(result.value);
return promiseCapability.promise;
}
});
// TODO: Remove from `core-js@4`
var promise$4 = promise$3;
var promise$5 = promise$4;
var promise$6 = promise$5;
var asyncToGenerator = createCommonjsModule(function (module) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
promise$6.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new promise$6(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
module.exports = _asyncToGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
var _asyncToGenerator = unwrapExports(asyncToGenerator);
var forEach$6 = forEach$2;
var forEach$7 = forEach$6;
var forEach$8 = forEach$7;
var forEach$9 = forEach$8;
var un$Reverse = functionUncurryThis([].reverse);
var test$1 = [1, 2];
// `Array.prototype.reverse` method
// https://tc39.es/ecma262/#sec-array.prototype.reverse
// fix for Safari 12.0 bug
// https://bugs.webkit.org/show_bug.cgi?id=188794
_export({ target: 'Array', proto: true, forced: String(test$1) === String(test$1.reverse()) }, {
reverse: function reverse() {
// eslint-disable-next-line no-self-assign -- dirty hack
if (isArray(this)) this.length = this.length;
return un$Reverse(this);
}
});
var reverse = entryVirtual('Array').reverse;
var ArrayPrototype$g = Array.prototype;
var reverse$1 = function (it) {
var own = it.reverse;
return it === ArrayPrototype$g || (objectIsPrototypeOf(ArrayPrototype$g, it) && own === ArrayPrototype$g.reverse) ? reverse : own;
};
var reverse$2 = reverse$1;
var reverse$3 = reverse$2;
var reverse$4 = reverse$3;
var reverse$5 = reverse$4;
var reverse$6 = reverse$5;
var regeneratorRuntime = createCommonjsModule(function (module) {
var _typeof = _typeof_1["default"];
function _regeneratorRuntime() {
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
return exports;
}, module.exports.__esModule = true, module.exports["default"] = module.exports;
var exports = {},
Op = Object.prototype,
hasOwn = Op.hasOwnProperty,
$Symbol = "function" == typeof symbol$5 ? symbol$5 : {},
iteratorSymbol = $Symbol.iterator || "@@iterator",
asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function define(obj, key, value) {
return defineProperty$9(obj, key, {
value: value,
enumerable: !0,
configurable: !0,
writable: !0
}), obj[key];
}
try {
define({}, "");
} catch (err) {
define = function define(obj, key, value) {
return obj[key] = value;
};
}
function wrap(innerFn, outerFn, self, tryLocsList) {
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
generator = create$5(protoGenerator.prototype),
context = new Context(tryLocsList || []);
return generator._invoke = function (innerFn, self, context) {
var state = "suspendedStart";
return function (method, arg) {
if ("executing" === state) throw new Error("Generator is already running");
if ("completed" === state) {
if ("throw" === method) throw arg;
return doneResult();
}
for (context.method = method, context.arg = arg;;) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
if ("suspendedStart" === state) throw state = "completed", context.arg;
context.dispatchException(context.arg);
} else "return" === context.method && context.abrupt("return", context.arg);
state = "executing";
var record = tryCatch(innerFn, self, context);
if ("normal" === record.type) {
if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
return {
value: record.arg,
done: context.done
};
}
"throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
}
};
}(innerFn, self, context), generator;
}
function tryCatch(fn, obj, arg) {
try {
return {
type: "normal",
arg: fn.call(obj, arg)
};
} catch (err) {
return {
type: "throw",
arg: err
};
}
}
exports.wrap = wrap;
var ContinueSentinel = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
var IteratorPrototype = {};
define(IteratorPrototype, iteratorSymbol, function () {
return this;
});
var getProto = getPrototypeOf$5,
NativeIteratorPrototype = getProto && getProto(getProto(values([])));
NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = create$5(IteratorPrototype);
function defineIteratorMethods(prototype) {
var _context;
forEach$9(_context = ["next", "throw", "return"]).call(_context, function (method) {
define(prototype, method, function (arg) {
return this._invoke(method, arg);
});
});
}
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if ("throw" !== record.type) {
var result = record.arg,
value = result.value;
return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
invoke("next", value, resolve, reject);
}, function (err) {
invoke("throw", err, resolve, reject);
}) : PromiseImpl.resolve(value).then(function (unwrapped) {
result.value = unwrapped, resolve(result);
}, function (error) {
return invoke("throw", error, resolve, reject);
});
}
reject(record.arg);
}
var previousPromise;
this._invoke = function (method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function (resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
};
}
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (undefined === method) {
if (context.delegate = null, "throw" === context.method) {
if (delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel;
context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
var info = record.arg;
return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
}
function pushTryEntry(locs) {
var entry = {
tryLoc: locs[0]
};
1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal", delete record.arg, entry.completion = record;
}
function Context(tryLocsList) {
this.tryEntries = [{
tryLoc: "root"
}], forEach$9(tryLocsList).call(tryLocsList, pushTryEntry, this), this.reset(!0);
}
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) return iteratorMethod.call(iterable);
if ("function" == typeof iterable.next) return iterable;
if (!isNaN(iterable.length)) {
var i = -1,
next = function next() {
for (; ++i < iterable.length;) {
if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
}
return next.value = undefined, next.done = !0, next;
};
return next.next = next;
}
}
return {
next: doneResult
};
}
function doneResult() {
return {
value: undefined,
done: !0
};
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
var ctor = "function" == typeof genFun && genFun.constructor;
return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
}, exports.mark = function (genFun) {
return setPrototypeOf$5 ? setPrototypeOf$5(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = create$5(Gp), genFun;
}, exports.awrap = function (arg) {
return {
__await: arg
};
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
return this;
}), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
void 0 === PromiseImpl && (PromiseImpl = promise$6);
var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
return result.done ? result.value : iter.next();
});
}, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
return this;
}), define(Gp, "toString", function () {
return "[object Generator]";
}), exports.keys = function (object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
return reverse$6(keys).call(keys), function next() {
for (; keys.length;) {
var key = keys.pop();
if (key in object) return next.value = key, next.done = !1, next;
}
return next.done = !0, next;
};
}, exports.values = values, Context.prototype = {
constructor: Context,
reset: function reset(skipTempReset) {
var _context2;
if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, forEach$9(_context2 = this.tryEntries).call(_context2, resetTryEntry), !skipTempReset) for (var name in this) {
"t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+slice$6(name).call(name, 1)) && (this[name] = undefined);
}
},
stop: function stop() {
this.done = !0;
var rootRecord = this.tryEntries[0].completion;
if ("throw" === rootRecord.type) throw rootRecord.arg;
return this.rval;
},
dispatchException: function dispatchException(exception) {
if (this.done) throw exception;
var context = this;
function handle(loc, caught) {
return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i],
record = entry.completion;
if ("root" === entry.tryLoc) return handle("end");
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc"),
hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
} else if (hasCatch) {
if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
} else {
if (!hasFinally) throw new Error("try statement without catch or finally");
if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
}
}
}
},
abrupt: function abrupt(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
var record = finallyEntry ? finallyEntry.completion : {};
return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
},
complete: function complete(record, afterLoc) {
if ("throw" === record.type) throw record.arg;
return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
},
finish: function finish(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
}
},
"catch": function _catch(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if ("throw" === record.type) {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
throw new Error("illegal catch attempt");
},
delegateYield: function delegateYield(iterable, resultName, nextLoc) {
return this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
}, "next" === this.method && (this.arg = undefined), ContinueSentinel;
}
}, exports;
}
module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(regeneratorRuntime);
var regenerator = regeneratorRuntime();
var promise$7 = promise$2;
const defaultOpts = {
xml: false,
decodeEntities: true,
};
const xmlModeDefault = {
_useHtmlParser2: true,
xmlMode: true,
};
/**
* Flatten the options for Cheerio.
*
* This will set `_useHtmlParser2` to true if `xml` is set to true.
*
* @param options - The options to flatten.
* @returns The flattened options.
*/
function flatten(options) {
return (options === null || options === void 0 ? void 0 : options.xml)
? typeof options.xml === 'boolean'
? xmlModeDefault
: { ...xmlModeDefault, ...options.xml }
: options !== null && options !== void 0 ? options : undefined;
}
/** Types of elements found in htmlparser2's DOM */
var ElementType;
(function (ElementType) {
/** Type for the root element of a document */
ElementType["Root"] = "root";
/** Type for Text */
ElementType["Text"] = "text";
/** Type for <? ... ?> */
ElementType["Directive"] = "directive";
/** Type for <!-- ... --> */
ElementType["Comment"] = "comment";
/** Type for <script> tags */
ElementType["Script"] = "script";
/** Type for <style> tags */
ElementType["Style"] = "style";
/** Type for Any tag */
ElementType["Tag"] = "tag";
/** Type for <![CDATA[ ... ]]> */
ElementType["CDATA"] = "cdata";
/** Type for <!doctype ...> */
ElementType["Doctype"] = "doctype";
})(ElementType || (ElementType = {}));
/**
* Tests whether an element is a tag or not.
*
* @param elem Element to test
*/
function isTag(elem) {
return (elem.type === ElementType.Tag ||
elem.type === ElementType.Script ||
elem.type === ElementType.Style);
}
// Exports for backwards compatibility
/** Type for the root element of a document */
const Root = ElementType.Root;
/** Type for Text */
const Text = ElementType.Text;
/** Type for <? ... ?> */
const Directive = ElementType.Directive;
/** Type for <!-- ... --> */
const Comment = ElementType.Comment;
/** Type for <script> tags */
const Script = ElementType.Script;
/** Type for <style> tags */
const Style = ElementType.Style;
/** Type for Any tag */
const Tag = ElementType.Tag;
/** Type for <![CDATA[ ... ]]> */
const CDATA = ElementType.CDATA;
/** Type for <!doctype ...> */
const Doctype = ElementType.Doctype;
/**
* This object will be used as the prototype for Nodes when creating a
* DOM-Level-1-compliant structure.
*/
class Node$2 {
constructor() {
/** Parent of the node */
this.parent = null;
/** Previous sibling */
this.prev = null;
/** Next sibling */
this.next = null;
/** The start index of the node. Requires `withStartIndices` on the handler to be `true. */
this.startIndex = null;
/** The end index of the node. Requires `withEndIndices` on the handler to be `true. */
this.endIndex = null;
}
// Read-write aliases for properties
/**
* Same as {@link parent}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get parentNode() {
return this.parent;
}
set parentNode(parent) {
this.parent = parent;
}
/**
* Same as {@link prev}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get previousSibling() {
return this.prev;
}
set previousSibling(prev) {
this.prev = prev;
}
/**
* Same as {@link next}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get nextSibling() {
return this.next;
}
set nextSibling(next) {
this.next = next;
}
/**
* Clone this node, and optionally its children.
*
* @param recursive Clone child nodes as well.
* @returns A clone of the node.
*/
cloneNode(recursive = false) {
return cloneNode(this, recursive);
}
}
/**
* A node that contains some data.
*/
class DataNode extends Node$2 {
/**
* @param data The content of the data node
*/
constructor(data) {
super();
this.data = data;
}
/**
* Same as {@link data}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get nodeValue() {
return this.data;
}
set nodeValue(data) {
this.data = data;
}
}
/**
* Text within the document.
*/
class Text$1 extends DataNode {
constructor() {
super(...arguments);
this.type = ElementType.Text;
}
get nodeType() {
return 3;
}
}
/**
* Comments within the document.
*/
class Comment$1 extends DataNode {
constructor() {
super(...arguments);
this.type = ElementType.Comment;
}
get nodeType() {
return 8;
}
}
/**
* Processing instructions, including doc types.
*/
class ProcessingInstruction extends DataNode {
constructor(name, data) {
super(data);
this.name = name;
this.type = ElementType.Directive;
}
get nodeType() {
return 1;
}
}
/**
* A `Node` that can have children.
*/
class NodeWithChildren extends Node$2 {
/**
* @param children Children of the node. Only certain node types can have children.
*/
constructor(children) {
super();
this.children = children;
}
// Aliases
/** First child of the node. */
get firstChild() {
var _a;
return (_a = this.children[0]) !== null && _a !== void 0 ? _a : null;
}
/** Last child of the node. */
get lastChild() {
return this.children.length > 0
? this.children[this.children.length - 1]
: null;
}
/**
* Same as {@link children}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get childNodes() {
return this.children;
}
set childNodes(children) {
this.children = children;
}
}
class CDATA$1 extends NodeWithChildren {
constructor() {
super(...arguments);
this.type = ElementType.CDATA;
}
get nodeType() {
return 4;
}
}
/**
* The root node of the document.
*/
class Document extends NodeWithChildren {
constructor() {
super(...arguments);
this.type = ElementType.Root;
}
get nodeType() {
return 9;
}
}
/**
* An element within the DOM.
*/
class Element extends NodeWithChildren {
/**
* @param name Name of the tag, eg. `div`, `span`.
* @param attribs Object mapping attribute names to attribute values.
* @param children Children of the node.
*/
constructor(name, attribs, children = [], type = name === "script"
? ElementType.Script
: name === "style"
? ElementType.Style
: ElementType.Tag) {
super(children);
this.name = name;
this.attribs = attribs;
this.type = type;
}
get nodeType() {
return 1;
}
// DOM Level 1 aliases
/**
* Same as {@link name}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get tagName() {
return this.name;
}
set tagName(name) {
this.name = name;
}
get attributes() {
return Object.keys(this.attribs).map((name) => {
var _a, _b;
return ({
name,
value: this.attribs[name],
namespace: (_a = this["x-attribsNamespace"]) === null || _a === void 0 ? void 0 : _a[name],
prefix: (_b = this["x-attribsPrefix"]) === null || _b === void 0 ? void 0 : _b[name],
});
});
}
}
/**
* @param node Node to check.
* @returns `true` if the node is a `Element`, `false` otherwise.
*/
function isTag$1(node) {
return isTag(node);
}
/**
* @param node Node to check.
* @returns `true` if the node has the type `CDATA`, `false` otherwise.
*/
function isCDATA(node) {
return node.type === ElementType.CDATA;
}
/**
* @param node Node to check.
* @returns `true` if the node has the type `Text`, `false` otherwise.
*/
function isText(node) {
return node.type === ElementType.Text;
}
/**
* @param node Node to check.
* @returns `true` if the node has the type `Comment`, `false` otherwise.
*/
function isComment(node) {
return node.type === ElementType.Comment;
}
/**
* @param node Node to check.
* @returns `true` if the node has the type `ProcessingInstruction`, `false` otherwise.
*/
function isDirective(node) {
return node.type === ElementType.Directive;
}
/**
* @param node Node to check.
* @returns `true` if the node has the type `ProcessingInstruction`, `false` otherwise.
*/
function isDocument(node) {
return node.type === ElementType.Root;
}
/**
* @param node Node to check.
* @returns `true` if the node has children, `false` otherwise.
*/
function hasChildren(node) {
return Object.prototype.hasOwnProperty.call(node, "children");
}
/**
* Clone a node, and optionally its children.
*
* @param recursive Clone child nodes as well.
* @returns A clone of the node.
*/
function cloneNode(node, recursive = false) {
let result;
if (isText(node)) {
result = new Text$1(node.data);
}
else if (isComment(node)) {
result = new Comment$1(node.data);
}
else if (isTag$1(node)) {
const children = recursive ? cloneChildren(node.children) : [];
const clone = new Element(node.name, { ...node.attribs }, children);
children.forEach((child) => (child.parent = clone));
if (node.namespace != null) {
clone.namespace = node.namespace;
}
if (node["x-attribsNamespace"]) {
clone["x-attribsNamespace"] = { ...node["x-attribsNamespace"] };
}
if (node["x-attribsPrefix"]) {
clone["x-attribsPrefix"] = { ...node["x-attribsPrefix"] };
}
result = clone;
}
else if (isCDATA(node)) {
const children = recursive ? cloneChildren(node.children) : [];
const clone = new CDATA$1(children);
children.forEach((child) => (child.parent = clone));
result = clone;
}
else if (isDocument(node)) {
const children = recursive ? cloneChildren(node.children) : [];
const clone = new Document(children);
children.forEach((child) => (child.parent = clone));
if (node["x-mode"]) {
clone["x-mode"] = node["x-mode"];
}
result = clone;
}
else if (isDirective(node)) {
const instruction = new ProcessingInstruction(node.name, node.data);
if (node["x-name"] != null) {
instruction["x-name"] = node["x-name"];
instruction["x-publicId"] = node["x-publicId"];
instruction["x-systemId"] = node["x-systemId"];
}
result = instruction;
}
else {
throw new Error(`Not implemented yet: ${node.type}`);
}
result.startIndex = node.startIndex;
result.endIndex = node.endIndex;
if (node.sourceCodeLocation != null) {
result.sourceCodeLocation = node.sourceCodeLocation;
}
return result;
}
function cloneChildren(childs) {
const children = childs.map((child) => cloneNode(child, true));
for (let i = 1; i < children.length; i++) {
children[i].prev = children[i - 1];
children[i - 1].next = children[i];
}
return children;
}
// Default options
const defaultOpts$1 = {
withStartIndices: false,
withEndIndices: false,
xmlMode: false,
};
class DomHandler {
/**
* @param callback Called once parsing has completed.
* @param options Settings for the handler.
* @param elementCB Callback whenever a tag is closed.
*/
constructor(callback, options, elementCB) {
/** The elements of the DOM */
this.dom = [];
/** The root element for the DOM */
this.root = new Document(this.dom);
/** Indicated whether parsing has been completed. */
this.done = false;
/** Stack of open tags. */
this.tagStack = [this.root];
/** A data node that is still being written to. */
this.lastNode = null;
/** Reference to the parser instance. Used for location information. */
this.parser = null;
// Make it possible to skip arguments, for backwards-compatibility
if (typeof options === "function") {
elementCB = options;
options = defaultOpts$1;
}
if (typeof callback === "object") {
options = callback;
callback = undefined;
}
this.callback = callback !== null && callback !== void 0 ? callback : null;
this.options = options !== null && options !== void 0 ? options : defaultOpts$1;
this.elementCB = elementCB !== null && elementCB !== void 0 ? elementCB : null;
}
onparserinit(parser) {
this.parser = parser;
}
// Resets the handler back to starting state
onreset() {
this.dom = [];
this.root = new Document(this.dom);
this.done = false;
this.tagStack = [this.root];
this.lastNode = null;
this.parser = null;
}
// Signals the handler that parsing is done
onend() {
if (this.done)
return;
this.done = true;
this.parser = null;
this.handleCallback(null);
}
onerror(error) {
this.handleCallback(error);
}
onclosetag() {
this.lastNode = null;
const elem = this.tagStack.pop();
if (this.options.withEndIndices) {
elem.endIndex = this.parser.endIndex;
}
if (this.elementCB)
this.elementCB(elem);
}
onopentag(name, attribs) {
const type = this.options.xmlMode ? ElementType.Tag : undefined;
const element = new Element(name, attribs, undefined, type);
this.addNode(element);
this.tagStack.push(element);
}
ontext(data) {
const { lastNode } = this;
if (lastNode && lastNode.type === ElementType.Text) {
lastNode.data += data;
if (this.options.withEndIndices) {
lastNode.endIndex = this.parser.endIndex;
}
}
else {
const node = new Text$1(data);
this.addNode(node);
this.lastNode = node;
}
}
oncomment(data) {
if (this.lastNode && this.lastNode.type === ElementType.Comment) {
this.lastNode.data += data;
return;
}
const node = new Comment$1(data);
this.addNode(node);
this.lastNode = node;
}
oncommentend() {
this.lastNode = null;
}
oncdatastart() {
const text = new Text$1("");
const node = new CDATA$1([text]);
this.addNode(node);
text.parent = node;
this.lastNode = text;
}
oncdataend() {
this.lastNode = null;
}
onprocessinginstruction(name, data) {
const node = new ProcessingInstruction(name, data);
this.addNode(node);
}
handleCallback(error) {
if (typeof this.callback === "function") {
this.callback(error, this.dom);
}
else if (error) {
throw error;
}
}
addNode(node) {
const parent = this.tagStack[this.tagStack.length - 1];
const previousSibling = parent.children[parent.children.length - 1];
if (this.options.withStartIndices) {
node.startIndex = this.parser.startIndex;
}
if (this.options.withEndIndices) {
node.endIndex = this.parser.endIndex;
}
parent.children.push(node);
if (previousSibling) {
node.prev = previousSibling;
previousSibling.next = node;
}
node.parent = parent;
this.lastNode = null;
}
}
const xmlReplacer = /["&'<>$\x80-\uFFFF]/g;
const xmlCodeMap = new Map([
[34, "&quot;"],
[38, "&amp;"],
[39, "&apos;"],
[60, "&lt;"],
[62, "&gt;"],
]);
// For compatibility with node < 4, we wrap `codePointAt`
const getCodePoint =
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
String.prototype.codePointAt != null
? (str, index) => str.codePointAt(index)
: // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
(c, index) => (c.charCodeAt(index) & 0xfc00) === 0xd800
? (c.charCodeAt(index) - 0xd800) * 0x400 +
c.charCodeAt(index + 1) -
0xdc00 +
0x10000
: c.charCodeAt(index);
/**
* Encodes all non-ASCII characters, as well as characters not valid in XML
* documents using XML entities.
*
* If a character has no equivalent entity, a
* numeric hexadecimal reference (eg. `&#xfc;`) will be used.
*/
function encodeXML(str) {
let ret = "";
let lastIdx = 0;
let match;
while ((match = xmlReplacer.exec(str)) !== null) {
const i = match.index;
const char = str.charCodeAt(i);
const next = xmlCodeMap.get(char);
if (next !== undefined) {
ret += str.substring(lastIdx, i) + next;
lastIdx = i + 1;
}
else {
ret += `${str.substring(lastIdx, i)}&#x${getCodePoint(str, i).toString(16)};`;
// Increase by 1 if we have a surrogate pair
lastIdx = xmlReplacer.lastIndex += Number((char & 0xfc00) === 0xd800);
}
}
return ret + str.substr(lastIdx);
}
function getEscaper(regex, map) {
return function escape(data) {
let match;
let lastIdx = 0;
let result = "";
while ((match = regex.exec(data))) {
if (lastIdx !== match.index) {
result += data.substring(lastIdx, match.index);
}
// We know that this chararcter will be in the map.
result += map.get(match[0].charCodeAt(0));
// Every match will be of length 1
lastIdx = match.index + 1;
}
return result + data.substring(lastIdx);
};
}
/**
* Encodes all characters that have to be escaped in HTML attributes,
* following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
*
* @param data String to escape.
*/
const escapeAttribute = getEscaper(/["&\u00A0]/g, new Map([
[34, "&quot;"],
[38, "&amp;"],
[160, "&nbsp;"],
]));
/**
* Encodes all characters that have to be escaped in HTML text,
* following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
*
* @param data String to escape.
*/
const escapeText = getEscaper(/[&<>\u00A0]/g, new Map([
[38, "&amp;"],
[60, "&lt;"],
[62, "&gt;"],
[160, "&nbsp;"],
]));
const elementNames = new Map([
"altGlyph",
"altGlyphDef",
"altGlyphItem",
"animateColor",
"animateMotion",
"animateTransform",
"clipPath",
"feBlend",
"feColorMatrix",
"feComponentTransfer",
"feComposite",
"feConvolveMatrix",
"feDiffuseLighting",
"feDisplacementMap",
"feDistantLight",
"feDropShadow",
"feFlood",
"feFuncA",
"feFuncB",
"feFuncG",
"feFuncR",
"feGaussianBlur",
"feImage",
"feMerge",
"feMergeNode",
"feMorphology",
"feOffset",
"fePointLight",
"feSpecularLighting",
"feSpotLight",
"feTile",
"feTurbulence",
"foreignObject",
"glyphRef",
"linearGradient",
"radialGradient",
"textPath",
].map((val) => [val.toLowerCase(), val]));
const attributeNames = new Map([
"definitionURL",
"attributeName",
"attributeType",
"baseFrequency",
"baseProfile",
"calcMode",
"clipPathUnits",
"diffuseConstant",
"edgeMode",
"filterUnits",
"glyphRef",
"gradientTransform",
"gradientUnits",
"kernelMatrix",
"kernelUnitLength",
"keyPoints",
"keySplines",
"keyTimes",
"lengthAdjust",
"limitingConeAngle",
"markerHeight",
"markerUnits",
"markerWidth",
"maskContentUnits",
"maskUnits",
"numOctaves",
"pathLength",
"patternContentUnits",
"patternTransform",
"patternUnits",
"pointsAtX",
"pointsAtY",
"pointsAtZ",
"preserveAlpha",
"preserveAspectRatio",
"primitiveUnits",
"refX",
"refY",
"repeatCount",
"repeatDur",
"requiredExtensions",
"requiredFeatures",
"specularConstant",
"specularExponent",
"spreadMethod",
"startOffset",
"stdDeviation",
"stitchTiles",
"surfaceScale",
"systemLanguage",
"tableValues",
"targetX",
"targetY",
"textLength",
"viewBox",
"viewTarget",
"xChannelSelector",
"yChannelSelector",
"zoomAndPan",
].map((val) => [val.toLowerCase(), val]));
/*
* Module dependencies
*/
const unencodedElements = new Set([
"style",
"script",
"xmp",
"iframe",
"noembed",
"noframes",
"plaintext",
"noscript",
]);
function replaceQuotes(value) {
return value.replace(/"/g, "&quot;");
}
/**
* Format attributes
*/
function formatAttributes(attributes, opts) {
var _a;
if (!attributes)
return;
const encode = ((_a = opts.encodeEntities) !== null && _a !== void 0 ? _a : opts.decodeEntities) === false
? replaceQuotes
: opts.xmlMode || opts.encodeEntities !== "utf8"
? encodeXML
: escapeAttribute;
return Object.keys(attributes)
.map((key) => {
var _a, _b;
const value = (_a = attributes[key]) !== null && _a !== void 0 ? _a : "";
if (opts.xmlMode === "foreign") {
/* Fix up mixed-case attribute names */
key = (_b = attributeNames.get(key)) !== null && _b !== void 0 ? _b : key;
}
if (!opts.emptyAttrs && !opts.xmlMode && value === "") {
return key;
}
return `${key}="${encode(value)}"`;
})
.join(" ");
}
/**
* Self-enclosing tags
*/
const singleTag = new Set([
"area",
"base",
"basefont",
"br",
"col",
"command",
"embed",
"frame",
"hr",
"img",
"input",
"isindex",
"keygen",
"link",
"meta",
"param",
"source",
"track",
"wbr",
]);
/**
* Renders a DOM node or an array of DOM nodes to a string.
*
* Can be thought of as the equivalent of the `outerHTML` of the passed node(s).
*
* @param node Node to be rendered.
* @param options Changes serialization behavior
*/
function render(node, options = {}) {
const nodes = "length" in node ? node : [node];
let output = "";
for (let i = 0; i < nodes.length; i++) {
output += renderNode(nodes[i], options);
}
return output;
}
function renderNode(node, options) {
switch (node.type) {
case Root:
return render(node.children, options);
// @ts-expect-error We don't use `Doctype` yet
case Doctype:
case Directive:
return renderDirective(node);
case Comment:
return renderComment(node);
case CDATA:
return renderCdata(node);
case Script:
case Style:
case Tag:
return renderTag(node, options);
case Text:
return renderText(node, options);
}
}
const foreignModeIntegrationPoints = new Set([
"mi",
"mo",
"mn",
"ms",
"mtext",
"annotation-xml",
"foreignObject",
"desc",
"title",
]);
const foreignElements = new Set(["svg", "math"]);
function renderTag(elem, opts) {
var _a;
// Handle SVG / MathML in HTML
if (opts.xmlMode === "foreign") {
/* Fix up mixed-case element names */
elem.name = (_a = elementNames.get(elem.name)) !== null && _a !== void 0 ? _a : elem.name;
/* Exit foreign mode at integration points */
if (elem.parent &&
foreignModeIntegrationPoints.has(elem.parent.name)) {
opts = { ...opts, xmlMode: false };
}
}
if (!opts.xmlMode && foreignElements.has(elem.name)) {
opts = { ...opts, xmlMode: "foreign" };
}
let tag = `<${elem.name}`;
const attribs = formatAttributes(elem.attribs, opts);
if (attribs) {
tag += ` ${attribs}`;
}
if (elem.children.length === 0 &&
(opts.xmlMode
? // In XML mode or foreign mode, and user hasn't explicitly turned off self-closing tags
opts.selfClosingTags !== false
: // User explicitly asked for self-closing tags, even in HTML mode
opts.selfClosingTags && singleTag.has(elem.name))) {
if (!opts.xmlMode)
tag += " ";
tag += "/>";
}
else {
tag += ">";
if (elem.children.length > 0) {
tag += render(elem.children, opts);
}
if (opts.xmlMode || !singleTag.has(elem.name)) {
tag += `</${elem.name}>`;
}
}
return tag;
}
function renderDirective(elem) {
return `<${elem.data}>`;
}
function renderText(elem, opts) {
var _a;
let data = elem.data || "";
// If entities weren't decoded, no need to encode them back
if (((_a = opts.encodeEntities) !== null && _a !== void 0 ? _a : opts.decodeEntities) !== false &&
!(!opts.xmlMode &&
elem.parent &&
unencodedElements.has(elem.parent.name))) {
data =
opts.xmlMode || opts.encodeEntities !== "utf8"
? encodeXML(data)
: escapeText(data);
}
return data;
}
function renderCdata(elem) {
return `<![CDATA[${elem.children[0].data}]]>`;
}
function renderComment(elem) {
return `<!--${elem.data}-->`;
}
/**
* @category Stringify
* @deprecated Use the `dom-serializer` module directly.
* @param node Node to get the outer HTML of.
* @param options Options for serialization.
* @returns `node`'s outer HTML.
*/
function getOuterHTML(node, options) {
return render(node, options);
}
/**
* @category Stringify
* @deprecated Use the `dom-serializer` module directly.
* @param node Node to get the inner HTML of.
* @param options Options for serialization.
* @returns `node`'s inner HTML.
*/
function getInnerHTML(node, options) {
return hasChildren(node)
? node.children.map((node) => getOuterHTML(node, options)).join("")
: "";
}
/**
* Get a node's inner text. Same as `textContent`, but inserts newlines for `<br>` tags.
*
* @category Stringify
* @deprecated Use `textContent` instead.
* @param node Node to get the inner text of.
* @returns `node`'s inner text.
*/
function getText(node) {
if (Array.isArray(node))
return node.map(getText).join("");
if (isTag$1(node))
return node.name === "br" ? "\n" : getText(node.children);
if (isCDATA(node))
return getText(node.children);
if (isText(node))
return node.data;
return "";
}
/**
* Get a node's text content.
*
* @category Stringify
* @param node Node to get the text content of.
* @returns `node`'s text content.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent}
*/
function textContent(node) {
if (Array.isArray(node))
return node.map(textContent).join("");
if (hasChildren(node) && !isComment(node)) {
return textContent(node.children);
}
if (isText(node))
return node.data;
return "";
}
/**
* Get a node's inner text.
*
* @category Stringify
* @param node Node to get the inner text of.
* @returns `node`'s inner text.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Node/innerText}
*/
function innerText(node) {
if (Array.isArray(node))
return node.map(innerText).join("");
if (hasChildren(node) && (node.type === ElementType.Tag || isCDATA(node))) {
return innerText(node.children);
}
if (isText(node))
return node.data;
return "";
}
/**
* Get a node's children.
*
* @category Traversal
* @param elem Node to get the children of.
* @returns `elem`'s children, or an empty array.
*/
function getChildren(elem) {
return hasChildren(elem) ? elem.children : [];
}
/**
* Get a node's parent.
*
* @category Traversal
* @param elem Node to get the parent of.
* @returns `elem`'s parent node.
*/
function getParent(elem) {
return elem.parent || null;
}
/**
* Gets an elements siblings, including the element itself.
*
* Attempts to get the children through the element's parent first. If we don't
* have a parent (the element is a root node), we walk the element's `prev` &
* `next` to get all remaining nodes.
*
* @category Traversal
* @param elem Element to get the siblings of.
* @returns `elem`'s siblings.
*/
function getSiblings(elem) {
const parent = getParent(elem);
if (parent != null)
return getChildren(parent);
const siblings = [elem];
let { prev, next } = elem;
while (prev != null) {
siblings.unshift(prev);
({ prev } = prev);
}
while (next != null) {
siblings.push(next);
({ next } = next);
}
return siblings;
}
/**
* Gets an attribute from an element.
*
* @category Traversal
* @param elem Element to check.
* @param name Attribute name to retrieve.
* @returns The element's attribute value, or `undefined`.
*/
function getAttributeValue(elem, name) {
var _a;
return (_a = elem.attribs) === null || _a === void 0 ? void 0 : _a[name];
}
/**
* Checks whether an element has an attribute.
*
* @category Traversal
* @param elem Element to check.
* @param name Attribute name to look for.
* @returns Returns whether `elem` has the attribute `name`.
*/
function hasAttrib(elem, name) {
return (elem.attribs != null &&
Object.prototype.hasOwnProperty.call(elem.attribs, name) &&
elem.attribs[name] != null);
}
/**
* Get the tag name of an element.
*
* @category Traversal
* @param elem The element to get the name for.
* @returns The tag name of `elem`.
*/
function getName(elem) {
return elem.name;
}
/**
* Returns the next element sibling of a node.
*
* @category Traversal
* @param elem The element to get the next sibling of.
* @returns `elem`'s next sibling that is a tag.
*/
function nextElementSibling(elem) {
let { next } = elem;
while (next !== null && !isTag$1(next))
({ next } = next);
return next;
}
/**
* Returns the previous element sibling of a node.
*
* @category Traversal
* @param elem The element to get the previous sibling of.
* @returns `elem`'s previous sibling that is a tag.
*/
function prevElementSibling(elem) {
let { prev } = elem;
while (prev !== null && !isTag$1(prev))
({ prev } = prev);
return prev;
}
/**
* Remove an element from the dom
*
* @category Manipulation
* @param elem The element to be removed
*/
function removeElement(elem) {
if (elem.prev)
elem.prev.next = elem.next;
if (elem.next)
elem.next.prev = elem.prev;
if (elem.parent) {
const childs = elem.parent.children;
childs.splice(childs.lastIndexOf(elem), 1);
}
}
/**
* Replace an element in the dom
*
* @category Manipulation
* @param elem The element to be replaced
* @param replacement The element to be added
*/
function replaceElement(elem, replacement) {
const prev = (replacement.prev = elem.prev);
if (prev) {
prev.next = replacement;
}
const next = (replacement.next = elem.next);
if (next) {
next.prev = replacement;
}
const parent = (replacement.parent = elem.parent);
if (parent) {
const childs = parent.children;
childs[childs.lastIndexOf(elem)] = replacement;
elem.parent = null;
}
}
/**
* Append a child to an element.
*
* @category Manipulation
* @param elem The element to append to.
* @param child The element to be added as a child.
*/
function appendChild(elem, child) {
removeElement(child);
child.next = null;
child.parent = elem;
if (elem.children.push(child) > 1) {
const sibling = elem.children[elem.children.length - 2];
sibling.next = child;
child.prev = sibling;
}
else {
child.prev = null;
}
}
/**
* Append an element after another.
*
* @category Manipulation
* @param elem The element to append after.
* @param next The element be added.
*/
function append(elem, next) {
removeElement(next);
const { parent } = elem;
const currNext = elem.next;
next.next = currNext;
next.prev = elem;
elem.next = next;
next.parent = parent;
if (currNext) {
currNext.prev = next;
if (parent) {
const childs = parent.children;
childs.splice(childs.lastIndexOf(currNext), 0, next);
}
}
else if (parent) {
parent.children.push(next);
}
}
/**
* Prepend a child to an element.
*
* @category Manipulation
* @param elem The element to prepend before.
* @param child The element to be added as a child.
*/
function prependChild(elem, child) {
removeElement(child);
child.parent = elem;
child.prev = null;
if (elem.children.unshift(child) !== 1) {
const sibling = elem.children[1];
sibling.prev = child;
child.next = sibling;
}
else {
child.next = null;
}
}
/**
* Prepend an element before another.
*
* @category Manipulation
* @param elem The element to prepend before.
* @param prev The element be added.
*/
function prepend(elem, prev) {
removeElement(prev);
const { parent } = elem;
if (parent) {
const childs = parent.children;
childs.splice(childs.indexOf(elem), 0, prev);
}
if (elem.prev) {
elem.prev.next = prev;
}
prev.parent = parent;
prev.prev = elem.prev;
prev.next = elem;
elem.prev = prev;
}
/**
* Search a node and its children for nodes passing a test function.
*
* @category Querying
* @param test Function to test nodes on.
* @param node Node to search. Will be included in the result set if it matches.
* @param recurse Also consider child nodes.
* @param limit Maximum number of nodes to return.
* @returns All nodes passing `test`.
*/
function filter$4(test, node, recurse = true, limit = Infinity) {
if (!Array.isArray(node))
node = [node];
return find$5(test, node, recurse, limit);
}
/**
* Search an array of node and its children for nodes passing a test function.
*
* @category Querying
* @param test Function to test nodes on.
* @param nodes Array of nodes to search.
* @param recurse Also consider child nodes.
* @param limit Maximum number of nodes to return.
* @returns All nodes passing `test`.
*/
function find$5(test, nodes, recurse, limit) {
const result = [];
for (const elem of nodes) {
if (test(elem)) {
result.push(elem);
if (--limit <= 0)
break;
}
if (recurse && hasChildren(elem) && elem.children.length > 0) {
const children = find$5(test, elem.children, recurse, limit);
result.push(...children);
limit -= children.length;
if (limit <= 0)
break;
}
}
return result;
}
/**
* Finds the first element inside of an array that matches a test function.
*
* @category Querying
* @param test Function to test nodes on.
* @param nodes Array of nodes to search.
* @returns The first node in the array that passes `test`.
* @deprecated Use `Array.prototype.find` directly.
*/
function findOneChild(test, nodes) {
return nodes.find(test);
}
/**
* Finds one element in a tree that passes a test.
*
* @category Querying
* @param test Function to test nodes on.
* @param nodes Array of nodes to search.
* @param recurse Also consider child nodes.
* @returns The first child node that passes `test`.
*/
function findOne(test, nodes, recurse = true) {
let elem = null;
for (let i = 0; i < nodes.length && !elem; i++) {
const checked = nodes[i];
if (!isTag$1(checked)) {
continue;
}
else if (test(checked)) {
elem = checked;
}
else if (recurse && checked.children.length > 0) {
elem = findOne(test, checked.children, true);
}
}
return elem;
}
/**
* @category Querying
* @param test Function to test nodes on.
* @param nodes Array of nodes to search.
* @returns Whether a tree of nodes contains at least one node passing the test.
*/
function existsOne(test, nodes) {
return nodes.some((checked) => isTag$1(checked) &&
(test(checked) ||
(checked.children.length > 0 &&
existsOne(test, checked.children))));
}
/**
* Search and array of nodes and its children for elements passing a test function.
*
* Same as `find`, but limited to elements and with less options, leading to reduced complexity.
*
* @category Querying
* @param test Function to test nodes on.
* @param nodes Array of nodes to search.
* @returns All nodes passing `test`.
*/
function findAll(test, nodes) {
var _a;
const result = [];
const stack = nodes.filter(isTag$1);
let elem;
while ((elem = stack.shift())) {
const children = (_a = elem.children) === null || _a === void 0 ? void 0 : _a.filter(isTag$1);
if (children && children.length > 0) {
stack.unshift(...children);
}
if (test(elem))
result.push(elem);
}
return result;
}
const Checks = {
tag_name(name) {
if (typeof name === "function") {
return (elem) => isTag$1(elem) && name(elem.name);
}
else if (name === "*") {
return isTag$1;
}
return (elem) => isTag$1(elem) && elem.name === name;
},
tag_type(type) {
if (typeof type === "function") {
return (elem) => type(elem.type);
}
return (elem) => elem.type === type;
},
tag_contains(data) {
if (typeof data === "function") {
return (elem) => isText(elem) && data(elem.data);
}
return (elem) => isText(elem) && elem.data === data;
},
};
/**
* @param attrib Attribute to check.
* @param value Attribute value to look for.
* @returns A function to check whether the a node has an attribute with a
* particular value.
*/
function getAttribCheck(attrib, value) {
if (typeof value === "function") {
return (elem) => isTag$1(elem) && value(elem.attribs[attrib]);
}
return (elem) => isTag$1(elem) && elem.attribs[attrib] === value;
}
/**
* @param a First function to combine.
* @param b Second function to combine.
* @returns A function taking a node and returning `true` if either of the input
* functions returns `true` for the node.
*/
function combineFuncs(a, b) {
return (elem) => a(elem) || b(elem);
}
/**
* @param options An object describing nodes to look for.
* @returns A function executing all checks in `options` and returning `true` if
* any of them match a node.
*/
function compileTest(options) {
const funcs = Object.keys(options).map((key) => {
const value = options[key];
return Object.prototype.hasOwnProperty.call(Checks, key)
? Checks[key](value)
: getAttribCheck(key, value);
});
return funcs.length === 0 ? null : funcs.reduce(combineFuncs);
}
/**
* @category Legacy Query Functions
* @param options An object describing nodes to look for.
* @param node The element to test.
* @returns Whether the element matches the description in `options`.
*/
function testElement(options, node) {
const test = compileTest(options);
return test ? test(node) : true;
}
/**
* @category Legacy Query Functions
* @param options An object describing nodes to look for.
* @param nodes Nodes to search through.
* @param recurse Also consider child nodes.
* @param limit Maximum number of nodes to return.
* @returns All nodes that match `options`.
*/
function getElements(options, nodes, recurse, limit = Infinity) {
const test = compileTest(options);
return test ? filter$4(test, nodes, recurse, limit) : [];
}
/**
* @category Legacy Query Functions
* @param id The unique ID attribute value to look for.
* @param nodes Nodes to search through.
* @param recurse Also consider child nodes.
* @returns The node with the supplied ID.
*/
function getElementById(id, nodes, recurse = true) {
if (!Array.isArray(nodes))
nodes = [nodes];
return findOne(getAttribCheck("id", id), nodes, recurse);
}
/**
* @category Legacy Query Functions
* @param tagName Tag name to search for.
* @param nodes Nodes to search through.
* @param recurse Also consider child nodes.
* @param limit Maximum number of nodes to return.
* @returns All nodes with the supplied `tagName`.
*/
function getElementsByTagName(tagName, nodes, recurse = true, limit = Infinity) {
return filter$4(Checks["tag_name"](tagName), nodes, recurse, limit);
}
/**
* @category Legacy Query Functions
* @param type Element type to look for.
* @param nodes Nodes to search through.
* @param recurse Also consider child nodes.
* @param limit Maximum number of nodes to return.
* @returns All nodes with the supplied `type`.
*/
function getElementsByTagType(type, nodes, recurse = true, limit = Infinity) {
return filter$4(Checks["tag_type"](type), nodes, recurse, limit);
}
/**
* Given an array of nodes, remove any member that is contained by another.
*
* @category Helpers
* @param nodes Nodes to filter.
* @returns Remaining nodes that aren't subtrees of each other.
*/
function removeSubsets(nodes) {
let idx = nodes.length;
/*
* Check if each node (or one of its ancestors) is already contained in the
* array.
*/
while (--idx >= 0) {
const node = nodes[idx];
/*
* Remove the node if it is not unique.
* We are going through the array from the end, so we only
* have to check nodes that preceed the node under consideration in the array.
*/
if (idx > 0 && nodes.lastIndexOf(node, idx - 1) >= 0) {
nodes.splice(idx, 1);
continue;
}
for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) {
if (nodes.includes(ancestor)) {
nodes.splice(idx, 1);
break;
}
}
}
return nodes;
}
/**
* @category Helpers
* @see {@link http://dom.spec.whatwg.org/#dom-node-comparedocumentposition}
*/
var DocumentPosition;
(function (DocumentPosition) {
DocumentPosition[DocumentPosition["DISCONNECTED"] = 1] = "DISCONNECTED";
DocumentPosition[DocumentPosition["PRECEDING"] = 2] = "PRECEDING";
DocumentPosition[DocumentPosition["FOLLOWING"] = 4] = "FOLLOWING";
DocumentPosition[DocumentPosition["CONTAINS"] = 8] = "CONTAINS";
DocumentPosition[DocumentPosition["CONTAINED_BY"] = 16] = "CONTAINED_BY";
})(DocumentPosition || (DocumentPosition = {}));
/**
* Compare the position of one node against another node in any other document.
* The return value is a bitmask with the values from {@link DocumentPosition}.
*
* Document order:
* > There is an ordering, document order, defined on all the nodes in the
* > document corresponding to the order in which the first character of the
* > XML representation of each node occurs in the XML representation of the
* > document after expansion of general entities. Thus, the document element
* > node will be the first node. Element nodes occur before their children.
* > Thus, document order orders element nodes in order of the occurrence of
* > their start-tag in the XML (after expansion of entities). The attribute
* > nodes of an element occur after the element and before its children. The
* > relative order of attribute nodes is implementation-dependent.
*
* Source:
* http://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-document-order
*
* @category Helpers
* @param nodeA The first node to use in the comparison
* @param nodeB The second node to use in the comparison
* @returns A bitmask describing the input nodes' relative position.
*
* See http://dom.spec.whatwg.org/#dom-node-comparedocumentposition for
* a description of these values.
*/
function compareDocumentPosition(nodeA, nodeB) {
const aParents = [];
const bParents = [];
if (nodeA === nodeB) {
return 0;
}
let current = hasChildren(nodeA) ? nodeA : nodeA.parent;
while (current) {
aParents.unshift(current);
current = current.parent;
}
current = hasChildren(nodeB) ? nodeB : nodeB.parent;
while (current) {
bParents.unshift(current);
current = current.parent;
}
const maxIdx = Math.min(aParents.length, bParents.length);
let idx = 0;
while (idx < maxIdx && aParents[idx] === bParents[idx]) {
idx++;
}
if (idx === 0) {
return DocumentPosition.DISCONNECTED;
}
const sharedParent = aParents[idx - 1];
const siblings = sharedParent.children;
const aSibling = aParents[idx];
const bSibling = bParents[idx];
if (siblings.indexOf(aSibling) > siblings.indexOf(bSibling)) {
if (sharedParent === nodeB) {
return DocumentPosition.FOLLOWING | DocumentPosition.CONTAINED_BY;
}
return DocumentPosition.FOLLOWING;
}
if (sharedParent === nodeA) {
return DocumentPosition.PRECEDING | DocumentPosition.CONTAINS;
}
return DocumentPosition.PRECEDING;
}
/**
* Sort an array of nodes based on their relative position in the document and
* remove any duplicate nodes. If the array contains nodes that do not belong to
* the same document, sort order is unspecified.
*
* @category Helpers
* @param nodes Array of DOM nodes.
* @returns Collection of unique nodes, sorted in document order.
*/
function uniqueSort(nodes) {
nodes = nodes.filter((node, i, arr) => !arr.includes(node, i + 1));
nodes.sort((a, b) => {
const relative = compareDocumentPosition(a, b);
if (relative & DocumentPosition.PRECEDING) {
return -1;
}
else if (relative & DocumentPosition.FOLLOWING) {
return 1;
}
return 0;
});
return nodes;
}
/**
* Get the feed object from the root of a DOM tree.
*
* @category Feeds
* @param doc - The DOM to to extract the feed from.
* @returns The feed.
*/
function getFeed(doc) {
const feedRoot = getOneElement(isValidFeed, doc);
return !feedRoot
? null
: feedRoot.name === "feed"
? getAtomFeed(feedRoot)
: getRssFeed(feedRoot);
}
/**
* Parse an Atom feed.
*
* @param feedRoot The root of the feed.
* @returns The parsed feed.
*/
function getAtomFeed(feedRoot) {
var _a;
const childs = feedRoot.children;
const feed = {
type: "atom",
items: getElementsByTagName("entry", childs).map((item) => {
var _a;
const { children } = item;
const entry = { media: getMediaElements(children) };
addConditionally(entry, "id", "id", children);
addConditionally(entry, "title", "title", children);
const href = (_a = getOneElement("link", children)) === null || _a === void 0 ? void 0 : _a.attribs["href"];
if (href) {
entry.link = href;
}
const description = fetch$1("summary", children) || fetch$1("content", children);
if (description) {
entry.description = description;
}
const pubDate = fetch$1("updated", children);
if (pubDate) {
entry.pubDate = new Date(pubDate);
}
return entry;
}),
};
addConditionally(feed, "id", "id", childs);
addConditionally(feed, "title", "title", childs);
const href = (_a = getOneElement("link", childs)) === null || _a === void 0 ? void 0 : _a.attribs["href"];
if (href) {
feed.link = href;
}
addConditionally(feed, "description", "subtitle", childs);
const updated = fetch$1("updated", childs);
if (updated) {
feed.updated = new Date(updated);
}
addConditionally(feed, "author", "email", childs, true);
return feed;
}
/**
* Parse a RSS feed.
*
* @param feedRoot The root of the feed.
* @returns The parsed feed.
*/
function getRssFeed(feedRoot) {
var _a, _b;
const childs = (_b = (_a = getOneElement("channel", feedRoot.children)) === null || _a === void 0 ? void 0 : _a.children) !== null && _b !== void 0 ? _b : [];
const feed = {
type: feedRoot.name.substr(0, 3),
id: "",
items: getElementsByTagName("item", feedRoot.children).map((item) => {
const { children } = item;
const entry = { media: getMediaElements(children) };
addConditionally(entry, "id", "guid", children);
addConditionally(entry, "title", "title", children);
addConditionally(entry, "link", "link", children);
addConditionally(entry, "description", "description", children);
const pubDate = fetch$1("pubDate", children);
if (pubDate)
entry.pubDate = new Date(pubDate);
return entry;
}),
};
addConditionally(feed, "title", "title", childs);
addConditionally(feed, "link", "link", childs);
addConditionally(feed, "description", "description", childs);
const updated = fetch$1("lastBuildDate", childs);
if (updated) {
feed.updated = new Date(updated);
}
addConditionally(feed, "author", "managingEditor", childs, true);
return feed;
}
const MEDIA_KEYS_STRING = ["url", "type", "lang"];
const MEDIA_KEYS_INT = [
"fileSize",
"bitrate",
"framerate",
"samplingrate",
"channels",
"duration",
"height",
"width",
];
/**
* Get all media elements of a feed item.
*
* @param where Nodes to search in.
* @returns Media elements.
*/
function getMediaElements(where) {
return getElementsByTagName("media:content", where).map((elem) => {
const { attribs } = elem;
const media = {
medium: attribs["medium"],
isDefault: !!attribs["isDefault"],
};
for (const attrib of MEDIA_KEYS_STRING) {
if (attribs[attrib]) {
media[attrib] = attribs[attrib];
}
}
for (const attrib of MEDIA_KEYS_INT) {
if (attribs[attrib]) {
media[attrib] = parseInt(attribs[attrib], 10);
}
}
if (attribs["expression"]) {
media.expression = attribs["expression"];
}
return media;
});
}
/**
* Get one element by tag name.
*
* @param tagName Tag name to look for
* @param node Node to search in
* @returns The element or null
*/
function getOneElement(tagName, node) {
return getElementsByTagName(tagName, node, true, 1)[0];
}
/**
* Get the text content of an element with a certain tag name.
*
* @param tagName Tag name to look for.
* @param where Node to search in.
* @param recurse Whether to recurse into child nodes.
* @returns The text content of the element.
*/
function fetch$1(tagName, where, recurse = false) {
return textContent(getElementsByTagName(tagName, where, recurse, 1)).trim();
}
/**
* Adds a property to an object if it has a value.
*
* @param obj Object to be extended
* @param prop Property name
* @param tagName Tag name that contains the conditionally added property
* @param where Element to search for the property
* @param recurse Whether to recurse into child nodes.
*/
function addConditionally(obj, prop, tagName, where, recurse = false) {
const val = fetch$1(tagName, where, recurse);
if (val)
obj[prop] = val;
}
/**
* Checks if an element is a feed root node.
*
* @param value The name of the element to check.
* @returns Whether an element is a feed root node.
*/
function isValidFeed(value) {
return value === "rss" || value === "feed" || value === "rdf:RDF";
}
var DomUtils = /*#__PURE__*/Object.freeze({
__proto__: null,
isTag: isTag$1,
isCDATA: isCDATA,
isText: isText,
isComment: isComment,
isDocument: isDocument,
hasChildren: hasChildren,
getOuterHTML: getOuterHTML,
getInnerHTML: getInnerHTML,
getText: getText,
textContent: textContent,
innerText: innerText,
getChildren: getChildren,
getParent: getParent,
getSiblings: getSiblings,
getAttributeValue: getAttributeValue,
hasAttrib: hasAttrib,
getName: getName,
nextElementSibling: nextElementSibling,
prevElementSibling: prevElementSibling,
removeElement: removeElement,
replaceElement: replaceElement,
appendChild: appendChild,
append: append,
prependChild: prependChild,
prepend: prepend,
filter: filter$4,
find: find$5,
findOneChild: findOneChild,
findOne: findOne,
existsOne: existsOne,
findAll: findAll,
testElement: testElement,
getElements: getElements,
getElementById: getElementById,
getElementsByTagName: getElementsByTagName,
getElementsByTagType: getElementsByTagType,
removeSubsets: removeSubsets,
get DocumentPosition () { return DocumentPosition; },
compareDocumentPosition: compareDocumentPosition,
uniqueSort: uniqueSort,
getFeed: getFeed
});
/**
* Helper function to render a DOM.
*
* @param that - Cheerio instance to render.
* @param dom - The DOM to render. Defaults to `that`'s root.
* @param options - Options for rendering.
* @returns The rendered document.
*/
function render$1(that, dom, options) {
if (!that)
return '';
return that(dom !== null && dom !== void 0 ? dom : that._root.children, null, undefined, options).toString();
}
/**
* Checks if a passed object is an options object.
*
* @param dom - Object to check if it is an options object.
* @returns Whether the object is an options object.
*/
function isOptions(dom, options) {
return (!options &&
typeof dom === 'object' &&
dom != null &&
!('length' in dom) &&
!('type' in dom));
}
function html$1(dom, options) {
/*
* Be flexible about parameters, sometimes we call html(),
* with options as only parameter
* check dom argument for dom element specific properties
* assume there is no 'length' or 'type' properties in the options object
*/
const toRender = isOptions(dom) ? ((options = dom), undefined) : dom;
/*
* Sometimes `$.html()` is used without preloading html,
* so fallback non-existing options to the default ones.
*/
const opts = {
...defaultOpts,
...this === null || this === void 0 ? void 0 : this._options,
...flatten(options !== null && options !== void 0 ? options : {}),
};
return render$1(this, toRender, opts);
}
/**
* Render the document as XML.
*
* @param dom - Element to render.
* @returns THe rendered document.
*/
function xml$1(dom) {
const options = { ...this._options, xmlMode: true };
return render$1(this, dom, options);
}
/**
* Render the document as text.
*
* This returns the `textContent` of the passed elements. The result will
* include the contents of `script` and `stype` elements. To avoid this, use
* `.prop('innerText')` instead.
*
* @param elements - Elements to render.
* @returns The rendered document.
*/
function text(elements) {
const elems = elements ? elements : this ? this.root() : [];
let ret = '';
for (let i = 0; i < elems.length; i++) {
ret += textContent(elems[i]);
}
return ret;
}
function parseHTML(data, context, keepScripts = typeof context === 'boolean' ? context : false) {
if (!data || typeof data !== 'string') {
return null;
}
if (typeof context === 'boolean') {
keepScripts = context;
}
const parsed = this.load(data, defaultOpts, false);
if (!keepScripts) {
parsed('script').remove();
}
/*
* The `children` array is used by Cheerio internally to group elements that
* share the same parents. When nodes created through `parseHTML` are
* inserted into previously-existing DOM structures, they will be removed
* from the `children` array. The results of `parseHTML` should remain
* constant across these operations, so a shallow copy should be returned.
*/
return parsed.root()[0].children.slice();
}
/**
* Sometimes you need to work with the top-level root element. To query it, you
* can use `$.root()`.
*
* @example
*
* ```js
* $.root().append('<ul id="vegetables"></ul>').html();
* //=> <ul id="fruits">...</ul><ul id="vegetables"></ul>
* ```
*
* @returns Cheerio instance wrapping the root node.
* @alias Cheerio.root
*/
function root$2() {
return this(this._root);
}
/**
* Checks to see if the `contained` DOM element is a descendant of the
* `container` DOM element.
*
* @param container - Potential parent node.
* @param contained - Potential child node.
* @returns Indicates if the nodes contain one another.
* @alias Cheerio.contains
* @see {@link https://api.jquery.com/jQuery.contains/}
*/
function contains(container, contained) {
// According to the jQuery API, an element does not "contain" itself
if (contained === container) {
return false;
}
/*
* Step up the descendants, stopping when the root element is reached
* (signaled by `.parent` returning a reference to the same object)
*/
let next = contained;
while (next && next !== next.parent) {
next = next.parent;
if (next === container) {
return true;
}
}
return false;
}
/**
* $.merge().
*
* @param arr1 - First array.
* @param arr2 - Second array.
* @returns `arr1`, with elements of `arr2` inserted.
* @alias Cheerio.merge
* @see {@link https://api.jquery.com/jQuery.merge/}
*/
function merge$2(arr1, arr2) {
if (!isArrayLike$1(arr1) || !isArrayLike$1(arr2)) {
return;
}
let newLength = arr1.length;
const len = +arr2.length;
for (let i = 0; i < len; i++) {
arr1[newLength++] = arr2[i];
}
arr1.length = newLength;
return arr1;
}
/**
* Checks if an object is array-like.
*
* @param item - Item to check.
* @returns Indicates if the item is array-like.
*/
function isArrayLike$1(item) {
if (Array.isArray(item)) {
return true;
}
if (typeof item !== 'object' ||
!Object.prototype.hasOwnProperty.call(item, 'length') ||
typeof item.length !== 'number' ||
item.length < 0) {
return false;
}
for (let i = 0; i < item.length; i++) {
if (!(i in item)) {
return false;
}
}
return true;
}
var staticMethods = /*#__PURE__*/Object.freeze({
__proto__: null,
html: html$1,
xml: xml$1,
text: text,
parseHTML: parseHTML,
root: root$2,
contains: contains,
merge: merge$2
});
/**
* Checks if an object is a Cheerio instance.
*
* @category Utils
* @param maybeCheerio - The object to check.
* @returns Whether the object is a Cheerio instance.
*/
function isCheerio(maybeCheerio) {
return maybeCheerio.cheerio != null;
}
/**
* Convert a string to camel case notation.
*
* @private
* @category Utils
* @param str - The string to be converted.
* @returns String in camel case notation.
*/
function camelCase(str) {
return str.replace(/[_.-](\w|$)/g, (_, x) => x.toUpperCase());
}
/**
* Convert a string from camel case to "CSS case", where word boundaries are
* described by hyphens ("-") and all characters are lower-case.
*
* @private
* @category Utils
* @param str - The string to be converted.
* @returns String in "CSS case".
*/
function cssCase(str) {
return str.replace(/[A-Z]/g, '-$&').toLowerCase();
}
/**
* Iterate over each DOM element without creating intermediary Cheerio instances.
*
* This is indented for use internally to avoid otherwise unnecessary memory
* pressure introduced by _make.
*
* @category Utils
* @param array - The array to iterate over.
* @param fn - Function to call.
* @returns The original instance.
*/
function domEach(array, fn) {
const len = array.length;
for (let i = 0; i < len; i++)
fn(array[i], i);
return array;
}
/**
* Create a deep copy of the given DOM structure. Sets the parents of the copies
* of the passed nodes to `null`.
*
* @private
* @category Utils
* @param dom - The domhandler-compliant DOM structure.
* @returns - The cloned DOM.
*/
function cloneDom(dom) {
const clone = 'length' in dom
? Array.prototype.map.call(dom, (el) => cloneNode(el, true))
: [cloneNode(dom, true)];
// Add a root node around the cloned nodes
const root = new Document(clone);
clone.forEach((node) => {
node.parent = root;
});
return clone;
}
var CharacterCodes;
(function (CharacterCodes) {
CharacterCodes[CharacterCodes["LowerA"] = 97] = "LowerA";
CharacterCodes[CharacterCodes["LowerZ"] = 122] = "LowerZ";
CharacterCodes[CharacterCodes["UpperA"] = 65] = "UpperA";
CharacterCodes[CharacterCodes["UpperZ"] = 90] = "UpperZ";
CharacterCodes[CharacterCodes["Exclamation"] = 33] = "Exclamation";
})(CharacterCodes || (CharacterCodes = {}));
/**
* Check if string is HTML.
*
* Tests for a `<` within a string, immediate followed by a letter and
* eventually followed by a `>`.
*
* @private
* @category Utils
* @param str - The string to check.
* @returns Indicates if `str` is HTML.
*/
function isHtml(str) {
const tagStart = str.indexOf('<');
if (tagStart < 0 || tagStart > str.length - 3)
return false;
const tagChar = str.charCodeAt(tagStart + 1);
return (((tagChar >= CharacterCodes.LowerA && tagChar <= CharacterCodes.LowerZ) ||
(tagChar >= CharacterCodes.UpperA && tagChar <= CharacterCodes.UpperZ) ||
tagChar === CharacterCodes.Exclamation) &&
str.includes('>', tagStart + 2));
}
/**
* Methods for getting and modifying attributes.
*
* @module cheerio/attributes
*/
const hasOwn = Object.prototype.hasOwnProperty;
const rspace = /\s+/;
const dataAttrPrefix = 'data-';
/*
* Lookup table for coercing string data-* attributes to their corresponding
* JavaScript primitives
*/
const primitives = {
null: null,
true: true,
false: false,
};
// Attributes that are booleans
const rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i;
// Matches strings that look like JSON objects or arrays
const rbrace = /^{[^]*}$|^\[[^]*]$/;
function getAttr(elem, name, xmlMode) {
var _a;
if (!elem || !isTag$1(elem))
return undefined;
(_a = elem.attribs) !== null && _a !== void 0 ? _a : (elem.attribs = {});
// Return the entire attribs object if no attribute specified
if (!name) {
return elem.attribs;
}
if (hasOwn.call(elem.attribs, name)) {
// Get the (decoded) attribute
return !xmlMode && rboolean.test(name) ? name : elem.attribs[name];
}
// Mimic the DOM and return text content as value for `option's`
if (elem.name === 'option' && name === 'value') {
return text(elem.children);
}
// Mimic DOM with default value for radios/checkboxes
if (elem.name === 'input' &&
(elem.attribs['type'] === 'radio' || elem.attribs['type'] === 'checkbox') &&
name === 'value') {
return 'on';
}
return undefined;
}
/**
* Sets the value of an attribute. The attribute will be deleted if the value is `null`.
*
* @private
* @param el - The element to set the attribute on.
* @param name - The attribute's name.
* @param value - The attribute's value.
*/
function setAttr(el, name, value) {
if (value === null) {
removeAttribute(el, name);
}
else {
el.attribs[name] = `${value}`;
}
}
function attr(name, value) {
// Set the value (with attr map support)
if (typeof name === 'object' || value !== undefined) {
if (typeof value === 'function') {
if (typeof name !== 'string') {
{
throw new Error('Bad combination of arguments.');
}
}
return domEach(this, (el, i) => {
if (isTag$1(el))
setAttr(el, name, value.call(el, i, el.attribs[name]));
});
}
return domEach(this, (el) => {
if (!isTag$1(el))
return;
if (typeof name === 'object') {
Object.keys(name).forEach((objName) => {
const objValue = name[objName];
setAttr(el, objName, objValue);
});
}
else {
setAttr(el, name, value);
}
});
}
return arguments.length > 1
? this
: getAttr(this[0], name, this.options.xmlMode);
}
/**
* Gets a node's prop.
*
* @private
* @category Attributes
* @param el - Element to get the prop of.
* @param name - Name of the prop.
* @returns The prop's value.
*/
function getProp(el, name, xmlMode) {
if (!el || !isTag$1(el))
return;
return name in el
? // @ts-expect-error TS doesn't like us accessing the value directly here.
el[name]
: !xmlMode && rboolean.test(name)
? getAttr(el, name, false) !== undefined
: getAttr(el, name, xmlMode);
}
/**
* Sets the value of a prop.
*
* @private
* @param el - The element to set the prop on.
* @param name - The prop's name.
* @param value - The prop's value.
*/
function setProp(el, name, value, xmlMode) {
if (name in el) {
// @ts-expect-error Overriding value
el[name] = value;
}
else {
setAttr(el, name, !xmlMode && rboolean.test(name) ? (value ? '' : null) : `${value}`);
}
}
function prop(name, value) {
var _a;
if (typeof name === 'string' && value === undefined) {
switch (name) {
case 'style': {
const property = this.css();
const keys = Object.keys(property);
keys.forEach((p, i) => {
property[i] = p;
});
property.length = keys.length;
return property;
}
case 'tagName':
case 'nodeName': {
const el = this[0];
return isTag$1(el) ? el.name.toUpperCase() : undefined;
}
case 'href':
case 'src': {
const el = this[0];
if (!isTag$1(el)) {
return undefined;
}
const prop = (_a = el.attribs) === null || _a === void 0 ? void 0 : _a[name];
/* eslint-disable node/no-unsupported-features/node-builtins */
if (typeof URL !== 'undefined' &&
((name === 'href' && (el.tagName === 'a' || el.name === 'link')) ||
(name === 'src' &&
(el.tagName === 'img' ||
el.tagName === 'iframe' ||
el.tagName === 'audio' ||
el.tagName === 'video' ||
el.tagName === 'source'))) &&
prop !== undefined &&
this.options.baseURI) {
return new URL(prop, this.options.baseURI).href;
}
/* eslint-enable node/no-unsupported-features/node-builtins */
return prop;
}
case 'innerText':
return innerText(this[0]);
case 'textContent':
return textContent(this[0]);
case 'outerHTML':
return this.clone().wrap('<container />').parent().html();
case 'innerHTML':
return this.html();
default:
return getProp(this[0], name, this.options.xmlMode);
}
}
if (typeof name === 'object' || value !== undefined) {
if (typeof value === 'function') {
if (typeof name === 'object') {
throw new Error('Bad combination of arguments.');
}
return domEach(this, (el, i) => {
if (isTag$1(el)) {
setProp(el, name, value.call(el, i, getProp(el, name, this.options.xmlMode)), this.options.xmlMode);
}
});
}
return domEach(this, (el) => {
if (!isTag$1(el))
return;
if (typeof name === 'object') {
Object.keys(name).forEach((key) => {
const val = name[key];
setProp(el, key, val, this.options.xmlMode);
});
}
else {
setProp(el, name, value, this.options.xmlMode);
}
});
}
return undefined;
}
/**
* Sets the value of a data attribute.
*
* @private
* @param el - The element to set the data attribute on.
* @param name - The data attribute's name.
* @param value - The data attribute's value.
*/
function setData(el, name, value) {
var _a;
const elem = el;
(_a = elem.data) !== null && _a !== void 0 ? _a : (elem.data = {});
if (typeof name === 'object')
Object.assign(elem.data, name);
else if (typeof name === 'string' && value !== undefined) {
elem.data[name] = value;
}
}
/**
* Read the specified attribute from the equivalent HTML5 `data-*` attribute,
* and (if present) cache the value in the node's internal data store. If no
* attribute name is specified, read _all_ HTML5 `data-*` attributes in this manner.
*
* @private
* @category Attributes
* @param el - Element to get the data attribute of.
* @param name - Name of the data attribute.
* @returns The data attribute's value, or a map with all of the data attributes.
*/
function readData(el, name) {
let domNames;
let jsNames;
let value;
if (name == null) {
domNames = Object.keys(el.attribs).filter((attrName) => attrName.startsWith(dataAttrPrefix));
jsNames = domNames.map((domName) => camelCase(domName.slice(dataAttrPrefix.length)));
}
else {
domNames = [dataAttrPrefix + cssCase(name)];
jsNames = [name];
}
for (let idx = 0; idx < domNames.length; ++idx) {
const domName = domNames[idx];
const jsName = jsNames[idx];
if (hasOwn.call(el.attribs, domName) &&
!hasOwn.call(el.data, jsName)) {
value = el.attribs[domName];
if (hasOwn.call(primitives, value)) {
value = primitives[value];
}
else if (value === String(Number(value))) {
value = Number(value);
}
else if (rbrace.test(value)) {
try {
value = JSON.parse(value);
}
catch (e) {
/* Ignore */
}
}
el.data[jsName] = value;
}
}
return name == null ? el.data : value;
}
function data$2(name, value) {
var _a;
const elem = this[0];
if (!elem || !isTag$1(elem))
return;
const dataEl = elem;
(_a = dataEl.data) !== null && _a !== void 0 ? _a : (dataEl.data = {});
// Return the entire data object if no data specified
if (!name) {
return readData(dataEl);
}
// Set the value (with attr map support)
if (typeof name === 'object' || value !== undefined) {
domEach(this, (el) => {
if (isTag$1(el)) {
if (typeof name === 'object')
setData(el, name);
else
setData(el, name, value);
}
});
return this;
}
if (hasOwn.call(dataEl.data, name)) {
return dataEl.data[name];
}
return readData(dataEl, name);
}
function val(value) {
const querying = arguments.length === 0;
const element = this[0];
if (!element || !isTag$1(element))
return querying ? undefined : this;
switch (element.name) {
case 'textarea':
return this.text(value);
case 'select': {
const option = this.find('option:selected');
if (!querying) {
if (this.attr('multiple') == null && typeof value === 'object') {
return this;
}
this.find('option').removeAttr('selected');
const values = typeof value !== 'object' ? [value] : value;
for (let i = 0; i < values.length; i++) {
this.find(`option[value="${values[i]}"]`).attr('selected', '');
}
return this;
}
return this.attr('multiple')
? option.toArray().map((el) => text(el.children))
: option.attr('value');
}
case 'input':
case 'option':
return querying
? this.attr('value')
: this.attr('value', value);
}
return undefined;
}
/**
* Remove an attribute.
*
* @private
* @param elem - Node to remove attribute from.
* @param name - Name of the attribute to remove.
*/
function removeAttribute(elem, name) {
if (!elem.attribs || !hasOwn.call(elem.attribs, name))
return;
delete elem.attribs[name];
}
/**
* Splits a space-separated list of names to individual names.
*
* @category Attributes
* @param names - Names to split.
* @returns - Split names.
*/
function splitNames(names) {
return names ? names.trim().split(rspace) : [];
}
/**
* Method for removing attributes by `name`.
*
* @category Attributes
* @example
*
* ```js
* $('.pear').removeAttr('class').html();
* //=> <li>Pear</li>
*
* $('.apple').attr('id', 'favorite');
* $('.apple').removeAttr('id class').html();
* //=> <li>Apple</li>
* ```
*
* @param name - Name of the attribute.
* @returns The instance itself.
* @see {@link https://api.jquery.com/removeAttr/}
*/
function removeAttr(name) {
const attrNames = splitNames(name);
for (let i = 0; i < attrNames.length; i++) {
domEach(this, (elem) => {
if (isTag$1(elem))
removeAttribute(elem, attrNames[i]);
});
}
return this;
}
/**
* Check to see if _any_ of the matched elements have the given `className`.
*
* @category Attributes
* @example
*
* ```js
* $('.pear').hasClass('pear');
* //=> true
*
* $('apple').hasClass('fruit');
* //=> false
*
* $('li').hasClass('pear');
* //=> true
* ```
*
* @param className - Name of the class.
* @returns Indicates if an element has the given `className`.
* @see {@link https://api.jquery.com/hasClass/}
*/
function hasClass(className) {
return this.toArray().some((elem) => {
const clazz = isTag$1(elem) && elem.attribs['class'];
let idx = -1;
if (clazz && className.length) {
while ((idx = clazz.indexOf(className, idx + 1)) > -1) {
const end = idx + className.length;
if ((idx === 0 || rspace.test(clazz[idx - 1])) &&
(end === clazz.length || rspace.test(clazz[end]))) {
return true;
}
}
}
return false;
});
}
/**
* Adds class(es) to all of the matched elements. Also accepts a `function`.
*
* @category Attributes
* @example
*
* ```js
* $('.pear').addClass('fruit').html();
* //=> <li class="pear fruit">Pear</li>
*
* $('.apple').addClass('fruit red').html();
* //=> <li class="apple fruit red">Apple</li>
* ```
*
* @param value - Name of new class.
* @returns The instance itself.
* @see {@link https://api.jquery.com/addClass/}
*/
function addClass(value) {
// Support functions
if (typeof value === 'function') {
return domEach(this, (el, i) => {
if (isTag$1(el)) {
const className = el.attribs['class'] || '';
addClass.call([el], value.call(el, i, className));
}
});
}
// Return if no value or not a string or function
if (!value || typeof value !== 'string')
return this;
const classNames = value.split(rspace);
const numElements = this.length;
for (let i = 0; i < numElements; i++) {
const el = this[i];
// If selected element isn't a tag, move on
if (!isTag$1(el))
continue;
// If we don't already have classes — always set xmlMode to false here, as it doesn't matter for classes
const className = getAttr(el, 'class', false);
if (!className) {
setAttr(el, 'class', classNames.join(' ').trim());
}
else {
let setClass = ` ${className} `;
// Check if class already exists
for (let j = 0; j < classNames.length; j++) {
const appendClass = `${classNames[j]} `;
if (!setClass.includes(` ${appendClass}`))
setClass += appendClass;
}
setAttr(el, 'class', setClass.trim());
}
}
return this;
}
/**
* Removes one or more space-separated classes from the selected elements. If no
* `className` is defined, all classes will be removed. Also accepts a `function`.
*
* @category Attributes
* @example
*
* ```js
* $('.pear').removeClass('pear').html();
* //=> <li class="">Pear</li>
*
* $('.apple').addClass('red').removeClass().html();
* //=> <li class="">Apple</li>
* ```
*
* @param name - Name of the class. If not specified, removes all elements.
* @returns The instance itself.
* @see {@link https://api.jquery.com/removeClass/}
*/
function removeClass(name) {
// Handle if value is a function
if (typeof name === 'function') {
return domEach(this, (el, i) => {
if (isTag$1(el)) {
removeClass.call([el], name.call(el, i, el.attribs['class'] || ''));
}
});
}
const classes = splitNames(name);
const numClasses = classes.length;
const removeAll = arguments.length === 0;
return domEach(this, (el) => {
if (!isTag$1(el))
return;
if (removeAll) {
// Short circuit the remove all case as this is the nice one
el.attribs['class'] = '';
}
else {
const elClasses = splitNames(el.attribs['class']);
let changed = false;
for (let j = 0; j < numClasses; j++) {
const index = elClasses.indexOf(classes[j]);
if (index >= 0) {
elClasses.splice(index, 1);
changed = true;
/*
* We have to do another pass to ensure that there are not duplicate
* classes listed
*/
j--;
}
}
if (changed) {
el.attribs['class'] = elClasses.join(' ');
}
}
});
}
/**
* Add or remove class(es) from the matched elements, depending on either the
* class's presence or the value of the switch argument. Also accepts a `function`.
*
* @category Attributes
* @example
*
* ```js
* $('.apple.green').toggleClass('fruit green red').html();
* //=> <li class="apple fruit red">Apple</li>
*
* $('.apple.green').toggleClass('fruit green red', true).html();
* //=> <li class="apple green fruit red">Apple</li>
* ```
*
* @param value - Name of the class. Can also be a function.
* @param stateVal - If specified the state of the class.
* @returns The instance itself.
* @see {@link https://api.jquery.com/toggleClass/}
*/
function toggleClass(value, stateVal) {
// Support functions
if (typeof value === 'function') {
return domEach(this, (el, i) => {
if (isTag$1(el)) {
toggleClass.call([el], value.call(el, i, el.attribs['class'] || '', stateVal), stateVal);
}
});
}
// Return if no value or not a string or function
if (!value || typeof value !== 'string')
return this;
const classNames = value.split(rspace);
const numClasses = classNames.length;
const state = typeof stateVal === 'boolean' ? (stateVal ? 1 : -1) : 0;
const numElements = this.length;
for (let i = 0; i < numElements; i++) {
const el = this[i];
// If selected element isn't a tag, move on
if (!isTag$1(el))
continue;
const elementClasses = splitNames(el.attribs['class']);
// Check if class already exists
for (let j = 0; j < numClasses; j++) {
// Check if the class name is currently defined
const index = elementClasses.indexOf(classNames[j]);
// Add if stateValue === true or we are toggling and there is no value
if (state >= 0 && index < 0) {
elementClasses.push(classNames[j]);
}
else if (state <= 0 && index >= 0) {
// Otherwise remove but only if the item exists
elementClasses.splice(index, 1);
}
}
el.attribs['class'] = elementClasses.join(' ');
}
return this;
}
var Attributes = /*#__PURE__*/Object.freeze({
__proto__: null,
attr: attr,
prop: prop,
data: data$2,
val: val,
removeAttr: removeAttr,
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
toggleClass: toggleClass
});
var SelectorType;
(function (SelectorType) {
SelectorType["Attribute"] = "attribute";
SelectorType["Pseudo"] = "pseudo";
SelectorType["PseudoElement"] = "pseudo-element";
SelectorType["Tag"] = "tag";
SelectorType["Universal"] = "universal";
// Traversals
SelectorType["Adjacent"] = "adjacent";
SelectorType["Child"] = "child";
SelectorType["Descendant"] = "descendant";
SelectorType["Parent"] = "parent";
SelectorType["Sibling"] = "sibling";
SelectorType["ColumnCombinator"] = "column-combinator";
})(SelectorType || (SelectorType = {}));
var AttributeAction;
(function (AttributeAction) {
AttributeAction["Any"] = "any";
AttributeAction["Element"] = "element";
AttributeAction["End"] = "end";
AttributeAction["Equals"] = "equals";
AttributeAction["Exists"] = "exists";
AttributeAction["Hyphen"] = "hyphen";
AttributeAction["Not"] = "not";
AttributeAction["Start"] = "start";
})(AttributeAction || (AttributeAction = {}));
const reName = /^[^\\#]?(?:\\(?:[\da-f]{1,6}\s?|.)|[\w\-\u00b0-\uFFFF])+/;
const reEscape = /\\([\da-f]{1,6}\s?|(\s)|.)/gi;
const actionTypes = new Map([
[126 /* Tilde */, AttributeAction.Element],
[94 /* Circumflex */, AttributeAction.Start],
[36 /* Dollar */, AttributeAction.End],
[42 /* Asterisk */, AttributeAction.Any],
[33 /* ExclamationMark */, AttributeAction.Not],
[124 /* Pipe */, AttributeAction.Hyphen],
]);
// Pseudos, whose data property is parsed as well.
const unpackPseudos = new Set([
"has",
"not",
"matches",
"is",
"where",
"host",
"host-context",
]);
/**
* Checks whether a specific selector is a traversal.
* This is useful eg. in swapping the order of elements that
* are not traversals.
*
* @param selector Selector to check.
*/
function isTraversal(selector) {
switch (selector.type) {
case SelectorType.Adjacent:
case SelectorType.Child:
case SelectorType.Descendant:
case SelectorType.Parent:
case SelectorType.Sibling:
case SelectorType.ColumnCombinator:
return true;
default:
return false;
}
}
const stripQuotesFromPseudos = new Set(["contains", "icontains"]);
// Unescape function taken from https://github.com/jquery/sizzle/blob/master/src/sizzle.js#L152
function funescape(_, escaped, escapedWhitespace) {
const high = parseInt(escaped, 16) - 0x10000;
// NaN means non-codepoint
return high !== high || escapedWhitespace
? escaped
: high < 0
? // BMP codepoint
String.fromCharCode(high + 0x10000)
: // Supplemental Plane codepoint (surrogate pair)
String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00);
}
function unescapeCSS(str) {
return str.replace(reEscape, funescape);
}
function isQuote(c) {
return c === 39 /* SingleQuote */ || c === 34 /* DoubleQuote */;
}
function isWhitespace(c) {
return (c === 32 /* Space */ ||
c === 9 /* Tab */ ||
c === 10 /* NewLine */ ||
c === 12 /* FormFeed */ ||
c === 13 /* CarriageReturn */);
}
/**
* Parses `selector`, optionally with the passed `options`.
*
* @param selector Selector to parse.
* @param options Options for parsing.
* @returns Returns a two-dimensional array.
* The first dimension represents selectors separated by commas (eg. `sub1, sub2`),
* the second contains the relevant tokens for that selector.
*/
function parse(selector) {
const subselects = [];
const endIndex = parseSelector(subselects, `${selector}`, 0);
if (endIndex < selector.length) {
throw new Error(`Unmatched selector: ${selector.slice(endIndex)}`);
}
return subselects;
}
function parseSelector(subselects, selector, selectorIndex) {
let tokens = [];
function getName(offset) {
const match = selector.slice(selectorIndex + offset).match(reName);
if (!match) {
throw new Error(`Expected name, found ${selector.slice(selectorIndex)}`);
}
const [name] = match;
selectorIndex += offset + name.length;
return unescapeCSS(name);
}
function stripWhitespace(offset) {
selectorIndex += offset;
while (selectorIndex < selector.length &&
isWhitespace(selector.charCodeAt(selectorIndex))) {
selectorIndex++;
}
}
function readValueWithParenthesis() {
selectorIndex += 1;
const start = selectorIndex;
let counter = 1;
for (; counter > 0 && selectorIndex < selector.length; selectorIndex++) {
if (selector.charCodeAt(selectorIndex) ===
40 /* LeftParenthesis */ &&
!isEscaped(selectorIndex)) {
counter++;
}
else if (selector.charCodeAt(selectorIndex) ===
41 /* RightParenthesis */ &&
!isEscaped(selectorIndex)) {
counter--;
}
}
if (counter) {
throw new Error("Parenthesis not matched");
}
return unescapeCSS(selector.slice(start, selectorIndex - 1));
}
function isEscaped(pos) {
let slashCount = 0;
while (selector.charCodeAt(--pos) === 92 /* BackSlash */)
slashCount++;
return (slashCount & 1) === 1;
}
function ensureNotTraversal() {
if (tokens.length > 0 && isTraversal(tokens[tokens.length - 1])) {
throw new Error("Did not expect successive traversals.");
}
}
function addTraversal(type) {
if (tokens.length > 0 &&
tokens[tokens.length - 1].type === SelectorType.Descendant) {
tokens[tokens.length - 1].type = type;
return;
}
ensureNotTraversal();
tokens.push({ type });
}
function addSpecialAttribute(name, action) {
tokens.push({
type: SelectorType.Attribute,
name,
action,
value: getName(1),
namespace: null,
ignoreCase: "quirks",
});
}
/**
* We have finished parsing the current part of the selector.
*
* Remove descendant tokens at the end if they exist,
* and return the last index, so that parsing can be
* picked up from here.
*/
function finalizeSubselector() {
if (tokens.length &&
tokens[tokens.length - 1].type === SelectorType.Descendant) {
tokens.pop();
}
if (tokens.length === 0) {
throw new Error("Empty sub-selector");
}
subselects.push(tokens);
}
stripWhitespace(0);
if (selector.length === selectorIndex) {
return selectorIndex;
}
loop: while (selectorIndex < selector.length) {
const firstChar = selector.charCodeAt(selectorIndex);
switch (firstChar) {
// Whitespace
case 32 /* Space */:
case 9 /* Tab */:
case 10 /* NewLine */:
case 12 /* FormFeed */:
case 13 /* CarriageReturn */: {
if (tokens.length === 0 ||
tokens[0].type !== SelectorType.Descendant) {
ensureNotTraversal();
tokens.push({ type: SelectorType.Descendant });
}
stripWhitespace(1);
break;
}
// Traversals
case 62 /* GreaterThan */: {
addTraversal(SelectorType.Child);
stripWhitespace(1);
break;
}
case 60 /* LessThan */: {
addTraversal(SelectorType.Parent);
stripWhitespace(1);
break;
}
case 126 /* Tilde */: {
addTraversal(SelectorType.Sibling);
stripWhitespace(1);
break;
}
case 43 /* Plus */: {
addTraversal(SelectorType.Adjacent);
stripWhitespace(1);
break;
}
// Special attribute selectors: .class, #id
case 46 /* Period */: {
addSpecialAttribute("class", AttributeAction.Element);
break;
}
case 35 /* Hash */: {
addSpecialAttribute("id", AttributeAction.Equals);
break;
}
case 91 /* LeftSquareBracket */: {
stripWhitespace(1);
// Determine attribute name and namespace
let name;
let namespace = null;
if (selector.charCodeAt(selectorIndex) === 124 /* Pipe */) {
// Equivalent to no namespace
name = getName(1);
}
else if (selector.startsWith("*|", selectorIndex)) {
namespace = "*";
name = getName(2);
}
else {
name = getName(0);
if (selector.charCodeAt(selectorIndex) === 124 /* Pipe */ &&
selector.charCodeAt(selectorIndex + 1) !==
61 /* Equal */) {
namespace = name;
name = getName(1);
}
}
stripWhitespace(0);
// Determine comparison operation
let action = AttributeAction.Exists;
const possibleAction = actionTypes.get(selector.charCodeAt(selectorIndex));
if (possibleAction) {
action = possibleAction;
if (selector.charCodeAt(selectorIndex + 1) !==
61 /* Equal */) {
throw new Error("Expected `=`");
}
stripWhitespace(2);
}
else if (selector.charCodeAt(selectorIndex) === 61 /* Equal */) {
action = AttributeAction.Equals;
stripWhitespace(1);
}
// Determine value
let value = "";
let ignoreCase = null;
if (action !== "exists") {
if (isQuote(selector.charCodeAt(selectorIndex))) {
const quote = selector.charCodeAt(selectorIndex);
let sectionEnd = selectorIndex + 1;
while (sectionEnd < selector.length &&
(selector.charCodeAt(sectionEnd) !== quote ||
isEscaped(sectionEnd))) {
sectionEnd += 1;
}
if (selector.charCodeAt(sectionEnd) !== quote) {
throw new Error("Attribute value didn't end");
}
value = unescapeCSS(selector.slice(selectorIndex + 1, sectionEnd));
selectorIndex = sectionEnd + 1;
}
else {
const valueStart = selectorIndex;
while (selectorIndex < selector.length &&
((!isWhitespace(selector.charCodeAt(selectorIndex)) &&
selector.charCodeAt(selectorIndex) !==
93 /* RightSquareBracket */) ||
isEscaped(selectorIndex))) {
selectorIndex += 1;
}
value = unescapeCSS(selector.slice(valueStart, selectorIndex));
}
stripWhitespace(0);
// See if we have a force ignore flag
const forceIgnore = selector.charCodeAt(selectorIndex) | 0x20;
// If the forceIgnore flag is set (either `i` or `s`), use that value
if (forceIgnore === 115 /* LowerS */) {
ignoreCase = false;
stripWhitespace(1);
}
else if (forceIgnore === 105 /* LowerI */) {
ignoreCase = true;
stripWhitespace(1);
}
}
if (selector.charCodeAt(selectorIndex) !==
93 /* RightSquareBracket */) {
throw new Error("Attribute selector didn't terminate");
}
selectorIndex += 1;
const attributeSelector = {
type: SelectorType.Attribute,
name,
action,
value,
namespace,
ignoreCase,
};
tokens.push(attributeSelector);
break;
}
case 58 /* Colon */: {
if (selector.charCodeAt(selectorIndex + 1) === 58 /* Colon */) {
tokens.push({
type: SelectorType.PseudoElement,
name: getName(2).toLowerCase(),
data: selector.charCodeAt(selectorIndex) ===
40 /* LeftParenthesis */
? readValueWithParenthesis()
: null,
});
continue;
}
const name = getName(1).toLowerCase();
let data = null;
if (selector.charCodeAt(selectorIndex) ===
40 /* LeftParenthesis */) {
if (unpackPseudos.has(name)) {
if (isQuote(selector.charCodeAt(selectorIndex + 1))) {
throw new Error(`Pseudo-selector ${name} cannot be quoted`);
}
data = [];
selectorIndex = parseSelector(data, selector, selectorIndex + 1);
if (selector.charCodeAt(selectorIndex) !==
41 /* RightParenthesis */) {
throw new Error(`Missing closing parenthesis in :${name} (${selector})`);
}
selectorIndex += 1;
}
else {
data = readValueWithParenthesis();
if (stripQuotesFromPseudos.has(name)) {
const quot = data.charCodeAt(0);
if (quot === data.charCodeAt(data.length - 1) &&
isQuote(quot)) {
data = data.slice(1, -1);
}
}
data = unescapeCSS(data);
}
}
tokens.push({ type: SelectorType.Pseudo, name, data });
break;
}
case 44 /* Comma */: {
finalizeSubselector();
tokens = [];
stripWhitespace(1);
break;
}
default: {
if (selector.startsWith("/*", selectorIndex)) {
const endIndex = selector.indexOf("*/", selectorIndex + 2);
if (endIndex < 0) {
throw new Error("Comment was not terminated");
}
selectorIndex = endIndex + 2;
// Remove leading whitespace
if (tokens.length === 0) {
stripWhitespace(0);
}
break;
}
let namespace = null;
let name;
if (firstChar === 42 /* Asterisk */) {
selectorIndex += 1;
name = "*";
}
else if (firstChar === 124 /* Pipe */) {
name = "";
if (selector.charCodeAt(selectorIndex + 1) === 124 /* Pipe */) {
addTraversal(SelectorType.ColumnCombinator);
stripWhitespace(2);
break;
}
}
else if (reName.test(selector.slice(selectorIndex))) {
name = getName(0);
}
else {
break loop;
}
if (selector.charCodeAt(selectorIndex) === 124 /* Pipe */ &&
selector.charCodeAt(selectorIndex + 1) !== 124 /* Pipe */) {
namespace = name;
if (selector.charCodeAt(selectorIndex + 1) ===
42 /* Asterisk */) {
name = "*";
selectorIndex += 2;
}
else {
name = getName(1);
}
}
tokens.push(name === "*"
? { type: SelectorType.Universal, namespace }
: { type: SelectorType.Tag, name, namespace });
}
}
}
finalizeSubselector();
return selectorIndex;
}
var boolbase = {
trueFunc: function trueFunc(){
return true;
},
falseFunc: function falseFunc(){
return false;
}
};
var boolbase_1 = boolbase.trueFunc;
var boolbase_2 = boolbase.falseFunc;
const procedure = new Map([
[SelectorType.Universal, 50],
[SelectorType.Tag, 30],
[SelectorType.Attribute, 1],
[SelectorType.Pseudo, 0],
]);
function isTraversal$1(token) {
return !procedure.has(token.type);
}
const attributes = new Map([
[AttributeAction.Exists, 10],
[AttributeAction.Equals, 8],
[AttributeAction.Not, 7],
[AttributeAction.Start, 6],
[AttributeAction.End, 6],
[AttributeAction.Any, 5],
]);
/**
* Sort the parts of the passed selector,
* as there is potential for optimization
* (some types of selectors are faster than others)
*
* @param arr Selector to sort
*/
function sortByProcedure(arr) {
const procs = arr.map(getProcedure);
for (let i = 1; i < arr.length; i++) {
const procNew = procs[i];
if (procNew < 0)
continue;
for (let j = i - 1; j >= 0 && procNew < procs[j]; j--) {
const token = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = token;
procs[j + 1] = procs[j];
procs[j] = procNew;
}
}
}
function getProcedure(token) {
var _a, _b;
let proc = (_a = procedure.get(token.type)) !== null && _a !== void 0 ? _a : -1;
if (token.type === SelectorType.Attribute) {
proc = (_b = attributes.get(token.action)) !== null && _b !== void 0 ? _b : 4;
if (token.action === AttributeAction.Equals && token.name === "id") {
// Prefer ID selectors (eg. #ID)
proc = 9;
}
if (token.ignoreCase) {
/*
* IgnoreCase adds some overhead, prefer "normal" token
* this is a binary operation, to ensure it's still an int
*/
proc >>= 1;
}
}
else if (token.type === SelectorType.Pseudo) {
if (!token.data) {
proc = 3;
}
else if (token.name === "has" || token.name === "contains") {
proc = 0; // Expensive in any case
}
else if (Array.isArray(token.data)) {
// Eg. :matches, :not
proc = Math.min(...token.data.map((d) => Math.min(...d.map(getProcedure))));
// If we have traversals, try to avoid executing this selector
if (proc < 0) {
proc = 0;
}
}
else {
proc = 2;
}
}
return proc;
}
/**
* All reserved characters in a regex, used for escaping.
*
* Taken from XRegExp, (c) 2007-2020 Steven Levithan under the MIT license
* https://github.com/slevithan/xregexp/blob/95eeebeb8fac8754d54eafe2b4743661ac1cf028/src/xregexp.js#L794
*/
const reChars = /[-[\]{}()*+?.,\\^$|#\s]/g;
function escapeRegex(value) {
return value.replace(reChars, "\\$&");
}
/**
* Attributes that are case-insensitive in HTML.
*
* @private
* @see https://html.spec.whatwg.org/multipage/semantics-other.html#case-sensitivity-of-selectors
*/
const caseInsensitiveAttributes = new Set([
"accept",
"accept-charset",
"align",
"alink",
"axis",
"bgcolor",
"charset",
"checked",
"clear",
"codetype",
"color",
"compact",
"declare",
"defer",
"dir",
"direction",
"disabled",
"enctype",
"face",
"frame",
"hreflang",
"http-equiv",
"lang",
"language",
"link",
"media",
"method",
"multiple",
"nohref",
"noresize",
"noshade",
"nowrap",
"readonly",
"rel",
"rev",
"rules",
"scope",
"scrolling",
"selected",
"shape",
"target",
"text",
"type",
"valign",
"valuetype",
"vlink",
]);
function shouldIgnoreCase(selector, options) {
return typeof selector.ignoreCase === "boolean"
? selector.ignoreCase
: selector.ignoreCase === "quirks"
? !!options.quirksMode
: !options.xmlMode && caseInsensitiveAttributes.has(selector.name);
}
/**
* Attribute selectors
*/
const attributeRules = {
equals(next, data, options) {
const { adapter } = options;
const { name } = data;
let { value } = data;
if (shouldIgnoreCase(data, options)) {
value = value.toLowerCase();
return (elem) => {
const attr = adapter.getAttributeValue(elem, name);
return (attr != null &&
attr.length === value.length &&
attr.toLowerCase() === value &&
next(elem));
};
}
return (elem) => adapter.getAttributeValue(elem, name) === value && next(elem);
},
hyphen(next, data, options) {
const { adapter } = options;
const { name } = data;
let { value } = data;
const len = value.length;
if (shouldIgnoreCase(data, options)) {
value = value.toLowerCase();
return function hyphenIC(elem) {
const attr = adapter.getAttributeValue(elem, name);
return (attr != null &&
(attr.length === len || attr.charAt(len) === "-") &&
attr.substr(0, len).toLowerCase() === value &&
next(elem));
};
}
return function hyphen(elem) {
const attr = adapter.getAttributeValue(elem, name);
return (attr != null &&
(attr.length === len || attr.charAt(len) === "-") &&
attr.substr(0, len) === value &&
next(elem));
};
},
element(next, data, options) {
const { adapter } = options;
const { name, value } = data;
if (/\s/.test(value)) {
return boolbase.falseFunc;
}
const regex = new RegExp(`(?:^|\\s)${escapeRegex(value)}(?:$|\\s)`, shouldIgnoreCase(data, options) ? "i" : "");
return function element(elem) {
const attr = adapter.getAttributeValue(elem, name);
return (attr != null &&
attr.length >= value.length &&
regex.test(attr) &&
next(elem));
};
},
exists(next, { name }, { adapter }) {
return (elem) => adapter.hasAttrib(elem, name) && next(elem);
},
start(next, data, options) {
const { adapter } = options;
const { name } = data;
let { value } = data;
const len = value.length;
if (len === 0) {
return boolbase.falseFunc;
}
if (shouldIgnoreCase(data, options)) {
value = value.toLowerCase();
return (elem) => {
const attr = adapter.getAttributeValue(elem, name);
return (attr != null &&
attr.length >= len &&
attr.substr(0, len).toLowerCase() === value &&
next(elem));
};
}
return (elem) => {
var _a;
return !!((_a = adapter.getAttributeValue(elem, name)) === null || _a === void 0 ? void 0 : _a.startsWith(value)) &&
next(elem);
};
},
end(next, data, options) {
const { adapter } = options;
const { name } = data;
let { value } = data;
const len = -value.length;
if (len === 0) {
return boolbase.falseFunc;
}
if (shouldIgnoreCase(data, options)) {
value = value.toLowerCase();
return (elem) => {
var _a;
return ((_a = adapter
.getAttributeValue(elem, name)) === null || _a === void 0 ? void 0 : _a.substr(len).toLowerCase()) === value && next(elem);
};
}
return (elem) => {
var _a;
return !!((_a = adapter.getAttributeValue(elem, name)) === null || _a === void 0 ? void 0 : _a.endsWith(value)) &&
next(elem);
};
},
any(next, data, options) {
const { adapter } = options;
const { name, value } = data;
if (value === "") {
return boolbase.falseFunc;
}
if (shouldIgnoreCase(data, options)) {
const regex = new RegExp(escapeRegex(value), "i");
return function anyIC(elem) {
const attr = adapter.getAttributeValue(elem, name);
return (attr != null &&
attr.length >= value.length &&
regex.test(attr) &&
next(elem));
};
}
return (elem) => {
var _a;
return !!((_a = adapter.getAttributeValue(elem, name)) === null || _a === void 0 ? void 0 : _a.includes(value)) &&
next(elem);
};
},
not(next, data, options) {
const { adapter } = options;
const { name } = data;
let { value } = data;
if (value === "") {
return (elem) => !!adapter.getAttributeValue(elem, name) && next(elem);
}
else if (shouldIgnoreCase(data, options)) {
value = value.toLowerCase();
return (elem) => {
const attr = adapter.getAttributeValue(elem, name);
return ((attr == null ||
attr.length !== value.length ||
attr.toLowerCase() !== value) &&
next(elem));
};
}
return (elem) => adapter.getAttributeValue(elem, name) !== value && next(elem);
},
};
// Following http://www.w3.org/TR/css3-selectors/#nth-child-pseudo
// Whitespace as per https://www.w3.org/TR/selectors-3/#lex is " \t\r\n\f"
const whitespace$1 = new Set([9, 10, 12, 13, 32]);
const ZERO = "0".charCodeAt(0);
const NINE = "9".charCodeAt(0);
/**
* Parses an expression.
*
* @throws An `Error` if parsing fails.
* @returns An array containing the integer step size and the integer offset of the nth rule.
* @example nthCheck.parse("2n+3"); // returns [2, 3]
*/
function parse$1(formula) {
formula = formula.trim().toLowerCase();
if (formula === "even") {
return [2, 0];
}
else if (formula === "odd") {
return [2, 1];
}
// Parse [ ['-'|'+']? INTEGER? {N} [ S* ['-'|'+'] S* INTEGER ]?
let idx = 0;
let a = 0;
let sign = readSign();
let number = readNumber();
if (idx < formula.length && formula.charAt(idx) === "n") {
idx++;
a = sign * (number !== null && number !== void 0 ? number : 1);
skipWhitespace();
if (idx < formula.length) {
sign = readSign();
skipWhitespace();
number = readNumber();
}
else {
sign = number = 0;
}
}
// Throw if there is anything else
if (number === null || idx < formula.length) {
throw new Error(`n-th rule couldn't be parsed ('${formula}')`);
}
return [a, sign * number];
function readSign() {
if (formula.charAt(idx) === "-") {
idx++;
return -1;
}
if (formula.charAt(idx) === "+") {
idx++;
}
return 1;
}
function readNumber() {
const start = idx;
let value = 0;
while (idx < formula.length &&
formula.charCodeAt(idx) >= ZERO &&
formula.charCodeAt(idx) <= NINE) {
value = value * 10 + (formula.charCodeAt(idx) - ZERO);
idx++;
}
// Return `null` if we didn't read anything.
return idx === start ? null : value;
}
function skipWhitespace() {
while (idx < formula.length &&
whitespace$1.has(formula.charCodeAt(idx))) {
idx++;
}
}
}
/**
* Returns a function that checks if an elements index matches the given rule
* highly optimized to return the fastest solution.
*
* @param parsed A tuple [a, b], as returned by `parse`.
* @returns A highly optimized function that returns whether an index matches the nth-check.
* @example
*
* ```js
* const check = nthCheck.compile([2, 3]);
*
* check(0); // `false`
* check(1); // `false`
* check(2); // `true`
* check(3); // `false`
* check(4); // `true`
* check(5); // `false`
* check(6); // `true`
* ```
*/
function compile(parsed) {
const a = parsed[0];
// Subtract 1 from `b`, to convert from one- to zero-indexed.
const b = parsed[1] - 1;
/*
* When `b <= 0`, `a * n` won't be lead to any matches for `a < 0`.
* Besides, the specification states that no elements are
* matched when `a` and `b` are 0.
*
* `b < 0` here as we subtracted 1 from `b` above.
*/
if (b < 0 && a <= 0)
return boolbase_2;
// When `a` is in the range -1..1, it matches any element (so only `b` is checked).
if (a === -1)
return (index) => index <= b;
if (a === 0)
return (index) => index === b;
// When `b <= 0` and `a === 1`, they match any element.
if (a === 1)
return b < 0 ? boolbase_1 : (index) => index >= b;
/*
* Otherwise, modulo can be used to check if there is a match.
*
* Modulo doesn't care about the sign, so let's use `a`s absolute value.
*/
const absA = Math.abs(a);
// Get `b mod a`, + a if this is negative.
const bMod = ((b % absA) + absA) % absA;
return a > 1
? (index) => index >= b && index % absA === bMod
: (index) => index <= b && index % absA === bMod;
}
/**
* Parses and compiles a formula to a highly optimized function.
* Combination of {@link parse} and {@link compile}.
*
* If the formula doesn't match any elements,
* it returns [`boolbase`](https://github.com/fb55/boolbase)'s `falseFunc`.
* Otherwise, a function accepting an _index_ is returned, which returns
* whether or not the passed _index_ matches the formula.
*
* Note: The nth-rule starts counting at `1`, the returned function at `0`.
*
* @param formula The formula to compile.
* @example
* const check = nthCheck("2n+3");
*
* check(0); // `false`
* check(1); // `false`
* check(2); // `true`
* check(3); // `false`
* check(4); // `true`
* check(5); // `false`
* check(6); // `true`
*/
function nthCheck(formula) {
return compile(parse$1(formula));
}
function getChildFunc(next, adapter) {
return (elem) => {
const parent = adapter.getParent(elem);
return parent != null && adapter.isTag(parent) && next(elem);
};
}
const filters = {
contains(next, text, { adapter }) {
return function contains(elem) {
return next(elem) && adapter.getText(elem).includes(text);
};
},
icontains(next, text, { adapter }) {
const itext = text.toLowerCase();
return function icontains(elem) {
return (next(elem) &&
adapter.getText(elem).toLowerCase().includes(itext));
};
},
// Location specific methods
"nth-child"(next, rule, { adapter, equals }) {
const func = nthCheck(rule);
if (func === boolbase.falseFunc)
return boolbase.falseFunc;
if (func === boolbase.trueFunc)
return getChildFunc(next, adapter);
return function nthChild(elem) {
const siblings = adapter.getSiblings(elem);
let pos = 0;
for (let i = 0; i < siblings.length; i++) {
if (equals(elem, siblings[i]))
break;
if (adapter.isTag(siblings[i])) {
pos++;
}
}
return func(pos) && next(elem);
};
},
"nth-last-child"(next, rule, { adapter, equals }) {
const func = nthCheck(rule);
if (func === boolbase.falseFunc)
return boolbase.falseFunc;
if (func === boolbase.trueFunc)
return getChildFunc(next, adapter);
return function nthLastChild(elem) {
const siblings = adapter.getSiblings(elem);
let pos = 0;
for (let i = siblings.length - 1; i >= 0; i--) {
if (equals(elem, siblings[i]))
break;
if (adapter.isTag(siblings[i])) {
pos++;
}
}
return func(pos) && next(elem);
};
},
"nth-of-type"(next, rule, { adapter, equals }) {
const func = nthCheck(rule);
if (func === boolbase.falseFunc)
return boolbase.falseFunc;
if (func === boolbase.trueFunc)
return getChildFunc(next, adapter);
return function nthOfType(elem) {
const siblings = adapter.getSiblings(elem);
let pos = 0;
for (let i = 0; i < siblings.length; i++) {
const currentSibling = siblings[i];
if (equals(elem, currentSibling))
break;
if (adapter.isTag(currentSibling) &&
adapter.getName(currentSibling) === adapter.getName(elem)) {
pos++;
}
}
return func(pos) && next(elem);
};
},
"nth-last-of-type"(next, rule, { adapter, equals }) {
const func = nthCheck(rule);
if (func === boolbase.falseFunc)
return boolbase.falseFunc;
if (func === boolbase.trueFunc)
return getChildFunc(next, adapter);
return function nthLastOfType(elem) {
const siblings = adapter.getSiblings(elem);
let pos = 0;
for (let i = siblings.length - 1; i >= 0; i--) {
const currentSibling = siblings[i];
if (equals(elem, currentSibling))
break;
if (adapter.isTag(currentSibling) &&
adapter.getName(currentSibling) === adapter.getName(elem)) {
pos++;
}
}
return func(pos) && next(elem);
};
},
// TODO determine the actual root element
root(next, _rule, { adapter }) {
return (elem) => {
const parent = adapter.getParent(elem);
return (parent == null || !adapter.isTag(parent)) && next(elem);
};
},
scope(next, rule, options, context) {
const { equals } = options;
if (!context || context.length === 0) {
// Equivalent to :root
return filters["root"](next, rule, options);
}
if (context.length === 1) {
// NOTE: can't be unpacked, as :has uses this for side-effects
return (elem) => equals(context[0], elem) && next(elem);
}
return (elem) => context.includes(elem) && next(elem);
},
hover: dynamicStatePseudo("isHovered"),
visited: dynamicStatePseudo("isVisited"),
active: dynamicStatePseudo("isActive"),
};
/**
* Dynamic state pseudos. These depend on optional Adapter methods.
*
* @param name The name of the adapter method to call.
* @returns Pseudo for the `filters` object.
*/
function dynamicStatePseudo(name) {
return function dynamicPseudo(next, _rule, { adapter }) {
const func = adapter[name];
if (typeof func !== "function") {
return boolbase.falseFunc;
}
return function active(elem) {
return func(elem) && next(elem);
};
};
}
// While filters are precompiled, pseudos get called when they are needed
const pseudos = {
empty(elem, { adapter }) {
return !adapter.getChildren(elem).some((elem) =>
// FIXME: `getText` call is potentially expensive.
adapter.isTag(elem) || adapter.getText(elem) !== "");
},
"first-child"(elem, { adapter, equals }) {
if (adapter.prevElementSibling) {
return adapter.prevElementSibling(elem) == null;
}
const firstChild = adapter
.getSiblings(elem)
.find((elem) => adapter.isTag(elem));
return firstChild != null && equals(elem, firstChild);
},
"last-child"(elem, { adapter, equals }) {
const siblings = adapter.getSiblings(elem);
for (let i = siblings.length - 1; i >= 0; i--) {
if (equals(elem, siblings[i]))
return true;
if (adapter.isTag(siblings[i]))
break;
}
return false;
},
"first-of-type"(elem, { adapter, equals }) {
const siblings = adapter.getSiblings(elem);
const elemName = adapter.getName(elem);
for (let i = 0; i < siblings.length; i++) {
const currentSibling = siblings[i];
if (equals(elem, currentSibling))
return true;
if (adapter.isTag(currentSibling) &&
adapter.getName(currentSibling) === elemName) {
break;
}
}
return false;
},
"last-of-type"(elem, { adapter, equals }) {
const siblings = adapter.getSiblings(elem);
const elemName = adapter.getName(elem);
for (let i = siblings.length - 1; i >= 0; i--) {
const currentSibling = siblings[i];
if (equals(elem, currentSibling))
return true;
if (adapter.isTag(currentSibling) &&
adapter.getName(currentSibling) === elemName) {
break;
}
}
return false;
},
"only-of-type"(elem, { adapter, equals }) {
const elemName = adapter.getName(elem);
return adapter
.getSiblings(elem)
.every((sibling) => equals(elem, sibling) ||
!adapter.isTag(sibling) ||
adapter.getName(sibling) !== elemName);
},
"only-child"(elem, { adapter, equals }) {
return adapter
.getSiblings(elem)
.every((sibling) => equals(elem, sibling) || !adapter.isTag(sibling));
},
};
function verifyPseudoArgs(func, name, subselect, argIndex) {
if (subselect === null) {
if (func.length > argIndex) {
throw new Error(`Pseudo-class :${name} requires an argument`);
}
}
else if (func.length === argIndex) {
throw new Error(`Pseudo-class :${name} doesn't have any arguments`);
}
}
/**
* Aliases are pseudos that are expressed as selectors.
*/
const aliases = {
// Links
"any-link": ":is(a, area, link)[href]",
link: ":any-link:not(:visited)",
// Forms
// https://html.spec.whatwg.org/multipage/scripting.html#disabled-elements
disabled: `:is(
:is(button, input, select, textarea, optgroup, option)[disabled],
optgroup[disabled] > option,
fieldset[disabled]:not(fieldset[disabled] legend:first-of-type *)
)`,
enabled: ":not(:disabled)",
checked: ":is(:is(input[type=radio], input[type=checkbox])[checked], option:selected)",
required: ":is(input, select, textarea)[required]",
optional: ":is(input, select, textarea):not([required])",
// JQuery extensions
// https://html.spec.whatwg.org/multipage/form-elements.html#concept-option-selectedness
selected: "option:is([selected], select:not([multiple]):not(:has(> option[selected])) > :first-of-type)",
checkbox: "[type=checkbox]",
file: "[type=file]",
password: "[type=password]",
radio: "[type=radio]",
reset: "[type=reset]",
image: "[type=image]",
submit: "[type=submit]",
parent: ":not(:empty)",
header: ":is(h1, h2, h3, h4, h5, h6)",
button: ":is(button, input[type=button])",
input: ":is(input, textarea, select, button)",
text: "input:is(:not([type!='']), [type=text])",
};
/** Used as a placeholder for :has. Will be replaced with the actual element. */
const PLACEHOLDER_ELEMENT = {};
function ensureIsTag(next, adapter) {
if (next === boolbase.falseFunc)
return boolbase.falseFunc;
return (elem) => adapter.isTag(elem) && next(elem);
}
function getNextSiblings(elem, adapter) {
const siblings = adapter.getSiblings(elem);
if (siblings.length <= 1)
return [];
const elemIndex = siblings.indexOf(elem);
if (elemIndex < 0 || elemIndex === siblings.length - 1)
return [];
return siblings.slice(elemIndex + 1).filter(adapter.isTag);
}
function copyOptions(options) {
// Not copied: context, rootFunc
return {
xmlMode: !!options.xmlMode,
lowerCaseAttributeNames: !!options.lowerCaseAttributeNames,
lowerCaseTags: !!options.lowerCaseTags,
quirksMode: !!options.quirksMode,
cacheResults: !!options.cacheResults,
pseudos: options.pseudos,
adapter: options.adapter,
equals: options.equals,
};
}
const is = (next, token, options, context, compileToken) => {
const func = compileToken(token, copyOptions(options), context);
return func === boolbase.trueFunc
? next
: func === boolbase.falseFunc
? boolbase.falseFunc
: (elem) => func(elem) && next(elem);
};
/*
* :not, :has, :is, :matches and :where have to compile selectors
* doing this in src/pseudos.ts would lead to circular dependencies,
* so we add them here
*/
const subselects = {
is,
/**
* `:matches` and `:where` are aliases for `:is`.
*/
matches: is,
where: is,
not(next, token, options, context, compileToken) {
const func = compileToken(token, copyOptions(options), context);
return func === boolbase.falseFunc
? next
: func === boolbase.trueFunc
? boolbase.falseFunc
: (elem) => !func(elem) && next(elem);
},
has(next, subselect, options, _context, compileToken) {
const { adapter } = options;
const opts = copyOptions(options);
opts.relativeSelector = true;
const context = subselect.some((s) => s.some(isTraversal$1))
? // Used as a placeholder. Will be replaced with the actual element.
[PLACEHOLDER_ELEMENT]
: undefined;
const compiled = compileToken(subselect, opts, context);
if (compiled === boolbase.falseFunc)
return boolbase.falseFunc;
const hasElement = ensureIsTag(compiled, adapter);
// If `compiled` is `trueFunc`, we can skip this.
if (context && compiled !== boolbase.trueFunc) {
/*
* `shouldTestNextSiblings` will only be true if the query starts with
* a traversal (sibling or adjacent). That means we will always have a context.
*/
const { shouldTestNextSiblings = false } = compiled;
return (elem) => {
if (!next(elem))
return false;
context[0] = elem;
const childs = adapter.getChildren(elem);
const nextElements = shouldTestNextSiblings
? [...childs, ...getNextSiblings(elem, adapter)]
: childs;
return adapter.existsOne(hasElement, nextElements);
};
}
return (elem) => next(elem) &&
adapter.existsOne(hasElement, adapter.getChildren(elem));
},
};
function compilePseudoSelector(next, selector, options, context, compileToken) {
var _a;
const { name, data } = selector;
if (Array.isArray(data)) {
if (!(name in subselects)) {
throw new Error(`Unknown pseudo-class :${name}(${data})`);
}
return subselects[name](next, data, options, context, compileToken);
}
const userPseudo = (_a = options.pseudos) === null || _a === void 0 ? void 0 : _a[name];
const stringPseudo = typeof userPseudo === "string" ? userPseudo : aliases[name];
if (typeof stringPseudo === "string") {
if (data != null) {
throw new Error(`Pseudo ${name} doesn't have any arguments`);
}
// The alias has to be parsed here, to make sure options are respected.
const alias = parse(stringPseudo);
return subselects["is"](next, alias, options, context, compileToken);
}
if (typeof userPseudo === "function") {
verifyPseudoArgs(userPseudo, name, data, 1);
return (elem) => userPseudo(elem, data) && next(elem);
}
if (name in filters) {
return filters[name](next, data, options, context);
}
if (name in pseudos) {
const pseudo = pseudos[name];
verifyPseudoArgs(pseudo, name, data, 2);
return (elem) => pseudo(elem, options, data) && next(elem);
}
throw new Error(`Unknown pseudo-class :${name}`);
}
function getElementParent(node, adapter) {
const parent = adapter.getParent(node);
if (parent && adapter.isTag(parent)) {
return parent;
}
return null;
}
/*
* All available rules
*/
function compileGeneralSelector(next, selector, options, context, compileToken) {
const { adapter, equals } = options;
switch (selector.type) {
case SelectorType.PseudoElement: {
throw new Error("Pseudo-elements are not supported by css-select");
}
case SelectorType.ColumnCombinator: {
throw new Error("Column combinators are not yet supported by css-select");
}
case SelectorType.Attribute: {
if (selector.namespace != null) {
throw new Error("Namespaced attributes are not yet supported by css-select");
}
if (!options.xmlMode || options.lowerCaseAttributeNames) {
selector.name = selector.name.toLowerCase();
}
return attributeRules[selector.action](next, selector, options);
}
case SelectorType.Pseudo: {
return compilePseudoSelector(next, selector, options, context, compileToken);
}
// Tags
case SelectorType.Tag: {
if (selector.namespace != null) {
throw new Error("Namespaced tag names are not yet supported by css-select");
}
let { name } = selector;
if (!options.xmlMode || options.lowerCaseTags) {
name = name.toLowerCase();
}
return function tag(elem) {
return adapter.getName(elem) === name && next(elem);
};
}
// Traversal
case SelectorType.Descendant: {
if (options.cacheResults === false ||
typeof WeakSet === "undefined") {
return function descendant(elem) {
let current = elem;
while ((current = getElementParent(current, adapter))) {
if (next(current)) {
return true;
}
}
return false;
};
}
// @ts-expect-error `ElementNode` is not extending object
const isFalseCache = new WeakSet();
return function cachedDescendant(elem) {
let current = elem;
while ((current = getElementParent(current, adapter))) {
if (!isFalseCache.has(current)) {
if (adapter.isTag(current) && next(current)) {
return true;
}
isFalseCache.add(current);
}
}
return false;
};
}
case "_flexibleDescendant": {
// Include element itself, only used while querying an array
return function flexibleDescendant(elem) {
let current = elem;
do {
if (next(current))
return true;
} while ((current = getElementParent(current, adapter)));
return false;
};
}
case SelectorType.Parent: {
return function parent(elem) {
return adapter
.getChildren(elem)
.some((elem) => adapter.isTag(elem) && next(elem));
};
}
case SelectorType.Child: {
return function child(elem) {
const parent = adapter.getParent(elem);
return parent != null && adapter.isTag(parent) && next(parent);
};
}
case SelectorType.Sibling: {
return function sibling(elem) {
const siblings = adapter.getSiblings(elem);
for (let i = 0; i < siblings.length; i++) {
const currentSibling = siblings[i];
if (equals(elem, currentSibling))
break;
if (adapter.isTag(currentSibling) && next(currentSibling)) {
return true;
}
}
return false;
};
}
case SelectorType.Adjacent: {
if (adapter.prevElementSibling) {
return function adjacent(elem) {
const previous = adapter.prevElementSibling(elem);
return previous != null && next(previous);
};
}
return function adjacent(elem) {
const siblings = adapter.getSiblings(elem);
let lastElement;
for (let i = 0; i < siblings.length; i++) {
const currentSibling = siblings[i];
if (equals(elem, currentSibling))
break;
if (adapter.isTag(currentSibling)) {
lastElement = currentSibling;
}
}
return !!lastElement && next(lastElement);
};
}
case SelectorType.Universal: {
if (selector.namespace != null && selector.namespace !== "*") {
throw new Error("Namespaced universal selectors are not yet supported by css-select");
}
return next;
}
}
}
function includesScopePseudo(t) {
return (t.type === SelectorType.Pseudo &&
(t.name === "scope" ||
(Array.isArray(t.data) &&
t.data.some((data) => data.some(includesScopePseudo)))));
}
const DESCENDANT_TOKEN = { type: SelectorType.Descendant };
const FLEXIBLE_DESCENDANT_TOKEN = {
type: "_flexibleDescendant",
};
const SCOPE_TOKEN = {
type: SelectorType.Pseudo,
name: "scope",
data: null,
};
/*
* CSS 4 Spec (Draft): 3.4.1. Absolutizing a Relative Selector
* http://www.w3.org/TR/selectors4/#absolutizing
*/
function absolutize(token, { adapter }, context) {
// TODO Use better check if the context is a document
const hasContext = !!(context === null || context === void 0 ? void 0 : context.every((e) => {
const parent = adapter.isTag(e) && adapter.getParent(e);
return e === PLACEHOLDER_ELEMENT || (parent && adapter.isTag(parent));
}));
for (const t of token) {
if (t.length > 0 &&
isTraversal$1(t[0]) &&
t[0].type !== SelectorType.Descendant) ;
else if (hasContext && !t.some(includesScopePseudo)) {
t.unshift(DESCENDANT_TOKEN);
}
else {
continue;
}
t.unshift(SCOPE_TOKEN);
}
}
function compileToken(token, options, context) {
var _a;
token.forEach(sortByProcedure);
context = (_a = options.context) !== null && _a !== void 0 ? _a : context;
const isArrayContext = Array.isArray(context);
const finalContext = context && (Array.isArray(context) ? context : [context]);
// Check if the selector is relative
if (options.relativeSelector !== false) {
absolutize(token, options, finalContext);
}
else if (token.some((t) => t.length > 0 && isTraversal$1(t[0]))) {
throw new Error("Relative selectors are not allowed when the `relativeSelector` option is disabled");
}
let shouldTestNextSiblings = false;
const query = token
.map((rules) => {
if (rules.length >= 2) {
const [first, second] = rules;
if (first.type !== SelectorType.Pseudo ||
first.name !== "scope") ;
else if (isArrayContext &&
second.type === SelectorType.Descendant) {
rules[1] = FLEXIBLE_DESCENDANT_TOKEN;
}
else if (second.type === SelectorType.Adjacent ||
second.type === SelectorType.Sibling) {
shouldTestNextSiblings = true;
}
}
return compileRules(rules, options, finalContext);
})
.reduce(reduceRules, boolbase.falseFunc);
query.shouldTestNextSiblings = shouldTestNextSiblings;
return query;
}
function compileRules(rules, options, context) {
var _a;
return rules.reduce((previous, rule) => previous === boolbase.falseFunc
? boolbase.falseFunc
: compileGeneralSelector(previous, rule, options, context, compileToken), (_a = options.rootFunc) !== null && _a !== void 0 ? _a : boolbase.trueFunc);
}
function reduceRules(a, b) {
if (b === boolbase.falseFunc || a === boolbase.trueFunc) {
return a;
}
if (a === boolbase.falseFunc || b === boolbase.trueFunc) {
return b;
}
return function combine(elem) {
return a(elem) || b(elem);
};
}
const defaultEquals = (a, b) => a === b;
const defaultOptions$1 = {
adapter: DomUtils,
equals: defaultEquals,
};
function convertOptionFormats(options) {
var _a, _b, _c, _d;
/*
* We force one format of options to the other one.
*/
// @ts-expect-error Default options may have incompatible `Node` / `ElementNode`.
const opts = options !== null && options !== void 0 ? options : defaultOptions$1;
// @ts-expect-error Same as above.
(_a = opts.adapter) !== null && _a !== void 0 ? _a : (opts.adapter = DomUtils);
// @ts-expect-error `equals` does not exist on `Options`
(_b = opts.equals) !== null && _b !== void 0 ? _b : (opts.equals = (_d = (_c = opts.adapter) === null || _c === void 0 ? void 0 : _c.equals) !== null && _d !== void 0 ? _d : defaultEquals);
return opts;
}
function wrapCompile(func) {
return function addAdapter(selector, options, context) {
const opts = convertOptionFormats(options);
return func(selector, opts, context);
};
}
const _compileToken = wrapCompile(compileToken);
function prepareContext(elems, adapter, shouldTestNextSiblings = false) {
/*
* Add siblings if the query requires them.
* See https://github.com/fb55/css-select/pull/43#issuecomment-225414692
*/
if (shouldTestNextSiblings) {
elems = appendNextSiblings(elems, adapter);
}
return Array.isArray(elems)
? adapter.removeSubsets(elems)
: adapter.getChildren(elems);
}
function appendNextSiblings(elem, adapter) {
// Order matters because jQuery seems to check the children before the siblings
const elems = Array.isArray(elem) ? elem.slice(0) : [elem];
const elemsLength = elems.length;
for (let i = 0; i < elemsLength; i++) {
const nextSiblings = getNextSiblings(elems[i], adapter);
elems.push(...nextSiblings);
}
return elems;
}
const filterNames = new Set([
"first",
"last",
"eq",
"gt",
"nth",
"lt",
"even",
"odd",
]);
function isFilter(s) {
if (s.type !== "pseudo")
return false;
if (filterNames.has(s.name))
return true;
if (s.name === "not" && Array.isArray(s.data)) {
// Only consider `:not` with embedded filters
return s.data.some((s) => s.some(isFilter));
}
return false;
}
function getLimit(filter, data, partLimit) {
const num = data != null ? parseInt(data, 10) : NaN;
switch (filter) {
case "first":
return 1;
case "nth":
case "eq":
return isFinite(num) ? (num >= 0 ? num + 1 : Infinity) : 0;
case "lt":
return isFinite(num)
? num >= 0
? Math.min(num, partLimit)
: Infinity
: 0;
case "gt":
return isFinite(num) ? Infinity : 0;
case "odd":
return 2 * partLimit;
case "even":
return 2 * partLimit - 1;
case "last":
case "not":
return Infinity;
}
}
function getDocumentRoot(node) {
while (node.parent)
node = node.parent;
return node;
}
function groupSelectors(selectors) {
const filteredSelectors = [];
const plainSelectors = [];
for (const selector of selectors) {
if (selector.some(isFilter)) {
filteredSelectors.push(selector);
}
else {
plainSelectors.push(selector);
}
}
return [plainSelectors, filteredSelectors];
}
const UNIVERSAL_SELECTOR = {
type: SelectorType.Universal,
namespace: null,
};
const SCOPE_PSEUDO = {
type: SelectorType.Pseudo,
name: "scope",
data: null,
};
function is$1(element, selector, options = {}) {
return some$4([element], selector, options);
}
function some$4(elements, selector, options = {}) {
if (typeof selector === "function")
return elements.some(selector);
const [plain, filtered] = groupSelectors(parse(selector));
return ((plain.length > 0 && elements.some(_compileToken(plain, options))) ||
filtered.some((sel) => filterBySelector(sel, elements, options).length > 0));
}
function filterByPosition(filter, elems, data, options) {
const num = typeof data === "string" ? parseInt(data, 10) : NaN;
switch (filter) {
case "first":
case "lt":
// Already done in `getLimit`
return elems;
case "last":
return elems.length > 0 ? [elems[elems.length - 1]] : elems;
case "nth":
case "eq":
return isFinite(num) && Math.abs(num) < elems.length
? [num < 0 ? elems[elems.length + num] : elems[num]]
: [];
case "gt":
return isFinite(num) ? elems.slice(num + 1) : [];
case "even":
return elems.filter((_, i) => i % 2 === 0);
case "odd":
return elems.filter((_, i) => i % 2 === 1);
case "not": {
const filtered = new Set(filterParsed(data, elems, options));
return elems.filter((e) => !filtered.has(e));
}
}
}
function filter$5(selector, elements, options = {}) {
return filterParsed(parse(selector), elements, options);
}
/**
* Filter a set of elements by a selector.
*
* Will return elements in the original order.
*
* @param selector Selector to filter by.
* @param elements Elements to filter.
* @param options Options for selector.
*/
function filterParsed(selector, elements, options) {
if (elements.length === 0)
return [];
const [plainSelectors, filteredSelectors] = groupSelectors(selector);
let found;
if (plainSelectors.length) {
const filtered = filterElements(elements, plainSelectors, options);
// If there are no filters, just return
if (filteredSelectors.length === 0) {
return filtered;
}
// Otherwise, we have to do some filtering
if (filtered.length) {
found = new Set(filtered);
}
}
for (let i = 0; i < filteredSelectors.length && (found === null || found === void 0 ? void 0 : found.size) !== elements.length; i++) {
const filteredSelector = filteredSelectors[i];
const missing = found
? elements.filter((e) => isTag$1(e) && !found.has(e))
: elements;
if (missing.length === 0)
break;
const filtered = filterBySelector(filteredSelector, elements, options);
if (filtered.length) {
if (!found) {
/*
* If we haven't found anything before the last selector,
* just return what we found now.
*/
if (i === filteredSelectors.length - 1) {
return filtered;
}
found = new Set(filtered);
}
else {
filtered.forEach((el) => found.add(el));
}
}
}
return typeof found !== "undefined"
? (found.size === elements.length
? elements
: // Filter elements to preserve order
elements.filter((el) => found.has(el)))
: [];
}
function filterBySelector(selector, elements, options) {
var _a;
if (selector.some(isTraversal)) {
/*
* Get root node, run selector with the scope
* set to all of our nodes.
*/
const root = (_a = options.root) !== null && _a !== void 0 ? _a : getDocumentRoot(elements[0]);
const opts = { ...options, context: elements, relativeSelector: false };
selector.push(SCOPE_PSEUDO);
return findFilterElements(root, selector, opts, true, elements.length);
}
// Performance optimization: If we don't have to traverse, just filter set.
return findFilterElements(elements, selector, options, false, elements.length);
}
function select(selector, root, options = {}, limit = Infinity) {
if (typeof selector === "function") {
return find$6(root, selector);
}
const [plain, filtered] = groupSelectors(parse(selector));
const results = filtered.map((sel) => findFilterElements(root, sel, options, true, limit));
// Plain selectors can be queried in a single go
if (plain.length) {
results.push(findElements(root, plain, options, limit));
}
if (results.length === 0) {
return [];
}
// If there was only a single selector, just return the result
if (results.length === 1) {
return results[0];
}
// Sort results, filtering for duplicates
return uniqueSort(results.reduce((a, b) => [...a, ...b]));
}
/**
*
* @param root Element(s) to search from.
* @param selector Selector to look for.
* @param options Options for querying.
* @param queryForSelector Query multiple levels deep for the initial selector, even if it doesn't contain a traversal.
*/
function findFilterElements(root, selector, options, queryForSelector, totalLimit) {
const filterIndex = selector.findIndex(isFilter);
const sub = selector.slice(0, filterIndex);
const filter = selector[filterIndex];
// If we are at the end of the selector, we can limit the number of elements to retrieve.
const partLimit = selector.length - 1 === filterIndex ? totalLimit : Infinity;
/*
* Set the number of elements to retrieve.
* Eg. for :first, we only have to get a single element.
*/
const limit = getLimit(filter.name, filter.data, partLimit);
if (limit === 0)
return [];
/*
* Skip `findElements` call if our selector starts with a positional
* pseudo.
*/
const elemsNoLimit = sub.length === 0 && !Array.isArray(root)
? getChildren(root).filter(isTag$1)
: sub.length === 0
? (Array.isArray(root) ? root : [root]).filter(isTag$1)
: queryForSelector || sub.some(isTraversal)
? findElements(root, [sub], options, limit)
: filterElements(root, [sub], options);
const elems = elemsNoLimit.slice(0, limit);
let result = filterByPosition(filter.name, elems, filter.data, options);
if (result.length === 0 || selector.length === filterIndex + 1) {
return result;
}
const remainingSelector = selector.slice(filterIndex + 1);
const remainingHasTraversal = remainingSelector.some(isTraversal);
if (remainingHasTraversal) {
if (isTraversal(remainingSelector[0])) {
const { type } = remainingSelector[0];
if (type === SelectorType.Sibling ||
type === SelectorType.Adjacent) {
// If we have a sibling traversal, we need to also look at the siblings.
result = prepareContext(result, DomUtils, true);
}
// Avoid a traversal-first selector error.
remainingSelector.unshift(UNIVERSAL_SELECTOR);
}
options = {
...options,
// Avoid absolutizing the selector
relativeSelector: false,
/*
* Add a custom root func, to make sure traversals don't match elements
* that aren't a part of the considered tree.
*/
rootFunc: (el) => result.includes(el),
};
}
else if (options.rootFunc && options.rootFunc !== boolbase_1) {
options = { ...options, rootFunc: boolbase_1 };
}
/*
* If we have another filter, recursively call `findFilterElements`,
* with the `recursive` flag disabled. We only have to look for more
* elements when we see a traversal.
*
* Otherwise,
*/
return remainingSelector.some(isFilter)
? findFilterElements(result, remainingSelector, options, false, totalLimit)
: remainingHasTraversal
? // Query existing elements to resolve traversal.
findElements(result, [remainingSelector], options, totalLimit)
: // If we don't have any more traversals, simply filter elements.
filterElements(result, [remainingSelector], options);
}
function findElements(root, sel, options, limit) {
const query = _compileToken(sel, options, root);
return find$6(root, query, limit);
}
function find$6(root, query, limit = Infinity) {
const elems = prepareContext(root, DomUtils, query.shouldTestNextSiblings);
return find$5((node) => isTag$1(node) && query(node), elems, true, limit);
}
function filterElements(elements, sel, options) {
const els = (Array.isArray(elements) ? elements : [elements]).filter(isTag$1);
if (els.length === 0)
return els;
const query = _compileToken(sel, options);
return query === boolbase_1 ? els : els.filter(query);
}
/**
* Methods for traversing the DOM structure.
*
* @module cheerio/traversing
*/
const reSiblingSelector = /^\s*[~+]/;
/**
* Get the descendants of each element in the current set of matched elements,
* filtered by a selector, jQuery object, or element.
*
* @category Traversing
* @example
*
* ```js
* $('#fruits').find('li').length;
* //=> 3
* $('#fruits').find($('.apple')).length;
* //=> 1
* ```
*
* @param selectorOrHaystack - Element to look for.
* @returns The found elements.
* @see {@link https://api.jquery.com/find/}
*/
function find$7(selectorOrHaystack) {
var _a;
if (!selectorOrHaystack) {
return this._make([]);
}
const context = this.toArray();
if (typeof selectorOrHaystack !== 'string') {
const haystack = isCheerio(selectorOrHaystack)
? selectorOrHaystack.toArray()
: [selectorOrHaystack];
return this._make(haystack.filter((elem) => context.some((node) => contains(node, elem))));
}
const elems = reSiblingSelector.test(selectorOrHaystack)
? context
: this.children().toArray();
const options = {
context,
root: (_a = this._root) === null || _a === void 0 ? void 0 : _a[0],
// Pass options that are recognized by `cheerio-select`
xmlMode: this.options.xmlMode,
lowerCaseTags: this.options.lowerCaseTags,
lowerCaseAttributeNames: this.options.lowerCaseAttributeNames,
pseudos: this.options.pseudos,
quirksMode: this.options.quirksMode,
};
return this._make(select(selectorOrHaystack, elems, options));
}
/**
* Creates a matcher, using a particular mapping function. Matchers provide a
* function that finds elements using a generating function, supporting filtering.
*
* @private
* @param matchMap - Mapping function.
* @returns - Function for wrapping generating functions.
*/
function _getMatcher(matchMap) {
return function (fn, ...postFns) {
return function (selector) {
var _a;
let matched = matchMap(fn, this);
if (selector) {
matched = filterArray(matched, selector, this.options.xmlMode, (_a = this._root) === null || _a === void 0 ? void 0 : _a[0]);
}
return this._make(
// Post processing is only necessary if there is more than one element.
this.length > 1 && matched.length > 1
? postFns.reduce((elems, fn) => fn(elems), matched)
: matched);
};
};
}
/** Matcher that adds multiple elements for each entry in the input. */
const _matcher = _getMatcher((fn, elems) => {
const ret = [];
for (let i = 0; i < elems.length; i++) {
const value = fn(elems[i]);
ret.push(value);
}
return new Array().concat(...ret);
});
/** Matcher that adds at most one element for each entry in the input. */
const _singleMatcher = _getMatcher((fn, elems) => {
const ret = [];
for (let i = 0; i < elems.length; i++) {
const value = fn(elems[i]);
if (value !== null) {
ret.push(value);
}
}
return ret;
});
/**
* Matcher that supports traversing until a condition is met.
*
* @returns A function usable for `*Until` methods.
*/
function _matchUntil(nextElem, ...postFns) {
// We use a variable here that is used from within the matcher.
let matches = null;
const innerMatcher = _getMatcher((nextElem, elems) => {
const matched = [];
domEach(elems, (elem) => {
for (let next; (next = nextElem(elem)); elem = next) {
// FIXME: `matched` might contain duplicates here and the index is too large.
if (matches === null || matches === void 0 ? void 0 : matches(next, matched.length))
break;
matched.push(next);
}
});
return matched;
})(nextElem, ...postFns);
return function (selector, filterSelector) {
// Override `matches` variable with the new target.
matches =
typeof selector === 'string'
? (elem) => is$1(elem, selector, this.options)
: selector
? getFilterFn(selector)
: null;
const ret = innerMatcher.call(this, filterSelector);
// Set `matches` to `null`, so we don't waste memory.
matches = null;
return ret;
};
}
function _removeDuplicates(elems) {
return Array.from(new Set(elems));
}
/**
* Get the parent of each element in the current set of matched elements,
* optionally filtered by a selector.
*
* @category Traversing
* @example
*
* ```js
* $('.pear').parent().attr('id');
* //=> fruits
* ```
*
* @param selector - If specified filter for parent.
* @returns The parents.
* @see {@link https://api.jquery.com/parent/}
*/
const parent = _singleMatcher(({ parent }) => (parent && !isDocument(parent) ? parent : null), _removeDuplicates);
/**
* Get a set of parents filtered by `selector` of each element in the current
* set of match elements.
*
* @category Traversing
* @example
*
* ```js
* $('.orange').parents().length;
* //=> 2
* $('.orange').parents('#fruits').length;
* //=> 1
* ```
*
* @param selector - If specified filter for parents.
* @returns The parents.
* @see {@link https://api.jquery.com/parents/}
*/
const parents = _matcher((elem) => {
const matched = [];
while (elem.parent && !isDocument(elem.parent)) {
matched.push(elem.parent);
elem = elem.parent;
}
return matched;
}, uniqueSort, (elems) => elems.reverse());
/**
* Get the ancestors of each element in the current set of matched elements, up
* to but not including the element matched by the selector, DOM node, or cheerio object.
*
* @category Traversing
* @example
*
* ```js
* $('.orange').parentsUntil('#food').length;
* //=> 1
* ```
*
* @param selector - Selector for element to stop at.
* @param filterSelector - Optional filter for parents.
* @returns The parents.
* @see {@link https://api.jquery.com/parentsUntil/}
*/
const parentsUntil = _matchUntil(({ parent }) => (parent && !isDocument(parent) ? parent : null), uniqueSort, (elems) => elems.reverse());
/**
* For each element in the set, get the first element that matches the selector
* by testing the element itself and traversing up through its ancestors in the DOM tree.
*
* @category Traversing
* @example
*
* ```js
* $('.orange').closest();
* //=> []
*
* $('.orange').closest('.apple');
* // => []
*
* $('.orange').closest('li');
* //=> [<li class="orange">Orange</li>]
*
* $('.orange').closest('#fruits');
* //=> [<ul id="fruits"> ... </ul>]
* ```
*
* @param selector - Selector for the element to find.
* @returns The closest nodes.
* @see {@link https://api.jquery.com/closest/}
*/
function closest(selector) {
var _a;
const set = [];
if (!selector) {
return this._make(set);
}
const selectOpts = {
xmlMode: this.options.xmlMode,
root: (_a = this._root) === null || _a === void 0 ? void 0 : _a[0],
};
const selectFn = typeof selector === 'string'
? (elem) => is$1(elem, selector, selectOpts)
: getFilterFn(selector);
domEach(this, (elem) => {
while (elem && isTag$1(elem)) {
if (selectFn(elem, 0)) {
// Do not add duplicate elements to the set
if (!set.includes(elem)) {
set.push(elem);
}
break;
}
elem = elem.parent;
}
});
return this._make(set);
}
/**
* Gets the next sibling of the first selected element, optionally filtered by a selector.
*
* @category Traversing
* @example
*
* ```js
* $('.apple').next().hasClass('orange');
* //=> true
* ```
*
* @param selector - If specified filter for sibling.
* @returns The next nodes.
* @see {@link https://api.jquery.com/next/}
*/
const next = _singleMatcher((elem) => nextElementSibling(elem));
/**
* Gets all the following siblings of the first selected element, optionally
* filtered by a selector.
*
* @category Traversing
* @example
*
* ```js
* $('.apple').nextAll();
* //=> [<li class="orange">Orange</li>, <li class="pear">Pear</li>]
* $('.apple').nextAll('.orange');
* //=> [<li class="orange">Orange</li>]
* ```
*
* @param selector - If specified filter for siblings.
* @returns The next nodes.
* @see {@link https://api.jquery.com/nextAll/}
*/
const nextAll = _matcher((elem) => {
const matched = [];
while (elem.next) {
elem = elem.next;
if (isTag$1(elem))
matched.push(elem);
}
return matched;
}, _removeDuplicates);
/**
* Gets all the following siblings up to but not including the element matched
* by the selector, optionally filtered by another selector.
*
* @category Traversing
* @example
*
* ```js
* $('.apple').nextUntil('.pear');
* //=> [<li class="orange">Orange</li>]
* ```
*
* @param selector - Selector for element to stop at.
* @param filterSelector - If specified filter for siblings.
* @returns The next nodes.
* @see {@link https://api.jquery.com/nextUntil/}
*/
const nextUntil = _matchUntil((el) => nextElementSibling(el), _removeDuplicates);
/**
* Gets the previous sibling of the first selected element optionally filtered
* by a selector.
*
* @category Traversing
* @example
*
* ```js
* $('.orange').prev().hasClass('apple');
* //=> true
* ```
*
* @param selector - If specified filter for siblings.
* @returns The previous nodes.
* @see {@link https://api.jquery.com/prev/}
*/
const prev = _singleMatcher((elem) => prevElementSibling(elem));
/**
* Gets all the preceding siblings of the first selected element, optionally
* filtered by a selector.
*
* @category Traversing
* @example
*
* ```js
* $('.pear').prevAll();
* //=> [<li class="orange">Orange</li>, <li class="apple">Apple</li>]
*
* $('.pear').prevAll('.orange');
* //=> [<li class="orange">Orange</li>]
* ```
*
* @param selector - If specified filter for siblings.
* @returns The previous nodes.
* @see {@link https://api.jquery.com/prevAll/}
*/
const prevAll = _matcher((elem) => {
const matched = [];
while (elem.prev) {
elem = elem.prev;
if (isTag$1(elem))
matched.push(elem);
}
return matched;
}, _removeDuplicates);
/**
* Gets all the preceding siblings up to but not including the element matched
* by the selector, optionally filtered by another selector.
*
* @category Traversing
* @example
*
* ```js
* $('.pear').prevUntil('.apple');
* //=> [<li class="orange">Orange</li>]
* ```
*
* @param selector - Selector for element to stop at.
* @param filterSelector - If specified filter for siblings.
* @returns The previous nodes.
* @see {@link https://api.jquery.com/prevUntil/}
*/
const prevUntil = _matchUntil((el) => prevElementSibling(el), _removeDuplicates);
/**
* Get the siblings of each element (excluding the element) in the set of
* matched elements, optionally filtered by a selector.
*
* @category Traversing
* @example
*
* ```js
* $('.pear').siblings().length;
* //=> 2
*
* $('.pear').siblings('.orange').length;
* //=> 1
* ```
*
* @param selector - If specified filter for siblings.
* @returns The siblings.
* @see {@link https://api.jquery.com/siblings/}
*/
const siblings = _matcher((elem) => getSiblings(elem).filter((el) => isTag$1(el) && el !== elem), uniqueSort);
/**
* Gets the element children of each element in the set of matched elements.
*
* @category Traversing
* @example
*
* ```js
* $('#fruits').children().length;
* //=> 3
*
* $('#fruits').children('.pear').text();
* //=> Pear
* ```
*
* @param selector - If specified filter for children.
* @returns The children.
* @see {@link https://api.jquery.com/children/}
*/
const children = _matcher((elem) => getChildren(elem).filter(isTag$1), _removeDuplicates);
/**
* Gets the children of each element in the set of matched elements, including
* text and comment nodes.
*
* @category Traversing
* @example
*
* ```js
* $('#fruits').contents().length;
* //=> 3
* ```
*
* @returns The children.
* @see {@link https://api.jquery.com/contents/}
*/
function contents() {
const elems = this.toArray().reduce((newElems, elem) => hasChildren(elem) ? newElems.concat(elem.children) : newElems, []);
return this._make(elems);
}
/**
* Iterates over a cheerio object, executing a function for each matched
* element. When the callback is fired, the function is fired in the context of
* the DOM element, so `this` refers to the current element, which is equivalent
* to the function parameter `element`. To break out of the `each` loop early,
* return with `false`.
*
* @category Traversing
* @example
*
* ```js
* const fruits = [];
*
* $('li').each(function (i, elem) {
* fruits[i] = $(this).text();
* });
*
* fruits.join(', ');
* //=> Apple, Orange, Pear
* ```
*
* @param fn - Function to execute.
* @returns The instance itself, useful for chaining.
* @see {@link https://api.jquery.com/each/}
*/
function each(fn) {
let i = 0;
const len = this.length;
while (i < len && fn.call(this[i], i, this[i]) !== false)
++i;
return this;
}
/**
* Pass each element in the current matched set through a function, producing a
* new Cheerio object containing the return values. The function can return an
* individual data item or an array of data items to be inserted into the
* resulting set. If an array is returned, the elements inside the array are
* inserted into the set. If the function returns null or undefined, no element
* will be inserted.
*
* @category Traversing
* @example
*
* ```js
* $('li')
* .map(function (i, el) {
* // this === el
* return $(this).text();
* })
* .toArray()
* .join(' ');
* //=> "apple orange pear"
* ```
*
* @param fn - Function to execute.
* @returns The mapped elements, wrapped in a Cheerio collection.
* @see {@link https://api.jquery.com/map/}
*/
function map$a(fn) {
let elems = [];
for (let i = 0; i < this.length; i++) {
const el = this[i];
const val = fn.call(el, i, el);
if (val != null) {
elems = elems.concat(val);
}
}
return this._make(elems);
}
/**
* Creates a function to test if a filter is matched.
*
* @param match - A filter.
* @returns A function that determines if a filter has been matched.
*/
function getFilterFn(match) {
if (typeof match === 'function') {
return (el, i) => match.call(el, i, el);
}
if (isCheerio(match)) {
return (el) => Array.prototype.includes.call(match, el);
}
return function (el) {
return match === el;
};
}
function filter$6(match) {
var _a;
return this._make(filterArray(this.toArray(), match, this.options.xmlMode, (_a = this._root) === null || _a === void 0 ? void 0 : _a[0]));
}
function filterArray(nodes, match, xmlMode, root) {
return typeof match === 'string'
? filter$5(match, nodes, { xmlMode, root })
: nodes.filter(getFilterFn(match));
}
/**
* Checks the current list of elements and returns `true` if _any_ of the
* elements match the selector. If using an element or Cheerio selection,
* returns `true` if _any_ of the elements match. If using a predicate function,
* the function is executed in the context of the selected element, so `this`
* refers to the current element.
*
* @category Attributes
* @param selector - Selector for the selection.
* @returns Whether or not the selector matches an element of the instance.
* @see {@link https://api.jquery.com/is/}
*/
function is$2(selector) {
const nodes = this.toArray();
return typeof selector === 'string'
? some$4(nodes.filter(isTag$1), selector, this.options)
: selector
? nodes.some(getFilterFn(selector))
: false;
}
/**
* Remove elements from the set of matched elements. Given a Cheerio object that
* represents a set of DOM elements, the `.not()` method constructs a new
* Cheerio object from a subset of the matching elements. The supplied selector
* is tested against each element; the elements that don't match the selector
* will be included in the result.
*
* The `.not()` method can take a function as its argument in the same way that
* `.filter()` does. Elements for which the function returns `true` are excluded
* from the filtered set; all other elements are included.
*
* @category Traversing
* @example <caption>Selector</caption>
*
* ```js
* $('li').not('.apple').length;
* //=> 2
* ```
*
* @example <caption>Function</caption>
*
* ```js
* $('li').not(function (i, el) {
* // this === el
* return $(this).attr('class') === 'orange';
* }).length; //=> 2
* ```
*
* @param match - Value to look for, following the rules above.
* @param container - Optional node to filter instead.
* @returns The filtered collection.
* @see {@link https://api.jquery.com/not/}
*/
function not(match) {
let nodes = this.toArray();
if (typeof match === 'string') {
const matches = new Set(filter$5(match, nodes, this.options));
nodes = nodes.filter((el) => !matches.has(el));
}
else {
const filterFn = getFilterFn(match);
nodes = nodes.filter((el, i) => !filterFn(el, i));
}
return this._make(nodes);
}
/**
* Filters the set of matched elements to only those which have the given DOM
* element as a descendant or which have a descendant that matches the given
* selector. Equivalent to `.filter(':has(selector)')`.
*
* @category Traversing
* @example <caption>Selector</caption>
*
* ```js
* $('ul').has('.pear').attr('id');
* //=> fruits
* ```
*
* @example <caption>Element</caption>
*
* ```js
* $('ul').has($('.pear')[0]).attr('id');
* //=> fruits
* ```
*
* @param selectorOrHaystack - Element to look for.
* @returns The filtered collection.
* @see {@link https://api.jquery.com/has/}
*/
function has$1(selectorOrHaystack) {
return this.filter(typeof selectorOrHaystack === 'string'
? // Using the `:has` selector here short-circuits searches.
`:has(${selectorOrHaystack})`
: (_, el) => this._make(el).find(selectorOrHaystack).length > 0);
}
/**
* Will select the first element of a cheerio object.
*
* @category Traversing
* @example
*
* ```js
* $('#fruits').children().first().text();
* //=> Apple
* ```
*
* @returns The first element.
* @see {@link https://api.jquery.com/first/}
*/
function first() {
return this.length > 1 ? this._make(this[0]) : this;
}
/**
* Will select the last element of a cheerio object.
*
* @category Traversing
* @example
*
* ```js
* $('#fruits').children().last().text();
* //=> Pear
* ```
*
* @returns The last element.
* @see {@link https://api.jquery.com/last/}
*/
function last$1() {
return this.length > 0 ? this._make(this[this.length - 1]) : this;
}
/**
* Reduce the set of matched elements to the one at the specified index. Use
* `.eq(-i)` to count backwards from the last selected element.
*
* @category Traversing
* @example
*
* ```js
* $('li').eq(0).text();
* //=> Apple
*
* $('li').eq(-1).text();
* //=> Pear
* ```
*
* @param i - Index of the element to select.
* @returns The element at the `i`th position.
* @see {@link https://api.jquery.com/eq/}
*/
function eq$1(i) {
var _a;
i = +i;
// Use the first identity optimization if possible
if (i === 0 && this.length <= 1)
return this;
if (i < 0)
i = this.length + i;
return this._make((_a = this[i]) !== null && _a !== void 0 ? _a : []);
}
function get$9(i) {
if (i == null) {
return this.toArray();
}
return this[i < 0 ? this.length + i : i];
}
/**
* Retrieve all the DOM elements contained in the jQuery set as an array.
*
* @example
*
* ```js
* $('li').toArray();
* //=> [ {...}, {...}, {...} ]
* ```
*
* @returns The contained items.
*/
function toArray$1() {
return Array.prototype.slice.call(this);
}
/**
* Search for a given element from among the matched elements.
*
* @category Traversing
* @example
*
* ```js
* $('.pear').index();
* //=> 2 $('.orange').index('li');
* //=> 1
* $('.apple').index($('#fruit, li'));
* //=> 1
* ```
*
* @param selectorOrNeedle - Element to look for.
* @returns The index of the element.
* @see {@link https://api.jquery.com/index/}
*/
function index(selectorOrNeedle) {
let $haystack;
let needle;
if (selectorOrNeedle == null) {
$haystack = this.parent().children();
needle = this[0];
}
else if (typeof selectorOrNeedle === 'string') {
$haystack = this._make(selectorOrNeedle);
needle = this[0];
}
else {
// eslint-disable-next-line @typescript-eslint/no-this-alias
$haystack = this;
needle = isCheerio(selectorOrNeedle)
? selectorOrNeedle[0]
: selectorOrNeedle;
}
return Array.prototype.indexOf.call($haystack, needle);
}
/**
* Gets the elements matching the specified range (0-based position).
*
* @category Traversing
* @example
*
* ```js
* $('li').slice(1).eq(0).text();
* //=> 'Orange'
*
* $('li').slice(1, 2).length;
* //=> 1
* ```
*
* @param start - An position at which the elements begin to be selected. If
* negative, it indicates an offset from the end of the set.
* @param end - An position at which the elements stop being selected. If
* negative, it indicates an offset from the end of the set. If omitted, the
* range continues until the end of the set.
* @returns The elements matching the specified range.
* @see {@link https://api.jquery.com/slice/}
*/
function slice$8(start, end) {
return this._make(Array.prototype.slice.call(this, start, end));
}
/**
* End the most recent filtering operation in the current chain and return the
* set of matched elements to its previous state.
*
* @category Traversing
* @example
*
* ```js
* $('li').eq(0).end().length;
* //=> 3
* ```
*
* @returns The previous state of the set of matched elements.
* @see {@link https://api.jquery.com/end/}
*/
function end() {
var _a;
return (_a = this.prevObject) !== null && _a !== void 0 ? _a : this._make([]);
}
/**
* Add elements to the set of matched elements.
*
* @category Traversing
* @example
*
* ```js
* $('.apple').add('.orange').length;
* //=> 2
* ```
*
* @param other - Elements to add.
* @param context - Optionally the context of the new selection.
* @returns The combined set.
* @see {@link https://api.jquery.com/add/}
*/
function add(other, context) {
const selection = this._make(other, context);
const contents = uniqueSort([...this.get(), ...selection.get()]);
return this._make(contents);
}
/**
* Add the previous set of elements on the stack to the current set, optionally
* filtered by a selector.
*
* @category Traversing
* @example
*
* ```js
* $('li').eq(0).addBack('.orange').length;
* //=> 2
* ```
*
* @param selector - Selector for the elements to add.
* @returns The combined set.
* @see {@link https://api.jquery.com/addBack/}
*/
function addBack(selector) {
return this.prevObject
? this.add(selector ? this.prevObject.filter(selector) : this.prevObject)
: this;
}
var Traversing = /*#__PURE__*/Object.freeze({
__proto__: null,
find: find$7,
parent: parent,
parents: parents,
parentsUntil: parentsUntil,
closest: closest,
next: next,
nextAll: nextAll,
nextUntil: nextUntil,
prev: prev,
prevAll: prevAll,
prevUntil: prevUntil,
siblings: siblings,
children: children,
contents: contents,
each: each,
map: map$a,
filter: filter$6,
filterArray: filterArray,
is: is$2,
not: not,
has: has$1,
first: first,
last: last$1,
eq: eq$1,
get: get$9,
toArray: toArray$1,
index: index,
slice: slice$8,
end: end,
add: add,
addBack: addBack
});
/**
* Get the parse function with options.
*
* @param parser - The parser function.
* @returns The parse function with options.
*/
function getParse(parser) {
/**
* Parse a HTML string or a node.
*
* @param content - The HTML string or node.
* @param options - The parser options.
* @param isDocument - If `content` is a document.
* @param context - The context node in the DOM tree.
* @returns The parsed document node.
*/
return function parse(content, options, isDocument$1, context) {
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(content)) {
content = content.toString();
}
if (typeof content === 'string') {
return parser(content, options, isDocument$1, context);
}
const doc = content;
if (!Array.isArray(doc) && isDocument(doc)) {
// If `doc` is already a root, just return it
return doc;
}
// Add conent to new root element
const root = new Document([]);
// Update the DOM using the root
update(doc, root);
return root;
};
}
/**
* Update the dom structure, for one changed layer.
*
* @param newChilds - The new children.
* @param parent - The new parent.
* @returns The parent node.
*/
function update(newChilds, parent) {
// Normalize
const arr = Array.isArray(newChilds) ? newChilds : [newChilds];
// Update parent
if (parent) {
parent.children = arr;
}
else {
parent = null;
}
// Update neighbors
for (let i = 0; i < arr.length; i++) {
const node = arr[i];
// Cleanly remove existing nodes from their previous structures.
if (node.parent && node.parent.children !== arr) {
removeElement(node);
}
if (parent) {
node.prev = arr[i - 1] || null;
node.next = arr[i + 1] || null;
}
else {
node.prev = node.next = null;
}
node.parent = parent;
}
return parent;
}
/**
* Methods for modifying the DOM structure.
*
* @module cheerio/manipulation
*/
/**
* Create an array of nodes, recursing into arrays and parsing strings if necessary.
*
* @private
* @category Manipulation
* @param elem - Elements to make an array of.
* @param clone - Optionally clone nodes.
* @returns The array of nodes.
*/
function _makeDomArray(elem, clone) {
if (elem == null) {
return [];
}
if (isCheerio(elem)) {
return clone ? cloneDom(elem.get()) : elem.get();
}
if (Array.isArray(elem)) {
return elem.reduce((newElems, el) => newElems.concat(this._makeDomArray(el, clone)), []);
}
if (typeof elem === 'string') {
return this._parse(elem, this.options, false, null).children;
}
return clone ? cloneDom([elem]) : [elem];
}
function _insert(concatenator) {
return function (...elems) {
const lastIdx = this.length - 1;
return domEach(this, (el, i) => {
if (!hasChildren(el))
return;
const domSrc = typeof elems[0] === 'function'
? elems[0].call(el, i, this._render(el.children))
: elems;
const dom = this._makeDomArray(domSrc, i < lastIdx);
concatenator(dom, el.children, el);
});
};
}
/**
* Modify an array in-place, removing some number of elements and adding new
* elements directly following them.
*
* @private
* @category Manipulation
* @param array - Target array to splice.
* @param spliceIdx - Index at which to begin changing the array.
* @param spliceCount - Number of elements to remove from the array.
* @param newElems - Elements to insert into the array.
* @param parent - The parent of the node.
* @returns The spliced array.
*/
function uniqueSplice(array, spliceIdx, spliceCount, newElems, parent) {
var _a, _b;
const spliceArgs = [
spliceIdx,
spliceCount,
...newElems,
];
const prev = spliceIdx === 0 ? null : array[spliceIdx - 1];
const next = spliceIdx + spliceCount >= array.length
? null
: array[spliceIdx + spliceCount];
/*
* Before splicing in new elements, ensure they do not already appear in the
* current array.
*/
for (let idx = 0; idx < newElems.length; ++idx) {
const node = newElems[idx];
const oldParent = node.parent;
if (oldParent) {
const oldSiblings = oldParent.children;
const prevIdx = oldSiblings.indexOf(node);
if (prevIdx > -1) {
oldParent.children.splice(prevIdx, 1);
if (parent === oldParent && spliceIdx > prevIdx) {
spliceArgs[0]--;
}
}
}
node.parent = parent;
if (node.prev) {
node.prev.next = (_a = node.next) !== null && _a !== void 0 ? _a : null;
}
if (node.next) {
node.next.prev = (_b = node.prev) !== null && _b !== void 0 ? _b : null;
}
node.prev = idx === 0 ? prev : newElems[idx - 1];
node.next = idx === newElems.length - 1 ? next : newElems[idx + 1];
}
if (prev) {
prev.next = newElems[0];
}
if (next) {
next.prev = newElems[newElems.length - 1];
}
return array.splice(...spliceArgs);
}
/**
* Insert every element in the set of matched elements to the end of the target.
*
* @category Manipulation
* @example
*
* ```js
* $('<li class="plum">Plum</li>').appendTo('#fruits');
* $.html();
* //=> <ul id="fruits">
* // <li class="apple">Apple</li>
* // <li class="orange">Orange</li>
* // <li class="pear">Pear</li>
* // <li class="plum">Plum</li>
* // </ul>
* ```
*
* @param target - Element to append elements to.
* @returns The instance itself.
* @see {@link https://api.jquery.com/appendTo/}
*/
function appendTo(target) {
const appendTarget = isCheerio(target) ? target : this._make(target);
appendTarget.append(this);
return this;
}
/**
* Insert every element in the set of matched elements to the beginning of the target.
*
* @category Manipulation
* @example
*
* ```js
* $('<li class="plum">Plum</li>').prependTo('#fruits');
* $.html();
* //=> <ul id="fruits">
* // <li class="plum">Plum</li>
* // <li class="apple">Apple</li>
* // <li class="orange">Orange</li>
* // <li class="pear">Pear</li>
* // </ul>
* ```
*
* @param target - Element to prepend elements to.
* @returns The instance itself.
* @see {@link https://api.jquery.com/prependTo/}
*/
function prependTo(target) {
const prependTarget = isCheerio(target) ? target : this._make(target);
prependTarget.prepend(this);
return this;
}
/**
* Inserts content as the _last_ child of each of the selected elements.
*
* @category Manipulation
* @example
*
* ```js
* $('ul').append('<li class="plum">Plum</li>');
* $.html();
* //=> <ul id="fruits">
* // <li class="apple">Apple</li>
* // <li class="orange">Orange</li>
* // <li class="pear">Pear</li>
* // <li class="plum">Plum</li>
* // </ul>
* ```
*
* @see {@link https://api.jquery.com/append/}
*/
const append$1 = _insert((dom, children, parent) => {
uniqueSplice(children, children.length, 0, dom, parent);
});
/**
* Inserts content as the _first_ child of each of the selected elements.
*
* @category Manipulation
* @example
*
* ```js
* $('ul').prepend('<li class="plum">Plum</li>');
* $.html();
* //=> <ul id="fruits">
* // <li class="plum">Plum</li>
* // <li class="apple">Apple</li>
* // <li class="orange">Orange</li>
* // <li class="pear">Pear</li>
* // </ul>
* ```
*
* @see {@link https://api.jquery.com/prepend/}
*/
const prepend$1 = _insert((dom, children, parent) => {
uniqueSplice(children, 0, 0, dom, parent);
});
function _wrap(insert) {
return function (wrapper) {
const lastIdx = this.length - 1;
const lastParent = this.parents().last();
for (let i = 0; i < this.length; i++) {
const el = this[i];
const wrap = typeof wrapper === 'function'
? wrapper.call(el, i, el)
: typeof wrapper === 'string' && !isHtml(wrapper)
? lastParent.find(wrapper).clone()
: wrapper;
const [wrapperDom] = this._makeDomArray(wrap, i < lastIdx);
if (!wrapperDom || !hasChildren(wrapperDom))
continue;
let elInsertLocation = wrapperDom;
/*
* Find the deepest child. Only consider the first tag child of each node
* (ignore text); stop if no children are found.
*/
let j = 0;
while (j < elInsertLocation.children.length) {
const child = elInsertLocation.children[j];
if (isTag$1(child)) {
elInsertLocation = child;
j = 0;
}
else {
j++;
}
}
insert(el, elInsertLocation, [wrapperDom]);
}
return this;
};
}
/**
* The .wrap() function can take any string or object that could be passed to
* the $() factory function to specify a DOM structure. This structure may be
* nested several levels deep, but should contain only one inmost element. A
* copy of this structure will be wrapped around each of the elements in the set
* of matched elements. This method returns the original set of elements for
* chaining purposes.
*
* @category Manipulation
* @example
*
* ```js
* const redFruit = $('<div class="red-fruit"></div>');
* $('.apple').wrap(redFruit);
*
* //=> <ul id="fruits">
* // <div class="red-fruit">
* // <li class="apple">Apple</li>
* // </div>
* // <li class="orange">Orange</li>
* // <li class="plum">Plum</li>
* // </ul>
*
* const healthy = $('<div class="healthy"></div>');
* $('li').wrap(healthy);
*
* //=> <ul id="fruits">
* // <div class="healthy">
* // <li class="apple">Apple</li>
* // </div>
* // <div class="healthy">
* // <li class="orange">Orange</li>
* // </div>
* // <div class="healthy">
* // <li class="plum">Plum</li>
* // </div>
* // </ul>
* ```
*
* @param wrapper - The DOM structure to wrap around each element in the selection.
* @see {@link https://api.jquery.com/wrap/}
*/
const wrap$2 = _wrap((el, elInsertLocation, wrapperDom) => {
const { parent } = el;
if (!parent)
return;
const siblings = parent.children;
const index = siblings.indexOf(el);
update([el], elInsertLocation);
/*
* The previous operation removed the current element from the `siblings`
* array, so the `dom` array can be inserted without removing any
* additional elements.
*/
uniqueSplice(siblings, index, 0, wrapperDom, parent);
});
/**
* The .wrapInner() function can take any string or object that could be passed
* to the $() factory function to specify a DOM structure. This structure may be
* nested several levels deep, but should contain only one inmost element. The
* structure will be wrapped around the content of each of the elements in the
* set of matched elements.
*
* @category Manipulation
* @example
*
* ```js
* const redFruit = $('<div class="red-fruit"></div>');
* $('.apple').wrapInner(redFruit);
*
* //=> <ul id="fruits">
* // <li class="apple">
* // <div class="red-fruit">Apple</div>
* // </li>
* // <li class="orange">Orange</li>
* // <li class="pear">Pear</li>
* // </ul>
*
* const healthy = $('<div class="healthy"></div>');
* $('li').wrapInner(healthy);
*
* //=> <ul id="fruits">
* // <li class="apple">
* // <div class="healthy">Apple</div>
* // </li>
* // <li class="orange">
* // <div class="healthy">Orange</div>
* // </li>
* // <li class="pear">
* // <div class="healthy">Pear</div>
* // </li>
* // </ul>
* ```
*
* @param wrapper - The DOM structure to wrap around the content of each element
* in the selection.
* @returns The instance itself, for chaining.
* @see {@link https://api.jquery.com/wrapInner/}
*/
const wrapInner = _wrap((el, elInsertLocation, wrapperDom) => {
if (!hasChildren(el))
return;
update(el.children, elInsertLocation);
update(wrapperDom, el);
});
/**
* The .unwrap() function, removes the parents of the set of matched elements
* from the DOM, leaving the matched elements in their place.
*
* @category Manipulation
* @example <caption>without selector</caption>
*
* ```js
* const $ = cheerio.load(
* '<div id=test>\n <div><p>Hello</p></div>\n <div><p>World</p></div>\n</div>'
* );
* $('#test p').unwrap();
*
* //=> <div id=test>
* // <p>Hello</p>
* // <p>World</p>
* // </div>
* ```
*
* @example <caption>with selector</caption>
*
* ```js
* const $ = cheerio.load(
* '<div id=test>\n <p>Hello</p>\n <b><p>World</p></b>\n</div>'
* );
* $('#test p').unwrap('b');
*
* //=> <div id=test>
* // <p>Hello</p>
* // <p>World</p>
* // </div>
* ```
*
* @param selector - A selector to check the parent element against. If an
* element's parent does not match the selector, the element won't be unwrapped.
* @returns The instance itself, for chaining.
* @see {@link https://api.jquery.com/unwrap/}
*/
function unwrap(selector) {
this.parent(selector)
.not('body')
.each((_, el) => {
this._make(el).replaceWith(el.children);
});
return this;
}
/**
* The .wrapAll() function can take any string or object that could be passed to
* the $() function to specify a DOM structure. This structure may be nested
* several levels deep, but should contain only one inmost element. The
* structure will be wrapped around all of the elements in the set of matched
* elements, as a single group.
*
* @category Manipulation
* @example <caption>With markup passed to `wrapAll`</caption>
*
* ```js
* const $ = cheerio.load(
* '<div class="container"><div class="inner">First</div><div class="inner">Second</div></div>'
* );
* $('.inner').wrapAll("<div class='new'></div>");
*
* //=> <div class="container">
* // <div class='new'>
* // <div class="inner">First</div>
* // <div class="inner">Second</div>
* // </div>
* // </div>
* ```
*
* @example <caption>With an existing cheerio instance</caption>
*
* ```js
* const $ = cheerio.load(
* '<span>Span 1</span><strong>Strong</strong><span>Span 2</span>'
* );
* const wrap = $('<div><p><em><b></b></em></p></div>');
* $('span').wrapAll(wrap);
*
* //=> <div>
* // <p>
* // <em>
* // <b>
* // <span>Span 1</span>
* // <span>Span 2</span>
* // </b>
* // </em>
* // </p>
* // </div>
* // <strong>Strong</strong>
* ```
*
* @param wrapper - The DOM structure to wrap around all matched elements in the
* selection.
* @returns The instance itself.
* @see {@link https://api.jquery.com/wrapAll/}
*/
function wrapAll(wrapper) {
const el = this[0];
if (el) {
const wrap = this._make(typeof wrapper === 'function' ? wrapper.call(el, 0, el) : wrapper).insertBefore(el);
// If html is given as wrapper, wrap may contain text elements
let elInsertLocation;
for (let i = 0; i < wrap.length; i++) {
if (wrap[i].type === 'tag')
elInsertLocation = wrap[i];
}
let j = 0;
/*
* Find the deepest child. Only consider the first tag child of each node
* (ignore text); stop if no children are found.
*/
while (elInsertLocation && j < elInsertLocation.children.length) {
const child = elInsertLocation.children[j];
if (child.type === 'tag') {
elInsertLocation = child;
j = 0;
}
else {
j++;
}
}
if (elInsertLocation)
this._make(elInsertLocation).append(this);
}
return this;
}
/* eslint-disable jsdoc/check-param-names*/
/**
* Insert content next to each element in the set of matched elements.
*
* @category Manipulation
* @example
*
* ```js
* $('.apple').after('<li class="plum">Plum</li>');
* $.html();
* //=> <ul id="fruits">
* // <li class="apple">Apple</li>
* // <li class="plum">Plum</li>
* // <li class="orange">Orange</li>
* // <li class="pear">Pear</li>
* // </ul>
* ```
*
* @param content - HTML string, DOM element, array of DOM elements or Cheerio
* to insert after each element in the set of matched elements.
* @returns The instance itself.
* @see {@link https://api.jquery.com/after/}
*/
function after(...elems) {
const lastIdx = this.length - 1;
return domEach(this, (el, i) => {
const { parent } = el;
if (!hasChildren(el) || !parent) {
return;
}
const siblings = parent.children;
const index = siblings.indexOf(el);
// If not found, move on
/* istanbul ignore next */
if (index < 0)
return;
const domSrc = typeof elems[0] === 'function'
? elems[0].call(el, i, this._render(el.children))
: elems;
const dom = this._makeDomArray(domSrc, i < lastIdx);
// Add element after `this` element
uniqueSplice(siblings, index + 1, 0, dom, parent);
});
}
/* eslint-enable jsdoc/check-param-names*/
/**
* Insert every element in the set of matched elements after the target.
*
* @category Manipulation
* @example
*
* ```js
* $('<li class="plum">Plum</li>').insertAfter('.apple');
* $.html();
* //=> <ul id="fruits">
* // <li class="apple">Apple</li>
* // <li class="plum">Plum</li>
* // <li class="orange">Orange</li>
* // <li class="pear">Pear</li>
* // </ul>
* ```
*
* @param target - Element to insert elements after.
* @returns The set of newly inserted elements.
* @see {@link https://api.jquery.com/insertAfter/}
*/
function insertAfter(target) {
if (typeof target === 'string') {
target = this._make(target);
}
this.remove();
const clones = [];
this._makeDomArray(target).forEach((el) => {
const clonedSelf = this.clone().toArray();
const { parent } = el;
if (!parent) {
return;
}
const siblings = parent.children;
const index = siblings.indexOf(el);
// If not found, move on
/* istanbul ignore next */
if (index < 0)
return;
// Add cloned `this` element(s) after target element
uniqueSplice(siblings, index + 1, 0, clonedSelf, parent);
clones.push(...clonedSelf);
});
return this._make(clones);
}
/* eslint-disable jsdoc/check-param-names*/
/**
* Insert content previous to each element in the set of matched elements.
*
* @category Manipulation
* @example
*
* ```js
* $('.apple').before('<li class="plum">Plum</li>');
* $.html();
* //=> <ul id="fruits">
* // <li class="plum">Plum</li>
* // <li class="apple">Apple</li>
* // <li class="orange">Orange</li>
* // <li class="pear">Pear</li>
* // </ul>
* ```
*
* @param content - HTML string, DOM element, array of DOM elements or Cheerio
* to insert before each element in the set of matched elements.
* @returns The instance itself.
* @see {@link https://api.jquery.com/before/}
*/
function before(...elems) {
const lastIdx = this.length - 1;
return domEach(this, (el, i) => {
const { parent } = el;
if (!hasChildren(el) || !parent) {
return;
}
const siblings = parent.children;
const index = siblings.indexOf(el);
// If not found, move on
/* istanbul ignore next */
if (index < 0)
return;
const domSrc = typeof elems[0] === 'function'
? elems[0].call(el, i, this._render(el.children))
: elems;
const dom = this._makeDomArray(domSrc, i < lastIdx);
// Add element before `el` element
uniqueSplice(siblings, index, 0, dom, parent);
});
}
/* eslint-enable jsdoc/check-param-names*/
/**
* Insert every element in the set of matched elements before the target.
*
* @category Manipulation
* @example
*
* ```js
* $('<li class="plum">Plum</li>').insertBefore('.apple');
* $.html();
* //=> <ul id="fruits">
* // <li class="plum">Plum</li>
* // <li class="apple">Apple</li>
* // <li class="orange">Orange</li>
* // <li class="pear">Pear</li>
* // </ul>
* ```
*
* @param target - Element to insert elements before.
* @returns The set of newly inserted elements.
* @see {@link https://api.jquery.com/insertBefore/}
*/
function insertBefore(target) {
const targetArr = this._make(target);
this.remove();
const clones = [];
domEach(targetArr, (el) => {
const clonedSelf = this.clone().toArray();
const { parent } = el;
if (!parent) {
return;
}
const siblings = parent.children;
const index = siblings.indexOf(el);
// If not found, move on
/* istanbul ignore next */
if (index < 0)
return;
// Add cloned `this` element(s) after target element
uniqueSplice(siblings, index, 0, clonedSelf, parent);
clones.push(...clonedSelf);
});
return this._make(clones);
}
/**
* Removes the set of matched elements from the DOM and all their children.
* `selector` filters the set of matched elements to be removed.
*
* @category Manipulation
* @example
*
* ```js
* $('.pear').remove();
* $.html();
* //=> <ul id="fruits">
* // <li class="apple">Apple</li>
* // <li class="orange">Orange</li>
* // </ul>
* ```
*
* @param selector - Optional selector for elements to remove.
* @returns The instance itself.
* @see {@link https://api.jquery.com/remove/}
*/
function remove$1(selector) {
// Filter if we have selector
const elems = selector ? this.filter(selector) : this;
domEach(elems, (el) => {
removeElement(el);
el.prev = el.next = el.parent = null;
});
return this;
}
/**
* Replaces matched elements with `content`.
*
* @category Manipulation
* @example
*
* ```js
* const plum = $('<li class="plum">Plum</li>');
* $('.pear').replaceWith(plum);
* $.html();
* //=> <ul id="fruits">
* // <li class="apple">Apple</li>
* // <li class="orange">Orange</li>
* // <li class="plum">Plum</li>
* // </ul>
* ```
*
* @param content - Replacement for matched elements.
* @returns The instance itself.
* @see {@link https://api.jquery.com/replaceWith/}
*/
function replaceWith(content) {
return domEach(this, (el, i) => {
const { parent } = el;
if (!parent) {
return;
}
const siblings = parent.children;
const cont = typeof content === 'function' ? content.call(el, i, el) : content;
const dom = this._makeDomArray(cont);
/*
* In the case that `dom` contains nodes that already exist in other
* structures, ensure those nodes are properly removed.
*/
update(dom, null);
const index = siblings.indexOf(el);
// Completely remove old element
uniqueSplice(siblings, index, 1, dom, parent);
if (!dom.includes(el)) {
el.parent = el.prev = el.next = null;
}
});
}
/**
* Empties an element, removing all its children.
*
* @category Manipulation
* @example
*
* ```js
* $('ul').empty();
* $.html();
* //=> <ul id="fruits"></ul>
* ```
*
* @returns The instance itself.
* @see {@link https://api.jquery.com/empty/}
*/
function empty$1() {
return domEach(this, (el) => {
if (!hasChildren(el))
return;
el.children.forEach((child) => {
child.next = child.prev = child.parent = null;
});
el.children.length = 0;
});
}
function html$2(str) {
if (str === undefined) {
const el = this[0];
if (!el || !hasChildren(el))
return null;
return this._render(el.children);
}
return domEach(this, (el) => {
if (!hasChildren(el))
return;
el.children.forEach((child) => {
child.next = child.prev = child.parent = null;
});
const content = isCheerio(str)
? str.toArray()
: this._parse(`${str}`, this.options, false, el).children;
update(content, el);
});
}
/**
* Turns the collection to a string. Alias for `.html()`.
*
* @category Manipulation
* @returns The rendered document.
*/
function toString$5() {
return this._render(this);
}
function text$1(str) {
// If `str` is undefined, act as a "getter"
if (str === undefined) {
return text(this);
}
if (typeof str === 'function') {
// Function support
return domEach(this, (el, i) => this._make(el).text(str.call(el, i, text([el]))));
}
// Append text node to each selected elements
return domEach(this, (el) => {
if (!hasChildren(el))
return;
el.children.forEach((child) => {
child.next = child.prev = child.parent = null;
});
const textNode = new Text$1(`${str}`);
update(textNode, el);
});
}
/**
* Clone the cheerio object.
*
* @category Manipulation
* @example
*
* ```js
* const moreFruit = $('#fruits').clone();
* ```
*
* @returns The cloned object.
* @see {@link https://api.jquery.com/clone/}
*/
function clone() {
return this._make(cloneDom(this.get()));
}
var Manipulation = /*#__PURE__*/Object.freeze({
__proto__: null,
_makeDomArray: _makeDomArray,
appendTo: appendTo,
prependTo: prependTo,
append: append$1,
prepend: prepend$1,
wrap: wrap$2,
wrapInner: wrapInner,
unwrap: unwrap,
wrapAll: wrapAll,
after: after,
insertAfter: insertAfter,
before: before,
insertBefore: insertBefore,
remove: remove$1,
replaceWith: replaceWith,
empty: empty$1,
html: html$2,
toString: toString$5,
text: text$1,
clone: clone
});
/**
* Set multiple CSS properties for every matched element.
*
* @category CSS
* @param prop - The names of the properties.
* @param val - The new values.
* @returns The instance itself.
* @see {@link https://api.jquery.com/css/}
*/
function css(prop, val) {
if ((prop != null && val != null) ||
// When `prop` is a "plain" object
(typeof prop === 'object' && !Array.isArray(prop))) {
return domEach(this, (el, i) => {
if (isTag$1(el)) {
// `prop` can't be an array here anymore.
setCss(el, prop, val, i);
}
});
}
if (this.length === 0) {
return undefined;
}
return getCss(this[0], prop);
}
/**
* Set styles of all elements.
*
* @private
* @param el - Element to set style of.
* @param prop - Name of property.
* @param value - Value to set property to.
* @param idx - Optional index within the selection.
*/
function setCss(el, prop, value, idx) {
if (typeof prop === 'string') {
const styles = getCss(el);
const val = typeof value === 'function' ? value.call(el, idx, styles[prop]) : value;
if (val === '') {
delete styles[prop];
}
else if (val != null) {
styles[prop] = val;
}
el.attribs['style'] = stringify$3(styles);
}
else if (typeof prop === 'object') {
Object.keys(prop).forEach((k, i) => {
setCss(el, k, prop[k], i);
});
}
}
function getCss(el, prop) {
if (!el || !isTag$1(el))
return;
const styles = parse$2(el.attribs['style']);
if (typeof prop === 'string') {
return styles[prop];
}
if (Array.isArray(prop)) {
const newStyles = {};
prop.forEach((item) => {
if (styles[item] != null) {
newStyles[item] = styles[item];
}
});
return newStyles;
}
return styles;
}
/**
* Stringify `obj` to styles.
*
* @private
* @category CSS
* @param obj - Object to stringify.
* @returns The serialized styles.
*/
function stringify$3(obj) {
return Object.keys(obj).reduce((str, prop) => `${str}${str ? ' ' : ''}${prop}: ${obj[prop]};`, '');
}
/**
* Parse `styles`.
*
* @private
* @category CSS
* @param styles - Styles to be parsed.
* @returns The parsed styles.
*/
function parse$2(styles) {
styles = (styles || '').trim();
if (!styles)
return {};
const obj = {};
let key;
for (const str of styles.split(';')) {
const n = str.indexOf(':');
// If there is no :, or if it is the first/last character, add to the previous item's value
if (n < 1 || n === str.length - 1) {
const trimmed = str.trimEnd();
if (trimmed.length > 0 && key !== undefined) {
obj[key] += `;${trimmed}`;
}
}
else {
key = str.slice(0, n).trim();
obj[key] = str.slice(n + 1).trim();
}
}
return obj;
}
var Css = /*#__PURE__*/Object.freeze({
__proto__: null,
css: css
});
/*
* https://github.com/jquery/jquery/blob/2.1.3/src/manipulation/var/rcheckableType.js
* https://github.com/jquery/jquery/blob/2.1.3/src/serialize.js
*/
const submittableSelector = 'input,select,textarea,keygen';
const r20 = /%20/g;
const rCRLF = /\r?\n/g;
/**
* Encode a set of form elements as a string for submission.
*
* @category Forms
* @example
*
* ```js
* $('<form><input name="foo" value="bar" /></form>').serialize();
* //=> 'foo=bar'
* ```
*
* @returns The serialized form.
* @see {@link https://api.jquery.com/serialize/}
*/
function serialize$1() {
// Convert form elements into name/value objects
const arr = this.serializeArray();
// Serialize each element into a key/value string
const retArr = arr.map((data) => `${encodeURIComponent(data.name)}=${encodeURIComponent(data.value)}`);
// Return the resulting serialization
return retArr.join('&').replace(r20, '+');
}
/**
* Encode a set of form elements as an array of names and values.
*
* @category Forms
* @example
*
* ```js
* $('<form><input name="foo" value="bar" /></form>').serializeArray();
* //=> [ { name: 'foo', value: 'bar' } ]
* ```
*
* @returns The serialized form.
* @see {@link https://api.jquery.com/serializeArray/}
*/
function serializeArray() {
// Resolve all form elements from either forms or collections of form elements
return this.map((_, elem) => {
const $elem = this._make(elem);
if (isTag$1(elem) && elem.name === 'form') {
return $elem.find(submittableSelector).toArray();
}
return $elem.filter(submittableSelector).toArray();
})
.filter(
// Verify elements have a name (`attr.name`) and are not disabled (`:enabled`)
'[name!=""]:enabled' +
// And cannot be clicked (`[type=submit]`) or are used in `x-www-form-urlencoded` (`[type=file]`)
':not(:submit, :button, :image, :reset, :file)' +
// And are either checked/don't have a checkable state
':matches([checked], :not(:checkbox, :radio))'
// Convert each of the elements to its value(s)
)
.map((_, elem) => {
var _a;
const $elem = this._make(elem);
const name = $elem.attr('name'); // We have filtered for elements with a name before.
// If there is no value set (e.g. `undefined`, `null`), then default value to empty
const value = (_a = $elem.val()) !== null && _a !== void 0 ? _a : '';
// If we have an array of values (e.g. `<select multiple>`), return an array of key/value pairs
if (Array.isArray(value)) {
return value.map((val) =>
/*
* We trim replace any line endings (e.g. `\r` or `\r\n` with `\r\n`) to guarantee consistency across platforms
* These can occur inside of `<textarea>'s`
*/
({ name, value: val.replace(rCRLF, '\r\n') }));
}
// Otherwise (e.g. `<input type="text">`, return only one key/value pair
return { name, value: value.replace(rCRLF, '\r\n') };
})
.toArray();
}
var Forms = /*#__PURE__*/Object.freeze({
__proto__: null,
serialize: serialize$1,
serializeArray: serializeArray
});
class Cheerio {
/**
* Instance of cheerio. Methods are specified in the modules. Usage of this
* constructor is not recommended. Please use `$.load` instead.
*
* @private
* @param elements - The new selection.
* @param root - Sets the root node.
* @param options - Options for the instance.
*/
constructor(elements, root, options) {
this.length = 0;
this.options = options;
this._root = root;
if (elements) {
for (let idx = 0; idx < elements.length; idx++) {
this[idx] = elements[idx];
}
this.length = elements.length;
}
}
}
/** Set a signature of the object. */
Cheerio.prototype.cheerio = '[cheerio object]';
/*
* Make cheerio an array-like object
*/
Cheerio.prototype.splice = Array.prototype.splice;
// Support for (const element of $(...)) iteration:
Cheerio.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
// Plug in the API
Object.assign(Cheerio.prototype, Attributes, Traversing, Manipulation, Css, Forms);
function getLoad(parse, render) {
/**
* Create a querying function, bound to a document created from the provided markup.
*
* Note that similar to web browser contexts, this operation may introduce
* `<html>`, `<head>`, and `<body>` elements; set `isDocument` to `false` to
* switch to fragment mode and disable this.
*
* @param content - Markup to be loaded.
* @param options - Options for the created instance.
* @param isDocument - Allows parser to be switched to fragment mode.
* @returns The loaded document.
* @see {@link https://cheerio.js.org#loading} for additional usage information.
*/
return function load(content, options, isDocument = true) {
if (content == null) {
throw new Error('cheerio.load() expects a string');
}
const internalOpts = { ...defaultOpts, ...flatten(options) };
const initialRoot = parse(content, internalOpts, isDocument, null);
/** Create an extended class here, so that extensions only live on one instance. */
class LoadedCheerio extends Cheerio {
_make(selector, context) {
const cheerio = initialize(selector, context);
cheerio.prevObject = this;
return cheerio;
}
_parse(content, options, isDocument, context) {
return parse(content, options, isDocument, context);
}
_render(dom) {
return render(dom, this.options);
}
}
function initialize(selector, context, root = initialRoot, opts) {
// $($)
if (selector && isCheerio(selector))
return selector;
const options = {
...internalOpts,
...flatten(opts),
};
const r = typeof root === 'string'
? [parse(root, options, false, null)]
: 'length' in root
? root
: [root];
const rootInstance = isCheerio(r)
? r
: new LoadedCheerio(r, null, options);
// Add a cyclic reference, so that calling methods on `_root` never fails.
rootInstance._root = rootInstance;
// $(), $(null), $(undefined), $(false)
if (!selector) {
return new LoadedCheerio(undefined, rootInstance, options);
}
const elements = typeof selector === 'string' && isHtml(selector)
? // $(<html>)
parse(selector, options, false, null).children
: isNode(selector)
? // $(dom)
[selector]
: Array.isArray(selector)
? // $([dom])
selector
: undefined;
const instance = new LoadedCheerio(elements, rootInstance, options);
if (elements) {
return instance;
}
if (typeof selector !== 'string') {
throw new Error('Unexpected type of selector');
}
// We know that our selector is a string now.
let search = selector;
const searchContext = !context
? // If we don't have a context, maybe we have a root, from loading
rootInstance
: typeof context === 'string'
? isHtml(context)
? // $('li', '<ul>...</ul>')
new LoadedCheerio([parse(context, options, false, null)], rootInstance, options)
: // $('li', 'ul')
((search = `${context} ${search}`), rootInstance)
: isCheerio(context)
? // $('li', $)
context
: // $('li', node), $('li', [nodes])
new LoadedCheerio(Array.isArray(context) ? context : [context], rootInstance, options);
// If we still don't have a context, return
if (!searchContext)
return instance;
/*
* #id, .class, tag
*/
return searchContext.find(search);
}
// Add in static methods & properties
Object.assign(initialize, staticMethods, {
load,
// `_root` and `_options` are used in static methods.
_root: initialRoot,
_options: internalOpts,
// Add `fn` for plugins
fn: LoadedCheerio.prototype,
// Add the prototype here to maintain `instanceof` behavior.
prototype: LoadedCheerio.prototype,
});
return initialize;
};
}
function isNode(obj) {
return (!!obj.name ||
obj.type === 'root' ||
obj.type === 'text' ||
obj.type === 'comment');
}
const UNDEFINED_CODE_POINTS = new Set([
65534, 65535, 131070, 131071, 196606, 196607, 262142, 262143, 327678, 327679, 393214,
393215, 458750, 458751, 524286, 524287, 589822, 589823, 655358, 655359, 720894,
720895, 786430, 786431, 851966, 851967, 917502, 917503, 983038, 983039, 1048574,
1048575, 1114110, 1114111,
]);
const REPLACEMENT_CHARACTER = '\uFFFD';
var CODE_POINTS;
(function (CODE_POINTS) {
CODE_POINTS[CODE_POINTS["EOF"] = -1] = "EOF";
CODE_POINTS[CODE_POINTS["NULL"] = 0] = "NULL";
CODE_POINTS[CODE_POINTS["TABULATION"] = 9] = "TABULATION";
CODE_POINTS[CODE_POINTS["CARRIAGE_RETURN"] = 13] = "CARRIAGE_RETURN";
CODE_POINTS[CODE_POINTS["LINE_FEED"] = 10] = "LINE_FEED";
CODE_POINTS[CODE_POINTS["FORM_FEED"] = 12] = "FORM_FEED";
CODE_POINTS[CODE_POINTS["SPACE"] = 32] = "SPACE";
CODE_POINTS[CODE_POINTS["EXCLAMATION_MARK"] = 33] = "EXCLAMATION_MARK";
CODE_POINTS[CODE_POINTS["QUOTATION_MARK"] = 34] = "QUOTATION_MARK";
CODE_POINTS[CODE_POINTS["NUMBER_SIGN"] = 35] = "NUMBER_SIGN";
CODE_POINTS[CODE_POINTS["AMPERSAND"] = 38] = "AMPERSAND";
CODE_POINTS[CODE_POINTS["APOSTROPHE"] = 39] = "APOSTROPHE";
CODE_POINTS[CODE_POINTS["HYPHEN_MINUS"] = 45] = "HYPHEN_MINUS";
CODE_POINTS[CODE_POINTS["SOLIDUS"] = 47] = "SOLIDUS";
CODE_POINTS[CODE_POINTS["DIGIT_0"] = 48] = "DIGIT_0";
CODE_POINTS[CODE_POINTS["DIGIT_9"] = 57] = "DIGIT_9";
CODE_POINTS[CODE_POINTS["SEMICOLON"] = 59] = "SEMICOLON";
CODE_POINTS[CODE_POINTS["LESS_THAN_SIGN"] = 60] = "LESS_THAN_SIGN";
CODE_POINTS[CODE_POINTS["EQUALS_SIGN"] = 61] = "EQUALS_SIGN";
CODE_POINTS[CODE_POINTS["GREATER_THAN_SIGN"] = 62] = "GREATER_THAN_SIGN";
CODE_POINTS[CODE_POINTS["QUESTION_MARK"] = 63] = "QUESTION_MARK";
CODE_POINTS[CODE_POINTS["LATIN_CAPITAL_A"] = 65] = "LATIN_CAPITAL_A";
CODE_POINTS[CODE_POINTS["LATIN_CAPITAL_F"] = 70] = "LATIN_CAPITAL_F";
CODE_POINTS[CODE_POINTS["LATIN_CAPITAL_X"] = 88] = "LATIN_CAPITAL_X";
CODE_POINTS[CODE_POINTS["LATIN_CAPITAL_Z"] = 90] = "LATIN_CAPITAL_Z";
CODE_POINTS[CODE_POINTS["RIGHT_SQUARE_BRACKET"] = 93] = "RIGHT_SQUARE_BRACKET";
CODE_POINTS[CODE_POINTS["GRAVE_ACCENT"] = 96] = "GRAVE_ACCENT";
CODE_POINTS[CODE_POINTS["LATIN_SMALL_A"] = 97] = "LATIN_SMALL_A";
CODE_POINTS[CODE_POINTS["LATIN_SMALL_F"] = 102] = "LATIN_SMALL_F";
CODE_POINTS[CODE_POINTS["LATIN_SMALL_X"] = 120] = "LATIN_SMALL_X";
CODE_POINTS[CODE_POINTS["LATIN_SMALL_Z"] = 122] = "LATIN_SMALL_Z";
CODE_POINTS[CODE_POINTS["REPLACEMENT_CHARACTER"] = 65533] = "REPLACEMENT_CHARACTER";
})(CODE_POINTS || (CODE_POINTS = {}));
const SEQUENCES = {
DASH_DASH: '--',
CDATA_START: '[CDATA[',
DOCTYPE: 'doctype',
SCRIPT: 'script',
PUBLIC: 'public',
SYSTEM: 'system',
};
//Surrogates
function isSurrogate(cp) {
return cp >= 55296 && cp <= 57343;
}
function isSurrogatePair(cp) {
return cp >= 56320 && cp <= 57343;
}
function getSurrogatePairCodePoint(cp1, cp2) {
return (cp1 - 55296) * 1024 + 9216 + cp2;
}
//NOTE: excluding NULL and ASCII whitespace
function isControlCodePoint(cp) {
return ((cp !== 0x20 && cp !== 0x0a && cp !== 0x0d && cp !== 0x09 && cp !== 0x0c && cp >= 0x01 && cp <= 0x1f) ||
(cp >= 0x7f && cp <= 0x9f));
}
function isUndefinedCodePoint(cp) {
return (cp >= 64976 && cp <= 65007) || UNDEFINED_CODE_POINTS.has(cp);
}
var ERR;
(function (ERR) {
ERR["controlCharacterInInputStream"] = "control-character-in-input-stream";
ERR["noncharacterInInputStream"] = "noncharacter-in-input-stream";
ERR["surrogateInInputStream"] = "surrogate-in-input-stream";
ERR["nonVoidHtmlElementStartTagWithTrailingSolidus"] = "non-void-html-element-start-tag-with-trailing-solidus";
ERR["endTagWithAttributes"] = "end-tag-with-attributes";
ERR["endTagWithTrailingSolidus"] = "end-tag-with-trailing-solidus";
ERR["unexpectedSolidusInTag"] = "unexpected-solidus-in-tag";
ERR["unexpectedNullCharacter"] = "unexpected-null-character";
ERR["unexpectedQuestionMarkInsteadOfTagName"] = "unexpected-question-mark-instead-of-tag-name";
ERR["invalidFirstCharacterOfTagName"] = "invalid-first-character-of-tag-name";
ERR["unexpectedEqualsSignBeforeAttributeName"] = "unexpected-equals-sign-before-attribute-name";
ERR["missingEndTagName"] = "missing-end-tag-name";
ERR["unexpectedCharacterInAttributeName"] = "unexpected-character-in-attribute-name";
ERR["unknownNamedCharacterReference"] = "unknown-named-character-reference";
ERR["missingSemicolonAfterCharacterReference"] = "missing-semicolon-after-character-reference";
ERR["unexpectedCharacterAfterDoctypeSystemIdentifier"] = "unexpected-character-after-doctype-system-identifier";
ERR["unexpectedCharacterInUnquotedAttributeValue"] = "unexpected-character-in-unquoted-attribute-value";
ERR["eofBeforeTagName"] = "eof-before-tag-name";
ERR["eofInTag"] = "eof-in-tag";
ERR["missingAttributeValue"] = "missing-attribute-value";
ERR["missingWhitespaceBetweenAttributes"] = "missing-whitespace-between-attributes";
ERR["missingWhitespaceAfterDoctypePublicKeyword"] = "missing-whitespace-after-doctype-public-keyword";
ERR["missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers"] = "missing-whitespace-between-doctype-public-and-system-identifiers";
ERR["missingWhitespaceAfterDoctypeSystemKeyword"] = "missing-whitespace-after-doctype-system-keyword";
ERR["missingQuoteBeforeDoctypePublicIdentifier"] = "missing-quote-before-doctype-public-identifier";
ERR["missingQuoteBeforeDoctypeSystemIdentifier"] = "missing-quote-before-doctype-system-identifier";
ERR["missingDoctypePublicIdentifier"] = "missing-doctype-public-identifier";
ERR["missingDoctypeSystemIdentifier"] = "missing-doctype-system-identifier";
ERR["abruptDoctypePublicIdentifier"] = "abrupt-doctype-public-identifier";
ERR["abruptDoctypeSystemIdentifier"] = "abrupt-doctype-system-identifier";
ERR["cdataInHtmlContent"] = "cdata-in-html-content";
ERR["incorrectlyOpenedComment"] = "incorrectly-opened-comment";
ERR["eofInScriptHtmlCommentLikeText"] = "eof-in-script-html-comment-like-text";
ERR["eofInDoctype"] = "eof-in-doctype";
ERR["nestedComment"] = "nested-comment";
ERR["abruptClosingOfEmptyComment"] = "abrupt-closing-of-empty-comment";
ERR["eofInComment"] = "eof-in-comment";
ERR["incorrectlyClosedComment"] = "incorrectly-closed-comment";
ERR["eofInCdata"] = "eof-in-cdata";
ERR["absenceOfDigitsInNumericCharacterReference"] = "absence-of-digits-in-numeric-character-reference";
ERR["nullCharacterReference"] = "null-character-reference";
ERR["surrogateCharacterReference"] = "surrogate-character-reference";
ERR["characterReferenceOutsideUnicodeRange"] = "character-reference-outside-unicode-range";
ERR["controlCharacterReference"] = "control-character-reference";
ERR["noncharacterCharacterReference"] = "noncharacter-character-reference";
ERR["missingWhitespaceBeforeDoctypeName"] = "missing-whitespace-before-doctype-name";
ERR["missingDoctypeName"] = "missing-doctype-name";
ERR["invalidCharacterSequenceAfterDoctypeName"] = "invalid-character-sequence-after-doctype-name";
ERR["duplicateAttribute"] = "duplicate-attribute";
ERR["nonConformingDoctype"] = "non-conforming-doctype";
ERR["missingDoctype"] = "missing-doctype";
ERR["misplacedDoctype"] = "misplaced-doctype";
ERR["endTagWithoutMatchingOpenElement"] = "end-tag-without-matching-open-element";
ERR["closingOfElementWithOpenChildElements"] = "closing-of-element-with-open-child-elements";
ERR["disallowedContentInNoscriptInHead"] = "disallowed-content-in-noscript-in-head";
ERR["openElementsLeftAfterEof"] = "open-elements-left-after-eof";
ERR["abandonedHeadElementChild"] = "abandoned-head-element-child";
ERR["misplacedStartTagForHeadElement"] = "misplaced-start-tag-for-head-element";
ERR["nestedNoscriptInHead"] = "nested-noscript-in-head";
ERR["eofInElementThatCanContainOnlyText"] = "eof-in-element-that-can-contain-only-text";
})(ERR || (ERR = {}));
//Const
const DEFAULT_BUFFER_WATERLINE = 1 << 16;
//Preprocessor
//NOTE: HTML input preprocessing
//(see: http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#preprocessing-the-input-stream)
class Preprocessor {
constructor(handler) {
this.handler = handler;
this.html = '';
this.pos = -1;
// NOTE: Initial `lastGapPos` is -2, to ensure `col` on initialisation is 0
this.lastGapPos = -2;
this.gapStack = [];
this.skipNextNewLine = false;
this.lastChunkWritten = false;
this.endOfChunkHit = false;
this.bufferWaterline = DEFAULT_BUFFER_WATERLINE;
this.isEol = false;
this.lineStartPos = 0;
this.droppedBufferSize = 0;
this.line = 1;
//NOTE: avoid reporting errors twice on advance/retreat
this.lastErrOffset = -1;
}
/** The column on the current line. If we just saw a gap (eg. a surrogate pair), return the index before. */
get col() {
return this.pos - this.lineStartPos + Number(this.lastGapPos !== this.pos);
}
get offset() {
return this.droppedBufferSize + this.pos;
}
getError(code) {
const { line, col, offset } = this;
return {
code,
startLine: line,
endLine: line,
startCol: col,
endCol: col,
startOffset: offset,
endOffset: offset,
};
}
_err(code) {
if (this.handler.onParseError && this.lastErrOffset !== this.offset) {
this.lastErrOffset = this.offset;
this.handler.onParseError(this.getError(code));
}
}
_addGap() {
this.gapStack.push(this.lastGapPos);
this.lastGapPos = this.pos;
}
_processSurrogate(cp) {
//NOTE: try to peek a surrogate pair
if (this.pos !== this.html.length - 1) {
const nextCp = this.html.charCodeAt(this.pos + 1);
if (isSurrogatePair(nextCp)) {
//NOTE: we have a surrogate pair. Peek pair character and recalculate code point.
this.pos++;
//NOTE: add a gap that should be avoided during retreat
this._addGap();
return getSurrogatePairCodePoint(cp, nextCp);
}
}
//NOTE: we are at the end of a chunk, therefore we can't infer the surrogate pair yet.
else if (!this.lastChunkWritten) {
this.endOfChunkHit = true;
return CODE_POINTS.EOF;
}
//NOTE: isolated surrogate
this._err(ERR.surrogateInInputStream);
return cp;
}
willDropParsedChunk() {
return this.pos > this.bufferWaterline;
}
dropParsedChunk() {
if (this.willDropParsedChunk()) {
this.html = this.html.substring(this.pos);
this.lineStartPos -= this.pos;
this.droppedBufferSize += this.pos;
this.pos = 0;
this.lastGapPos = -2;
this.gapStack.length = 0;
}
}
write(chunk, isLastChunk) {
if (this.html.length > 0) {
this.html += chunk;
}
else {
this.html = chunk;
}
this.endOfChunkHit = false;
this.lastChunkWritten = isLastChunk;
}
insertHtmlAtCurrentPos(chunk) {
this.html = this.html.substring(0, this.pos + 1) + chunk + this.html.substring(this.pos + 1);
this.endOfChunkHit = false;
}
startsWith(pattern, caseSensitive) {
// Check if our buffer has enough characters
if (this.pos + pattern.length > this.html.length) {
this.endOfChunkHit = !this.lastChunkWritten;
return false;
}
if (caseSensitive) {
return this.html.startsWith(pattern, this.pos);
}
for (let i = 0; i < pattern.length; i++) {
const cp = this.html.charCodeAt(this.pos + i) | 0x20;
if (cp !== pattern.charCodeAt(i)) {
return false;
}
}
return true;
}
peek(offset) {
const pos = this.pos + offset;
if (pos >= this.html.length) {
this.endOfChunkHit = !this.lastChunkWritten;
return CODE_POINTS.EOF;
}
return this.html.charCodeAt(pos);
}
advance() {
this.pos++;
//NOTE: LF should be in the last column of the line
if (this.isEol) {
this.isEol = false;
this.line++;
this.lineStartPos = this.pos;
}
if (this.pos >= this.html.length) {
this.endOfChunkHit = !this.lastChunkWritten;
return CODE_POINTS.EOF;
}
let cp = this.html.charCodeAt(this.pos);
//NOTE: all U+000D CARRIAGE RETURN (CR) characters must be converted to U+000A LINE FEED (LF) characters
if (cp === CODE_POINTS.CARRIAGE_RETURN) {
this.isEol = true;
this.skipNextNewLine = true;
return CODE_POINTS.LINE_FEED;
}
//NOTE: any U+000A LINE FEED (LF) characters that immediately follow a U+000D CARRIAGE RETURN (CR) character
//must be ignored.
if (cp === CODE_POINTS.LINE_FEED) {
this.isEol = true;
if (this.skipNextNewLine) {
// `line` will be bumped again in the recursive call.
this.line--;
this.skipNextNewLine = false;
this._addGap();
return this.advance();
}
}
this.skipNextNewLine = false;
if (isSurrogate(cp)) {
cp = this._processSurrogate(cp);
}
//OPTIMIZATION: first check if code point is in the common allowed
//range (ASCII alphanumeric, whitespaces, big chunk of BMP)
//before going into detailed performance cost validation.
const isCommonValidRange = this.handler.onParseError === null ||
(cp > 0x1f && cp < 0x7f) ||
cp === CODE_POINTS.LINE_FEED ||
cp === CODE_POINTS.CARRIAGE_RETURN ||
(cp > 0x9f && cp < 64976);
if (!isCommonValidRange) {
this._checkForProblematicCharacters(cp);
}
return cp;
}
_checkForProblematicCharacters(cp) {
if (isControlCodePoint(cp)) {
this._err(ERR.controlCharacterInInputStream);
}
else if (isUndefinedCodePoint(cp)) {
this._err(ERR.noncharacterInInputStream);
}
}
retreat(count) {
this.pos -= count;
while (this.pos < this.lastGapPos) {
this.lastGapPos = this.gapStack.pop();
this.pos--;
}
this.isEol = false;
}
}
var TokenType;
(function (TokenType) {
TokenType[TokenType["CHARACTER"] = 0] = "CHARACTER";
TokenType[TokenType["NULL_CHARACTER"] = 1] = "NULL_CHARACTER";
TokenType[TokenType["WHITESPACE_CHARACTER"] = 2] = "WHITESPACE_CHARACTER";
TokenType[TokenType["START_TAG"] = 3] = "START_TAG";
TokenType[TokenType["END_TAG"] = 4] = "END_TAG";
TokenType[TokenType["COMMENT"] = 5] = "COMMENT";
TokenType[TokenType["DOCTYPE"] = 6] = "DOCTYPE";
TokenType[TokenType["EOF"] = 7] = "EOF";
TokenType[TokenType["HIBERNATION"] = 8] = "HIBERNATION";
})(TokenType || (TokenType = {}));
function getTokenAttr(token, attrName) {
for (let i = token.attrs.length - 1; i >= 0; i--) {
if (token.attrs[i].name === attrName) {
return token.attrs[i].value;
}
}
return null;
}
var decodeDataHtml = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
// Generated using scripts/write-decode-map.ts
// prettier-ignore
exports.default = new Uint16Array([7489, 60, 213, 305, 650, 1181, 1403, 1488, 1653, 1758, 1954, 2006, 2063, 2634, 2705, 3489, 3693, 3849, 3878, 4298, 4648, 4833, 5141, 5277, 5315, 5343, 5413, 0, 0, 0, 0, 0, 0, 5483, 5837, 6541, 7186, 7645, 8062, 8288, 8624, 8845, 9152, 9211, 9282, 10276, 10514, 11528, 11848, 12238, 12310, 12986, 13881, 14252, 14590, 14888, 14961, 15072, 15150, 2048, 69, 77, 97, 98, 99, 102, 103, 108, 109, 110, 111, 112, 114, 115, 116, 117, 92, 98, 102, 109, 115, 127, 132, 139, 144, 149, 152, 166, 179, 185, 200, 207, 108, 105, 103, 32827, 198, 16582, 80, 32827, 38, 16422, 99, 117, 116, 101, 32827, 193, 16577, 114, 101, 118, 101, 59, 16642, 256, 105, 121, 120, 125, 114, 99, 32827, 194, 16578, 59, 17424, 114, 59, 49152, 55349, 56580, 114, 97, 118, 101, 32827, 192, 16576, 112, 104, 97, 59, 17297, 97, 99, 114, 59, 16640, 100, 59, 27219, 256, 103, 112, 157, 161, 111, 110, 59, 16644, 102, 59, 49152, 55349, 56632, 112, 108, 121, 70, 117, 110, 99, 116, 105, 111, 110, 59, 24673, 105, 110, 103, 32827, 197, 16581, 256, 99, 115, 190, 195, 114, 59, 49152, 55349, 56476, 105, 103, 110, 59, 25172, 105, 108, 100, 101, 32827, 195, 16579, 109, 108, 32827, 196, 16580, 1024, 97, 99, 101, 102, 111, 114, 115, 117, 229, 251, 254, 279, 284, 290, 295, 298, 256, 99, 114, 234, 242, 107, 115, 108, 97, 115, 104, 59, 25110, 374, 246, 248, 59, 27367, 101, 100, 59, 25350, 121, 59, 17425, 384, 99, 114, 116, 261, 267, 276, 97, 117, 115, 101, 59, 25141, 110, 111, 117, 108, 108, 105, 115, 59, 24876, 97, 59, 17298, 114, 59, 49152, 55349, 56581, 112, 102, 59, 49152, 55349, 56633, 101, 118, 101, 59, 17112, 99, 242, 275, 109, 112, 101, 113, 59, 25166, 1792, 72, 79, 97, 99, 100, 101, 102, 104, 105, 108, 111, 114, 115, 117, 333, 337, 342, 384, 414, 418, 437, 439, 442, 476, 533, 627, 632, 638, 99, 121, 59, 17447, 80, 89, 32827, 169, 16553, 384, 99, 112, 121, 349, 354, 378, 117, 116, 101, 59, 16646, 256, 59, 105, 359, 360, 25298, 116, 97, 108, 68, 105, 102, 102, 101, 114, 101, 110, 116, 105, 97, 108, 68, 59, 24901, 108, 101, 121, 115, 59, 24877, 512, 97, 101, 105, 111, 393, 398, 404, 408, 114, 111, 110, 59, 16652, 100, 105, 108, 32827, 199, 16583, 114, 99, 59, 16648, 110, 105, 110, 116, 59, 25136, 111, 116, 59, 16650, 256, 100, 110, 423, 429, 105, 108, 108, 97, 59, 16568, 116, 101, 114, 68, 111, 116, 59, 16567, 242, 383, 105, 59, 17319, 114, 99, 108, 101, 512, 68, 77, 80, 84, 455, 459, 465, 470, 111, 116, 59, 25241, 105, 110, 117, 115, 59, 25238, 108, 117, 115, 59, 25237, 105, 109, 101, 115, 59, 25239, 111, 256, 99, 115, 482, 504, 107, 119, 105, 115, 101, 67, 111, 110, 116, 111, 117, 114, 73, 110, 116, 101, 103, 114, 97, 108, 59, 25138, 101, 67, 117, 114, 108, 121, 256, 68, 81, 515, 527, 111, 117, 98, 108, 101, 81, 117, 111, 116, 101, 59, 24605, 117, 111, 116, 101, 59, 24601, 512, 108, 110, 112, 117, 542, 552, 583, 597, 111, 110, 256, 59, 101, 549, 550, 25143, 59, 27252, 384, 103, 105, 116, 559, 566, 570, 114, 117, 101, 110, 116, 59, 25185, 110, 116, 59, 25135, 111, 117, 114, 73, 110, 116, 101, 103, 114, 97, 108, 59, 25134, 256, 102, 114, 588, 590, 59, 24834, 111, 100, 117, 99, 116, 59, 25104, 110, 116, 101, 114, 67, 108, 111, 99, 107, 119, 105, 115, 101, 67, 111, 110, 116, 111, 117, 114, 73, 110, 116, 101, 103, 114, 97, 108, 59, 25139, 111, 115, 115, 59, 27183, 99, 114, 59, 49152, 55349, 56478, 112, 256, 59, 67, 644, 645, 25299, 97, 112, 59, 25165, 1408, 68, 74, 83, 90, 97, 99, 101, 102, 105, 111, 115, 672, 684, 688, 692, 696, 715, 727, 737, 742, 819, 1165, 256, 59, 111, 377, 677, 116, 114, 97, 104, 100, 59, 26897, 99, 121, 59, 17410, 99, 121, 59, 17413, 99, 121, 59, 17423, 384, 103, 114, 115, 703, 708, 711, 103, 101, 114, 59, 24609, 114, 59, 24993, 104, 118, 59, 27364, 256, 97, 121, 720, 725, 114, 111, 110, 59, 16654, 59, 17428, 108, 256, 59, 116, 733, 734, 25095, 97, 59, 17300, 114, 59, 49152, 55349, 56583, 256, 97, 102, 747, 807, 256, 99, 109, 752, 802, 114, 105, 116, 105, 99, 97, 108, 512, 65, 68, 71, 84, 768, 774, 790, 796, 99, 117, 116, 101, 59, 16564, 111, 372, 779, 781, 59, 17113, 98, 108, 101, 65, 99, 117, 116, 101, 59, 17117, 114, 97, 118, 101, 59, 16480, 105, 108, 100, 101, 59, 17116, 111, 110, 100, 59, 25284, 102, 101, 114, 101, 110, 116, 105, 97, 108, 68, 59, 24902, 1136, 829, 0, 0, 0, 834, 852, 0, 1029, 102, 59, 49152, 55349, 56635, 384, 59, 68, 69, 840, 841, 845, 16552, 111, 116, 59, 24796, 113, 117, 97, 108, 59, 25168, 98, 108, 101, 768, 67, 68, 76, 82, 85, 86, 867, 882, 898, 975, 994, 1016, 111, 110, 116, 111, 117, 114, 73, 110, 116, 101, 103, 114, 97, 236, 569, 111, 628, 889, 0, 0, 891, 187, 841, 110, 65, 114, 114, 111, 119, 59, 25043, 256, 101, 111, 903, 932, 102, 116, 384, 65, 82, 84, 912, 918, 929, 114, 114, 111, 119, 59, 25040, 105, 103, 104, 116, 65, 114, 114, 111, 119, 59, 25044, 101, 229, 714, 110, 103, 256, 76, 82, 939, 964, 101, 102, 116, 256, 65, 82, 947, 953, 114, 114, 111, 119, 59, 26616, 105, 103, 104, 116, 65, 114, 114, 111, 119, 59, 26618, 105, 103, 104, 116, 65, 114, 114, 111, 119, 59, 26617, 105, 103, 104, 116, 256, 65, 84, 984, 990, 114, 114, 111, 119, 59, 25042, 101, 101, 59, 25256, 112, 577, 1001, 0, 0, 1007, 114, 114, 111, 119, 59, 25041, 111, 119, 110, 65, 114, 114, 111, 119, 59, 25045, 101, 114, 116, 105, 99, 97, 108, 66, 97, 114, 59, 25125, 110, 768, 65, 66, 76, 82, 84, 97, 1042, 1066, 1072, 1118, 1151, 892, 114, 114, 111, 119, 384, 59, 66, 85, 1053, 1054, 1058, 24979, 97, 114, 59, 26899, 112, 65, 114, 114, 111, 119, 59, 25077, 114, 101, 118, 101, 59, 17169, 101, 102, 116, 722, 1082, 0, 1094, 0, 1104, 105, 103, 104, 116, 86, 101, 99, 116, 111, 114, 59, 26960, 101, 101, 86, 101, 99, 116, 111, 114, 59, 26974, 101, 99, 116, 111, 114, 256, 59, 66, 1113, 1114, 25021, 97, 114, 59, 26966, 105, 103, 104, 116, 468, 1127, 0, 1137, 101, 101, 86, 101, 99, 116, 111, 114, 59, 26975, 101, 99, 116, 111, 114, 256, 59, 66, 1146, 1147, 25025, 97, 114, 59, 26967, 101, 101, 256, 59, 65, 1158, 1159, 25252, 114, 114, 111, 119, 59, 24999, 256, 99, 116, 1170, 1175, 114, 59, 49152, 55349, 56479, 114, 111, 107, 59, 16656, 2048, 78, 84, 97, 99, 100, 102, 103, 108, 109, 111, 112, 113, 115, 116, 117, 120, 1213, 1216, 1220, 1227, 1246, 1250, 1255, 1262, 1269, 1313, 1327, 1334, 1362, 1373, 1376, 1381, 71, 59, 16714, 72, 32827, 208, 16592, 99, 117, 116, 101, 32827, 201, 16585, 384, 97, 105, 121, 1234, 1239, 1244, 114, 111, 110, 59, 16666, 114, 99, 32827, 202, 16586, 59, 17453, 111, 116, 59, 16662, 114, 59, 49152, 55349, 56584, 114, 97, 118, 101, 32827, 200, 16584, 101, 109, 101, 110, 116, 59, 25096, 256, 97, 112, 1274, 1278, 99, 114, 59, 16658, 116, 121, 595, 1286, 0, 0, 1298, 109, 97, 108, 108, 83, 113, 117, 97, 114, 101, 59, 26107, 101, 114, 121, 83, 109, 97, 108, 108, 83, 113, 117, 97, 114, 101, 59, 26027, 256, 103, 112, 1318, 1322, 111, 110, 59, 16664, 102, 59, 49152, 55349, 56636, 115, 105, 108, 111, 110, 59, 17301, 117, 256, 97, 105, 1340, 1353, 108, 256, 59, 84, 1346, 1347, 27253, 105, 108, 100, 101, 59, 25154, 108, 105, 98, 114, 105, 117, 109, 59, 25036, 256, 99, 105, 1367, 1370, 114, 59, 24880, 109, 59, 27251, 97, 59, 17303, 109, 108, 32827, 203, 16587, 256, 105, 112, 1386, 1391, 115, 116, 115, 59, 25091, 111, 110, 101, 110, 116, 105, 97, 108, 69, 59, 24903, 640, 99, 102, 105, 111, 115, 1413, 1416, 1421, 1458, 1484, 121, 59, 17444, 114, 59, 49152, 55349, 56585, 108, 108, 101, 100, 595, 1431, 0, 0, 1443, 109, 97, 108, 108, 83, 113, 117, 97, 114, 101, 59, 26108, 101, 114, 121, 83, 109, 97, 108, 108, 83, 113, 117, 97, 114, 101, 59, 26026, 880, 1466, 0, 1471, 0, 0, 1476, 102, 59, 49152, 55349, 56637, 65, 108, 108, 59, 25088, 114, 105, 101, 114, 116, 114, 102, 59, 24881, 99, 242, 1483, 1536, 74, 84, 97, 98, 99, 100, 102, 103, 111, 114, 115, 116, 1512, 1516, 1519, 1530, 1536, 1554, 1558, 1563, 1565, 1571, 1644, 1650, 99, 121, 59, 17411, 32827, 62, 16446, 109, 109, 97, 256, 59, 100, 1527, 1528, 17299, 59, 17372, 114, 101, 118, 101, 59, 16670, 384, 101, 105, 121, 1543, 1548, 1552, 100, 105, 108, 59, 16674, 114, 99, 59, 16668, 59, 17427, 111, 116, 59, 16672, 114, 59, 49152, 55349, 56586, 59, 25305, 112, 102, 59, 49152, 55349, 56638, 101, 97, 116, 101, 114, 768, 69, 70, 71, 76, 83, 84, 1589, 1604, 1614, 1622, 1627, 1638, 113, 117, 97, 108, 256, 59, 76, 1598, 1599, 25189, 101, 115, 115, 59, 25307, 117, 108, 108, 69, 113, 117, 97, 108, 59, 25191, 114, 101, 97, 116, 101, 114, 59, 27298, 101, 115, 115, 59, 25207, 108, 97, 110, 116, 69, 113, 117, 97, 108, 59, 27262, 105, 108, 100, 101, 59, 25203, 99, 114, 59, 49152, 55349, 56482, 59, 25195, 1024, 65, 97, 99, 102, 105, 111, 115, 117, 1669, 1675, 1686, 1691, 1694, 1706, 1726, 1738, 82, 68, 99, 121, 59, 17450, 256, 99, 116, 1680, 1684, 101, 107, 59, 17095, 59, 16478, 105, 114, 99, 59, 16676, 114, 59, 24844, 108, 98, 101, 114, 116, 83, 112, 97, 99, 101, 59, 24843, 496, 1711, 0, 1714, 102, 59, 24845, 105, 122, 111, 110, 116, 97, 108, 76, 105, 110, 101, 59, 25856, 256, 99, 116, 1731, 1733, 242, 1705, 114, 111, 107, 59, 16678, 109, 112, 324, 1744, 1752, 111, 119, 110, 72, 117, 109, 240, 303, 113, 117, 97, 108, 59, 25167, 1792, 69, 74, 79, 97, 99, 100, 102, 103, 109, 110, 111, 115, 116, 117, 1786, 1790, 1795, 1799, 1806, 1818, 1822, 1825, 1832, 1860, 1912, 1931, 1935, 1941, 99, 121, 59, 17429, 108, 105, 103, 59, 16690, 99, 121, 59, 17409, 99, 117, 116, 101, 32827, 205, 16589, 256, 105, 121, 1811, 1816, 114, 99, 32827, 206, 16590, 59, 17432, 111, 116, 59, 16688, 114, 59, 24849, 114, 97, 118, 101, 32827, 204, 16588, 384, 59, 97, 112, 1824, 1839, 1855, 256, 99, 103, 1844, 1847, 114, 59, 16682, 105, 110, 97, 114, 121, 73, 59, 24904, 108, 105, 101, 243, 989, 500, 1865, 0, 1890, 256, 59, 101, 1869, 1870, 25132, 256, 103, 114, 1875, 1880, 114, 97, 108, 59, 25131, 115, 101, 99, 116, 105, 111, 110, 59, 25282, 105, 115, 105, 98, 108, 101, 256, 67, 84, 1900, 1906, 111, 109, 109, 97, 59, 24675, 105, 109, 101, 115, 59, 24674, 384, 103, 112, 116, 1919, 1923, 1928, 111, 110, 59, 16686, 102, 59, 49152, 55349, 56640, 97, 59, 17305, 99, 114, 59, 24848, 105, 108, 100, 101, 59, 16680, 491, 1946, 0, 1950, 99, 121, 59, 17414, 108, 32827, 207, 16591, 640, 99, 102, 111, 115, 117, 1964, 1975, 1980, 1986, 2000, 256, 105, 121, 1969, 1973, 114, 99, 59, 16692, 59, 17433, 114, 59, 49152, 55349, 56589, 112, 102, 59, 49152, 55349, 56641, 483, 1991, 0, 1996, 114, 59, 49152, 55349, 56485, 114, 99, 121, 59, 17416, 107, 99, 121, 59, 17412, 896, 72, 74, 97, 99, 102, 111, 115, 2020, 2024, 2028, 2033, 2045, 2050, 2056, 99, 121, 59, 17445, 99, 121, 59, 17420, 112, 112, 97, 59, 17306, 256, 101, 121, 2038, 2043, 100, 105, 108, 59, 16694, 59, 17434, 114, 59, 49152, 55349, 56590, 112, 102, 59, 49152, 55349, 56642, 99, 114, 59, 49152, 55349, 56486, 1408, 74, 84, 97, 99, 101, 102, 108, 109, 111, 115, 116, 2085, 2089, 2092, 2128, 2147, 2483, 2488, 2503, 2509, 2615, 2631, 99, 121, 59, 17417, 32827, 60, 16444, 640, 99, 109, 110, 112, 114, 2103, 2108, 2113, 2116, 2125, 117, 116, 101, 59, 16697, 98, 100, 97, 59, 17307, 103, 59, 26602, 108, 97, 99, 101, 116, 114, 102, 59, 24850, 114, 59, 24990, 384, 97, 101, 121, 2135, 2140, 2145, 114, 111, 110, 59, 16701, 100, 105, 108, 59, 16699, 59, 17435, 256, 102, 115, 2152, 2416, 116, 1280, 65, 67, 68, 70, 82, 84, 85, 86, 97, 114, 2174, 2217, 2225, 2272, 2278, 2300, 2351, 2395, 912, 2410, 256, 110, 114, 2179, 2191, 103, 108, 101, 66, 114, 97, 99, 107, 101, 116, 59, 26600, 114, 111, 119, 384, 59, 66, 82, 2201, 2202, 2206, 24976, 97, 114, 59, 25060, 105, 103, 104, 116, 65, 114, 114, 111, 119, 59, 25030, 101, 105, 108, 105, 110, 103, 59, 25352, 111, 501, 2231, 0, 2243, 98, 108, 101, 66, 114, 97, 99, 107, 101, 116, 59, 26598, 110, 468, 2248, 0, 2258, 101, 101, 86, 101, 99, 116, 111, 114, 59, 26977, 101, 99, 116, 111, 114, 256, 59, 66, 2267, 2268, 25027, 97, 114, 59, 26969, 108, 111, 111, 114, 59, 25354, 105, 103, 104, 116, 256, 65, 86, 2287, 2293, 114, 114, 111, 119, 59, 24980, 101, 99, 116, 111, 114, 59, 26958, 256, 101, 114, 2305, 2327, 101, 384, 59, 65, 86, 2313, 2314, 2320, 25251, 114, 114, 111, 119, 59, 24996, 101, 99, 116, 111, 114, 59, 26970, 105, 97, 110, 103, 108, 101, 384, 59, 66, 69, 2340, 2341, 2345, 25266, 97, 114, 59, 27087, 113, 117, 97, 108, 59, 25268, 112, 384, 68, 84, 86, 2359, 2370, 2380, 111, 119, 110, 86, 101, 99, 116, 111, 114, 59, 26961, 101, 101, 86, 101, 99, 116, 111, 114, 59, 26976, 101, 99, 116, 111, 114, 256, 59, 66, 2390, 2391, 25023, 97, 114, 59, 26968, 101, 99, 116, 111, 114, 256, 59, 66, 2405, 2406, 25020, 97, 114, 59, 26962, 105, 103, 104, 116, 225, 924, 115, 768, 69, 70, 71, 76, 83, 84, 2430, 2443, 2453, 2461, 2466, 2477, 113, 117, 97, 108, 71, 114, 101, 97, 116, 101, 114, 59, 25306, 117, 108, 108, 69, 113, 117, 97, 108, 59, 25190, 114, 101, 97, 116, 101, 114, 59, 25206, 101, 115, 115, 59, 27297, 108, 97, 110, 116, 69, 113, 117, 97, 108, 59, 27261, 105, 108, 100, 101, 59, 25202, 114, 59, 49152, 55349, 56591, 256, 59, 101, 2493, 2494, 25304, 102, 116, 97, 114, 114, 111, 119, 59, 25050, 105, 100, 111, 116, 59, 16703, 384, 110, 112, 119, 2516, 2582, 2587, 103, 512, 76, 82, 108, 114, 2526, 2551, 2562, 2576, 101, 102, 116, 256, 65, 82, 2534, 2540, 114, 114, 111, 119, 59, 26613, 105, 103, 104, 116, 65, 114, 114, 111, 119, 59, 26615, 105, 103, 104, 116, 65, 114, 114, 111, 119, 59, 26614, 101, 102, 116, 256, 97, 114, 947, 2570, 105, 103, 104, 116, 225, 959, 105, 103, 104, 116, 225, 970, 102, 59, 49152, 55349, 56643, 101, 114, 256, 76, 82, 2594, 2604, 101, 102, 116, 65, 114, 114, 111, 119, 59, 24985, 105, 103, 104, 116, 65, 114, 114, 111, 119, 59, 24984, 384, 99, 104, 116, 2622, 2624, 2626, 242, 2124, 59, 25008, 114, 111, 107, 59, 16705, 59, 25194, 1024, 97, 99, 101, 102, 105, 111, 115, 117, 2650, 2653, 2656, 2679, 2684, 2693, 2699, 2702, 112, 59, 26885, 121, 59, 17436, 256, 100, 108, 2661, 2671, 105, 117, 109, 83, 112, 97, 99, 101, 59, 24671, 108, 105, 110, 116, 114, 102, 59, 24883, 114, 59, 49152, 55349, 56592, 110, 117, 115, 80, 108, 117, 115, 59, 25107, 112, 102, 59, 49152, 55349, 56644, 99, 242, 2678, 59, 17308, 1152, 74, 97, 99, 101, 102, 111, 115, 116, 117, 2723, 2727, 2733, 2752, 2836, 2841, 3473, 3479, 3486, 99, 121, 59, 17418, 99, 117, 116, 101, 59, 16707, 384, 97, 101, 121, 2740, 2745, 2750, 114, 111, 110, 59, 16711, 100, 105, 108, 59, 16709, 59, 17437, 384, 103, 115, 119, 2759, 2800, 2830, 97, 116, 105, 118, 101, 384, 77, 84, 86, 2771, 2783, 2792, 101, 100, 105, 117, 109, 83, 112, 97, 99, 101, 59, 24587, 104, 105, 256, 99, 110, 2790, 2776, 235, 2777, 101, 114, 121, 84, 104, 105, 238, 2777, 116, 101, 100, 256, 71, 76, 2808, 2822, 114, 101, 97, 116, 101, 114, 71, 114, 101, 97, 116, 101, 242, 1651, 101, 115, 115, 76, 101, 115, 243, 2632, 76, 105, 110, 101, 59, 16394, 114, 59, 49152, 55349, 56593, 512, 66, 110, 112, 116, 2850, 2856, 2871, 2874, 114, 101, 97, 107, 59, 24672, 66, 114, 101, 97, 107, 105, 110, 103, 83, 112, 97, 99, 101, 59, 16544, 102, 59, 24853, 1664, 59, 67, 68, 69, 71, 72, 76, 78, 80, 82, 83, 84, 86, 2901, 2902, 2922, 2940, 2977, 3051, 3076, 3166, 3204, 3238, 3288, 3425, 3461, 27372, 256, 111, 117, 2907, 2916, 110, 103, 114, 117, 101, 110, 116, 59, 25186, 112, 67, 97, 112, 59, 25197, 111, 117, 98, 108, 101, 86, 101, 114, 116, 105, 99, 97, 108, 66, 97, 114, 59, 25126, 384, 108, 113, 120, 2947, 2954, 2971, 101, 109, 101, 110, 116, 59, 25097, 117, 97, 108, 256, 59, 84, 2962, 2963, 25184, 105, 108, 100, 101, 59, 49152, 8770, 824, 105, 115, 116, 115, 59, 25092, 114, 101, 97, 116, 101, 114, 896, 59, 69, 70, 71, 76, 83, 84, 2998, 2999, 3005, 3017, 3027, 3032, 3045, 25199, 113, 117, 97, 108, 59, 25201, 117, 108, 108, 69, 113, 117, 97, 108, 59, 49152, 8807, 824, 114, 101, 97, 116, 101, 114, 59, 49152, 8811, 824, 101, 115, 115, 59, 25209, 108, 97, 110, 116, 69, 113, 117, 97, 108, 59, 49152, 10878, 824, 105, 108, 100, 101, 59, 25205, 117, 109, 112, 324, 3058, 3069, 111, 119, 110, 72, 117, 109, 112, 59, 49152, 8782, 824, 113, 117, 97, 108, 59, 49152, 8783, 824, 101, 256, 102, 115, 3082, 3111, 116, 84, 114, 105, 97, 110, 103, 108, 101, 384, 59, 66, 69, 3098, 3099, 3105, 25322, 97, 114, 59, 49152, 10703, 824, 113, 117, 97, 108, 59, 25324, 115, 768, 59, 69, 71, 76, 83, 84, 3125, 3126, 3132, 3140, 3147, 3160, 25198, 113, 117, 97, 108, 59, 25200, 114, 101, 97, 116, 101, 114, 59, 25208, 101, 115, 115, 59, 49152, 8810, 824, 108, 97, 110, 116, 69, 113, 117, 97, 108, 59, 49152, 10877, 824, 105, 108, 100, 101, 59, 25204, 101, 115, 116, 101, 100, 256, 71, 76, 3176, 3193, 114, 101, 97, 116, 101, 114, 71, 114, 101, 97, 116, 101, 114, 59, 49152, 10914, 824, 101, 115, 115, 76, 101, 115, 115, 59, 49152, 10913, 824, 114, 101, 99, 101, 100, 101, 115, 384, 59, 69, 83, 3218, 3219, 3227, 25216, 113, 117, 97, 108, 59, 49152, 10927, 824, 108, 97, 110, 116, 69, 113, 117, 97, 108, 59, 25312, 256, 101, 105, 3243, 3257, 118, 101, 114, 115, 101, 69, 108, 101, 109, 101, 110, 116, 59, 25100, 103, 104, 116, 84, 114, 105, 97, 110, 103, 108, 101, 384, 59, 66, 69, 3275, 3276, 3282, 25323, 97, 114, 59, 49152, 10704, 824, 113, 117, 97, 108, 59, 25325, 256, 113, 117, 3293, 3340, 117, 97, 114, 101, 83, 117, 256, 98, 112, 3304, 3321, 115, 101, 116, 256, 59, 69, 3312, 3315, 49152, 8847, 824, 113, 117, 97, 108, 59, 25314, 101, 114, 115, 101, 116, 256, 59, 69, 3331, 3334, 49152, 8848, 824, 113, 117, 97, 108, 59, 25315, 384, 98, 99, 112, 3347, 3364, 3406, 115, 101, 116, 256, 59, 69, 3355, 3358, 49152, 8834, 8402, 113, 117, 97, 108, 59, 25224, 99, 101, 101, 100, 115, 512, 59, 69, 83, 84, 3378, 3379, 3387, 3398, 25217, 113, 117, 97, 108, 59, 49152, 10928, 824, 108, 97, 110, 116, 69, 113, 117, 97, 108, 59, 25313, 105, 108, 100, 101, 59, 49152, 8831, 824, 101, 114, 115, 101, 116, 256, 59, 69, 3416, 3419, 49152, 8835, 8402, 113, 117, 97, 108, 59, 25225, 105, 108, 100, 101, 512, 59, 69, 70, 84, 3438, 3439, 3445, 3455, 25153, 113, 117, 97, 108, 59, 25156, 117, 108, 108, 69, 113, 117, 97, 108, 59, 25159, 105, 108, 100, 101, 59, 25161, 101, 114, 116, 105, 99, 97, 108, 66, 97, 114, 59, 25124, 99, 114, 59, 49152, 55349, 56489, 105, 108, 100, 101, 32827, 209, 16593, 59, 17309, 1792, 69, 97, 99, 100, 102, 103, 109, 111, 112, 114, 115, 116, 117, 118, 3517, 3522, 3529, 3541, 3547, 3552, 3559, 3580, 3586, 3616, 3618, 3634, 3647, 3652, 108, 105, 103, 59, 16722, 99, 117, 116, 101, 32827, 211, 16595, 256, 105, 121, 3534, 3539, 114, 99, 32827, 212, 16596, 59, 17438, 98, 108, 97, 99, 59, 16720, 114, 59, 49152, 55349, 56594, 114, 97, 118, 101, 32827, 210, 16594, 384, 97, 101, 105, 3566, 3570, 3574, 99, 114, 59, 16716, 103, 97, 59, 17321, 99, 114, 111, 110, 59, 17311, 112, 102, 59, 49152, 55349, 56646, 101, 110, 67, 117, 114, 108, 121, 256, 68, 81, 3598, 3610, 111, 117, 98, 108, 101, 81, 117, 111, 116, 101, 59, 24604, 117, 111, 116, 101, 59, 24600, 59, 27220, 256, 99, 108, 3623, 3628, 114, 59, 49152, 55349, 56490, 97, 115, 104, 32827, 216, 16600, 105, 364, 3639, 3644, 100, 101, 32827, 213, 16597, 101, 115, 59, 27191, 109, 108, 32827, 214, 16598, 101, 114, 256, 66, 80, 3659, 3680, 256, 97, 114, 3664, 3667, 114, 59, 24638, 97, 99, 256, 101, 107, 3674, 3676, 59, 25566, 101, 116, 59, 25524, 97, 114, 101, 110, 116, 104, 101, 115, 105, 115, 59, 25564, 1152, 97, 99, 102, 104, 105, 108, 111, 114, 115, 3711, 3719, 3722, 3727, 3730, 3732, 3741, 3760, 3836, 114, 116, 105, 97, 108, 68, 59, 25090, 121, 59, 17439, 114, 59, 49152, 55349, 56595, 105, 59, 17318, 59, 17312, 117, 115, 77, 105, 110, 117, 115, 59, 16561, 256, 105, 112, 3746, 3757, 110, 99, 97, 114, 101, 112, 108, 97, 110, 229, 1693, 102, 59, 24857, 512, 59, 101, 105, 111, 3769, 3770, 3808, 3812, 27323, 99, 101, 100, 101, 115, 512, 59, 69, 83, 84, 3784, 3785, 3791, 3802, 25210, 113, 117, 97, 108, 59, 27311, 108, 97, 110, 116, 69, 113, 117, 97, 108, 59, 25212, 105, 108, 100, 101, 59, 25214, 109, 101, 59, 24627, 256, 100, 112, 3817, 3822, 117, 99, 116, 59, 25103, 111, 114, 116, 105, 111, 110, 256, 59, 97, 549, 3833, 108, 59, 25117, 256, 99, 105, 3841, 3846, 114, 59, 49152, 55349, 56491, 59, 17320, 512, 85, 102, 111, 115, 3857, 3862, 3867, 3871, 79, 84, 32827, 34, 16418, 114, 59, 49152, 55349, 56596, 112, 102, 59, 24858, 99, 114, 59, 49152, 55349, 56492, 1536, 66, 69, 97, 99, 101, 102, 104, 105, 111, 114, 115, 117, 3902, 3907, 3911, 3936, 3955, 4007, 4010, 4013, 4246, 4265, 4276, 4286, 97, 114, 114, 59, 26896, 71, 32827, 174, 16558, 384, 99, 110, 114, 3918, 3923, 3926, 117, 116, 101, 59, 16724, 103, 59, 26603, 114, 256, 59, 116, 3932, 3933, 24992, 108, 59, 26902, 384, 97, 101, 121, 3943, 3948, 3953, 114, 111, 110, 59, 16728, 100, 105, 108, 59, 16726, 59, 17440, 256, 59, 118, 3960, 3961, 24860, 101, 114, 115, 101, 256, 69, 85, 3970, 3993, 256, 108, 113, 3975, 3982, 101, 109, 101, 110, 116, 59, 25099, 117, 105, 108, 105, 98, 114, 105, 117, 109, 59, 25035, 112, 69, 113, 117, 105, 108, 105, 98, 114, 105, 117, 109, 59, 26991, 114, 187, 3961, 111, 59, 17313, 103, 104, 116, 1024, 65, 67, 68, 70, 84, 85, 86, 97, 4033, 4075, 4083, 4130, 4136, 4187, 4231, 984, 256, 110, 114, 4038, 4050, 103, 108, 101, 66, 114, 97, 99, 107, 101, 116, 59, 26601, 114, 111, 119, 384, 59, 66, 76, 4060, 4061, 4065, 24978, 97, 114, 59, 25061, 101, 102, 116, 65, 114, 114, 111, 119, 59, 25028, 101, 105, 108, 105, 110, 103, 59, 25353, 111, 501, 4089, 0, 4101, 98, 108, 101, 66, 114, 97, 99, 107, 101, 116, 59, 26599, 110, 468, 4106, 0, 4116, 101, 101, 86, 101, 99, 116, 111, 114, 59, 26973, 101, 99, 116, 111, 114, 256, 59, 66, 4125, 4126, 25026, 97, 114, 59, 26965, 108, 111, 111, 114, 59, 25355, 256, 101, 114, 4141, 4163, 101, 384, 59, 65, 86, 4149, 4150, 4156, 25250, 114, 114, 111, 119, 59, 24998, 101, 99, 116, 111, 114, 59, 26971, 105, 97, 110, 103, 108, 101, 384, 59, 66, 69, 4176, 4177, 4181, 25267, 97, 114, 59, 27088, 113, 117, 97, 108, 59, 25269, 112, 384, 68, 84, 86, 4195, 4206, 4216, 111, 119, 110, 86, 101, 99, 116, 111, 114, 59, 26959, 101, 101, 86, 101, 99, 116, 111, 114, 59, 26972, 101, 99, 116, 111, 114, 256, 59, 66, 4226, 4227, 25022, 97, 114, 59, 26964, 101, 99, 116, 111, 114, 256, 59, 66, 4241, 4242, 25024, 97, 114, 59, 26963, 256, 112, 117, 4251, 4254, 102, 59, 24861, 110, 100, 73, 109, 112, 108, 105, 101, 115, 59, 26992, 105, 103, 104, 116, 97, 114, 114, 111, 119, 59, 25051, 256, 99, 104, 4281, 4284, 114, 59, 24859, 59, 25009, 108, 101, 68, 101, 108, 97, 121, 101, 100, 59, 27124, 1664, 72, 79, 97, 99, 102, 104, 105, 109, 111, 113, 115, 116, 117, 4324, 4337, 4343, 4349, 4377, 4382, 4433, 4438, 4449, 4455, 4533, 4539, 4543, 256, 67, 99, 4329, 4334, 72, 99, 121, 59, 17449, 121, 59, 17448, 70, 84, 99, 121, 59, 17452, 99, 117, 116, 101, 59, 16730, 640, 59, 97, 101, 105, 121, 4360, 4361, 4366, 4371, 4375, 27324, 114, 111, 110, 59, 16736, 100, 105, 108, 59, 16734, 114, 99, 59, 16732, 59, 17441, 114, 59, 49152, 55349, 56598, 111, 114, 116, 512, 68, 76, 82, 85, 4394, 4404, 4414, 4425, 111, 119, 110, 65, 114, 114, 111, 119, 187, 1054, 101, 102, 116, 65, 114, 114, 111, 119, 187, 2202, 105, 103, 104, 116, 65, 114, 114, 111, 119, 187, 4061, 112, 65, 114, 114, 111, 119, 59, 24977, 103, 109, 97, 59, 17315, 97, 108, 108, 67, 105, 114, 99, 108, 101, 59, 25112, 112, 102, 59, 49152, 55349, 56650, 626, 4461, 0, 0, 4464, 116, 59, 25114, 97, 114, 101, 512, 59, 73, 83, 85, 4475, 4476, 4489, 4527, 26017, 110, 116, 101, 114, 115, 101, 99, 116, 105, 111, 110, 59, 25235, 117, 256, 98, 112, 4495, 4510, 115, 101, 116, 256, 59, 69, 4503, 4504, 25231, 113, 117, 97, 108, 59, 25233, 101, 114, 115, 101, 116, 256, 59, 69, 4520, 4521, 25232, 113, 117, 97, 108, 59, 25234, 110, 105, 111, 110, 59, 25236, 99, 114, 59, 49152, 55349, 56494, 97, 114, 59, 25286, 512, 98, 99, 109, 112, 4552, 4571, 4617, 4619, 256, 59, 115, 4557, 4558, 25296, 101, 116, 256, 59, 69, 4557, 4565, 113, 117, 97, 108, 59, 25222, 256, 99, 104, 4576, 4613, 101, 101, 100, 115, 512, 59, 69, 83, 84, 4589, 4590, 4596, 4607, 25211, 113, 117, 97, 108, 59, 27312, 108, 97, 110, 116, 69, 113, 117, 97, 108, 59, 25213, 105, 108, 100, 101, 59, 25215, 84, 104, 225, 3980, 59, 25105, 384, 59, 101, 115, 4626, 4627, 4643, 25297, 114, 115, 101, 116, 256, 59, 69, 4636, 4637, 25219, 113, 117, 97, 108, 59, 25223, 101, 116, 187, 4627, 1408, 72, 82, 83, 97, 99, 102, 104, 105, 111, 114, 115, 4670, 4676, 4681, 4693, 4702, 4721, 4726, 4767, 4802, 4808, 4817, 79, 82, 78, 32827, 222, 16606, 65, 68, 69, 59, 24866, 256, 72, 99, 4686, 4690, 99, 121, 59, 17419, 121, 59, 17446, 256, 98, 117, 4698, 4700, 59, 16393, 59, 17316, 384, 97, 101, 121, 4709, 4714, 4719, 114, 111, 110, 59, 16740, 100, 105, 108, 59, 16738, 59, 17442, 114, 59, 49152, 55349, 56599, 256, 101, 105, 4731, 4745, 498, 4736, 0, 4743, 101, 102, 111, 114, 101, 59, 25140, 97, 59, 17304, 256, 99, 110, 4750, 4760, 107, 83, 112, 97, 99, 101, 59, 49152, 8287, 8202, 83, 112, 97, 99, 101, 59, 24585, 108, 100, 101, 512, 59, 69, 70, 84, 4779, 4780, 4786, 4796, 25148, 113, 117, 97, 108, 59, 25155, 117, 108, 108, 69, 113, 117, 97, 108, 59, 25157, 105, 108, 100, 101, 59, 25160, 112, 102, 59, 49152, 55349, 56651, 105, 112, 108, 101, 68, 111, 116, 59, 24795, 256, 99, 116, 4822, 4827, 114, 59, 49152, 55349, 56495, 114, 111, 107, 59, 16742, 2785, 4855, 4878, 4890, 4902, 0, 4908, 4913, 0, 0, 0, 0, 0, 4920, 4925, 4983, 4997, 0, 5119, 5124, 5130, 5136, 256, 99, 114, 4859, 4865, 117, 116, 101, 32827, 218, 16602, 114, 256, 59, 111, 4871, 4872, 24991, 99, 105, 114, 59, 26953, 114, 483, 4883, 0, 4886, 121, 59, 17422, 118, 101, 59, 16748, 256, 105, 121, 4894, 4899, 114, 99, 32827, 219, 16603, 59, 17443, 98, 108, 97, 99, 59, 16752, 114, 59, 49152, 55349, 56600, 114, 97, 118, 101, 32827, 217, 16601, 97, 99, 114, 59, 16746, 256, 100, 105, 4929, 4969, 101, 114, 256, 66, 80, 4936, 4957, 256, 97, 114, 4941, 4944, 114, 59, 16479, 97, 99, 256, 101, 107, 4951, 4953, 59, 25567, 101, 116, 59, 25525, 97, 114, 101, 110, 116, 104, 101, 115, 105, 115, 59, 25565, 111, 110, 256, 59, 80, 4976, 4977, 25283, 108, 117, 115, 59, 25230, 256, 103, 112, 4987, 4991, 111, 110, 59, 16754, 102, 59, 49152, 55349, 56652, 1024, 65, 68, 69, 84, 97, 100, 112, 115, 5013, 5038, 5048, 5060, 1000, 5074, 5079, 5107, 114, 114, 111, 119, 384, 59, 66, 68, 4432, 5024, 5028, 97, 114, 59, 26898, 111, 119, 110, 65, 114, 114, 111, 119, 59, 25029, 111, 119, 110, 65, 114, 114, 111, 119, 59, 24981, 113, 117, 105, 108, 105, 98, 114, 105, 117, 109, 59, 26990, 101, 101, 256, 59, 65, 5067, 5068, 25253, 114, 114, 111, 119, 59, 24997, 111, 119, 110, 225, 1011, 101, 114, 256, 76, 82, 5086, 5096, 101, 102, 116, 65, 114, 114, 111, 119, 59, 24982, 105, 103, 104, 116, 65, 114, 114, 111, 119, 59, 24983, 105, 256, 59, 108, 5113, 5114, 17362, 111, 110, 59, 17317, 105, 110, 103, 59, 16750, 99, 114, 59, 49152, 55349, 56496, 105, 108, 100, 101, 59, 16744, 109, 108, 32827, 220, 16604, 1152, 68, 98, 99, 100, 101, 102, 111, 115, 118, 5159, 5164, 5168, 5171, 5182, 5253, 5258, 5264, 5270, 97, 115, 104, 59, 25259, 97, 114, 59, 27371, 121, 59, 17426, 97, 115, 104, 256, 59, 108, 5179, 5180, 25257, 59, 27366, 256, 101, 114, 5187, 5189, 59, 25281, 384, 98, 116, 121, 5196, 5200, 5242, 97, 114, 59, 24598, 256, 59, 105, 5199, 5205, 99, 97, 108, 512, 66, 76, 83, 84, 5217, 5221, 5226, 5236, 97, 114, 59, 25123, 105, 110, 101, 59, 16508, 101, 112, 97, 114, 97, 116, 111, 114, 59, 26456, 105, 108, 100, 101, 59, 25152, 84, 104, 105, 110, 83, 112, 97, 99, 101, 59, 24586, 114, 59, 49152, 55349, 56601, 112, 102, 59, 49152, 55349, 56653, 99, 114, 59, 49152, 55349, 56497, 100, 97, 115, 104, 59, 25258, 640, 99, 101, 102, 111, 115, 5287, 5292, 5297, 5302, 5308, 105, 114, 99, 59, 16756, 100, 103, 101, 59, 25280, 114, 59, 49152, 55349, 56602, 112, 102, 59, 49152, 55349, 56654, 99, 114, 59, 49152, 55349, 56498, 512, 102, 105, 111, 115, 5323, 5328, 5330, 5336, 114, 59, 49152, 55349, 56603, 59, 17310, 112, 102, 59, 49152, 55349, 56655, 99, 114, 59, 49152, 55349, 56499, 1152, 65, 73, 85, 97, 99, 102, 111, 115, 117, 5361, 5365, 5369, 5373, 5380, 5391, 5396, 5402, 5408, 99, 121, 59, 17455, 99, 121, 59, 17415, 99, 121, 59, 17454, 99, 117, 116, 101, 32827, 221, 16605, 256, 105, 121, 5385, 5389, 114, 99, 59, 16758, 59, 17451, 114, 59, 49152, 55349, 56604, 112, 102, 59, 49152, 55349, 56656, 99, 114, 59, 49152, 55349, 56500, 109, 108, 59, 16760, 1024, 72, 97, 99, 100, 101, 102, 111, 115, 5429, 5433, 5439, 5451, 5455, 5469, 5472, 5476, 99, 121, 59, 17430, 99, 117, 116, 101, 59, 16761, 256, 97, 121, 5444, 5449, 114, 111, 110, 59, 16765, 59, 17431, 111, 116, 59, 16763, 498, 5460, 0, 5467, 111, 87, 105, 100, 116, 232, 2777, 97, 59, 17302, 114, 59, 24872, 112, 102, 59, 24868, 99, 114, 59, 49152, 55349, 56501, 3041, 5507, 5514, 5520, 0, 5552, 5558, 5567, 0, 0, 0, 0, 5574, 5595, 5611, 5727, 5741, 0, 5781, 5787, 5810, 5817, 0, 5822, 99, 117, 116, 101, 32827, 225, 16609, 114, 101, 118, 101, 59, 16643, 768, 59, 69, 100, 105, 117, 121, 5532, 5533, 5537, 5539, 5544, 5549, 25150, 59, 49152, 8766, 819, 59, 25151, 114, 99, 32827, 226, 16610, 116, 101, 32955, 180, 774, 59, 17456, 108, 105, 103, 32827, 230, 16614, 256, 59, 114, 178, 5562, 59, 49152, 55349, 56606, 114, 97, 118, 101, 32827, 224, 16608, 256, 101, 112, 5578, 5590, 256, 102, 112, 5583, 5588, 115, 121, 109, 59, 24885, 232, 5587, 104, 97, 59, 17329, 256, 97, 112, 5599, 99, 256, 99, 108, 5604, 5607, 114, 59, 16641, 103, 59, 27199, 612, 5616, 0, 0, 5642, 640, 59, 97, 100, 115, 118, 5626, 5627, 5631, 5633, 5639, 25127, 110, 100, 59, 27221, 59, 27228, 108, 111, 112, 101, 59, 27224, 59, 27226, 896, 59, 101, 108, 109, 114, 115, 122, 5656, 5657, 5659, 5662, 5695, 5711, 5721, 25120, 59, 27044, 101, 187, 5657, 115, 100, 256, 59, 97, 5669, 5670, 25121, 1121, 5680, 5682, 5684, 5686, 5688, 5690, 5692, 5694, 59, 27048, 59, 27049, 59, 27050, 59, 27051, 59, 27052, 59, 27053, 59, 27054, 59, 27055, 116, 256, 59, 118, 5701, 5702, 25119, 98, 256, 59, 100, 5708, 5709, 25278, 59, 27037, 256, 112, 116, 5716, 5719, 104, 59, 25122, 187, 185, 97, 114, 114, 59, 25468, 256, 103, 112, 5731, 5735, 111, 110, 59, 16645, 102, 59, 49152, 55349, 56658, 896, 59, 69, 97, 101, 105, 111, 112, 4801, 5755, 5757, 5762, 5764, 5767, 5770, 59, 27248, 99, 105, 114, 59, 27247, 59, 25162, 100, 59, 25163, 115, 59, 16423, 114, 111, 120, 256, 59, 101, 4801, 5778, 241, 5763, 105, 110, 103, 32827, 229, 16613, 384, 99, 116, 121, 5793, 5798, 5800, 114, 59, 49152, 55349, 56502, 59, 16426, 109, 112, 256, 59, 101, 4801, 5807, 241, 648, 105, 108, 100, 101, 32827, 227, 16611, 109, 108, 32827, 228, 16612, 256, 99, 105, 5826, 5832, 111, 110, 105, 110, 244, 626, 110, 116, 59, 27153, 2048, 78, 97, 98, 99, 100, 101, 102, 105, 107, 108, 110, 111, 112, 114, 115, 117, 5869, 5873, 5936, 5948, 5955, 5960, 6008, 6013, 6112, 6118, 6201, 6224, 5901, 6461, 6472, 6512, 111, 116, 59, 27373, 256, 99, 114, 5878, 5918, 107, 512, 99, 101, 112, 115, 5888, 5893, 5901, 5907, 111, 110, 103, 59, 25164, 112, 115, 105, 108, 111, 110, 59, 17398, 114, 105, 109, 101, 59, 24629, 105, 109, 256, 59, 101, 5914, 5915, 25149, 113, 59, 25293, 374, 5922, 5926, 101, 101, 59, 25277, 101, 100, 256, 59, 103, 5932, 5933, 25349, 101, 187, 5933, 114, 107, 256, 59, 116, 4956, 5943, 98, 114, 107, 59, 25526, 256, 111, 121, 5889, 5953, 59, 17457, 113, 117, 111, 59, 24606, 640, 99, 109, 112, 114, 116, 5971, 5979, 5985, 5988, 5992, 97, 117, 115, 256, 59, 101, 266, 265, 112, 116, 121, 118, 59, 27056, 115, 233, 5900, 110, 111, 245, 275, 384, 97, 104, 119, 5999, 6001, 6003, 59, 17330, 59, 24886, 101, 101, 110, 59, 25196, 114, 59, 49152, 55349, 56607, 103, 896, 99, 111, 115, 116, 117, 118, 119, 6029, 6045, 6067, 6081, 6101, 6107, 6110, 384, 97, 105, 117, 6036, 6038, 6042, 240, 1888, 114, 99, 59, 26095, 112, 187, 4977, 384, 100, 112, 116, 6052, 6056, 6061, 111, 116, 59, 27136, 108, 117, 115, 59, 27137, 105, 109, 101, 115, 59, 27138, 625, 6073, 0, 0, 6078, 99, 117, 112, 59, 27142, 97, 114, 59, 26117, 114, 105, 97, 110, 103, 108, 101, 256, 100, 117, 6093, 6098, 111, 119, 110, 59, 26045, 112, 59, 26035, 112, 108, 117, 115, 59, 27140, 101, 229, 5188, 229, 5293, 97, 114, 111, 119, 59, 26893, 384, 97, 107, 111, 6125, 6182, 6197, 256, 99, 110, 6130, 6179, 107, 384, 108, 115, 116, 6138, 1451, 6146, 111, 122, 101, 110, 103, 101, 59, 27115, 114, 105, 97, 110, 103, 108, 101, 512, 59, 100, 108, 114, 6162, 6163, 6168, 6173, 26036, 111, 119, 110, 59, 26046, 101, 102, 116, 59, 26050, 105, 103, 104, 116, 59, 26040, 107, 59, 25635, 433, 6187, 0, 6195, 434, 6191, 0, 6193, 59, 26002, 59, 26001, 52, 59, 26003, 99, 107, 59, 25992, 256, 101, 111, 6206, 6221, 256, 59, 113, 6211, 6214, 49152, 61, 8421, 117, 105, 118, 59, 49152, 8801, 8421, 116, 59, 25360, 512, 112, 116, 119, 120, 6233, 6238, 6247, 6252, 102, 59, 49152, 55349, 56659, 256, 59, 116, 5067, 6243, 111, 109, 187, 5068, 116, 105, 101, 59, 25288, 1536, 68, 72, 85, 86, 98, 100, 104, 109, 112, 116, 117, 118, 6277, 6294, 6314, 6331, 6359, 6363, 6380, 6399, 6405, 6410, 6416, 6433, 512, 76, 82, 108, 114, 6286, 6288, 6290, 6292, 59, 25943, 59, 25940, 59, 25942, 59, 25939, 640, 59, 68, 85, 100, 117, 6305, 6306, 6308, 6310, 6312, 25936, 59, 25958, 59, 25961, 59, 25956, 59, 25959, 512, 76, 82, 108, 114, 6323, 6325, 6327, 6329, 59, 25949, 59, 25946, 59, 25948, 59, 25945, 896, 59, 72, 76, 82, 104, 108, 114, 6346, 6347, 6349, 6351, 6353, 6355, 6357, 25937, 59, 25964, 59, 25955, 59, 25952, 59, 25963, 59, 25954, 59, 25951, 111, 120, 59, 27081, 512, 76, 82, 108, 114, 6372, 6374, 6376, 6378, 59, 25941, 59, 25938, 59, 25872, 59, 25868, 640, 59, 68, 85, 100, 117, 1725, 6391, 6393, 6395, 6397, 59, 25957, 59, 25960, 59, 25900, 59, 25908, 105, 110, 117, 115, 59, 25247, 108, 117, 115, 59, 25246, 105, 109, 101, 115, 59, 25248, 512, 76, 82, 108, 114, 6425, 6427, 6429, 6431, 59, 25947, 59, 25944, 59, 25880, 59, 25876, 896, 59, 72, 76, 82, 104, 108, 114, 6448, 6449, 6451, 6453, 6455, 6457, 6459, 25858, 59, 25962, 59, 25953, 59, 25950, 59, 25916, 59, 25892, 59, 25884, 256, 101, 118, 291, 6466, 98, 97, 114, 32827, 166, 16550, 512, 99, 101, 105, 111, 6481, 6486, 6490, 6496, 114, 59, 49152, 55349, 56503, 109, 105, 59, 24655, 109, 256, 59, 101, 5914, 5916, 108, 384, 59, 98, 104, 6504, 6505, 6507, 16476, 59, 27077, 115, 117, 98, 59, 26568, 364, 6516, 6526, 108, 256, 59, 101, 6521, 6522, 24610, 116, 187, 6522, 112, 384, 59, 69, 101, 303, 6533, 6535, 59, 27310, 256, 59, 113, 1756, 1755, 3297, 6567, 0, 6632, 6673, 6677, 6706, 0, 6711, 6736, 0, 0, 6836, 0, 0, 6849, 0, 0, 6945, 6958, 6989, 6994, 0, 7165, 0, 7180, 384, 99, 112, 114, 6573, 6578, 6621, 117, 116, 101, 59, 16647, 768, 59, 97, 98, 99, 100, 115, 6591, 6592, 6596, 6602, 6613, 6617, 25129, 110, 100, 59, 27204, 114, 99, 117, 112, 59, 27209, 256, 97, 117, 6607, 6610, 112, 59, 27211, 112, 59, 27207, 111, 116, 59, 27200, 59, 49152, 8745, 65024, 256, 101, 111, 6626, 6629, 116, 59, 24641, 238, 1683, 512, 97, 101, 105, 117, 6640, 6651, 6657, 6661, 496, 6645, 0, 6648, 115, 59, 27213, 111, 110, 59, 16653, 100, 105, 108, 32827, 231, 16615, 114, 99, 59, 16649, 112, 115, 256, 59, 115, 6668, 6669, 27212, 109, 59, 27216, 111, 116, 59, 16651, 384, 100, 109, 110, 6683, 6688, 6694, 105, 108, 32955, 184, 429, 112, 116, 121, 118, 59, 27058, 116, 33024, 162, 59, 101, 6701, 6702, 16546, 114, 228, 434, 114, 59, 49152, 55349, 56608, 384, 99, 101, 105, 6717, 6720, 6733, 121, 59, 17479, 99, 107, 256, 59, 109, 6727, 6728, 26387, 97, 114, 107, 187, 6728, 59, 17351, 114, 896, 59, 69, 99, 101, 102, 109, 115, 6751, 6752, 6754, 6763, 6820, 6826, 6830, 26059, 59, 27075, 384, 59, 101, 108, 6761, 6762, 6765, 17094, 113, 59, 25175, 101, 609, 6772, 0, 0, 6792, 114, 114, 111, 119, 256, 108, 114, 6780, 6785, 101, 102, 116, 59, 25018, 105, 103, 104, 116, 59, 25019, 640, 82, 83, 97, 99, 100, 6802, 6804, 6806, 6810, 6815, 187, 3911, 59, 25800, 115, 116, 59, 25243, 105, 114, 99, 59, 25242, 97, 115, 104, 59, 25245, 110, 105, 110, 116, 59, 27152, 105, 100, 59, 27375, 99, 105, 114, 59, 27074, 117, 98, 115, 256, 59, 117, 6843, 6844, 26211, 105, 116, 187, 6844, 748, 6855, 6868, 6906, 0, 6922, 111, 110, 256, 59, 101, 6861, 6862, 16442, 256, 59, 113, 199, 198, 621, 6873, 0, 0, 6882, 97, 256, 59, 116, 6878, 6879, 16428, 59, 16448, 384, 59, 102, 108, 6888, 6889, 6891, 25089, 238, 4448, 101, 256, 109, 120, 6897, 6902, 101, 110, 116, 187, 6889, 101, 243, 589, 487, 6910, 0, 6919, 256, 59, 100, 4795, 6914, 111, 116, 59, 27245, 110, 244, 582, 384, 102, 114, 121, 6928, 6932, 6935, 59, 49152, 55349, 56660, 111, 228, 596, 33024, 169, 59, 115, 341, 6941, 114, 59, 24855, 256, 97, 111, 6949, 6953, 114, 114, 59, 25013, 115, 115, 59, 26391, 256, 99, 117, 6962, 6967, 114, 59, 49152, 55349, 56504, 256, 98, 112, 6972, 6980, 256, 59, 101, 6977, 6978, 27343, 59, 27345, 256, 59, 101, 6985, 6986, 27344, 59, 27346, 100, 111, 116, 59, 25327, 896, 100, 101, 108, 112, 114, 118, 119, 7008, 7020, 7031, 7042, 7084, 7124, 7161, 97, 114, 114, 256, 108, 114, 7016, 7018, 59, 26936, 59, 26933, 624, 7026, 0, 0, 7029, 114, 59, 25310, 99, 59, 25311, 97, 114, 114, 256, 59, 112, 7039, 7040, 25014, 59, 26941, 768, 59, 98, 99, 100, 111, 115, 7055, 7056, 7062, 7073, 7077, 7080, 25130, 114, 99, 97, 112, 59, 27208, 256, 97, 117, 7067, 7070, 112, 59, 27206, 112, 59, 27210, 111, 116, 59, 25229, 114, 59, 27205, 59, 49152, 8746, 65024, 512, 97, 108, 114, 118, 7093, 7103, 7134, 7139, 114, 114, 256, 59, 109, 7100, 7101, 25015, 59, 26940, 121, 384, 101, 118, 119, 7111, 7124, 7128, 113, 624, 7118, 0, 0, 7122, 114, 101, 227, 7027, 117, 227, 7029, 101, 101, 59, 25294, 101, 100, 103, 101, 59, 25295, 101, 110, 32827, 164, 16548, 101, 97, 114, 114, 111, 119, 256, 108, 114, 7150, 7155, 101, 102, 116, 187, 7040, 105, 103, 104, 116, 187, 7101, 101, 228, 7133, 256, 99, 105, 7169, 7175, 111, 110, 105, 110, 244, 503, 110, 116, 59, 25137, 108, 99, 116, 121, 59, 25389, 2432, 65, 72, 97, 98, 99, 100, 101, 102, 104, 105, 106, 108, 111, 114, 115, 116, 117, 119, 122, 7224, 7227, 7231, 7261, 7273, 7285, 7306, 7326, 7340, 7351, 7419, 7423, 7437, 7547, 7569, 7595, 7611, 7622, 7629, 114, 242, 897, 97, 114, 59, 26981, 512, 103, 108, 114, 115, 7240, 7245, 7250, 7252, 103, 101, 114, 59, 24608, 101, 116, 104, 59, 24888, 242, 4403, 104, 256, 59, 118, 7258, 7259, 24592, 187, 2314, 363, 7265, 7271, 97, 114, 111, 119, 59, 26895, 97, 227, 789, 256, 97, 121, 7278, 7283, 114, 111, 110, 59, 16655, 59, 17460, 384, 59, 97, 111, 818, 7292, 7300, 256, 103, 114, 703, 7297, 114, 59, 25034, 116, 115, 101, 113, 59, 27255, 384, 103, 108, 109, 7313, 7316, 7320, 32827, 176, 16560, 116, 97, 59, 17332, 112, 116, 121, 118, 59, 27057, 256, 105, 114, 7331, 7336, 115, 104, 116, 59, 27007, 59, 49152, 55349, 56609, 97, 114, 256, 108, 114, 7347, 7349, 187, 2268, 187, 4126, 640, 97, 101, 103, 115, 118, 7362, 888, 7382, 7388, 7392, 109, 384, 59, 111, 115, 806, 7370, 7380, 110, 100, 256, 59, 115, 806, 7377, 117, 105, 116, 59, 26214, 97, 109, 109, 97, 59, 17373, 105, 110, 59, 25330, 384, 59, 105, 111, 7399, 7400, 7416, 16631, 100, 101, 33024, 247, 59, 111, 7399, 7408, 110, 116, 105, 109, 101, 115, 59, 25287, 110, 248, 7415, 99, 121, 59, 17490, 99, 623, 7430, 0, 0, 7434, 114, 110, 59, 25374, 111, 112, 59, 25357, 640, 108, 112, 116, 117, 119, 7448, 7453, 7458, 7497, 7509, 108, 97, 114, 59, 16420, 102, 59, 49152, 55349, 56661, 640, 59, 101, 109, 112, 115, 779, 7469, 7479, 7485, 7490, 113, 256, 59, 100, 850, 7475, 111, 116, 59, 25169, 105, 110, 117, 115, 59, 25144, 108, 117, 115, 59, 25108, 113, 117, 97, 114, 101, 59, 25249, 98, 108, 101, 98, 97, 114, 119, 101, 100, 103, 229, 250, 110, 384, 97, 100, 104, 4398, 7517, 7527, 111, 119, 110, 97, 114, 114, 111, 119, 243, 7299, 97, 114, 112, 111, 111, 110, 256, 108, 114, 7538, 7542, 101, 102, 244, 7348, 105, 103, 104, 244, 7350, 354, 7551, 7557, 107, 97, 114, 111, 247, 3906, 623, 7562, 0, 0, 7566, 114, 110, 59, 25375, 111, 112, 59, 25356, 384, 99, 111, 116, 7576, 7587, 7590, 256, 114, 121, 7581, 7585, 59, 49152, 55349, 56505, 59, 17493, 108, 59, 27126, 114, 111, 107, 59, 16657, 256, 100, 114, 7600, 7604, 111, 116, 59, 25329, 105, 256, 59, 102, 7610, 6166, 26047, 256, 97, 104, 7616, 7619, 114, 242, 1065, 97, 242, 4006, 97, 110, 103, 108, 101, 59, 27046, 256, 99, 105, 7634, 7637, 121, 59, 17503, 103, 114, 97, 114, 114, 59, 26623, 2304, 68, 97, 99, 100, 101, 102, 103, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 120, 7681, 7689, 7705, 7736, 1400, 7740, 7753, 7777, 7806, 7845, 7855, 7869, 7905, 7978, 7991, 8004, 8014, 8026, 256, 68, 111, 7686, 7476, 111, 244, 7305, 256, 99, 115, 7694, 7700, 117, 116, 101, 32827, 233, 16617, 116, 101, 114, 59, 27246, 512, 97, 105, 111, 121, 7714, 7719, 7729, 7734, 114, 111, 110, 59, 16667, 114, 256, 59, 99, 7725, 7726, 25174, 32827, 234, 16618, 108, 111, 110, 59, 25173, 59, 17485, 111, 116, 59, 16663, 256, 68, 114, 7745, 7749, 111, 116, 59, 25170, 59, 49152, 55349, 56610, 384, 59, 114, 115, 7760, 7761, 7767, 27290, 97, 118, 101, 32827, 232, 16616, 256, 59, 100, 7772, 7773, 27286, 111, 116, 59, 27288, 512, 59, 105, 108, 115, 7786, 7787, 7794, 7796, 27289, 110, 116, 101, 114, 115, 59, 25575, 59, 24851, 256, 59, 100, 7801, 7802, 27285, 111, 116, 59, 27287, 384, 97, 112, 115, 7813, 7817, 7831, 99, 114, 59, 16659, 116, 121, 384, 59, 115, 118, 7826, 7827, 7829, 25093, 101, 116, 187, 7827, 112, 256, 49, 59, 7837, 7844, 307, 7841, 7843, 59, 24580, 59, 24581, 24579, 256, 103, 115, 7850, 7852, 59, 16715, 112, 59, 24578, 256, 103, 112, 7860, 7864, 111, 110, 59, 16665, 102, 59, 49152, 55349, 56662, 384, 97, 108, 115, 7876, 7886, 7890, 114, 256, 59, 115, 7882, 7883, 25301, 108, 59, 27107, 117, 115, 59, 27249, 105, 384, 59, 108, 118, 7898, 7899, 7903, 17333, 111, 110, 187, 7899, 59, 17397, 512, 99, 115, 117, 118, 7914, 7923, 7947, 7971, 256, 105, 111, 7919, 7729, 114, 99, 187, 7726, 617, 7929, 0, 0, 7931, 237, 1352, 97, 110, 116, 256, 103, 108, 7938, 7942, 116, 114, 187, 7773, 101, 115, 115, 187, 7802, 384, 97, 101, 105, 7954, 7958, 7962, 108, 115, 59, 16445, 115, 116, 59, 25183, 118, 256, 59, 68, 565, 7968, 68, 59, 27256, 112, 97, 114, 115, 108, 59, 27109, 256, 68, 97, 7983, 7987, 111, 116, 59, 25171, 114, 114, 59, 26993, 384, 99, 100, 105, 7998, 8001, 7928, 114, 59, 24879, 111, 244, 850, 256, 97, 104, 8009, 8011, 59, 17335, 32827, 240, 16624, 256, 109, 114, 8019, 8023, 108, 32827, 235, 16619, 111, 59, 24748, 384, 99, 105, 112, 8033, 8036, 8039, 108, 59, 16417, 115, 244, 1390, 256, 101, 111, 8044, 8052, 99, 116, 97, 116, 105, 111, 238, 1369, 110, 101, 110, 116, 105, 97, 108, 229, 1401, 2529, 8082, 0, 8094, 0, 8097, 8103, 0, 0, 8134, 8140, 0, 8147, 0, 8166, 8170, 8192, 0, 8200, 8282, 108, 108, 105, 110, 103, 100, 111, 116, 115, 101, 241, 7748, 121, 59, 17476, 109, 97, 108, 101, 59, 26176, 384, 105, 108, 114, 8109, 8115, 8129, 108, 105, 103, 59, 32768, 64259, 617, 8121, 0, 0, 8125, 103, 59, 32768, 64256, 105, 103, 59, 32768, 64260, 59, 49152, 55349, 56611, 108, 105, 103, 59, 32768, 64257, 108, 105, 103, 59, 49152, 102, 106, 384, 97, 108, 116, 8153, 8156, 8161, 116, 59, 26221, 105, 103, 59, 32768, 64258, 110, 115, 59, 26033, 111, 102, 59, 16786, 496, 8174, 0, 8179, 102, 59, 49152, 55349, 56663, 256, 97, 107, 1471, 8183, 256, 59, 118, 8188, 8189, 25300, 59, 27353, 97, 114, 116, 105, 110, 116, 59, 27149, 256, 97, 111, 8204, 8277, 256, 99, 115, 8209, 8274, 945, 8218, 8240, 8248, 8261, 8264, 0, 8272, 946, 8226, 8229, 8231, 8234, 8236, 0, 8238, 32827, 189, 16573, 59, 24915, 32827, 188, 16572, 59, 24917, 59, 24921, 59, 24923, 435, 8244, 0, 8246, 59, 24916, 59, 24918, 692, 8254, 8257, 0, 0, 8259, 32827, 190, 16574, 59, 24919, 59, 24924, 53, 59, 24920, 438, 8268, 0, 8270, 59, 24922, 59, 24925, 56, 59, 24926, 108, 59, 24644, 119, 110, 59, 25378, 99, 114, 59, 49152, 55349, 56507, 2176, 69, 97, 98, 99, 100, 101, 102, 103, 105, 106, 108, 110, 111, 114, 115, 116, 118, 8322, 8329, 8351, 8357, 8368, 8372, 8432, 8437, 8442, 8447, 8451, 8466, 8504, 791, 8510, 8530, 8606, 256, 59, 108, 1613, 8327, 59, 27276, 384, 99, 109, 112, 8336, 8341, 8349, 117, 116, 101, 59, 16885, 109, 97, 256, 59, 100, 8348, 7386, 17331, 59, 27270, 114, 101, 118, 101, 59, 16671, 256, 105, 121, 8362, 8366, 114, 99, 59, 16669, 59, 17459, 111, 116, 59, 16673, 512, 59, 108, 113, 115, 1598, 1602, 8381, 8393, 384, 59, 113, 115, 1598, 1612, 8388, 108, 97, 110, 244, 1637, 512, 59, 99, 100, 108, 1637, 8402, 8405, 8421, 99, 59, 27305, 111, 116, 256, 59, 111, 8412, 8413, 27264, 256, 59, 108, 8418, 8419, 27266, 59, 27268, 256, 59, 101, 8426, 8429, 49152, 8923, 65024, 115, 59, 27284, 114, 59, 49152, 55349, 56612, 256, 59, 103, 1651, 1563, 109, 101, 108, 59, 24887, 99, 121, 59, 17491, 512, 59, 69, 97, 106, 1626, 8460, 8462, 8464, 59, 27282, 59, 27301, 59, 27300, 512, 69, 97, 101, 115, 8475, 8477, 8489, 8500, 59, 25193, 112, 256, 59, 112, 8483, 8484, 27274, 114, 111, 120, 187, 8484, 256, 59, 113, 8494, 8495, 27272, 256, 59, 113, 8494, 8475, 105, 109, 59, 25319, 112, 102, 59, 49152, 55349, 56664, 256, 99, 105, 8515, 8518, 114, 59, 24842, 109, 384, 59, 101, 108, 1643, 8526, 8528, 59, 27278, 59, 27280, 33536, 62, 59, 99, 100, 108, 113, 114, 1518, 8544, 8554, 8558, 8563, 8569, 256, 99, 105, 8549, 8551, 59, 27303, 114, 59, 27258, 111, 116, 59, 25303, 80, 97, 114, 59, 27029, 117, 101, 115, 116, 59, 27260, 640, 97, 100, 101, 108, 115, 8580, 8554, 8592, 1622, 8603, 496, 8585, 0, 8590, 112, 114, 111, 248, 8350, 114, 59, 27000, 113, 256, 108, 113, 1599, 8598, 108, 101, 115, 243, 8328, 105, 237, 1643, 256, 101, 110, 8611, 8621, 114, 116, 110, 101, 113, 113, 59, 49152, 8809, 65024, 197, 8618, 1280, 65, 97, 98, 99, 101, 102, 107, 111, 115, 121, 8644, 8647, 8689, 8693, 8698, 8728, 8733, 8751, 8808, 8829, 114, 242, 928, 512, 105, 108, 109, 114, 8656, 8660, 8663, 8667, 114, 115, 240, 5252, 102, 187, 8228, 105, 108, 244, 1705, 256, 100, 114, 8672, 8676, 99, 121, 59, 17482, 384, 59, 99, 119, 2292, 8683, 8687, 105, 114, 59, 26952, 59, 25005, 97, 114, 59, 24847, 105, 114, 99, 59, 16677, 384, 97, 108, 114, 8705, 8718, 8723, 114, 116, 115, 256, 59, 117, 8713, 8714, 26213, 105, 116, 187, 8714, 108, 105, 112, 59, 24614, 99, 111, 110, 59, 25273, 114, 59, 49152, 55349, 56613, 115, 256, 101, 119, 8739, 8745, 97, 114, 111, 119, 59, 26917, 97, 114, 111, 119, 59, 26918, 640, 97, 109, 111, 112, 114, 8762, 8766, 8771, 8798, 8803, 114, 114, 59, 25087, 116, 104, 116, 59, 25147, 107, 256, 108, 114, 8777, 8787, 101, 102, 116, 97, 114, 114, 111, 119, 59, 25001, 105, 103, 104, 116, 97, 114, 114, 111, 119, 59, 25002, 102, 59, 49152, 55349, 56665, 98, 97, 114, 59, 24597, 384, 99, 108, 116, 8815, 8820, 8824, 114, 59, 49152, 55349, 56509, 97, 115, 232, 8692, 114, 111, 107, 59, 16679, 256, 98, 112, 8834, 8839, 117, 108, 108, 59, 24643, 104, 101, 110, 187, 7259, 2785, 8867, 0, 8874, 0, 8888, 8901, 8910, 0, 8917, 8947, 0, 0, 8952, 8994, 9063, 9058, 9087, 0, 9094, 9130, 9140, 99, 117, 116, 101, 32827, 237, 16621, 384, 59, 105, 121, 1905, 8880, 8885, 114, 99, 32827, 238, 16622, 59, 17464, 256, 99, 120, 8892, 8895, 121, 59, 17461, 99, 108, 32827, 161, 16545, 256, 102, 114, 927, 8905, 59, 49152, 55349, 56614, 114, 97, 118, 101, 32827, 236, 16620, 512, 59, 105, 110, 111, 1854, 8925, 8937, 8942, 256, 105, 110, 8930, 8934, 110, 116, 59, 27148, 116, 59, 25133, 102, 105, 110, 59, 27100, 116, 97, 59, 24873, 108, 105, 103, 59, 16691, 384, 97, 111, 112, 8958, 8986, 8989, 384, 99, 103, 116, 8965, 8968, 8983, 114, 59, 16683, 384, 101, 108, 112, 1823, 8975, 8979, 105, 110, 229, 1934, 97, 114, 244, 1824, 104, 59, 16689, 102, 59, 25271, 101, 100, 59, 16821, 640, 59, 99, 102, 111, 116, 1268, 9004, 9009, 9021, 9025, 97, 114, 101, 59, 24837, 105, 110, 256, 59, 116, 9016, 9017, 25118, 105, 101, 59, 27101, 100, 111, 244, 8985, 640, 59, 99, 101, 108, 112, 1879, 9036, 9040, 9051, 9057, 97, 108, 59, 25274, 256, 103, 114, 9045, 9049, 101, 114, 243, 5475, 227, 9037, 97, 114, 104, 107, 59, 27159, 114, 111, 100, 59, 27196, 512, 99, 103, 112, 116, 9071, 9074, 9078, 9083, 121, 59, 17489, 111, 110, 59, 16687, 102, 59, 49152, 55349, 56666, 97, 59, 17337, 117, 101, 115, 116, 32827, 191, 16575, 256, 99, 105, 9098, 9103, 114, 59, 49152, 55349, 56510, 110, 640, 59, 69, 100, 115, 118, 1268, 9115, 9117, 9121, 1267, 59, 25337, 111, 116, 59, 25333, 256, 59, 118, 9126, 9127, 25332, 59, 25331, 256, 59, 105, 1911, 9134, 108, 100, 101, 59, 16681, 491, 9144, 0, 9148, 99, 121, 59, 17494, 108, 32827, 239, 16623, 768, 99, 102, 109, 111, 115, 117, 9164, 9175, 9180, 9185, 9191, 9205, 256, 105, 121, 9169, 9173, 114, 99, 59, 16693, 59, 17465, 114, 59, 49152, 55349, 56615, 97, 116, 104, 59, 16951, 112, 102, 59, 49152, 55349, 56667, 483, 9196, 0, 9201, 114, 59, 49152, 55349, 56511, 114, 99, 121, 59, 17496, 107, 99, 121, 59, 17492, 1024, 97, 99, 102, 103, 104, 106, 111, 115, 9227, 9238, 9250, 9255, 9261, 9265, 9269, 9275, 112, 112, 97, 256, 59, 118, 9235, 9236, 17338, 59, 17392, 256, 101, 121, 9243, 9248, 100, 105, 108, 59, 16695, 59, 17466, 114, 59, 49152, 55349, 56616, 114, 101, 101, 110, 59, 16696, 99, 121, 59, 17477, 99, 121, 59, 17500, 112, 102, 59, 49152, 55349, 56668, 99, 114, 59, 49152, 55349, 56512, 2944, 65, 66, 69, 72, 97, 98, 99, 100, 101, 102, 103, 104, 106, 108, 109, 110, 111, 112, 114, 115, 116, 117, 118, 9328, 9345, 9350, 9357, 9361, 9486, 9533, 9562, 9600, 9806, 9822, 9829, 9849, 9853, 9882, 9906, 9944, 10077, 10088, 10123, 10176, 10241, 10258, 384, 97, 114, 116, 9335, 9338, 9340, 114, 242, 2502, 242, 917, 97, 105, 108, 59, 26907, 97, 114, 114, 59, 26894, 256, 59, 103, 2452, 9355, 59, 27275, 97, 114, 59, 26978, 2403, 9381, 0, 9386, 0, 9393, 0, 0, 0, 0, 0, 9397, 9402, 0, 9414, 9416, 9421, 0, 9465, 117, 116, 101, 59, 16698, 109, 112, 116, 121, 118, 59, 27060, 114, 97, 238, 2124, 98, 100, 97, 59, 17339, 103, 384, 59, 100, 108, 2190, 9409, 9411, 59, 27025, 229, 2190, 59, 27269, 117, 111, 32827, 171, 16555, 114, 1024, 59, 98, 102, 104, 108, 112, 115, 116, 2201, 9438, 9446, 9449, 9451, 9454, 9457, 9461, 256, 59, 102, 2205, 9443, 115, 59, 26911, 115, 59, 26909, 235, 8786, 112, 59, 25003, 108, 59, 26937, 105, 109, 59, 26995, 108, 59, 24994, 384, 59, 97, 101, 9471, 9472, 9476, 27307, 105, 108, 59, 26905, 256, 59, 115, 9481, 9482, 27309, 59, 49152, 10925, 65024, 384, 97, 98, 114, 9493, 9497, 9501, 114, 114, 59, 26892, 114, 107, 59, 26482, 256, 97, 107, 9506, 9516, 99, 256, 101, 107, 9512, 9514, 59, 16507, 59, 16475, 256, 101, 115, 9521, 9523, 59, 27019, 108, 256, 100, 117, 9529, 9531, 59, 27023, 59, 27021, 512, 97, 101, 117, 121, 9542, 9547, 9558, 9560, 114, 111, 110, 59, 16702, 256, 100, 105, 9552, 9556, 105, 108, 59, 16700, 236, 2224, 226, 9513, 59, 17467, 512, 99, 113, 114, 115, 9571, 9574, 9581, 9597, 97, 59, 26934, 117, 111, 256, 59, 114, 3609, 5958, 256, 100, 117, 9586, 9591, 104, 97, 114, 59, 26983, 115, 104, 97, 114, 59, 26955, 104, 59, 25010, 640, 59, 102, 103, 113, 115, 9611, 9612, 2441, 9715, 9727, 25188, 116, 640, 97, 104, 108, 114, 116, 9624, 9636, 9655, 9666, 9704, 114, 114, 111, 119, 256, 59, 116, 2201, 9633, 97, 233, 9462, 97, 114, 112, 111, 111, 110, 256, 100, 117, 9647, 9652, 111, 119, 110, 187, 1114, 112, 187, 2406, 101, 102, 116, 97, 114, 114, 111, 119, 115, 59, 25031, 105, 103, 104, 116, 384, 97, 104, 115, 9677, 9686, 9694, 114, 114, 111, 119, 256, 59, 115, 2292, 2215, 97, 114, 112, 111, 111, 110, 243, 3992, 113, 117, 105, 103, 97, 114, 114, 111, 247, 8688, 104, 114, 101, 101, 116, 105, 109, 101, 115, 59, 25291, 384, 59, 113, 115, 9611, 2451, 9722, 108, 97, 110, 244, 2476, 640, 59, 99, 100, 103, 115, 2476, 9738, 9741, 9757, 9768, 99, 59, 27304, 111, 116, 256, 59, 111, 9748, 9749, 27263, 256, 59, 114, 9754, 9755, 27265, 59, 27267, 256, 59, 101, 9762, 9765, 49152, 8922, 65024, 115, 59, 27283, 640, 97, 100, 101, 103, 115, 9779, 9785, 9789, 9801, 9803, 112, 112, 114, 111, 248, 9414, 111, 116, 59, 25302, 113, 256, 103, 113, 9795, 9797, 244, 2441, 103, 116, 242, 9356, 244, 2459, 105, 237, 2482, 384, 105, 108, 114, 9813, 2273, 9818, 115, 104, 116, 59, 27004, 59, 49152, 55349, 56617, 256, 59, 69, 2460, 9827, 59, 27281, 353, 9833, 9846, 114, 256, 100, 117, 9650, 9838, 256, 59, 108, 2405, 9843, 59, 26986, 108, 107, 59, 25988, 99, 121, 59, 17497, 640, 59, 97, 99, 104, 116, 2632, 9864, 9867, 9873, 9878, 114, 242, 9665, 111, 114, 110, 101, 242, 7432, 97, 114, 100, 59, 26987, 114, 105, 59, 26106, 256, 105, 111, 9887, 9892, 100, 111, 116, 59, 16704, 117, 115, 116, 256, 59, 97, 9900, 9901, 25520, 99, 104, 101, 187, 9901, 512, 69, 97, 101, 115, 9915, 9917, 9929, 9940, 59, 25192, 112, 256, 59, 112, 9923, 9924, 27273, 114, 111, 120, 187, 9924, 256, 59, 113, 9934, 9935, 27271, 256, 59, 113, 9934, 9915, 105, 109, 59, 25318, 1024, 97, 98, 110, 111, 112, 116, 119, 122, 9961, 9972, 9975, 10010, 10031, 10049, 10055, 10064, 256, 110, 114, 9966, 9969, 103, 59, 26604, 114, 59, 25085, 114, 235, 2241, 103, 384, 108, 109, 114, 9983, 9997, 10004, 101, 102, 116, 256, 97, 114, 2534, 9991, 105, 103, 104, 116, 225, 2546, 97, 112, 115, 116, 111, 59, 26620, 105, 103, 104, 116, 225, 2557, 112, 97, 114, 114, 111, 119, 256, 108, 114, 10021, 10025, 101, 102, 244, 9453, 105, 103, 104, 116, 59, 25004, 384, 97, 102, 108, 10038, 10041, 10045, 114, 59, 27013, 59, 49152, 55349, 56669, 117, 115, 59, 27181, 105, 109, 101, 115, 59, 27188, 353, 10059, 10063, 115, 116, 59, 25111, 225, 4942, 384, 59, 101, 102, 10071, 10072, 6144, 26058, 110, 103, 101, 187, 10072, 97, 114, 256, 59, 108, 10084, 10085, 16424, 116, 59, 27027, 640, 97, 99, 104, 109, 116, 10099, 10102, 10108, 10117, 10119, 114, 242, 2216, 111, 114, 110, 101, 242, 7564, 97, 114, 256, 59, 100, 3992, 10115, 59, 26989, 59, 24590, 114, 105, 59, 25279, 768, 97, 99, 104, 105, 113, 116, 10136, 10141, 2624, 10146, 10158, 10171, 113, 117, 111, 59, 24633, 114, 59, 49152, 55349, 56513, 109, 384, 59, 101, 103, 2482, 10154, 10156, 59, 27277, 59, 27279, 256, 98, 117, 9514, 10163, 111, 256, 59, 114, 3615, 10169, 59, 24602, 114, 111, 107, 59, 16706, 33792, 60, 59, 99, 100, 104, 105, 108, 113, 114, 2091, 10194, 9785, 10204, 10208, 10213, 10218, 10224, 256, 99, 105, 10199, 10201, 59, 27302, 114, 59, 27257, 114, 101, 229, 9714, 109, 101, 115, 59, 25289, 97, 114, 114, 59, 26998, 117, 101, 115, 116, 59, 27259, 256, 80, 105, 10229, 10233, 97, 114, 59, 27030, 384, 59, 101, 102, 10240, 2349, 6171, 26051, 114, 256, 100, 117, 10247, 10253, 115, 104, 97, 114, 59, 26954, 104, 97, 114, 59, 26982, 256, 101, 110, 10263, 10273, 114, 116, 110, 101, 113, 113, 59, 49152, 8808, 65024, 197, 10270, 1792, 68, 97, 99, 100, 101, 102, 104, 105, 108, 110, 111, 112, 115, 117, 10304, 10309, 10370, 10382, 10387, 10400, 10405, 10408, 10458, 10466, 10468, 2691, 10483, 10498, 68, 111, 116, 59, 25146, 512, 99, 108, 112, 114, 10318, 10322, 10339, 10365, 114, 32827, 175, 16559, 256, 101, 116, 10327, 10329, 59, 26178, 256, 59, 101, 10334, 10335, 26400, 115, 101, 187, 10335, 256, 59, 115, 4155, 10344, 116, 111, 512, 59, 100, 108, 117, 4155, 10355, 10359, 10363, 111, 119, 238, 1164, 101, 102, 244, 2319, 240, 5073, 107, 101, 114, 59, 26030, 256, 111, 121, 10375, 10380, 109, 109, 97, 59, 27177, 59, 17468, 97, 115, 104, 59, 24596, 97, 115, 117, 114, 101, 100, 97, 110, 103, 108, 101, 187, 5670, 114, 59, 49152, 55349, 56618, 111, 59, 24871, 384, 99, 100, 110, 10415, 10420, 10441, 114, 111, 32827, 181, 16565, 512, 59, 97, 99, 100, 5220, 10429, 10432, 10436, 115, 244, 5799, 105, 114, 59, 27376, 111, 116, 32955, 183, 437, 117, 115, 384, 59, 98, 100, 10450, 6403, 10451, 25106, 256, 59, 117, 7484, 10456, 59, 27178, 355, 10462, 10465, 112, 59, 27355, 242, 8722, 240, 2689, 256, 100, 112, 10473, 10478, 101, 108, 115, 59, 25255, 102, 59, 49152, 55349, 56670, 256, 99, 116, 10488, 10493, 114, 59, 49152, 55349, 56514, 112, 111, 115, 187, 5533, 384, 59, 108, 109, 10505, 10506, 10509, 17340, 116, 105, 109, 97, 112, 59, 25272, 3072, 71, 76, 82, 86, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 108, 109, 111, 112, 114, 115, 116, 117, 118, 119, 10562, 10579, 10622, 10633, 10648, 10714, 10729, 10773, 10778, 10840, 10845, 10883, 10901, 10916, 10920, 11012, 11015, 11076, 11135, 11182, 11316, 11367, 11388, 11497, 256, 103, 116, 10567, 10571, 59, 49152, 8921, 824, 256, 59, 118, 10576, 3023, 49152, 8811, 8402, 384, 101, 108, 116, 10586, 10610, 10614, 102, 116, 256, 97, 114, 10593, 10599, 114, 114, 111, 119, 59, 25037, 105, 103, 104, 116, 97, 114, 114, 111, 119, 59, 25038, 59, 49152, 8920, 824, 256, 59, 118, 10619, 3143, 49152, 8810, 8402, 105, 103, 104, 116, 97, 114, 114, 111, 119, 59, 25039, 256, 68, 100, 10638, 10643, 97, 115, 104, 59, 25263, 97, 115, 104, 59, 25262, 640, 98, 99, 110, 112, 116, 10659, 10663, 10668, 10673, 10700, 108, 97, 187, 734, 117, 116, 101, 59, 16708, 103, 59, 49152, 8736, 8402, 640, 59, 69, 105, 111, 112, 3460, 10684, 10688, 10693, 10696, 59, 49152, 10864, 824, 100, 59, 49152, 8779, 824, 115, 59, 16713, 114, 111, 248, 3460, 117, 114, 256, 59, 97, 10707, 10708, 26222, 108, 256, 59, 115, 10707, 2872, 499, 10719, 0, 10723, 112, 32955, 160, 2871, 109, 112, 256, 59, 101, 3065, 3072, 640, 97, 101, 111, 117, 121, 10740, 10750, 10755, 10768, 10771, 496, 10745, 0, 10747, 59, 27203, 111, 110, 59, 16712, 100, 105, 108, 59, 16710, 110, 103, 256, 59, 100, 3454, 10762, 111, 116, 59, 49152, 10861, 824, 112, 59, 27202, 59, 17469, 97, 115, 104, 59, 24595, 896, 59, 65, 97, 100, 113, 115, 120, 2962, 10793, 10797, 10811, 10817, 10821, 10832, 114, 114, 59, 25047, 114, 256, 104, 114, 10803, 10806, 107, 59, 26916, 256, 59, 111, 5106, 5104, 111, 116, 59, 49152, 8784, 824, 117, 105, 246, 2915, 256, 101, 105, 10826, 10830, 97, 114, 59, 26920, 237, 2968, 105, 115, 116, 256, 59, 115, 2976, 2975, 114, 59, 49152, 55349, 56619, 512, 69, 101, 115, 116, 3013, 10854, 10873, 10876, 384, 59, 113, 115, 3004, 10861, 3041, 384, 59, 113, 115, 3004, 3013, 10868, 108, 97, 110, 244, 3042, 105, 237, 3050, 256, 59, 114, 2998, 10881, 187, 2999, 384, 65, 97, 112, 10890, 10893, 10897, 114, 242, 10609, 114, 114, 59, 25006, 97, 114, 59, 27378, 384, 59, 115, 118, 3981, 10908, 3980, 256, 59, 100, 10913, 10914, 25340, 59, 25338, 99, 121, 59, 17498, 896, 65, 69, 97, 100, 101, 115, 116, 10935, 10938, 10942, 10946, 10949, 10998, 11001, 114, 242, 10598, 59, 49152, 8806, 824, 114, 114, 59, 24986, 114, 59, 24613, 512, 59, 102, 113, 115, 3131, 10958, 10979, 10991, 116, 256, 97, 114, 10964, 10969, 114, 114, 111, 247, 10945, 105, 103, 104, 116, 97, 114, 114, 111, 247, 10896, 384, 59, 113, 115, 3131, 10938, 10986, 108, 97, 110, 244, 3157, 256, 59, 115, 3157, 10996, 187, 3126, 105, 237, 3165, 256, 59, 114, 3125, 11006, 105, 256, 59, 101, 3098, 3109, 105, 228, 3472, 256, 112, 116, 11020, 11025, 102, 59, 49152, 55349, 56671, 33152, 172, 59, 105, 110, 11033, 11034, 11062, 16556, 110, 512, 59, 69, 100, 118, 2953, 11044, 11048, 11054, 59, 49152, 8953, 824, 111, 116, 59, 49152, 8949, 824, 481, 2953, 11059, 11061, 59, 25335, 59, 25334, 105, 256, 59, 118, 3256, 11068, 481, 3256, 11073, 11075, 59, 25342, 59, 25341, 384, 97, 111, 114, 11083, 11107, 11113, 114, 512, 59, 97, 115, 116, 2939, 11093, 11098, 11103, 108, 108, 101, 236, 2939, 108, 59, 49152, 11005, 8421, 59, 49152, 8706, 824, 108, 105, 110, 116, 59, 27156, 384, 59, 99, 101, 3218, 11120, 11123, 117, 229, 3237, 256, 59, 99, 3224, 11128, 256, 59, 101, 3218, 11133, 241, 3224, 512, 65, 97, 105, 116, 11144, 11147, 11165, 11175, 114, 242, 10632, 114, 114, 384, 59, 99, 119, 11156, 11157, 11161, 24987, 59, 49152, 10547, 824, 59, 49152, 8605, 824, 103, 104, 116, 97, 114, 114, 111, 119, 187, 11157, 114, 105, 256, 59, 101, 3275, 3286, 896, 99, 104, 105, 109, 112, 113, 117, 11197, 11213, 11225, 11012, 2936, 11236, 11247, 512, 59, 99, 101, 114, 3378, 11206, 3383, 11209, 117, 229, 3397, 59, 49152, 55349, 56515, 111, 114, 116, 621, 11013, 0, 0, 11222, 97, 114, 225, 11094, 109, 256, 59, 101, 3438, 11231, 256, 59, 113, 3444, 3443, 115, 117, 256, 98, 112, 11243, 11245, 229, 3320, 229, 3339, 384, 98, 99, 112, 11254, 11281, 11289, 512, 59, 69, 101, 115, 11263, 11264, 3362, 11268, 25220, 59, 49152, 10949, 824, 101, 116, 256, 59, 101, 3355, 11275, 113, 256, 59, 113, 3363, 11264, 99, 256, 59, 101, 3378, 11287, 241, 3384, 512, 59, 69, 101, 115, 11298, 11299, 3423, 11303, 25221, 59, 49152, 10950, 824, 101, 116, 256, 59, 101, 3416, 11310, 113, 256, 59, 113, 3424, 11299, 512, 103, 105, 108, 114, 11325, 11327, 11333, 11335, 236, 3031, 108, 100, 101, 32827, 241, 16625, 231, 3139, 105, 97, 110, 103, 108, 101, 256, 108, 114, 11346, 11356, 101, 102, 116, 256, 59, 101, 3098, 11354, 241, 3110, 105, 103, 104, 116, 256, 59, 101, 3275, 11365, 241, 3287, 256, 59, 109, 11372, 11373, 17341, 384, 59, 101, 115, 11380, 11381, 11385, 16419, 114, 111, 59, 24854, 112, 59, 24583, 1152, 68, 72, 97, 100, 103, 105, 108, 114, 115, 11407, 11412, 11417, 11422, 11427, 11440, 11446, 11475, 11491, 97, 115, 104, 59, 25261, 97, 114, 114, 59, 26884, 112, 59, 49152, 8781, 8402, 97, 115, 104, 59, 25260, 256, 101, 116, 11432, 11436, 59, 49152, 8805, 8402, 59, 49152, 62, 8402, 110, 102, 105, 110, 59, 27102, 384, 65, 101, 116, 11453, 11457, 11461, 114, 114, 59, 26882, 59, 49152, 8804, 8402, 256, 59, 114, 11466, 11469, 49152, 60, 8402, 105, 101, 59, 49152, 8884, 8402, 256, 65, 116, 11480, 11484, 114, 114, 59, 26883, 114, 105, 101, 59, 49152, 8885, 8402, 105, 109, 59, 49152, 8764, 8402, 384, 65, 97, 110, 11504, 11508, 11522, 114, 114, 59, 25046, 114, 256, 104, 114, 11514, 11517, 107, 59, 26915, 256, 59, 111, 5095, 5093, 101, 97, 114, 59, 26919, 4691, 6805, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11565, 0, 11576, 11592, 11616, 11621, 11634, 11652, 6919, 0, 0, 11661, 11691, 0, 11720, 11726, 0, 11740, 11801, 11819, 11838, 11843, 256, 99, 115, 11569, 6807, 117, 116, 101, 32827, 243, 16627, 256, 105, 121, 11580, 11589, 114, 256, 59, 99, 6814, 11586, 32827, 244, 16628, 59, 17470, 640, 97, 98, 105, 111, 115, 6816, 11602, 11607, 456, 11610, 108, 97, 99, 59, 16721, 118, 59, 27192, 111, 108, 100, 59, 27068, 108, 105, 103, 59, 16723, 256, 99, 114, 11625, 11629, 105, 114, 59, 27071, 59, 49152, 55349, 56620, 879, 11641, 0, 0, 11644, 0, 11650, 110, 59, 17115, 97, 118, 101, 32827, 242, 16626, 59, 27073, 256, 98, 109, 11656, 3572, 97, 114, 59, 27061, 512, 97, 99, 105, 116, 11669, 11672, 11685, 11688, 114, 242, 6784, 256, 105, 114, 11677, 11680, 114, 59, 27070, 111, 115, 115, 59, 27067, 110, 229, 3666, 59, 27072, 384, 97, 101, 105, 11697, 11701, 11705, 99, 114, 59, 16717, 103, 97, 59, 17353, 384, 99, 100, 110, 11712, 11717, 461, 114, 111, 110, 59, 17343, 59, 27062, 112, 102, 59, 49152, 55349, 56672, 384, 97, 101, 108, 11732, 11735, 466, 114, 59, 27063, 114, 112, 59, 27065, 896, 59, 97, 100, 105, 111, 115, 118, 11754, 11755, 11758, 11784, 11789, 11792, 11798, 25128, 114, 242, 6790, 512, 59, 101, 102, 109, 11767, 11768, 11778, 11781, 27229, 114, 256, 59, 111, 11774, 11775, 24884, 102, 187, 11775, 32827, 170, 16554, 32827, 186, 16570, 103, 111, 102, 59, 25270, 114, 59, 27222, 108, 111, 112, 101, 59, 27223, 59, 27227, 384, 99, 108, 111, 11807, 11809, 11815, 242, 11777, 97, 115, 104, 32827, 248, 16632, 108, 59, 25240, 105, 364, 11823, 11828, 100, 101, 32827, 245, 16629, 101, 115, 256, 59, 97, 475, 11834, 115, 59, 27190, 109, 108, 32827, 246, 16630, 98, 97, 114, 59, 25405, 2785, 11870, 0, 11901, 0, 11904, 11933, 0, 11938, 11961, 0, 0, 11979, 3740, 0, 12051, 0, 0, 12075, 12220, 0, 12232, 114, 512, 59, 97, 115, 116, 1027, 11879, 11890, 3717, 33024, 182, 59, 108, 11885, 11886, 16566, 108, 101, 236, 1027, 617, 11896, 0, 0, 11899, 109, 59, 27379, 59, 27389, 121, 59, 17471, 114, 640, 99, 105, 109, 112, 116, 11915, 11919, 11923, 6245, 11927, 110, 116, 59, 16421, 111, 100, 59, 16430, 105, 108, 59, 24624, 101, 110, 107, 59, 24625, 114, 59, 49152, 55349, 56621, 384, 105, 109, 111, 11944, 11952, 11956, 256, 59, 118, 11949, 11950, 17350, 59, 17365, 109, 97, 244, 2678, 110, 101, 59, 26126, 384, 59, 116, 118, 11967, 11968, 11976, 17344, 99, 104, 102, 111, 114, 107, 187, 8189, 59, 17366, 256, 97, 117, 11983, 11999, 110, 256, 99, 107, 11989, 11997, 107, 256, 59, 104, 8692, 11995, 59, 24846, 246, 8692, 115, 1152, 59, 97, 98, 99, 100, 101, 109, 115, 116, 12019, 12020, 6408, 12025, 12029, 12036, 12038, 12042, 12046, 16427, 99, 105, 114, 59, 27171, 105, 114, 59, 27170, 256, 111, 117, 7488, 12034, 59, 27173, 59, 27250, 110, 32955, 177, 3741, 105, 109, 59, 27174, 119, 111, 59, 27175, 384, 105, 112, 117, 12057, 12064, 12069, 110, 116, 105, 110, 116, 59, 27157, 102, 59, 49152, 55349, 56673, 110, 100, 32827, 163, 16547, 1280, 59, 69, 97, 99, 101, 105, 110, 111, 115, 117, 3784, 12095, 12097, 12100, 12103, 12161, 12169, 12178, 12158, 12214, 59, 27315, 112, 59, 27319, 117, 229, 3801, 256, 59, 99, 3790, 12108, 768, 59, 97, 99, 101, 110, 115, 3784, 12121, 12127, 12134, 12136, 12158, 112, 112, 114, 111, 248, 12099, 117, 114, 108, 121, 101, 241, 3801, 241, 3790, 384, 97, 101, 115, 12143, 12150, 12154, 112, 112, 114, 111, 120, 59, 27321, 113, 113, 59, 27317, 105, 109, 59, 25320, 105, 237, 3807, 109, 101, 256, 59, 115, 12168, 3758, 24626, 384, 69, 97, 115, 12152, 12176, 12154, 240, 12149, 384, 100, 102, 112, 3820, 12185, 12207, 384, 97, 108, 115, 12192, 12197, 12202, 108, 97, 114, 59, 25390, 105, 110, 101, 59, 25362, 117, 114, 102, 59, 25363, 256, 59, 116, 3835, 12212, 239, 3835, 114, 101, 108, 59, 25264, 256, 99, 105, 12224, 12229, 114, 59, 49152, 55349, 56517, 59, 17352, 110, 99, 115, 112, 59, 24584, 768, 102, 105, 111, 112, 115, 117, 12250, 8930, 12255, 12261, 12267, 12273, 114, 59, 49152, 55349, 56622, 112, 102, 59, 49152, 55349, 56674, 114, 105, 109, 101, 59, 24663, 99, 114, 59, 49152, 55349, 56518, 384, 97, 101, 111, 12280, 12297, 12307, 116, 256, 101, 105, 12286, 12293, 114, 110, 105, 111, 110, 243, 1712, 110, 116, 59, 27158, 115, 116, 256, 59, 101, 12304, 12305, 16447, 241, 7961, 244, 3860, 2688, 65, 66, 72, 97, 98, 99, 100, 101, 102, 104, 105, 108, 109, 110, 111, 112, 114, 115, 116, 117, 120, 12352, 12369, 12373, 12377, 12512, 12558, 12587, 12615, 12642, 12658, 12686, 12806, 12821, 12836, 12841, 12888, 12910, 12914, 12944, 12976, 12983, 384, 97, 114, 116, 12359, 12362, 12364, 114, 242, 4275, 242, 989, 97, 105, 108, 59, 26908, 97, 114, 242, 7269, 97, 114, 59, 26980, 896, 99, 100, 101, 110, 113, 114, 116, 12392, 12405, 12408, 12415, 12431, 12436, 12492, 256, 101, 117, 12397, 12401, 59, 49152, 8765, 817, 116, 101, 59, 16725, 105, 227, 4462, 109, 112, 116, 121, 118, 59, 27059, 103, 512, 59, 100, 101, 108, 4049, 12425, 12427, 12429, 59, 27026, 59, 27045, 229, 4049, 117, 111, 32827, 187, 16571, 114, 1408, 59, 97, 98, 99, 102, 104, 108, 112, 115, 116, 119, 4060, 12460, 12463, 12471, 12473, 12476, 12478, 12480, 12483, 12487, 12490, 112, 59, 26997, 256, 59, 102, 4064, 12468, 115, 59, 26912, 59, 26931, 115, 59, 26910, 235, 8797, 240, 10030, 108, 59, 26949, 105, 109, 59, 26996, 108, 59, 24995, 59, 24989, 256, 97, 105, 12497, 12501, 105, 108, 59, 26906, 111, 256, 59, 110, 12507, 12508, 25142, 97, 108, 243, 3870, 384, 97, 98, 114, 12519, 12522, 12526, 114, 242, 6117, 114, 107, 59, 26483, 256, 97, 107, 12531, 12541, 99, 256, 101, 107, 12537, 12539, 59, 16509, 59, 16477, 256, 101, 115, 12546, 12548, 59, 27020, 108, 256, 100, 117, 12554, 12556, 59, 27022, 59, 27024, 512, 97, 101, 117, 121, 12567, 12572, 12583, 12585, 114, 111, 110, 59, 16729, 256, 100, 105, 12577, 12581, 105, 108, 59, 16727, 236, 4082, 226, 12538, 59, 17472, 512, 99, 108, 113, 115, 12596, 12599, 12605, 12612, 97, 59, 26935, 100, 104, 97, 114, 59, 26985, 117, 111, 256, 59, 114, 526, 525, 104, 59, 25011, 384, 97, 99, 103, 12622, 12639, 3908, 108, 512, 59, 105, 112, 115, 3960, 12632, 12635, 4252, 110, 229, 4283, 97, 114, 244, 4009, 116, 59, 26029, 384, 105, 108, 114, 12649, 4131, 12654, 115, 104, 116, 59, 27005, 59, 49152, 55349, 56623, 256, 97, 111, 12663, 12678, 114, 256, 100, 117, 12669, 12671, 187, 1147, 256, 59, 108, 4241, 12676, 59, 26988, 256, 59, 118, 12683, 12684, 17345, 59, 17393, 384, 103, 110, 115, 12693, 12793, 12796, 104, 116, 768, 97, 104, 108, 114, 115, 116, 12708, 12720, 12738, 12760, 12772, 12782, 114, 114, 111, 119, 256, 59, 116, 4060, 12717, 97, 233, 12488, 97, 114, 112, 111, 111, 110, 256, 100, 117, 12731, 12735, 111, 119, 238, 12670, 112, 187, 4242, 101, 102, 116, 256, 97, 104, 12746, 12752, 114, 114, 111, 119, 243, 4074, 97, 114, 112, 111, 111, 110, 243, 1361, 105, 103, 104, 116, 97, 114, 114, 111, 119, 115, 59, 25033, 113, 117, 105, 103, 97, 114, 114, 111, 247, 12491, 104, 114, 101, 101, 116, 105, 109, 101, 115, 59, 25292, 103, 59, 17114, 105, 110, 103, 100, 111, 116, 115, 101, 241, 7986, 384, 97, 104, 109, 12813, 12816, 12819, 114, 242, 4074, 97, 242, 1361, 59, 24591, 111, 117, 115, 116, 256, 59, 97, 12830, 12831, 25521, 99, 104, 101, 187, 12831, 109, 105, 100, 59, 27374, 512, 97, 98, 112, 116, 12850, 12861, 12864, 12882, 256, 110, 114, 12855, 12858, 103, 59, 26605, 114, 59, 25086, 114, 235, 4099, 384, 97, 102, 108, 12871, 12874, 12878, 114, 59, 27014, 59, 49152, 55349, 56675, 117, 115, 59, 27182, 105, 109, 101, 115, 59, 27189, 256, 97, 112, 12893, 12903, 114, 256, 59, 103, 12899, 12900, 16425, 116, 59, 27028, 111, 108, 105, 110, 116, 59, 27154, 97, 114, 242, 12771, 512, 97, 99, 104, 113, 12923, 12928, 4284, 12933, 113, 117, 111, 59, 24634, 114, 59, 49152, 55349, 56519, 256, 98, 117, 12539, 12938, 111, 256, 59, 114, 532, 531, 384, 104, 105, 114, 12951, 12955, 12960, 114, 101, 229, 12792, 109, 101, 115, 59, 25290, 105, 512, 59, 101, 102, 108, 12970, 4185, 6177, 12971, 26041, 116, 114, 105, 59, 27086, 108, 117, 104, 97, 114, 59, 26984, 59, 24862, 3425, 13013, 13019, 13023, 13100, 13112, 13169, 0, 13178, 13220, 0, 0, 13292, 13296, 0, 13352, 13384, 13402, 13485, 13489, 13514, 13553, 0, 13846, 0, 0, 13875, 99, 117, 116, 101, 59, 16731, 113, 117, 239, 10170, 1280, 59, 69, 97, 99, 101, 105, 110, 112, 115, 121, 4589, 13043, 13045, 13055, 13058, 13067, 13071, 13087, 13094, 13097, 59, 27316, 496, 13050, 0, 13052, 59, 27320, 111, 110, 59, 16737, 117, 229, 4606, 256, 59, 100, 4595, 13063, 105, 108, 59, 16735, 114, 99, 59, 16733, 384, 69, 97, 115, 13078, 13080, 13083, 59, 27318, 112, 59, 27322, 105, 109, 59, 25321, 111, 108, 105, 110, 116, 59, 27155, 105, 237, 4612, 59, 17473, 111, 116, 384, 59, 98, 101, 13108, 7495, 13109, 25285, 59, 27238, 896, 65, 97, 99, 109, 115, 116, 120, 13126, 13130, 13143, 13147, 13150, 13155, 13165, 114, 114, 59, 25048, 114, 256, 104, 114, 13136, 13138, 235, 8744, 256, 59, 111, 2614, 2612, 116, 32827, 167, 16551, 105, 59, 16443, 119, 97, 114, 59, 26921, 109, 256, 105, 110, 13161, 240, 110, 117, 243, 241, 116, 59, 26422, 114, 256, 59, 111, 13174, 8277, 49152, 55349, 56624, 512, 97, 99, 111, 121, 13186, 13190, 13201, 13216, 114, 112, 59, 26223, 256, 104, 121, 13195, 13199, 99, 121, 59, 17481, 59, 17480, 114, 116, 621, 13209, 0, 0, 13212, 105, 228, 5220, 97, 114, 97, 236, 11887, 32827, 173, 16557, 256, 103, 109, 13224, 13236, 109, 97, 384, 59, 102, 118, 13233, 13234, 13234, 17347, 59, 17346, 1024, 59, 100, 101, 103, 108, 110, 112, 114, 4779, 13253, 13257, 13262, 13270, 13278, 13281, 13286, 111, 116, 59, 27242, 256, 59, 113, 4785, 4784, 256, 59, 69, 13267, 13268, 27294, 59, 27296, 256, 59, 69, 13275, 13276, 27293, 59, 27295, 101, 59, 25158, 108, 117, 115, 59, 27172, 97, 114, 114, 59, 26994, 97, 114, 242, 4413, 512, 97, 101, 105, 116, 13304, 13320, 13327, 13335, 256, 108, 115, 13309, 13316, 108, 115, 101, 116, 109, 233, 13162, 104, 112, 59, 27187, 112, 97, 114, 115, 108, 59, 27108, 256, 100, 108, 5219, 13332, 101, 59, 25379, 256, 59, 101, 13340, 13341, 27306, 256, 59, 115, 13346, 13347, 27308, 59, 49152, 10924, 65024, 384, 102, 108, 112, 13358, 13363, 13378, 116, 99, 121, 59, 17484, 256, 59, 98, 13368, 13369, 16431, 256, 59, 97, 13374, 13375, 27076, 114, 59, 25407, 102, 59, 49152, 55349, 56676, 97, 256, 100, 114, 13389, 1026, 101, 115, 256, 59, 117, 13396, 13397, 26208, 105, 116, 187, 13397, 384, 99, 115, 117, 13408, 13433, 13471, 256, 97, 117, 13413, 13423, 112, 256, 59, 115, 4488, 13419, 59, 49152, 8851, 65024, 112, 256, 59, 115, 4532, 13429, 59, 49152, 8852, 65024, 117, 256, 98, 112, 13439, 13455, 384, 59, 101, 115, 4503, 4508, 13446, 101, 116, 256, 59, 101, 4503, 13453, 241, 4509, 384, 59, 101, 115, 4520, 4525, 13462, 101, 116, 256, 59, 101, 4520, 13469, 241, 4526, 384, 59, 97, 102, 4475, 13478, 1456, 114, 357, 13483, 1457, 187, 4476, 97, 114, 242, 4424, 512, 99, 101, 109, 116, 13497, 13502, 13506, 13509, 114, 59, 49152, 55349, 56520, 116, 109, 238, 241, 105, 236, 13333, 97, 114, 230, 4542, 256, 97, 114, 13518, 13525, 114, 256, 59, 102, 13524, 6079, 26118, 256, 97, 110, 13530, 13549, 105, 103, 104, 116, 256, 101, 112, 13539, 13546, 112, 115, 105, 108, 111, 238, 7904, 104, 233, 11951, 115, 187, 10322, 640, 98, 99, 109, 110, 112, 13563, 13662, 4617, 13707, 13710, 1152, 59, 69, 100, 101, 109, 110, 112, 114, 115, 13582, 13583, 13585, 13589, 13598, 13603, 13612, 13617, 13622, 25218, 59, 27333, 111, 116, 59, 27325, 256, 59, 100, 4570, 13594, 111, 116, 59, 27331, 117, 108, 116, 59, 27329, 256, 69, 101, 13608, 13610, 59, 27339, 59, 25226, 108, 117, 115, 59, 27327, 97, 114, 114, 59, 27001, 384, 101, 105, 117, 13629, 13650, 13653, 116, 384, 59, 101, 110, 13582, 13637, 13643, 113, 256, 59, 113, 4570, 13583, 101, 113, 256, 59, 113, 13611, 13608, 109, 59, 27335, 256, 98, 112, 13658, 13660, 59, 27349, 59, 27347, 99, 768, 59, 97, 99, 101, 110, 115, 4589, 13676, 13682, 13689, 13691, 13094, 112, 112, 114, 111, 248, 13050, 117, 114, 108, 121, 101, 241, 4606, 241, 4595, 384, 97, 101, 115, 13698, 13704, 13083, 112, 112, 114, 111, 248, 13082, 113, 241, 13079, 103, 59, 26218, 1664, 49, 50, 51, 59, 69, 100, 101, 104, 108, 109, 110, 112, 115, 13737, 13740, 13743, 4636, 13746, 13748, 13760, 13769, 13781, 13786, 13791, 13800, 13805, 32827, 185, 16569, 32827, 178, 16562, 32827, 179, 16563, 59, 27334, 256, 111, 115, 13753, 13756, 116, 59, 27326, 117, 98, 59, 27352, 256, 59, 100, 4642, 13765, 111, 116, 59, 27332, 115, 256, 111, 117, 13775, 13778, 108, 59, 26569, 98, 59, 27351, 97, 114, 114, 59, 27003, 117, 108, 116, 59, 27330, 256, 69, 101, 13796, 13798, 59, 27340, 59, 25227, 108, 117, 115, 59, 27328, 384, 101, 105, 117, 13812, 13833, 13836, 116, 384, 59, 101, 110, 4636, 13820, 13826, 113, 256, 59, 113, 4642, 13746, 101, 113, 256, 59, 113, 13799, 13796, 109, 59, 27336, 256, 98, 112, 13841, 13843, 59, 27348, 59, 27350, 384, 65, 97, 110, 13852, 13856, 13869, 114, 114, 59, 25049, 114, 256, 104, 114, 13862, 13864, 235, 8750, 256, 59, 111, 2603, 2601, 119, 97, 114, 59, 26922, 108, 105, 103, 32827, 223, 16607, 3041, 13905, 13917, 13920, 4814, 13939, 13945, 0, 13950, 14018, 0, 0, 0, 0, 0, 14043, 14083, 0, 14089, 14188, 0, 0, 0, 14215, 626, 13910, 0, 0, 13915, 103, 101, 116, 59, 25366, 59, 17348, 114, 235, 3679, 384, 97, 101, 121, 13926, 13931, 13936, 114, 111, 110, 59, 16741, 100, 105, 108, 59, 16739, 59, 17474, 108, 114, 101, 99, 59, 25365, 114, 59, 49152, 55349, 56625, 512, 101, 105, 107, 111, 13958, 13981, 14005, 14012, 498, 13963, 0, 13969, 101, 256, 52, 102, 4740, 4737, 97, 384, 59, 115, 118, 13976, 13977, 13979, 17336, 121, 109, 59, 17361, 256, 99, 110, 13986, 14002, 107, 256, 97, 115, 13992, 13998, 112, 112, 114, 111, 248, 4801, 105, 109, 187, 4780, 115, 240, 4766, 256, 97, 115, 14010, 13998, 240, 4801, 114, 110, 32827, 254, 16638, 492, 799, 14022, 8935, 101, 115, 33152, 215, 59, 98, 100, 14031, 14032, 14040, 16599, 256, 59, 97, 6415, 14037, 114, 59, 27185, 59, 27184, 384, 101, 112, 115, 14049, 14051, 14080, 225, 10829, 512, 59, 98, 99, 102, 1158, 14060, 14064, 14068, 111, 116, 59, 25398, 105, 114, 59, 27377, 256, 59, 111, 14073, 14076, 49152, 55349, 56677, 114, 107, 59, 27354, 225, 13154, 114, 105, 109, 101, 59, 24628, 384, 97, 105, 112, 14095, 14098, 14180, 100, 229, 4680, 896, 97, 100, 101, 109, 112, 115, 116, 14113, 14157, 14144, 14161, 14167, 14172, 14175, 110, 103, 108, 101, 640, 59, 100, 108, 113, 114, 14128, 14129, 14134, 14144, 14146, 26037, 111, 119, 110, 187, 7611, 101, 102, 116, 256, 59, 101, 10240, 14142, 241, 2350, 59, 25180, 105, 103, 104, 116, 256, 59, 101, 12970, 14155, 241, 4186, 111, 116, 59, 26092, 105, 110, 117, 115, 59, 27194, 108, 117, 115, 59, 27193, 98, 59, 27085, 105, 109, 101, 59, 27195, 101, 122, 105, 117, 109, 59, 25570, 384, 99, 104, 116, 14194, 14205, 14209, 256, 114, 121, 14199, 14203, 59, 49152, 55349, 56521, 59, 17478, 99, 121, 59, 17499, 114, 111, 107, 59, 16743, 256, 105, 111, 14219, 14222, 120, 244, 6007, 104, 101, 97, 100, 256, 108, 114, 14231, 14240, 101, 102, 116, 97, 114, 114, 111, 247, 2127, 105, 103, 104, 116, 97, 114, 114, 111, 119, 187, 3933, 2304, 65, 72, 97, 98, 99, 100, 102, 103, 104, 108, 109, 111, 112, 114, 115, 116, 117, 119, 14288, 14291, 14295, 14308, 14320, 14332, 14350, 14364, 14371, 14388, 14417, 14429, 14443, 14505, 14540, 14546, 14570, 14582, 114, 242, 1005, 97, 114, 59, 26979, 256, 99, 114, 14300, 14306, 117, 116, 101, 32827, 250, 16634, 242, 4432, 114, 483, 14314, 0, 14317, 121, 59, 17502, 118, 101, 59, 16749, 256, 105, 121, 14325, 14330, 114, 99, 32827, 251, 16635, 59, 17475, 384, 97, 98, 104, 14339, 14342, 14347, 114, 242, 5037, 108, 97, 99, 59, 16753, 97, 242, 5059, 256, 105, 114, 14355, 14360, 115, 104, 116, 59, 27006, 59, 49152, 55349, 56626, 114, 97, 118, 101, 32827, 249, 16633, 353, 14375, 14385, 114, 256, 108, 114, 14380, 14382, 187, 2391, 187, 4227, 108, 107, 59, 25984, 256, 99, 116, 14393, 14413, 623, 14399, 0, 0, 14410, 114, 110, 256, 59, 101, 14405, 14406, 25372, 114, 187, 14406, 111, 112, 59, 25359, 114, 105, 59, 26104, 256, 97, 108, 14422, 14426, 99, 114, 59, 16747, 32955, 168, 841, 256, 103, 112, 14434, 14438, 111, 110, 59, 16755, 102, 59, 49152, 55349, 56678, 768, 97, 100, 104, 108, 115, 117, 4427, 14456, 14461, 4978, 14481, 14496, 111, 119, 110, 225, 5043, 97, 114, 112, 111, 111, 110, 256, 108, 114, 14472, 14476, 101, 102, 244, 14381, 105, 103, 104, 244, 14383, 105, 384, 59, 104, 108, 14489, 14490, 14492, 17349, 187, 5114, 111, 110, 187, 14490, 112, 97, 114, 114, 111, 119, 115, 59, 25032, 384, 99, 105, 116, 14512, 14532, 14536, 623, 14518, 0, 0, 14529, 114, 110, 256, 59, 101, 14524, 14525, 25373, 114, 187, 14525, 111, 112, 59, 25358, 110, 103, 59, 16751, 114, 105, 59, 26105, 99, 114, 59, 49152, 55349, 56522, 384, 100, 105, 114, 14553, 14557, 14562, 111, 116, 59, 25328, 108, 100, 101, 59, 16745, 105, 256, 59, 102, 14128, 14568, 187, 6163, 256, 97, 109, 14575, 14578, 114, 242, 14504, 108, 32827, 252, 16636, 97, 110, 103, 108, 101, 59, 27047, 1920, 65, 66, 68, 97, 99, 100, 101, 102, 108, 110, 111, 112, 114, 115, 122, 14620, 14623, 14633, 14637, 14773, 14776, 14781, 14815, 14820, 14824, 14835, 14841, 14845, 14849, 14880, 114, 242, 1015, 97, 114, 256, 59, 118, 14630, 14631, 27368, 59, 27369, 97, 115, 232, 993, 256, 110, 114, 14642, 14647, 103, 114, 116, 59, 27036, 896, 101, 107, 110, 112, 114, 115, 116, 13539, 14662, 14667, 14674, 14685, 14692, 14742, 97, 112, 112, 225, 9237, 111, 116, 104, 105, 110, 231, 7830, 384, 104, 105, 114, 13547, 11976, 14681, 111, 112, 244, 12213, 256, 59, 104, 5047, 14690, 239, 12685, 256, 105, 117, 14697, 14701, 103, 109, 225, 13235, 256, 98, 112, 14706, 14724, 115, 101, 116, 110, 101, 113, 256, 59, 113, 14717, 14720, 49152, 8842, 65024, 59, 49152, 10955, 65024, 115, 101, 116, 110, 101, 113, 256, 59, 113, 14735, 14738, 49152, 8843, 65024, 59, 49152, 10956, 65024, 256, 104, 114, 14747, 14751, 101, 116, 225, 13980, 105, 97, 110, 103, 108, 101, 256, 108, 114, 14762, 14767, 101, 102, 116, 187, 2341, 105, 103, 104, 116, 187, 4177, 121, 59, 17458, 97, 115, 104, 187, 4150, 384, 101, 108, 114, 14788, 14802, 14807, 384, 59, 98, 101, 11754, 14795, 14799, 97, 114, 59, 25275, 113, 59, 25178, 108, 105, 112, 59, 25326, 256, 98, 116, 14812, 5224, 97, 242, 5225, 114, 59, 49152, 55349, 56627, 116, 114, 233, 14766, 115, 117, 256, 98, 112, 14831, 14833, 187, 3356, 187, 3417, 112, 102, 59, 49152, 55349, 56679, 114, 111, 240, 3835, 116, 114, 233, 14772, 256, 99, 117, 14854, 14859, 114, 59, 49152, 55349, 56523, 256, 98, 112, 14864, 14872, 110, 256, 69, 101, 14720, 14870, 187, 14718, 110, 256, 69, 101, 14738, 14878, 187, 14736, 105, 103, 122, 97, 103, 59, 27034, 896, 99, 101, 102, 111, 112, 114, 115, 14902, 14907, 14934, 14939, 14932, 14945, 14954, 105, 114, 99, 59, 16757, 256, 100, 105, 14912, 14929, 256, 98, 103, 14917, 14921, 97, 114, 59, 27231, 101, 256, 59, 113, 5626, 14927, 59, 25177, 101, 114, 112, 59, 24856, 114, 59, 49152, 55349, 56628, 112, 102, 59, 49152, 55349, 56680, 256, 59, 101, 5241, 14950, 97, 116, 232, 5241, 99, 114, 59, 49152, 55349, 56524, 2787, 6030, 14983, 0, 14987, 0, 14992, 15003, 0, 0, 15005, 15016, 15019, 15023, 0, 0, 15043, 15054, 0, 15064, 6108, 6111, 116, 114, 233, 6097, 114, 59, 49152, 55349, 56629, 256, 65, 97, 14996, 14999, 114, 242, 963, 114, 242, 2550, 59, 17342, 256, 65, 97, 15009, 15012, 114, 242, 952, 114, 242, 2539, 97, 240, 10003, 105, 115, 59, 25339, 384, 100, 112, 116, 6052, 15029, 15038, 256, 102, 108, 15034, 6057, 59, 49152, 55349, 56681, 105, 109, 229, 6066, 256, 65, 97, 15047, 15050, 114, 242, 974, 114, 242, 2561, 256, 99, 113, 15058, 6072, 114, 59, 49152, 55349, 56525, 256, 112, 116, 6102, 15068, 114, 233, 6100, 1024, 97, 99, 101, 102, 105, 111, 115, 117, 15088, 15101, 15112, 15116, 15121, 15125, 15131, 15137, 99, 256, 117, 121, 15094, 15099, 116, 101, 32827, 253, 16637, 59, 17487, 256, 105, 121, 15106, 15110, 114, 99, 59, 16759, 59, 17483, 110, 32827, 165, 16549, 114, 59, 49152, 55349, 56630, 99, 121, 59, 17495, 112, 102, 59, 49152, 55349, 56682, 99, 114, 59, 49152, 55349, 56526, 256, 99, 109, 15142, 15145, 121, 59, 17486, 108, 32827, 255, 16639, 1280, 97, 99, 100, 101, 102, 104, 105, 111, 115, 119, 15170, 15176, 15188, 15192, 15204, 15209, 15213, 15220, 15226, 15232, 99, 117, 116, 101, 59, 16762, 256, 97, 121, 15181, 15186, 114, 111, 110, 59, 16766, 59, 17463, 111, 116, 59, 16764, 256, 101, 116, 15197, 15201, 116, 114, 230, 5471, 97, 59, 17334, 114, 59, 49152, 55349, 56631, 99, 121, 59, 17462, 103, 114, 97, 114, 114, 59, 25053, 112, 102, 59, 49152, 55349, 56683, 99, 114, 59, 49152, 55349, 56527, 256, 106, 110, 15237, 15239, 59, 24589, 106, 59, 24588]);
});
unwrapExports(decodeDataHtml);
var decodeDataXml = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
// Generated using scripts/write-decode-map.ts
// prettier-ignore
exports.default = new Uint16Array([512, 97, 103, 108, 113, 9, 21, 24, 27, 621, 15, 0, 0, 18, 112, 59, 16422, 111, 115, 59, 16423, 116, 59, 16446, 116, 59, 16444, 117, 111, 116, 59, 16418]);
});
unwrapExports(decodeDataXml);
var decode_codepoint = createCommonjsModule(function (module, exports) {
// Adapted from https://github.com/mathiasbynens/he/blob/36afe179392226cf1b6ccdb16ebbb7a5a844d93a/src/he.js#L106-L134
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.replaceCodePoint = exports.fromCodePoint = void 0;
var decodeMap = new Map([
[0, 65533],
[128, 8364],
[130, 8218],
[131, 402],
[132, 8222],
[133, 8230],
[134, 8224],
[135, 8225],
[136, 710],
[137, 8240],
[138, 352],
[139, 8249],
[140, 338],
[142, 381],
[145, 8216],
[146, 8217],
[147, 8220],
[148, 8221],
[149, 8226],
[150, 8211],
[151, 8212],
[152, 732],
[153, 8482],
[154, 353],
[155, 8250],
[156, 339],
[158, 382],
[159, 376],
]);
exports.fromCodePoint =
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, node/no-unsupported-features/es-builtins
(_a = String.fromCodePoint) !== null && _a !== void 0 ? _a : function (codePoint) {
var output = "";
if (codePoint > 0xffff) {
codePoint -= 0x10000;
output += String.fromCharCode(((codePoint >>> 10) & 0x3ff) | 0xd800);
codePoint = 0xdc00 | (codePoint & 0x3ff);
}
output += String.fromCharCode(codePoint);
return output;
};
function replaceCodePoint(codePoint) {
var _a;
if ((codePoint >= 0xd800 && codePoint <= 0xdfff) || codePoint > 0x10ffff) {
return 0xfffd;
}
return (_a = decodeMap.get(codePoint)) !== null && _a !== void 0 ? _a : codePoint;
}
exports.replaceCodePoint = replaceCodePoint;
function decodeCodePoint(codePoint) {
return (0, exports.fromCodePoint)(replaceCodePoint(codePoint));
}
exports.default = decodeCodePoint;
});
unwrapExports(decode_codepoint);
var decode_codepoint_1 = decode_codepoint.replaceCodePoint;
var decode_codepoint_2 = decode_codepoint.fromCodePoint;
var decode = createCommonjsModule(function (module, exports) {
var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.decodeXML = exports.decodeHTMLStrict = exports.decodeHTML = exports.determineBranch = exports.BinTrieFlags = exports.fromCodePoint = exports.replaceCodePoint = exports.decodeCodePoint = exports.xmlDecodeTree = exports.htmlDecodeTree = void 0;
var decode_data_html_js_1 = __importDefault(decodeDataHtml);
exports.htmlDecodeTree = decode_data_html_js_1.default;
var decode_data_xml_js_1 = __importDefault(decodeDataXml);
exports.xmlDecodeTree = decode_data_xml_js_1.default;
var decode_codepoint_js_1 = __importDefault(decode_codepoint);
exports.decodeCodePoint = decode_codepoint_js_1.default;
var decode_codepoint_js_2 = decode_codepoint;
Object.defineProperty(exports, "replaceCodePoint", { enumerable: true, get: function () { return decode_codepoint_js_2.replaceCodePoint; } });
Object.defineProperty(exports, "fromCodePoint", { enumerable: true, get: function () { return decode_codepoint_js_2.fromCodePoint; } });
var CharCodes;
(function (CharCodes) {
CharCodes[CharCodes["NUM"] = 35] = "NUM";
CharCodes[CharCodes["SEMI"] = 59] = "SEMI";
CharCodes[CharCodes["ZERO"] = 48] = "ZERO";
CharCodes[CharCodes["NINE"] = 57] = "NINE";
CharCodes[CharCodes["LOWER_A"] = 97] = "LOWER_A";
CharCodes[CharCodes["LOWER_F"] = 102] = "LOWER_F";
CharCodes[CharCodes["LOWER_X"] = 120] = "LOWER_X";
/** Bit that needs to be set to convert an upper case ASCII character to lower case */
CharCodes[CharCodes["To_LOWER_BIT"] = 32] = "To_LOWER_BIT";
})(CharCodes || (CharCodes = {}));
var BinTrieFlags;
(function (BinTrieFlags) {
BinTrieFlags[BinTrieFlags["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH";
BinTrieFlags[BinTrieFlags["BRANCH_LENGTH"] = 16256] = "BRANCH_LENGTH";
BinTrieFlags[BinTrieFlags["JUMP_TABLE"] = 127] = "JUMP_TABLE";
})(BinTrieFlags = exports.BinTrieFlags || (exports.BinTrieFlags = {}));
function getDecoder(decodeTree) {
return function decodeHTMLBinary(str, strict) {
var ret = "";
var lastIdx = 0;
var strIdx = 0;
while ((strIdx = str.indexOf("&", strIdx)) >= 0) {
ret += str.slice(lastIdx, strIdx);
lastIdx = strIdx;
// Skip the "&"
strIdx += 1;
// If we have a numeric entity, handle this separately.
if (str.charCodeAt(strIdx) === CharCodes.NUM) {
// Skip the leading "&#". For hex entities, also skip the leading "x".
var start = strIdx + 1;
var base = 10;
var cp = str.charCodeAt(start);
if ((cp | CharCodes.To_LOWER_BIT) === CharCodes.LOWER_X) {
base = 16;
strIdx += 1;
start += 1;
}
do
cp = str.charCodeAt(++strIdx);
while ((cp >= CharCodes.ZERO && cp <= CharCodes.NINE) ||
(base === 16 &&
(cp | CharCodes.To_LOWER_BIT) >= CharCodes.LOWER_A &&
(cp | CharCodes.To_LOWER_BIT) <= CharCodes.LOWER_F));
if (start !== strIdx) {
var entity = str.substring(start, strIdx);
var parsed = parseInt(entity, base);
if (str.charCodeAt(strIdx) === CharCodes.SEMI) {
strIdx += 1;
}
else if (strict) {
continue;
}
ret += (0, decode_codepoint_js_1.default)(parsed);
lastIdx = strIdx;
}
continue;
}
var resultIdx = 0;
var excess = 1;
var treeIdx = 0;
var current = decodeTree[treeIdx];
for (; strIdx < str.length; strIdx++, excess++) {
treeIdx = determineBranch(decodeTree, current, treeIdx + 1, str.charCodeAt(strIdx));
if (treeIdx < 0)
break;
current = decodeTree[treeIdx];
var masked = current & BinTrieFlags.VALUE_LENGTH;
// If the branch is a value, store it and continue
if (masked) {
// If we have a legacy entity while parsing strictly, just skip the number of bytes
if (!strict || str.charCodeAt(strIdx) === CharCodes.SEMI) {
resultIdx = treeIdx;
excess = 0;
}
// The mask is the number of bytes of the value, including the current byte.
var valueLength = (masked >> 14) - 1;
if (valueLength === 0)
break;
treeIdx += valueLength;
}
}
if (resultIdx !== 0) {
var valueLength = (decodeTree[resultIdx] & BinTrieFlags.VALUE_LENGTH) >> 14;
ret +=
valueLength === 1
? String.fromCharCode(decodeTree[resultIdx] & ~BinTrieFlags.VALUE_LENGTH)
: valueLength === 2
? String.fromCharCode(decodeTree[resultIdx + 1])
: String.fromCharCode(decodeTree[resultIdx + 1], decodeTree[resultIdx + 2]);
lastIdx = strIdx - excess + 1;
}
}
return ret + str.slice(lastIdx);
};
}
function determineBranch(decodeTree, current, nodeIdx, char) {
var branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
var jumpOffset = current & BinTrieFlags.JUMP_TABLE;
// Case 1: Single branch encoded in jump offset
if (branchCount === 0) {
return jumpOffset !== 0 && char === jumpOffset ? nodeIdx : -1;
}
// Case 2: Multiple branches encoded in jump table
if (jumpOffset) {
var value = char - jumpOffset;
return value < 0 || value > branchCount
? -1
: decodeTree[nodeIdx + value] - 1;
}
// Case 3: Multiple branches encoded in dictionary
// Binary search for the character.
var lo = nodeIdx;
var hi = lo + branchCount - 1;
while (lo <= hi) {
var mid = (lo + hi) >>> 1;
var midVal = decodeTree[mid];
if (midVal < char) {
lo = mid + 1;
}
else if (midVal > char) {
hi = mid - 1;
}
else {
return decodeTree[mid + branchCount];
}
}
return -1;
}
exports.determineBranch = determineBranch;
var htmlDecoder = getDecoder(decode_data_html_js_1.default);
var xmlDecoder = getDecoder(decode_data_xml_js_1.default);
function decodeHTML(str) {
return htmlDecoder(str, false);
}
exports.decodeHTML = decodeHTML;
function decodeHTMLStrict(str) {
return htmlDecoder(str, true);
}
exports.decodeHTMLStrict = decodeHTMLStrict;
function decodeXML(str) {
return xmlDecoder(str, true);
}
exports.decodeXML = decodeXML;
});
unwrapExports(decode);
var decode_1 = decode.decodeXML;
var decode_2 = decode.decodeHTMLStrict;
var decode_3 = decode.decodeHTML;
var decode_4 = decode.determineBranch;
var decode_5 = decode.BinTrieFlags;
var decode_6 = decode.fromCodePoint;
var decode_7 = decode.replaceCodePoint;
var decode_8 = decode.decodeCodePoint;
var decode_9 = decode.xmlDecodeTree;
var decode_10 = decode.htmlDecodeTree;
/** All valid namespaces in HTML. */
var NS;
(function (NS) {
NS["HTML"] = "http://www.w3.org/1999/xhtml";
NS["MATHML"] = "http://www.w3.org/1998/Math/MathML";
NS["SVG"] = "http://www.w3.org/2000/svg";
NS["XLINK"] = "http://www.w3.org/1999/xlink";
NS["XML"] = "http://www.w3.org/XML/1998/namespace";
NS["XMLNS"] = "http://www.w3.org/2000/xmlns/";
})(NS || (NS = {}));
var ATTRS;
(function (ATTRS) {
ATTRS["TYPE"] = "type";
ATTRS["ACTION"] = "action";
ATTRS["ENCODING"] = "encoding";
ATTRS["PROMPT"] = "prompt";
ATTRS["NAME"] = "name";
ATTRS["COLOR"] = "color";
ATTRS["FACE"] = "face";
ATTRS["SIZE"] = "size";
})(ATTRS || (ATTRS = {}));
/**
* The mode of the document.
*
* @see {@link https://dom.spec.whatwg.org/#concept-document-limited-quirks}
*/
var DOCUMENT_MODE;
(function (DOCUMENT_MODE) {
DOCUMENT_MODE["NO_QUIRKS"] = "no-quirks";
DOCUMENT_MODE["QUIRKS"] = "quirks";
DOCUMENT_MODE["LIMITED_QUIRKS"] = "limited-quirks";
})(DOCUMENT_MODE || (DOCUMENT_MODE = {}));
var TAG_NAMES;
(function (TAG_NAMES) {
TAG_NAMES["A"] = "a";
TAG_NAMES["ADDRESS"] = "address";
TAG_NAMES["ANNOTATION_XML"] = "annotation-xml";
TAG_NAMES["APPLET"] = "applet";
TAG_NAMES["AREA"] = "area";
TAG_NAMES["ARTICLE"] = "article";
TAG_NAMES["ASIDE"] = "aside";
TAG_NAMES["B"] = "b";
TAG_NAMES["BASE"] = "base";
TAG_NAMES["BASEFONT"] = "basefont";
TAG_NAMES["BGSOUND"] = "bgsound";
TAG_NAMES["BIG"] = "big";
TAG_NAMES["BLOCKQUOTE"] = "blockquote";
TAG_NAMES["BODY"] = "body";
TAG_NAMES["BR"] = "br";
TAG_NAMES["BUTTON"] = "button";
TAG_NAMES["CAPTION"] = "caption";
TAG_NAMES["CENTER"] = "center";
TAG_NAMES["CODE"] = "code";
TAG_NAMES["COL"] = "col";
TAG_NAMES["COLGROUP"] = "colgroup";
TAG_NAMES["DD"] = "dd";
TAG_NAMES["DESC"] = "desc";
TAG_NAMES["DETAILS"] = "details";
TAG_NAMES["DIALOG"] = "dialog";
TAG_NAMES["DIR"] = "dir";
TAG_NAMES["DIV"] = "div";
TAG_NAMES["DL"] = "dl";
TAG_NAMES["DT"] = "dt";
TAG_NAMES["EM"] = "em";
TAG_NAMES["EMBED"] = "embed";
TAG_NAMES["FIELDSET"] = "fieldset";
TAG_NAMES["FIGCAPTION"] = "figcaption";
TAG_NAMES["FIGURE"] = "figure";
TAG_NAMES["FONT"] = "font";
TAG_NAMES["FOOTER"] = "footer";
TAG_NAMES["FOREIGN_OBJECT"] = "foreignObject";
TAG_NAMES["FORM"] = "form";
TAG_NAMES["FRAME"] = "frame";
TAG_NAMES["FRAMESET"] = "frameset";
TAG_NAMES["H1"] = "h1";
TAG_NAMES["H2"] = "h2";
TAG_NAMES["H3"] = "h3";
TAG_NAMES["H4"] = "h4";
TAG_NAMES["H5"] = "h5";
TAG_NAMES["H6"] = "h6";
TAG_NAMES["HEAD"] = "head";
TAG_NAMES["HEADER"] = "header";
TAG_NAMES["HGROUP"] = "hgroup";
TAG_NAMES["HR"] = "hr";
TAG_NAMES["HTML"] = "html";
TAG_NAMES["I"] = "i";
TAG_NAMES["IMG"] = "img";
TAG_NAMES["IMAGE"] = "image";
TAG_NAMES["INPUT"] = "input";
TAG_NAMES["IFRAME"] = "iframe";
TAG_NAMES["KEYGEN"] = "keygen";
TAG_NAMES["LABEL"] = "label";
TAG_NAMES["LI"] = "li";
TAG_NAMES["LINK"] = "link";
TAG_NAMES["LISTING"] = "listing";
TAG_NAMES["MAIN"] = "main";
TAG_NAMES["MALIGNMARK"] = "malignmark";
TAG_NAMES["MARQUEE"] = "marquee";
TAG_NAMES["MATH"] = "math";
TAG_NAMES["MENU"] = "menu";
TAG_NAMES["META"] = "meta";
TAG_NAMES["MGLYPH"] = "mglyph";
TAG_NAMES["MI"] = "mi";
TAG_NAMES["MO"] = "mo";
TAG_NAMES["MN"] = "mn";
TAG_NAMES["MS"] = "ms";
TAG_NAMES["MTEXT"] = "mtext";
TAG_NAMES["NAV"] = "nav";
TAG_NAMES["NOBR"] = "nobr";
TAG_NAMES["NOFRAMES"] = "noframes";
TAG_NAMES["NOEMBED"] = "noembed";
TAG_NAMES["NOSCRIPT"] = "noscript";
TAG_NAMES["OBJECT"] = "object";
TAG_NAMES["OL"] = "ol";
TAG_NAMES["OPTGROUP"] = "optgroup";
TAG_NAMES["OPTION"] = "option";
TAG_NAMES["P"] = "p";
TAG_NAMES["PARAM"] = "param";
TAG_NAMES["PLAINTEXT"] = "plaintext";
TAG_NAMES["PRE"] = "pre";
TAG_NAMES["RB"] = "rb";
TAG_NAMES["RP"] = "rp";
TAG_NAMES["RT"] = "rt";
TAG_NAMES["RTC"] = "rtc";
TAG_NAMES["RUBY"] = "ruby";
TAG_NAMES["S"] = "s";
TAG_NAMES["SCRIPT"] = "script";
TAG_NAMES["SECTION"] = "section";
TAG_NAMES["SELECT"] = "select";
TAG_NAMES["SOURCE"] = "source";
TAG_NAMES["SMALL"] = "small";
TAG_NAMES["SPAN"] = "span";
TAG_NAMES["STRIKE"] = "strike";
TAG_NAMES["STRONG"] = "strong";
TAG_NAMES["STYLE"] = "style";
TAG_NAMES["SUB"] = "sub";
TAG_NAMES["SUMMARY"] = "summary";
TAG_NAMES["SUP"] = "sup";
TAG_NAMES["TABLE"] = "table";
TAG_NAMES["TBODY"] = "tbody";
TAG_NAMES["TEMPLATE"] = "template";
TAG_NAMES["TEXTAREA"] = "textarea";
TAG_NAMES["TFOOT"] = "tfoot";
TAG_NAMES["TD"] = "td";
TAG_NAMES["TH"] = "th";
TAG_NAMES["THEAD"] = "thead";
TAG_NAMES["TITLE"] = "title";
TAG_NAMES["TR"] = "tr";
TAG_NAMES["TRACK"] = "track";
TAG_NAMES["TT"] = "tt";
TAG_NAMES["U"] = "u";
TAG_NAMES["UL"] = "ul";
TAG_NAMES["SVG"] = "svg";
TAG_NAMES["VAR"] = "var";
TAG_NAMES["WBR"] = "wbr";
TAG_NAMES["XMP"] = "xmp";
})(TAG_NAMES || (TAG_NAMES = {}));
/**
* Tag IDs are numeric IDs for known tag names.
*
* We use tag IDs to improve the performance of tag name comparisons.
*/
var TAG_ID;
(function (TAG_ID) {
TAG_ID[TAG_ID["UNKNOWN"] = 0] = "UNKNOWN";
TAG_ID[TAG_ID["A"] = 1] = "A";
TAG_ID[TAG_ID["ADDRESS"] = 2] = "ADDRESS";
TAG_ID[TAG_ID["ANNOTATION_XML"] = 3] = "ANNOTATION_XML";
TAG_ID[TAG_ID["APPLET"] = 4] = "APPLET";
TAG_ID[TAG_ID["AREA"] = 5] = "AREA";
TAG_ID[TAG_ID["ARTICLE"] = 6] = "ARTICLE";
TAG_ID[TAG_ID["ASIDE"] = 7] = "ASIDE";
TAG_ID[TAG_ID["B"] = 8] = "B";
TAG_ID[TAG_ID["BASE"] = 9] = "BASE";
TAG_ID[TAG_ID["BASEFONT"] = 10] = "BASEFONT";
TAG_ID[TAG_ID["BGSOUND"] = 11] = "BGSOUND";
TAG_ID[TAG_ID["BIG"] = 12] = "BIG";
TAG_ID[TAG_ID["BLOCKQUOTE"] = 13] = "BLOCKQUOTE";
TAG_ID[TAG_ID["BODY"] = 14] = "BODY";
TAG_ID[TAG_ID["BR"] = 15] = "BR";
TAG_ID[TAG_ID["BUTTON"] = 16] = "BUTTON";
TAG_ID[TAG_ID["CAPTION"] = 17] = "CAPTION";
TAG_ID[TAG_ID["CENTER"] = 18] = "CENTER";
TAG_ID[TAG_ID["CODE"] = 19] = "CODE";
TAG_ID[TAG_ID["COL"] = 20] = "COL";
TAG_ID[TAG_ID["COLGROUP"] = 21] = "COLGROUP";
TAG_ID[TAG_ID["DD"] = 22] = "DD";
TAG_ID[TAG_ID["DESC"] = 23] = "DESC";
TAG_ID[TAG_ID["DETAILS"] = 24] = "DETAILS";
TAG_ID[TAG_ID["DIALOG"] = 25] = "DIALOG";
TAG_ID[TAG_ID["DIR"] = 26] = "DIR";
TAG_ID[TAG_ID["DIV"] = 27] = "DIV";
TAG_ID[TAG_ID["DL"] = 28] = "DL";
TAG_ID[TAG_ID["DT"] = 29] = "DT";
TAG_ID[TAG_ID["EM"] = 30] = "EM";
TAG_ID[TAG_ID["EMBED"] = 31] = "EMBED";
TAG_ID[TAG_ID["FIELDSET"] = 32] = "FIELDSET";
TAG_ID[TAG_ID["FIGCAPTION"] = 33] = "FIGCAPTION";
TAG_ID[TAG_ID["FIGURE"] = 34] = "FIGURE";
TAG_ID[TAG_ID["FONT"] = 35] = "FONT";
TAG_ID[TAG_ID["FOOTER"] = 36] = "FOOTER";
TAG_ID[TAG_ID["FOREIGN_OBJECT"] = 37] = "FOREIGN_OBJECT";
TAG_ID[TAG_ID["FORM"] = 38] = "FORM";
TAG_ID[TAG_ID["FRAME"] = 39] = "FRAME";
TAG_ID[TAG_ID["FRAMESET"] = 40] = "FRAMESET";
TAG_ID[TAG_ID["H1"] = 41] = "H1";
TAG_ID[TAG_ID["H2"] = 42] = "H2";
TAG_ID[TAG_ID["H3"] = 43] = "H3";
TAG_ID[TAG_ID["H4"] = 44] = "H4";
TAG_ID[TAG_ID["H5"] = 45] = "H5";
TAG_ID[TAG_ID["H6"] = 46] = "H6";
TAG_ID[TAG_ID["HEAD"] = 47] = "HEAD";
TAG_ID[TAG_ID["HEADER"] = 48] = "HEADER";
TAG_ID[TAG_ID["HGROUP"] = 49] = "HGROUP";
TAG_ID[TAG_ID["HR"] = 50] = "HR";
TAG_ID[TAG_ID["HTML"] = 51] = "HTML";
TAG_ID[TAG_ID["I"] = 52] = "I";
TAG_ID[TAG_ID["IMG"] = 53] = "IMG";
TAG_ID[TAG_ID["IMAGE"] = 54] = "IMAGE";
TAG_ID[TAG_ID["INPUT"] = 55] = "INPUT";
TAG_ID[TAG_ID["IFRAME"] = 56] = "IFRAME";
TAG_ID[TAG_ID["KEYGEN"] = 57] = "KEYGEN";
TAG_ID[TAG_ID["LABEL"] = 58] = "LABEL";
TAG_ID[TAG_ID["LI"] = 59] = "LI";
TAG_ID[TAG_ID["LINK"] = 60] = "LINK";
TAG_ID[TAG_ID["LISTING"] = 61] = "LISTING";
TAG_ID[TAG_ID["MAIN"] = 62] = "MAIN";
TAG_ID[TAG_ID["MALIGNMARK"] = 63] = "MALIGNMARK";
TAG_ID[TAG_ID["MARQUEE"] = 64] = "MARQUEE";
TAG_ID[TAG_ID["MATH"] = 65] = "MATH";
TAG_ID[TAG_ID["MENU"] = 66] = "MENU";
TAG_ID[TAG_ID["META"] = 67] = "META";
TAG_ID[TAG_ID["MGLYPH"] = 68] = "MGLYPH";
TAG_ID[TAG_ID["MI"] = 69] = "MI";
TAG_ID[TAG_ID["MO"] = 70] = "MO";
TAG_ID[TAG_ID["MN"] = 71] = "MN";
TAG_ID[TAG_ID["MS"] = 72] = "MS";
TAG_ID[TAG_ID["MTEXT"] = 73] = "MTEXT";
TAG_ID[TAG_ID["NAV"] = 74] = "NAV";
TAG_ID[TAG_ID["NOBR"] = 75] = "NOBR";
TAG_ID[TAG_ID["NOFRAMES"] = 76] = "NOFRAMES";
TAG_ID[TAG_ID["NOEMBED"] = 77] = "NOEMBED";
TAG_ID[TAG_ID["NOSCRIPT"] = 78] = "NOSCRIPT";
TAG_ID[TAG_ID["OBJECT"] = 79] = "OBJECT";
TAG_ID[TAG_ID["OL"] = 80] = "OL";
TAG_ID[TAG_ID["OPTGROUP"] = 81] = "OPTGROUP";
TAG_ID[TAG_ID["OPTION"] = 82] = "OPTION";
TAG_ID[TAG_ID["P"] = 83] = "P";
TAG_ID[TAG_ID["PARAM"] = 84] = "PARAM";
TAG_ID[TAG_ID["PLAINTEXT"] = 85] = "PLAINTEXT";
TAG_ID[TAG_ID["PRE"] = 86] = "PRE";
TAG_ID[TAG_ID["RB"] = 87] = "RB";
TAG_ID[TAG_ID["RP"] = 88] = "RP";
TAG_ID[TAG_ID["RT"] = 89] = "RT";
TAG_ID[TAG_ID["RTC"] = 90] = "RTC";
TAG_ID[TAG_ID["RUBY"] = 91] = "RUBY";
TAG_ID[TAG_ID["S"] = 92] = "S";
TAG_ID[TAG_ID["SCRIPT"] = 93] = "SCRIPT";
TAG_ID[TAG_ID["SECTION"] = 94] = "SECTION";
TAG_ID[TAG_ID["SELECT"] = 95] = "SELECT";
TAG_ID[TAG_ID["SOURCE"] = 96] = "SOURCE";
TAG_ID[TAG_ID["SMALL"] = 97] = "SMALL";
TAG_ID[TAG_ID["SPAN"] = 98] = "SPAN";
TAG_ID[TAG_ID["STRIKE"] = 99] = "STRIKE";
TAG_ID[TAG_ID["STRONG"] = 100] = "STRONG";
TAG_ID[TAG_ID["STYLE"] = 101] = "STYLE";
TAG_ID[TAG_ID["SUB"] = 102] = "SUB";
TAG_ID[TAG_ID["SUMMARY"] = 103] = "SUMMARY";
TAG_ID[TAG_ID["SUP"] = 104] = "SUP";
TAG_ID[TAG_ID["TABLE"] = 105] = "TABLE";
TAG_ID[TAG_ID["TBODY"] = 106] = "TBODY";
TAG_ID[TAG_ID["TEMPLATE"] = 107] = "TEMPLATE";
TAG_ID[TAG_ID["TEXTAREA"] = 108] = "TEXTAREA";
TAG_ID[TAG_ID["TFOOT"] = 109] = "TFOOT";
TAG_ID[TAG_ID["TD"] = 110] = "TD";
TAG_ID[TAG_ID["TH"] = 111] = "TH";
TAG_ID[TAG_ID["THEAD"] = 112] = "THEAD";
TAG_ID[TAG_ID["TITLE"] = 113] = "TITLE";
TAG_ID[TAG_ID["TR"] = 114] = "TR";
TAG_ID[TAG_ID["TRACK"] = 115] = "TRACK";
TAG_ID[TAG_ID["TT"] = 116] = "TT";
TAG_ID[TAG_ID["U"] = 117] = "U";
TAG_ID[TAG_ID["UL"] = 118] = "UL";
TAG_ID[TAG_ID["SVG"] = 119] = "SVG";
TAG_ID[TAG_ID["VAR"] = 120] = "VAR";
TAG_ID[TAG_ID["WBR"] = 121] = "WBR";
TAG_ID[TAG_ID["XMP"] = 122] = "XMP";
})(TAG_ID || (TAG_ID = {}));
const TAG_NAME_TO_ID = new Map([
[TAG_NAMES.A, TAG_ID.A],
[TAG_NAMES.ADDRESS, TAG_ID.ADDRESS],
[TAG_NAMES.ANNOTATION_XML, TAG_ID.ANNOTATION_XML],
[TAG_NAMES.APPLET, TAG_ID.APPLET],
[TAG_NAMES.AREA, TAG_ID.AREA],
[TAG_NAMES.ARTICLE, TAG_ID.ARTICLE],
[TAG_NAMES.ASIDE, TAG_ID.ASIDE],
[TAG_NAMES.B, TAG_ID.B],
[TAG_NAMES.BASE, TAG_ID.BASE],
[TAG_NAMES.BASEFONT, TAG_ID.BASEFONT],
[TAG_NAMES.BGSOUND, TAG_ID.BGSOUND],
[TAG_NAMES.BIG, TAG_ID.BIG],
[TAG_NAMES.BLOCKQUOTE, TAG_ID.BLOCKQUOTE],
[TAG_NAMES.BODY, TAG_ID.BODY],
[TAG_NAMES.BR, TAG_ID.BR],
[TAG_NAMES.BUTTON, TAG_ID.BUTTON],
[TAG_NAMES.CAPTION, TAG_ID.CAPTION],
[TAG_NAMES.CENTER, TAG_ID.CENTER],
[TAG_NAMES.CODE, TAG_ID.CODE],
[TAG_NAMES.COL, TAG_ID.COL],
[TAG_NAMES.COLGROUP, TAG_ID.COLGROUP],
[TAG_NAMES.DD, TAG_ID.DD],
[TAG_NAMES.DESC, TAG_ID.DESC],
[TAG_NAMES.DETAILS, TAG_ID.DETAILS],
[TAG_NAMES.DIALOG, TAG_ID.DIALOG],
[TAG_NAMES.DIR, TAG_ID.DIR],
[TAG_NAMES.DIV, TAG_ID.DIV],
[TAG_NAMES.DL, TAG_ID.DL],
[TAG_NAMES.DT, TAG_ID.DT],
[TAG_NAMES.EM, TAG_ID.EM],
[TAG_NAMES.EMBED, TAG_ID.EMBED],
[TAG_NAMES.FIELDSET, TAG_ID.FIELDSET],
[TAG_NAMES.FIGCAPTION, TAG_ID.FIGCAPTION],
[TAG_NAMES.FIGURE, TAG_ID.FIGURE],
[TAG_NAMES.FONT, TAG_ID.FONT],
[TAG_NAMES.FOOTER, TAG_ID.FOOTER],
[TAG_NAMES.FOREIGN_OBJECT, TAG_ID.FOREIGN_OBJECT],
[TAG_NAMES.FORM, TAG_ID.FORM],
[TAG_NAMES.FRAME, TAG_ID.FRAME],
[TAG_NAMES.FRAMESET, TAG_ID.FRAMESET],
[TAG_NAMES.H1, TAG_ID.H1],
[TAG_NAMES.H2, TAG_ID.H2],
[TAG_NAMES.H3, TAG_ID.H3],
[TAG_NAMES.H4, TAG_ID.H4],
[TAG_NAMES.H5, TAG_ID.H5],
[TAG_NAMES.H6, TAG_ID.H6],
[TAG_NAMES.HEAD, TAG_ID.HEAD],
[TAG_NAMES.HEADER, TAG_ID.HEADER],
[TAG_NAMES.HGROUP, TAG_ID.HGROUP],
[TAG_NAMES.HR, TAG_ID.HR],
[TAG_NAMES.HTML, TAG_ID.HTML],
[TAG_NAMES.I, TAG_ID.I],
[TAG_NAMES.IMG, TAG_ID.IMG],
[TAG_NAMES.IMAGE, TAG_ID.IMAGE],
[TAG_NAMES.INPUT, TAG_ID.INPUT],
[TAG_NAMES.IFRAME, TAG_ID.IFRAME],
[TAG_NAMES.KEYGEN, TAG_ID.KEYGEN],
[TAG_NAMES.LABEL, TAG_ID.LABEL],
[TAG_NAMES.LI, TAG_ID.LI],
[TAG_NAMES.LINK, TAG_ID.LINK],
[TAG_NAMES.LISTING, TAG_ID.LISTING],
[TAG_NAMES.MAIN, TAG_ID.MAIN],
[TAG_NAMES.MALIGNMARK, TAG_ID.MALIGNMARK],
[TAG_NAMES.MARQUEE, TAG_ID.MARQUEE],
[TAG_NAMES.MATH, TAG_ID.MATH],
[TAG_NAMES.MENU, TAG_ID.MENU],
[TAG_NAMES.META, TAG_ID.META],
[TAG_NAMES.MGLYPH, TAG_ID.MGLYPH],
[TAG_NAMES.MI, TAG_ID.MI],
[TAG_NAMES.MO, TAG_ID.MO],
[TAG_NAMES.MN, TAG_ID.MN],
[TAG_NAMES.MS, TAG_ID.MS],
[TAG_NAMES.MTEXT, TAG_ID.MTEXT],
[TAG_NAMES.NAV, TAG_ID.NAV],
[TAG_NAMES.NOBR, TAG_ID.NOBR],
[TAG_NAMES.NOFRAMES, TAG_ID.NOFRAMES],
[TAG_NAMES.NOEMBED, TAG_ID.NOEMBED],
[TAG_NAMES.NOSCRIPT, TAG_ID.NOSCRIPT],
[TAG_NAMES.OBJECT, TAG_ID.OBJECT],
[TAG_NAMES.OL, TAG_ID.OL],
[TAG_NAMES.OPTGROUP, TAG_ID.OPTGROUP],
[TAG_NAMES.OPTION, TAG_ID.OPTION],
[TAG_NAMES.P, TAG_ID.P],
[TAG_NAMES.PARAM, TAG_ID.PARAM],
[TAG_NAMES.PLAINTEXT, TAG_ID.PLAINTEXT],
[TAG_NAMES.PRE, TAG_ID.PRE],
[TAG_NAMES.RB, TAG_ID.RB],
[TAG_NAMES.RP, TAG_ID.RP],
[TAG_NAMES.RT, TAG_ID.RT],
[TAG_NAMES.RTC, TAG_ID.RTC],
[TAG_NAMES.RUBY, TAG_ID.RUBY],
[TAG_NAMES.S, TAG_ID.S],
[TAG_NAMES.SCRIPT, TAG_ID.SCRIPT],
[TAG_NAMES.SECTION, TAG_ID.SECTION],
[TAG_NAMES.SELECT, TAG_ID.SELECT],
[TAG_NAMES.SOURCE, TAG_ID.SOURCE],
[TAG_NAMES.SMALL, TAG_ID.SMALL],
[TAG_NAMES.SPAN, TAG_ID.SPAN],
[TAG_NAMES.STRIKE, TAG_ID.STRIKE],
[TAG_NAMES.STRONG, TAG_ID.STRONG],
[TAG_NAMES.STYLE, TAG_ID.STYLE],
[TAG_NAMES.SUB, TAG_ID.SUB],
[TAG_NAMES.SUMMARY, TAG_ID.SUMMARY],
[TAG_NAMES.SUP, TAG_ID.SUP],
[TAG_NAMES.TABLE, TAG_ID.TABLE],
[TAG_NAMES.TBODY, TAG_ID.TBODY],
[TAG_NAMES.TEMPLATE, TAG_ID.TEMPLATE],
[TAG_NAMES.TEXTAREA, TAG_ID.TEXTAREA],
[TAG_NAMES.TFOOT, TAG_ID.TFOOT],
[TAG_NAMES.TD, TAG_ID.TD],
[TAG_NAMES.TH, TAG_ID.TH],
[TAG_NAMES.THEAD, TAG_ID.THEAD],
[TAG_NAMES.TITLE, TAG_ID.TITLE],
[TAG_NAMES.TR, TAG_ID.TR],
[TAG_NAMES.TRACK, TAG_ID.TRACK],
[TAG_NAMES.TT, TAG_ID.TT],
[TAG_NAMES.U, TAG_ID.U],
[TAG_NAMES.UL, TAG_ID.UL],
[TAG_NAMES.SVG, TAG_ID.SVG],
[TAG_NAMES.VAR, TAG_ID.VAR],
[TAG_NAMES.WBR, TAG_ID.WBR],
[TAG_NAMES.XMP, TAG_ID.XMP],
]);
function getTagID(tagName) {
var _a;
return (_a = TAG_NAME_TO_ID.get(tagName)) !== null && _a !== void 0 ? _a : TAG_ID.UNKNOWN;
}
const $ = TAG_ID;
const SPECIAL_ELEMENTS = {
[NS.HTML]: new Set([
$.ADDRESS,
$.APPLET,
$.AREA,
$.ARTICLE,
$.ASIDE,
$.BASE,
$.BASEFONT,
$.BGSOUND,
$.BLOCKQUOTE,
$.BODY,
$.BR,
$.BUTTON,
$.CAPTION,
$.CENTER,
$.COL,
$.COLGROUP,
$.DD,
$.DETAILS,
$.DIR,
$.DIV,
$.DL,
$.DT,
$.EMBED,
$.FIELDSET,
$.FIGCAPTION,
$.FIGURE,
$.FOOTER,
$.FORM,
$.FRAME,
$.FRAMESET,
$.H1,
$.H2,
$.H3,
$.H4,
$.H5,
$.H6,
$.HEAD,
$.HEADER,
$.HGROUP,
$.HR,
$.HTML,
$.IFRAME,
$.IMG,
$.INPUT,
$.LI,
$.LINK,
$.LISTING,
$.MAIN,
$.MARQUEE,
$.MENU,
$.META,
$.NAV,
$.NOEMBED,
$.NOFRAMES,
$.NOSCRIPT,
$.OBJECT,
$.OL,
$.P,
$.PARAM,
$.PLAINTEXT,
$.PRE,
$.SCRIPT,
$.SECTION,
$.SELECT,
$.SOURCE,
$.STYLE,
$.SUMMARY,
$.TABLE,
$.TBODY,
$.TD,
$.TEMPLATE,
$.TEXTAREA,
$.TFOOT,
$.TH,
$.THEAD,
$.TITLE,
$.TR,
$.TRACK,
$.UL,
$.WBR,
$.XMP,
]),
[NS.MATHML]: new Set([$.MI, $.MO, $.MN, $.MS, $.MTEXT, $.ANNOTATION_XML]),
[NS.SVG]: new Set([$.TITLE, $.FOREIGN_OBJECT, $.DESC]),
[NS.XLINK]: new Set(),
[NS.XML]: new Set(),
[NS.XMLNS]: new Set(),
};
function isNumberedHeader(tn) {
return tn === $.H1 || tn === $.H2 || tn === $.H3 || tn === $.H4 || tn === $.H5 || tn === $.H6;
}
const UNESCAPED_TEXT = new Set([
TAG_NAMES.STYLE,
TAG_NAMES.SCRIPT,
TAG_NAMES.XMP,
TAG_NAMES.IFRAME,
TAG_NAMES.NOEMBED,
TAG_NAMES.NOFRAMES,
TAG_NAMES.PLAINTEXT,
]);
function hasUnescapedText(tn, scriptingEnabled) {
return UNESCAPED_TEXT.has(tn) || (scriptingEnabled && tn === TAG_NAMES.NOSCRIPT);
}
//C1 Unicode control character reference replacements
const C1_CONTROLS_REFERENCE_REPLACEMENTS = new Map([
[0x80, 8364],
[0x82, 8218],
[0x83, 402],
[0x84, 8222],
[0x85, 8230],
[0x86, 8224],
[0x87, 8225],
[0x88, 710],
[0x89, 8240],
[0x8a, 352],
[0x8b, 8249],
[0x8c, 338],
[0x8e, 381],
[0x91, 8216],
[0x92, 8217],
[0x93, 8220],
[0x94, 8221],
[0x95, 8226],
[0x96, 8211],
[0x97, 8212],
[0x98, 732],
[0x99, 8482],
[0x9a, 353],
[0x9b, 8250],
[0x9c, 339],
[0x9e, 382],
[0x9f, 376],
]);
//States
var State;
(function (State) {
State[State["DATA"] = 0] = "DATA";
State[State["RCDATA"] = 1] = "RCDATA";
State[State["RAWTEXT"] = 2] = "RAWTEXT";
State[State["SCRIPT_DATA"] = 3] = "SCRIPT_DATA";
State[State["PLAINTEXT"] = 4] = "PLAINTEXT";
State[State["TAG_OPEN"] = 5] = "TAG_OPEN";
State[State["END_TAG_OPEN"] = 6] = "END_TAG_OPEN";
State[State["TAG_NAME"] = 7] = "TAG_NAME";
State[State["RCDATA_LESS_THAN_SIGN"] = 8] = "RCDATA_LESS_THAN_SIGN";
State[State["RCDATA_END_TAG_OPEN"] = 9] = "RCDATA_END_TAG_OPEN";
State[State["RCDATA_END_TAG_NAME"] = 10] = "RCDATA_END_TAG_NAME";
State[State["RAWTEXT_LESS_THAN_SIGN"] = 11] = "RAWTEXT_LESS_THAN_SIGN";
State[State["RAWTEXT_END_TAG_OPEN"] = 12] = "RAWTEXT_END_TAG_OPEN";
State[State["RAWTEXT_END_TAG_NAME"] = 13] = "RAWTEXT_END_TAG_NAME";
State[State["SCRIPT_DATA_LESS_THAN_SIGN"] = 14] = "SCRIPT_DATA_LESS_THAN_SIGN";
State[State["SCRIPT_DATA_END_TAG_OPEN"] = 15] = "SCRIPT_DATA_END_TAG_OPEN";
State[State["SCRIPT_DATA_END_TAG_NAME"] = 16] = "SCRIPT_DATA_END_TAG_NAME";
State[State["SCRIPT_DATA_ESCAPE_START"] = 17] = "SCRIPT_DATA_ESCAPE_START";
State[State["SCRIPT_DATA_ESCAPE_START_DASH"] = 18] = "SCRIPT_DATA_ESCAPE_START_DASH";
State[State["SCRIPT_DATA_ESCAPED"] = 19] = "SCRIPT_DATA_ESCAPED";
State[State["SCRIPT_DATA_ESCAPED_DASH"] = 20] = "SCRIPT_DATA_ESCAPED_DASH";
State[State["SCRIPT_DATA_ESCAPED_DASH_DASH"] = 21] = "SCRIPT_DATA_ESCAPED_DASH_DASH";
State[State["SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN"] = 22] = "SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN";
State[State["SCRIPT_DATA_ESCAPED_END_TAG_OPEN"] = 23] = "SCRIPT_DATA_ESCAPED_END_TAG_OPEN";
State[State["SCRIPT_DATA_ESCAPED_END_TAG_NAME"] = 24] = "SCRIPT_DATA_ESCAPED_END_TAG_NAME";
State[State["SCRIPT_DATA_DOUBLE_ESCAPE_START"] = 25] = "SCRIPT_DATA_DOUBLE_ESCAPE_START";
State[State["SCRIPT_DATA_DOUBLE_ESCAPED"] = 26] = "SCRIPT_DATA_DOUBLE_ESCAPED";
State[State["SCRIPT_DATA_DOUBLE_ESCAPED_DASH"] = 27] = "SCRIPT_DATA_DOUBLE_ESCAPED_DASH";
State[State["SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH"] = 28] = "SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH";
State[State["SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN"] = 29] = "SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN";
State[State["SCRIPT_DATA_DOUBLE_ESCAPE_END"] = 30] = "SCRIPT_DATA_DOUBLE_ESCAPE_END";
State[State["BEFORE_ATTRIBUTE_NAME"] = 31] = "BEFORE_ATTRIBUTE_NAME";
State[State["ATTRIBUTE_NAME"] = 32] = "ATTRIBUTE_NAME";
State[State["AFTER_ATTRIBUTE_NAME"] = 33] = "AFTER_ATTRIBUTE_NAME";
State[State["BEFORE_ATTRIBUTE_VALUE"] = 34] = "BEFORE_ATTRIBUTE_VALUE";
State[State["ATTRIBUTE_VALUE_DOUBLE_QUOTED"] = 35] = "ATTRIBUTE_VALUE_DOUBLE_QUOTED";
State[State["ATTRIBUTE_VALUE_SINGLE_QUOTED"] = 36] = "ATTRIBUTE_VALUE_SINGLE_QUOTED";
State[State["ATTRIBUTE_VALUE_UNQUOTED"] = 37] = "ATTRIBUTE_VALUE_UNQUOTED";
State[State["AFTER_ATTRIBUTE_VALUE_QUOTED"] = 38] = "AFTER_ATTRIBUTE_VALUE_QUOTED";
State[State["SELF_CLOSING_START_TAG"] = 39] = "SELF_CLOSING_START_TAG";
State[State["BOGUS_COMMENT"] = 40] = "BOGUS_COMMENT";
State[State["MARKUP_DECLARATION_OPEN"] = 41] = "MARKUP_DECLARATION_OPEN";
State[State["COMMENT_START"] = 42] = "COMMENT_START";
State[State["COMMENT_START_DASH"] = 43] = "COMMENT_START_DASH";
State[State["COMMENT"] = 44] = "COMMENT";
State[State["COMMENT_LESS_THAN_SIGN"] = 45] = "COMMENT_LESS_THAN_SIGN";
State[State["COMMENT_LESS_THAN_SIGN_BANG"] = 46] = "COMMENT_LESS_THAN_SIGN_BANG";
State[State["COMMENT_LESS_THAN_SIGN_BANG_DASH"] = 47] = "COMMENT_LESS_THAN_SIGN_BANG_DASH";
State[State["COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH"] = 48] = "COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH";
State[State["COMMENT_END_DASH"] = 49] = "COMMENT_END_DASH";
State[State["COMMENT_END"] = 50] = "COMMENT_END";
State[State["COMMENT_END_BANG"] = 51] = "COMMENT_END_BANG";
State[State["DOCTYPE"] = 52] = "DOCTYPE";
State[State["BEFORE_DOCTYPE_NAME"] = 53] = "BEFORE_DOCTYPE_NAME";
State[State["DOCTYPE_NAME"] = 54] = "DOCTYPE_NAME";
State[State["AFTER_DOCTYPE_NAME"] = 55] = "AFTER_DOCTYPE_NAME";
State[State["AFTER_DOCTYPE_PUBLIC_KEYWORD"] = 56] = "AFTER_DOCTYPE_PUBLIC_KEYWORD";
State[State["BEFORE_DOCTYPE_PUBLIC_IDENTIFIER"] = 57] = "BEFORE_DOCTYPE_PUBLIC_IDENTIFIER";
State[State["DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED"] = 58] = "DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED";
State[State["DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED"] = 59] = "DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED";
State[State["AFTER_DOCTYPE_PUBLIC_IDENTIFIER"] = 60] = "AFTER_DOCTYPE_PUBLIC_IDENTIFIER";
State[State["BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS"] = 61] = "BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS";
State[State["AFTER_DOCTYPE_SYSTEM_KEYWORD"] = 62] = "AFTER_DOCTYPE_SYSTEM_KEYWORD";
State[State["BEFORE_DOCTYPE_SYSTEM_IDENTIFIER"] = 63] = "BEFORE_DOCTYPE_SYSTEM_IDENTIFIER";
State[State["DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED"] = 64] = "DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED";
State[State["DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED"] = 65] = "DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED";
State[State["AFTER_DOCTYPE_SYSTEM_IDENTIFIER"] = 66] = "AFTER_DOCTYPE_SYSTEM_IDENTIFIER";
State[State["BOGUS_DOCTYPE"] = 67] = "BOGUS_DOCTYPE";
State[State["CDATA_SECTION"] = 68] = "CDATA_SECTION";
State[State["CDATA_SECTION_BRACKET"] = 69] = "CDATA_SECTION_BRACKET";
State[State["CDATA_SECTION_END"] = 70] = "CDATA_SECTION_END";
State[State["CHARACTER_REFERENCE"] = 71] = "CHARACTER_REFERENCE";
State[State["NAMED_CHARACTER_REFERENCE"] = 72] = "NAMED_CHARACTER_REFERENCE";
State[State["AMBIGUOUS_AMPERSAND"] = 73] = "AMBIGUOUS_AMPERSAND";
State[State["NUMERIC_CHARACTER_REFERENCE"] = 74] = "NUMERIC_CHARACTER_REFERENCE";
State[State["HEXADEMICAL_CHARACTER_REFERENCE_START"] = 75] = "HEXADEMICAL_CHARACTER_REFERENCE_START";
State[State["DECIMAL_CHARACTER_REFERENCE_START"] = 76] = "DECIMAL_CHARACTER_REFERENCE_START";
State[State["HEXADEMICAL_CHARACTER_REFERENCE"] = 77] = "HEXADEMICAL_CHARACTER_REFERENCE";
State[State["DECIMAL_CHARACTER_REFERENCE"] = 78] = "DECIMAL_CHARACTER_REFERENCE";
State[State["NUMERIC_CHARACTER_REFERENCE_END"] = 79] = "NUMERIC_CHARACTER_REFERENCE_END";
})(State || (State = {}));
//Tokenizer initial states for different modes
const TokenizerMode = {
DATA: State.DATA,
RCDATA: State.RCDATA,
RAWTEXT: State.RAWTEXT,
SCRIPT_DATA: State.SCRIPT_DATA,
PLAINTEXT: State.PLAINTEXT,
CDATA_SECTION: State.CDATA_SECTION,
};
//Utils
//OPTIMIZATION: these utility functions should not be moved out of this module. V8 Crankshaft will not inline
//this functions if they will be situated in another module due to context switch.
//Always perform inlining check before modifying this functions ('node --trace-inlining').
function isAsciiDigit(cp) {
return cp >= CODE_POINTS.DIGIT_0 && cp <= CODE_POINTS.DIGIT_9;
}
function isAsciiUpper(cp) {
return cp >= CODE_POINTS.LATIN_CAPITAL_A && cp <= CODE_POINTS.LATIN_CAPITAL_Z;
}
function isAsciiLower(cp) {
return cp >= CODE_POINTS.LATIN_SMALL_A && cp <= CODE_POINTS.LATIN_SMALL_Z;
}
function isAsciiLetter(cp) {
return isAsciiLower(cp) || isAsciiUpper(cp);
}
function isAsciiAlphaNumeric(cp) {
return isAsciiLetter(cp) || isAsciiDigit(cp);
}
function isAsciiUpperHexDigit(cp) {
return cp >= CODE_POINTS.LATIN_CAPITAL_A && cp <= CODE_POINTS.LATIN_CAPITAL_F;
}
function isAsciiLowerHexDigit(cp) {
return cp >= CODE_POINTS.LATIN_SMALL_A && cp <= CODE_POINTS.LATIN_SMALL_F;
}
function isAsciiHexDigit(cp) {
return isAsciiDigit(cp) || isAsciiUpperHexDigit(cp) || isAsciiLowerHexDigit(cp);
}
function toAsciiLower(cp) {
return cp + 32;
}
function isWhitespace$1(cp) {
return cp === CODE_POINTS.SPACE || cp === CODE_POINTS.LINE_FEED || cp === CODE_POINTS.TABULATION || cp === CODE_POINTS.FORM_FEED;
}
function isEntityInAttributeInvalidEnd(nextCp) {
return nextCp === CODE_POINTS.EQUALS_SIGN || isAsciiAlphaNumeric(nextCp);
}
function isScriptDataDoubleEscapeSequenceEnd(cp) {
return isWhitespace$1(cp) || cp === CODE_POINTS.SOLIDUS || cp === CODE_POINTS.GREATER_THAN_SIGN;
}
//Tokenizer
class Tokenizer {
constructor(options, handler) {
this.options = options;
this.handler = handler;
this.paused = false;
/** Ensures that the parsing loop isn't run multiple times at once. */
this.inLoop = false;
/**
* Indicates that the current adjusted node exists, is not an element in the HTML namespace,
* and that it is not an integration point for either MathML or HTML.
*
* @see {@link https://html.spec.whatwg.org/multipage/parsing.html#tree-construction}
*/
this.inForeignNode = false;
this.lastStartTagName = '';
this.active = false;
this.state = State.DATA;
this.returnState = State.DATA;
this.charRefCode = -1;
this.consumedAfterSnapshot = -1;
this.currentCharacterToken = null;
this.currentToken = null;
this.currentAttr = { name: '', value: '' };
this.preprocessor = new Preprocessor(handler);
this.currentLocation = this.getCurrentLocation(-1);
}
//Errors
_err(code) {
var _a, _b;
(_b = (_a = this.handler).onParseError) === null || _b === void 0 ? void 0 : _b.call(_a, this.preprocessor.getError(code));
}
// NOTE: `offset` may never run across line boundaries.
getCurrentLocation(offset) {
if (!this.options.sourceCodeLocationInfo) {
return null;
}
return {
startLine: this.preprocessor.line,
startCol: this.preprocessor.col - offset,
startOffset: this.preprocessor.offset - offset,
endLine: -1,
endCol: -1,
endOffset: -1,
};
}
_runParsingLoop() {
if (this.inLoop)
return;
this.inLoop = true;
while (this.active && !this.paused) {
this.consumedAfterSnapshot = 0;
const cp = this._consume();
if (!this._ensureHibernation()) {
this._callState(cp);
}
}
this.inLoop = false;
}
//API
pause() {
this.paused = true;
}
resume(writeCallback) {
if (!this.paused) {
throw new Error('Parser was already resumed');
}
this.paused = false;
// Necessary for synchronous resume.
if (this.inLoop)
return;
this._runParsingLoop();
if (!this.paused) {
writeCallback === null || writeCallback === void 0 ? void 0 : writeCallback();
}
}
write(chunk, isLastChunk, writeCallback) {
this.active = true;
this.preprocessor.write(chunk, isLastChunk);
this._runParsingLoop();
if (!this.paused) {
writeCallback === null || writeCallback === void 0 ? void 0 : writeCallback();
}
}
insertHtmlAtCurrentPos(chunk) {
this.active = true;
this.preprocessor.insertHtmlAtCurrentPos(chunk);
this._runParsingLoop();
}
//Hibernation
_ensureHibernation() {
if (this.preprocessor.endOfChunkHit) {
this._unconsume(this.consumedAfterSnapshot);
this.active = false;
return true;
}
return false;
}
//Consumption
_consume() {
this.consumedAfterSnapshot++;
return this.preprocessor.advance();
}
_unconsume(count) {
this.consumedAfterSnapshot -= count;
this.preprocessor.retreat(count);
}
_reconsumeInState(state) {
this.state = state;
this._unconsume(1);
}
_advanceBy(count) {
this.consumedAfterSnapshot += count;
for (let i = 0; i < count; i++) {
this.preprocessor.advance();
}
}
_consumeSequenceIfMatch(pattern, caseSensitive) {
if (this.preprocessor.startsWith(pattern, caseSensitive)) {
// We will already have consumed one character before calling this method.
this._advanceBy(pattern.length - 1);
return true;
}
return false;
}
//Token creation
_createStartTagToken() {
this.currentToken = {
type: TokenType.START_TAG,
tagName: '',
tagID: TAG_ID.UNKNOWN,
selfClosing: false,
ackSelfClosing: false,
attrs: [],
location: this.getCurrentLocation(1),
};
}
_createEndTagToken() {
this.currentToken = {
type: TokenType.END_TAG,
tagName: '',
tagID: TAG_ID.UNKNOWN,
selfClosing: false,
ackSelfClosing: false,
attrs: [],
location: this.getCurrentLocation(2),
};
}
_createCommentToken(offset) {
this.currentToken = {
type: TokenType.COMMENT,
data: '',
location: this.getCurrentLocation(offset),
};
}
_createDoctypeToken(initialName) {
this.currentToken = {
type: TokenType.DOCTYPE,
name: initialName,
forceQuirks: false,
publicId: null,
systemId: null,
location: this.currentLocation,
};
}
_createCharacterToken(type, chars) {
this.currentCharacterToken = {
type,
chars,
location: this.currentLocation,
};
}
//Tag attributes
_createAttr(attrNameFirstCh) {
this.currentAttr = {
name: attrNameFirstCh,
value: '',
};
this.currentLocation = this.getCurrentLocation(0);
}
_leaveAttrName() {
var _a;
var _b;
const token = this.currentToken;
if (getTokenAttr(token, this.currentAttr.name) === null) {
token.attrs.push(this.currentAttr);
if (token.location && this.currentLocation) {
const attrLocations = ((_a = (_b = token.location).attrs) !== null && _a !== void 0 ? _a : (_b.attrs = Object.create(null)));
attrLocations[this.currentAttr.name] = this.currentLocation;
// Set end location
this._leaveAttrValue();
}
}
else {
this._err(ERR.duplicateAttribute);
}
}
_leaveAttrValue() {
if (this.currentLocation) {
this.currentLocation.endLine = this.preprocessor.line;
this.currentLocation.endCol = this.preprocessor.col;
this.currentLocation.endOffset = this.preprocessor.offset;
}
}
//Token emission
prepareToken(ct) {
this._emitCurrentCharacterToken(ct.location);
this.currentToken = null;
if (ct.location) {
ct.location.endLine = this.preprocessor.line;
ct.location.endCol = this.preprocessor.col + 1;
ct.location.endOffset = this.preprocessor.offset + 1;
}
this.currentLocation = this.getCurrentLocation(-1);
}
emitCurrentTagToken() {
const ct = this.currentToken;
this.prepareToken(ct);
ct.tagID = getTagID(ct.tagName);
if (ct.type === TokenType.START_TAG) {
this.lastStartTagName = ct.tagName;
this.handler.onStartTag(ct);
}
else {
if (ct.attrs.length > 0) {
this._err(ERR.endTagWithAttributes);
}
if (ct.selfClosing) {
this._err(ERR.endTagWithTrailingSolidus);
}
this.handler.onEndTag(ct);
}
this.preprocessor.dropParsedChunk();
}
emitCurrentComment(ct) {
this.prepareToken(ct);
this.handler.onComment(ct);
this.preprocessor.dropParsedChunk();
}
emitCurrentDoctype(ct) {
this.prepareToken(ct);
this.handler.onDoctype(ct);
this.preprocessor.dropParsedChunk();
}
_emitCurrentCharacterToken(nextLocation) {
if (this.currentCharacterToken) {
//NOTE: if we have a pending character token, make it's end location equal to the
//current token's start location.
if (nextLocation && this.currentCharacterToken.location) {
this.currentCharacterToken.location.endLine = nextLocation.startLine;
this.currentCharacterToken.location.endCol = nextLocation.startCol;
this.currentCharacterToken.location.endOffset = nextLocation.startOffset;
}
switch (this.currentCharacterToken.type) {
case TokenType.CHARACTER: {
this.handler.onCharacter(this.currentCharacterToken);
break;
}
case TokenType.NULL_CHARACTER: {
this.handler.onNullCharacter(this.currentCharacterToken);
break;
}
case TokenType.WHITESPACE_CHARACTER: {
this.handler.onWhitespaceCharacter(this.currentCharacterToken);
break;
}
}
this.currentCharacterToken = null;
}
}
_emitEOFToken() {
const location = this.getCurrentLocation(0);
if (location) {
location.endLine = location.startLine;
location.endCol = location.startCol;
location.endOffset = location.startOffset;
}
this._emitCurrentCharacterToken(location);
this.handler.onEof({ type: TokenType.EOF, location });
this.active = false;
}
//Characters emission
//OPTIMIZATION: specification uses only one type of character tokens (one token per character).
//This causes a huge memory overhead and a lot of unnecessary parser loops. parse5 uses 3 groups of characters.
//If we have a sequence of characters that belong to the same group, the parser can process it
//as a single solid character token.
//So, there are 3 types of character tokens in parse5:
//1)TokenType.NULL_CHARACTER - \u0000-character sequences (e.g. '\u0000\u0000\u0000')
//2)TokenType.WHITESPACE_CHARACTER - any whitespace/new-line character sequences (e.g. '\n \r\t \f')
//3)TokenType.CHARACTER - any character sequence which don't belong to groups 1 and 2 (e.g. 'abcdef1234@@#$%^')
_appendCharToCurrentCharacterToken(type, ch) {
if (this.currentCharacterToken) {
if (this.currentCharacterToken.type !== type) {
this.currentLocation = this.getCurrentLocation(0);
this._emitCurrentCharacterToken(this.currentLocation);
this.preprocessor.dropParsedChunk();
}
else {
this.currentCharacterToken.chars += ch;
return;
}
}
this._createCharacterToken(type, ch);
}
_emitCodePoint(cp) {
let type = TokenType.CHARACTER;
if (isWhitespace$1(cp)) {
type = TokenType.WHITESPACE_CHARACTER;
}
else if (cp === CODE_POINTS.NULL) {
type = TokenType.NULL_CHARACTER;
}
this._appendCharToCurrentCharacterToken(type, String.fromCodePoint(cp));
}
//NOTE: used when we emit characters explicitly.
//This is always for non-whitespace and non-null characters, which allows us to avoid additional checks.
_emitChars(ch) {
this._appendCharToCurrentCharacterToken(TokenType.CHARACTER, ch);
}
// Character reference helpers
_matchNamedCharacterReference(cp) {
let result = null;
let excess = 0;
let withoutSemicolon = false;
for (let i = 0, current = decode_10[0]; i >= 0; cp = this._consume()) {
i = decode_4(decode_10, current, i + 1, cp);
if (i < 0)
break;
excess += 1;
current = decode_10[i];
const masked = current & decode_5.VALUE_LENGTH;
// If the branch is a value, store it and continue
if (masked) {
// The mask is the number of bytes of the value, including the current byte.
const valueLength = (masked >> 14) - 1;
// Attribute values that aren't terminated properly aren't parsed, and shouldn't lead to a parser error.
// See the example in https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state
if (cp !== CODE_POINTS.SEMICOLON &&
this._isCharacterReferenceInAttribute() &&
isEntityInAttributeInvalidEnd(this.preprocessor.peek(1))) {
//NOTE: we don't flush all consumed code points here, and instead switch back to the original state after
//emitting an ampersand. This is fine, as alphanumeric characters won't be parsed differently in attributes.
result = [CODE_POINTS.AMPERSAND];
// Skip over the value.
i += valueLength;
}
else {
// If this is a surrogate pair, consume the next two bytes.
result =
valueLength === 0
? [decode_10[i] & ~decode_5.VALUE_LENGTH]
: valueLength === 1
? [decode_10[++i]]
: [decode_10[++i], decode_10[++i]];
excess = 0;
withoutSemicolon = cp !== CODE_POINTS.SEMICOLON;
}
if (valueLength === 0) {
// If the value is zero-length, we're done.
this._consume();
break;
}
}
}
this._unconsume(excess);
if (withoutSemicolon && !this.preprocessor.endOfChunkHit) {
this._err(ERR.missingSemicolonAfterCharacterReference);
}
// We want to emit the error above on the code point after the entity.
// We always consume one code point too many in the loop, and we wait to
// unconsume it until after the error is emitted.
this._unconsume(1);
return result;
}
_isCharacterReferenceInAttribute() {
return (this.returnState === State.ATTRIBUTE_VALUE_DOUBLE_QUOTED ||
this.returnState === State.ATTRIBUTE_VALUE_SINGLE_QUOTED ||
this.returnState === State.ATTRIBUTE_VALUE_UNQUOTED);
}
_flushCodePointConsumedAsCharacterReference(cp) {
if (this._isCharacterReferenceInAttribute()) {
this.currentAttr.value += String.fromCodePoint(cp);
}
else {
this._emitCodePoint(cp);
}
}
// Calling states this way turns out to be much faster than any other approach.
_callState(cp) {
switch (this.state) {
case State.DATA: {
this._stateData(cp);
break;
}
case State.RCDATA: {
this._stateRcdata(cp);
break;
}
case State.RAWTEXT: {
this._stateRawtext(cp);
break;
}
case State.SCRIPT_DATA: {
this._stateScriptData(cp);
break;
}
case State.PLAINTEXT: {
this._statePlaintext(cp);
break;
}
case State.TAG_OPEN: {
this._stateTagOpen(cp);
break;
}
case State.END_TAG_OPEN: {
this._stateEndTagOpen(cp);
break;
}
case State.TAG_NAME: {
this._stateTagName(cp);
break;
}
case State.RCDATA_LESS_THAN_SIGN: {
this._stateRcdataLessThanSign(cp);
break;
}
case State.RCDATA_END_TAG_OPEN: {
this._stateRcdataEndTagOpen(cp);
break;
}
case State.RCDATA_END_TAG_NAME: {
this._stateRcdataEndTagName(cp);
break;
}
case State.RAWTEXT_LESS_THAN_SIGN: {
this._stateRawtextLessThanSign(cp);
break;
}
case State.RAWTEXT_END_TAG_OPEN: {
this._stateRawtextEndTagOpen(cp);
break;
}
case State.RAWTEXT_END_TAG_NAME: {
this._stateRawtextEndTagName(cp);
break;
}
case State.SCRIPT_DATA_LESS_THAN_SIGN: {
this._stateScriptDataLessThanSign(cp);
break;
}
case State.SCRIPT_DATA_END_TAG_OPEN: {
this._stateScriptDataEndTagOpen(cp);
break;
}
case State.SCRIPT_DATA_END_TAG_NAME: {
this._stateScriptDataEndTagName(cp);
break;
}
case State.SCRIPT_DATA_ESCAPE_START: {
this._stateScriptDataEscapeStart(cp);
break;
}
case State.SCRIPT_DATA_ESCAPE_START_DASH: {
this._stateScriptDataEscapeStartDash(cp);
break;
}
case State.SCRIPT_DATA_ESCAPED: {
this._stateScriptDataEscaped(cp);
break;
}
case State.SCRIPT_DATA_ESCAPED_DASH: {
this._stateScriptDataEscapedDash(cp);
break;
}
case State.SCRIPT_DATA_ESCAPED_DASH_DASH: {
this._stateScriptDataEscapedDashDash(cp);
break;
}
case State.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN: {
this._stateScriptDataEscapedLessThanSign(cp);
break;
}
case State.SCRIPT_DATA_ESCAPED_END_TAG_OPEN: {
this._stateScriptDataEscapedEndTagOpen(cp);
break;
}
case State.SCRIPT_DATA_ESCAPED_END_TAG_NAME: {
this._stateScriptDataEscapedEndTagName(cp);
break;
}
case State.SCRIPT_DATA_DOUBLE_ESCAPE_START: {
this._stateScriptDataDoubleEscapeStart(cp);
break;
}
case State.SCRIPT_DATA_DOUBLE_ESCAPED: {
this._stateScriptDataDoubleEscaped(cp);
break;
}
case State.SCRIPT_DATA_DOUBLE_ESCAPED_DASH: {
this._stateScriptDataDoubleEscapedDash(cp);
break;
}
case State.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH: {
this._stateScriptDataDoubleEscapedDashDash(cp);
break;
}
case State.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN: {
this._stateScriptDataDoubleEscapedLessThanSign(cp);
break;
}
case State.SCRIPT_DATA_DOUBLE_ESCAPE_END: {
this._stateScriptDataDoubleEscapeEnd(cp);
break;
}
case State.BEFORE_ATTRIBUTE_NAME: {
this._stateBeforeAttributeName(cp);
break;
}
case State.ATTRIBUTE_NAME: {
this._stateAttributeName(cp);
break;
}
case State.AFTER_ATTRIBUTE_NAME: {
this._stateAfterAttributeName(cp);
break;
}
case State.BEFORE_ATTRIBUTE_VALUE: {
this._stateBeforeAttributeValue(cp);
break;
}
case State.ATTRIBUTE_VALUE_DOUBLE_QUOTED: {
this._stateAttributeValueDoubleQuoted(cp);
break;
}
case State.ATTRIBUTE_VALUE_SINGLE_QUOTED: {
this._stateAttributeValueSingleQuoted(cp);
break;
}
case State.ATTRIBUTE_VALUE_UNQUOTED: {
this._stateAttributeValueUnquoted(cp);
break;
}
case State.AFTER_ATTRIBUTE_VALUE_QUOTED: {
this._stateAfterAttributeValueQuoted(cp);
break;
}
case State.SELF_CLOSING_START_TAG: {
this._stateSelfClosingStartTag(cp);
break;
}
case State.BOGUS_COMMENT: {
this._stateBogusComment(cp);
break;
}
case State.MARKUP_DECLARATION_OPEN: {
this._stateMarkupDeclarationOpen(cp);
break;
}
case State.COMMENT_START: {
this._stateCommentStart(cp);
break;
}
case State.COMMENT_START_DASH: {
this._stateCommentStartDash(cp);
break;
}
case State.COMMENT: {
this._stateComment(cp);
break;
}
case State.COMMENT_LESS_THAN_SIGN: {
this._stateCommentLessThanSign(cp);
break;
}
case State.COMMENT_LESS_THAN_SIGN_BANG: {
this._stateCommentLessThanSignBang(cp);
break;
}
case State.COMMENT_LESS_THAN_SIGN_BANG_DASH: {
this._stateCommentLessThanSignBangDash(cp);
break;
}
case State.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH: {
this._stateCommentLessThanSignBangDashDash(cp);
break;
}
case State.COMMENT_END_DASH: {
this._stateCommentEndDash(cp);
break;
}
case State.COMMENT_END: {
this._stateCommentEnd(cp);
break;
}
case State.COMMENT_END_BANG: {
this._stateCommentEndBang(cp);
break;
}
case State.DOCTYPE: {
this._stateDoctype(cp);
break;
}
case State.BEFORE_DOCTYPE_NAME: {
this._stateBeforeDoctypeName(cp);
break;
}
case State.DOCTYPE_NAME: {
this._stateDoctypeName(cp);
break;
}
case State.AFTER_DOCTYPE_NAME: {
this._stateAfterDoctypeName(cp);
break;
}
case State.AFTER_DOCTYPE_PUBLIC_KEYWORD: {
this._stateAfterDoctypePublicKeyword(cp);
break;
}
case State.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER: {
this._stateBeforeDoctypePublicIdentifier(cp);
break;
}
case State.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED: {
this._stateDoctypePublicIdentifierDoubleQuoted(cp);
break;
}
case State.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED: {
this._stateDoctypePublicIdentifierSingleQuoted(cp);
break;
}
case State.AFTER_DOCTYPE_PUBLIC_IDENTIFIER: {
this._stateAfterDoctypePublicIdentifier(cp);
break;
}
case State.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS: {
this._stateBetweenDoctypePublicAndSystemIdentifiers(cp);
break;
}
case State.AFTER_DOCTYPE_SYSTEM_KEYWORD: {
this._stateAfterDoctypeSystemKeyword(cp);
break;
}
case State.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER: {
this._stateBeforeDoctypeSystemIdentifier(cp);
break;
}
case State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED: {
this._stateDoctypeSystemIdentifierDoubleQuoted(cp);
break;
}
case State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED: {
this._stateDoctypeSystemIdentifierSingleQuoted(cp);
break;
}
case State.AFTER_DOCTYPE_SYSTEM_IDENTIFIER: {
this._stateAfterDoctypeSystemIdentifier(cp);
break;
}
case State.BOGUS_DOCTYPE: {
this._stateBogusDoctype(cp);
break;
}
case State.CDATA_SECTION: {
this._stateCdataSection(cp);
break;
}
case State.CDATA_SECTION_BRACKET: {
this._stateCdataSectionBracket(cp);
break;
}
case State.CDATA_SECTION_END: {
this._stateCdataSectionEnd(cp);
break;
}
case State.CHARACTER_REFERENCE: {
this._stateCharacterReference(cp);
break;
}
case State.NAMED_CHARACTER_REFERENCE: {
this._stateNamedCharacterReference(cp);
break;
}
case State.AMBIGUOUS_AMPERSAND: {
this._stateAmbiguousAmpersand(cp);
break;
}
case State.NUMERIC_CHARACTER_REFERENCE: {
this._stateNumericCharacterReference(cp);
break;
}
case State.HEXADEMICAL_CHARACTER_REFERENCE_START: {
this._stateHexademicalCharacterReferenceStart(cp);
break;
}
case State.DECIMAL_CHARACTER_REFERENCE_START: {
this._stateDecimalCharacterReferenceStart(cp);
break;
}
case State.HEXADEMICAL_CHARACTER_REFERENCE: {
this._stateHexademicalCharacterReference(cp);
break;
}
case State.DECIMAL_CHARACTER_REFERENCE: {
this._stateDecimalCharacterReference(cp);
break;
}
case State.NUMERIC_CHARACTER_REFERENCE_END: {
this._stateNumericCharacterReferenceEnd();
break;
}
default: {
throw new Error('Unknown state');
}
}
}
// State machine
// Data state
//------------------------------------------------------------------
_stateData(cp) {
switch (cp) {
case CODE_POINTS.LESS_THAN_SIGN: {
this.state = State.TAG_OPEN;
break;
}
case CODE_POINTS.AMPERSAND: {
this.returnState = State.DATA;
this.state = State.CHARACTER_REFERENCE;
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
this._emitCodePoint(cp);
break;
}
case CODE_POINTS.EOF: {
this._emitEOFToken();
break;
}
default: {
this._emitCodePoint(cp);
}
}
}
// RCDATA state
//------------------------------------------------------------------
_stateRcdata(cp) {
switch (cp) {
case CODE_POINTS.AMPERSAND: {
this.returnState = State.RCDATA;
this.state = State.CHARACTER_REFERENCE;
break;
}
case CODE_POINTS.LESS_THAN_SIGN: {
this.state = State.RCDATA_LESS_THAN_SIGN;
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
this._emitChars(REPLACEMENT_CHARACTER);
break;
}
case CODE_POINTS.EOF: {
this._emitEOFToken();
break;
}
default: {
this._emitCodePoint(cp);
}
}
}
// RAWTEXT state
//------------------------------------------------------------------
_stateRawtext(cp) {
switch (cp) {
case CODE_POINTS.LESS_THAN_SIGN: {
this.state = State.RAWTEXT_LESS_THAN_SIGN;
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
this._emitChars(REPLACEMENT_CHARACTER);
break;
}
case CODE_POINTS.EOF: {
this._emitEOFToken();
break;
}
default: {
this._emitCodePoint(cp);
}
}
}
// Script data state
//------------------------------------------------------------------
_stateScriptData(cp) {
switch (cp) {
case CODE_POINTS.LESS_THAN_SIGN: {
this.state = State.SCRIPT_DATA_LESS_THAN_SIGN;
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
this._emitChars(REPLACEMENT_CHARACTER);
break;
}
case CODE_POINTS.EOF: {
this._emitEOFToken();
break;
}
default: {
this._emitCodePoint(cp);
}
}
}
// PLAINTEXT state
//------------------------------------------------------------------
_statePlaintext(cp) {
switch (cp) {
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
this._emitChars(REPLACEMENT_CHARACTER);
break;
}
case CODE_POINTS.EOF: {
this._emitEOFToken();
break;
}
default: {
this._emitCodePoint(cp);
}
}
}
// Tag open state
//------------------------------------------------------------------
_stateTagOpen(cp) {
if (isAsciiLetter(cp)) {
this._createStartTagToken();
this.state = State.TAG_NAME;
this._stateTagName(cp);
}
else
switch (cp) {
case CODE_POINTS.EXCLAMATION_MARK: {
this.state = State.MARKUP_DECLARATION_OPEN;
break;
}
case CODE_POINTS.SOLIDUS: {
this.state = State.END_TAG_OPEN;
break;
}
case CODE_POINTS.QUESTION_MARK: {
this._err(ERR.unexpectedQuestionMarkInsteadOfTagName);
this._createCommentToken(1);
this.state = State.BOGUS_COMMENT;
this._stateBogusComment(cp);
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofBeforeTagName);
this._emitChars('<');
this._emitEOFToken();
break;
}
default: {
this._err(ERR.invalidFirstCharacterOfTagName);
this._emitChars('<');
this.state = State.DATA;
this._stateData(cp);
}
}
}
// End tag open state
//------------------------------------------------------------------
_stateEndTagOpen(cp) {
if (isAsciiLetter(cp)) {
this._createEndTagToken();
this.state = State.TAG_NAME;
this._stateTagName(cp);
}
else
switch (cp) {
case CODE_POINTS.GREATER_THAN_SIGN: {
this._err(ERR.missingEndTagName);
this.state = State.DATA;
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofBeforeTagName);
this._emitChars('</');
this._emitEOFToken();
break;
}
default: {
this._err(ERR.invalidFirstCharacterOfTagName);
this._createCommentToken(2);
this.state = State.BOGUS_COMMENT;
this._stateBogusComment(cp);
}
}
}
// Tag name state
//------------------------------------------------------------------
_stateTagName(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.SPACE:
case CODE_POINTS.LINE_FEED:
case CODE_POINTS.TABULATION:
case CODE_POINTS.FORM_FEED: {
this.state = State.BEFORE_ATTRIBUTE_NAME;
break;
}
case CODE_POINTS.SOLIDUS: {
this.state = State.SELF_CLOSING_START_TAG;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this.state = State.DATA;
this.emitCurrentTagToken();
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
token.tagName += REPLACEMENT_CHARACTER;
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInTag);
this._emitEOFToken();
break;
}
default: {
token.tagName += String.fromCodePoint(isAsciiUpper(cp) ? toAsciiLower(cp) : cp);
}
}
}
// RCDATA less-than sign state
//------------------------------------------------------------------
_stateRcdataLessThanSign(cp) {
if (cp === CODE_POINTS.SOLIDUS) {
this.state = State.RCDATA_END_TAG_OPEN;
}
else {
this._emitChars('<');
this.state = State.RCDATA;
this._stateRcdata(cp);
}
}
// RCDATA end tag open state
//------------------------------------------------------------------
_stateRcdataEndTagOpen(cp) {
if (isAsciiLetter(cp)) {
this.state = State.RCDATA_END_TAG_NAME;
this._stateRcdataEndTagName(cp);
}
else {
this._emitChars('</');
this.state = State.RCDATA;
this._stateRcdata(cp);
}
}
handleSpecialEndTag(_cp) {
if (!this.preprocessor.startsWith(this.lastStartTagName, false)) {
return !this._ensureHibernation();
}
this._createEndTagToken();
const token = this.currentToken;
token.tagName = this.lastStartTagName;
const cp = this.preprocessor.peek(this.lastStartTagName.length);
switch (cp) {
case CODE_POINTS.SPACE:
case CODE_POINTS.LINE_FEED:
case CODE_POINTS.TABULATION:
case CODE_POINTS.FORM_FEED: {
this._advanceBy(this.lastStartTagName.length);
this.state = State.BEFORE_ATTRIBUTE_NAME;
return false;
}
case CODE_POINTS.SOLIDUS: {
this._advanceBy(this.lastStartTagName.length);
this.state = State.SELF_CLOSING_START_TAG;
return false;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this._advanceBy(this.lastStartTagName.length);
this.emitCurrentTagToken();
this.state = State.DATA;
return false;
}
default: {
return !this._ensureHibernation();
}
}
}
// RCDATA end tag name state
//------------------------------------------------------------------
_stateRcdataEndTagName(cp) {
if (this.handleSpecialEndTag(cp)) {
this._emitChars('</');
this.state = State.RCDATA;
this._stateRcdata(cp);
}
}
// RAWTEXT less-than sign state
//------------------------------------------------------------------
_stateRawtextLessThanSign(cp) {
if (cp === CODE_POINTS.SOLIDUS) {
this.state = State.RAWTEXT_END_TAG_OPEN;
}
else {
this._emitChars('<');
this.state = State.RAWTEXT;
this._stateRawtext(cp);
}
}
// RAWTEXT end tag open state
//------------------------------------------------------------------
_stateRawtextEndTagOpen(cp) {
if (isAsciiLetter(cp)) {
this.state = State.RAWTEXT_END_TAG_NAME;
this._stateRawtextEndTagName(cp);
}
else {
this._emitChars('</');
this.state = State.RAWTEXT;
this._stateRawtext(cp);
}
}
// RAWTEXT end tag name state
//------------------------------------------------------------------
_stateRawtextEndTagName(cp) {
if (this.handleSpecialEndTag(cp)) {
this._emitChars('</');
this.state = State.RAWTEXT;
this._stateRawtext(cp);
}
}
// Script data less-than sign state
//------------------------------------------------------------------
_stateScriptDataLessThanSign(cp) {
switch (cp) {
case CODE_POINTS.SOLIDUS: {
this.state = State.SCRIPT_DATA_END_TAG_OPEN;
break;
}
case CODE_POINTS.EXCLAMATION_MARK: {
this.state = State.SCRIPT_DATA_ESCAPE_START;
this._emitChars('<!');
break;
}
default: {
this._emitChars('<');
this.state = State.SCRIPT_DATA;
this._stateScriptData(cp);
}
}
}
// Script data end tag open state
//------------------------------------------------------------------
_stateScriptDataEndTagOpen(cp) {
if (isAsciiLetter(cp)) {
this.state = State.SCRIPT_DATA_END_TAG_NAME;
this._stateScriptDataEndTagName(cp);
}
else {
this._emitChars('</');
this.state = State.SCRIPT_DATA;
this._stateScriptData(cp);
}
}
// Script data end tag name state
//------------------------------------------------------------------
_stateScriptDataEndTagName(cp) {
if (this.handleSpecialEndTag(cp)) {
this._emitChars('</');
this.state = State.SCRIPT_DATA;
this._stateScriptData(cp);
}
}
// Script data escape start state
//------------------------------------------------------------------
_stateScriptDataEscapeStart(cp) {
if (cp === CODE_POINTS.HYPHEN_MINUS) {
this.state = State.SCRIPT_DATA_ESCAPE_START_DASH;
this._emitChars('-');
}
else {
this.state = State.SCRIPT_DATA;
this._stateScriptData(cp);
}
}
// Script data escape start dash state
//------------------------------------------------------------------
_stateScriptDataEscapeStartDash(cp) {
if (cp === CODE_POINTS.HYPHEN_MINUS) {
this.state = State.SCRIPT_DATA_ESCAPED_DASH_DASH;
this._emitChars('-');
}
else {
this.state = State.SCRIPT_DATA;
this._stateScriptData(cp);
}
}
// Script data escaped state
//------------------------------------------------------------------
_stateScriptDataEscaped(cp) {
switch (cp) {
case CODE_POINTS.HYPHEN_MINUS: {
this.state = State.SCRIPT_DATA_ESCAPED_DASH;
this._emitChars('-');
break;
}
case CODE_POINTS.LESS_THAN_SIGN: {
this.state = State.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
this._emitChars(REPLACEMENT_CHARACTER);
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInScriptHtmlCommentLikeText);
this._emitEOFToken();
break;
}
default: {
this._emitCodePoint(cp);
}
}
}
// Script data escaped dash state
//------------------------------------------------------------------
_stateScriptDataEscapedDash(cp) {
switch (cp) {
case CODE_POINTS.HYPHEN_MINUS: {
this.state = State.SCRIPT_DATA_ESCAPED_DASH_DASH;
this._emitChars('-');
break;
}
case CODE_POINTS.LESS_THAN_SIGN: {
this.state = State.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
this.state = State.SCRIPT_DATA_ESCAPED;
this._emitChars(REPLACEMENT_CHARACTER);
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInScriptHtmlCommentLikeText);
this._emitEOFToken();
break;
}
default: {
this.state = State.SCRIPT_DATA_ESCAPED;
this._emitCodePoint(cp);
}
}
}
// Script data escaped dash dash state
//------------------------------------------------------------------
_stateScriptDataEscapedDashDash(cp) {
switch (cp) {
case CODE_POINTS.HYPHEN_MINUS: {
this._emitChars('-');
break;
}
case CODE_POINTS.LESS_THAN_SIGN: {
this.state = State.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this.state = State.SCRIPT_DATA;
this._emitChars('>');
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
this.state = State.SCRIPT_DATA_ESCAPED;
this._emitChars(REPLACEMENT_CHARACTER);
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInScriptHtmlCommentLikeText);
this._emitEOFToken();
break;
}
default: {
this.state = State.SCRIPT_DATA_ESCAPED;
this._emitCodePoint(cp);
}
}
}
// Script data escaped less-than sign state
//------------------------------------------------------------------
_stateScriptDataEscapedLessThanSign(cp) {
if (cp === CODE_POINTS.SOLIDUS) {
this.state = State.SCRIPT_DATA_ESCAPED_END_TAG_OPEN;
}
else if (isAsciiLetter(cp)) {
this._emitChars('<');
this.state = State.SCRIPT_DATA_DOUBLE_ESCAPE_START;
this._stateScriptDataDoubleEscapeStart(cp);
}
else {
this._emitChars('<');
this.state = State.SCRIPT_DATA_ESCAPED;
this._stateScriptDataEscaped(cp);
}
}
// Script data escaped end tag open state
//------------------------------------------------------------------
_stateScriptDataEscapedEndTagOpen(cp) {
if (isAsciiLetter(cp)) {
this.state = State.SCRIPT_DATA_ESCAPED_END_TAG_NAME;
this._stateScriptDataEscapedEndTagName(cp);
}
else {
this._emitChars('</');
this.state = State.SCRIPT_DATA_ESCAPED;
this._stateScriptDataEscaped(cp);
}
}
// Script data escaped end tag name state
//------------------------------------------------------------------
_stateScriptDataEscapedEndTagName(cp) {
if (this.handleSpecialEndTag(cp)) {
this._emitChars('</');
this.state = State.SCRIPT_DATA_ESCAPED;
this._stateScriptDataEscaped(cp);
}
}
// Script data double escape start state
//------------------------------------------------------------------
_stateScriptDataDoubleEscapeStart(cp) {
if (this.preprocessor.startsWith(SEQUENCES.SCRIPT, false) &&
isScriptDataDoubleEscapeSequenceEnd(this.preprocessor.peek(SEQUENCES.SCRIPT.length))) {
this._emitCodePoint(cp);
for (let i = 0; i < SEQUENCES.SCRIPT.length; i++) {
this._emitCodePoint(this._consume());
}
this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
}
else if (!this._ensureHibernation()) {
this.state = State.SCRIPT_DATA_ESCAPED;
this._stateScriptDataEscaped(cp);
}
}
// Script data double escaped state
//------------------------------------------------------------------
_stateScriptDataDoubleEscaped(cp) {
switch (cp) {
case CODE_POINTS.HYPHEN_MINUS: {
this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED_DASH;
this._emitChars('-');
break;
}
case CODE_POINTS.LESS_THAN_SIGN: {
this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN;
this._emitChars('<');
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
this._emitChars(REPLACEMENT_CHARACTER);
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInScriptHtmlCommentLikeText);
this._emitEOFToken();
break;
}
default: {
this._emitCodePoint(cp);
}
}
}
// Script data double escaped dash state
//------------------------------------------------------------------
_stateScriptDataDoubleEscapedDash(cp) {
switch (cp) {
case CODE_POINTS.HYPHEN_MINUS: {
this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH;
this._emitChars('-');
break;
}
case CODE_POINTS.LESS_THAN_SIGN: {
this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN;
this._emitChars('<');
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
this._emitChars(REPLACEMENT_CHARACTER);
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInScriptHtmlCommentLikeText);
this._emitEOFToken();
break;
}
default: {
this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
this._emitCodePoint(cp);
}
}
}
// Script data double escaped dash dash state
//------------------------------------------------------------------
_stateScriptDataDoubleEscapedDashDash(cp) {
switch (cp) {
case CODE_POINTS.HYPHEN_MINUS: {
this._emitChars('-');
break;
}
case CODE_POINTS.LESS_THAN_SIGN: {
this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN;
this._emitChars('<');
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this.state = State.SCRIPT_DATA;
this._emitChars('>');
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
this._emitChars(REPLACEMENT_CHARACTER);
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInScriptHtmlCommentLikeText);
this._emitEOFToken();
break;
}
default: {
this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
this._emitCodePoint(cp);
}
}
}
// Script data double escaped less-than sign state
//------------------------------------------------------------------
_stateScriptDataDoubleEscapedLessThanSign(cp) {
if (cp === CODE_POINTS.SOLIDUS) {
this.state = State.SCRIPT_DATA_DOUBLE_ESCAPE_END;
this._emitChars('/');
}
else {
this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
this._stateScriptDataDoubleEscaped(cp);
}
}
// Script data double escape end state
//------------------------------------------------------------------
_stateScriptDataDoubleEscapeEnd(cp) {
if (this.preprocessor.startsWith(SEQUENCES.SCRIPT, false) &&
isScriptDataDoubleEscapeSequenceEnd(this.preprocessor.peek(SEQUENCES.SCRIPT.length))) {
this._emitCodePoint(cp);
for (let i = 0; i < SEQUENCES.SCRIPT.length; i++) {
this._emitCodePoint(this._consume());
}
this.state = State.SCRIPT_DATA_ESCAPED;
}
else if (!this._ensureHibernation()) {
this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
this._stateScriptDataDoubleEscaped(cp);
}
}
// Before attribute name state
//------------------------------------------------------------------
_stateBeforeAttributeName(cp) {
switch (cp) {
case CODE_POINTS.SPACE:
case CODE_POINTS.LINE_FEED:
case CODE_POINTS.TABULATION:
case CODE_POINTS.FORM_FEED: {
// Ignore whitespace
break;
}
case CODE_POINTS.SOLIDUS:
case CODE_POINTS.GREATER_THAN_SIGN:
case CODE_POINTS.EOF: {
this.state = State.AFTER_ATTRIBUTE_NAME;
this._stateAfterAttributeName(cp);
break;
}
case CODE_POINTS.EQUALS_SIGN: {
this._err(ERR.unexpectedEqualsSignBeforeAttributeName);
this._createAttr('=');
this.state = State.ATTRIBUTE_NAME;
break;
}
default: {
this._createAttr('');
this.state = State.ATTRIBUTE_NAME;
this._stateAttributeName(cp);
}
}
}
// Attribute name state
//------------------------------------------------------------------
_stateAttributeName(cp) {
switch (cp) {
case CODE_POINTS.SPACE:
case CODE_POINTS.LINE_FEED:
case CODE_POINTS.TABULATION:
case CODE_POINTS.FORM_FEED:
case CODE_POINTS.SOLIDUS:
case CODE_POINTS.GREATER_THAN_SIGN:
case CODE_POINTS.EOF: {
this._leaveAttrName();
this.state = State.AFTER_ATTRIBUTE_NAME;
this._stateAfterAttributeName(cp);
break;
}
case CODE_POINTS.EQUALS_SIGN: {
this._leaveAttrName();
this.state = State.BEFORE_ATTRIBUTE_VALUE;
break;
}
case CODE_POINTS.QUOTATION_MARK:
case CODE_POINTS.APOSTROPHE:
case CODE_POINTS.LESS_THAN_SIGN: {
this._err(ERR.unexpectedCharacterInAttributeName);
this.currentAttr.name += String.fromCodePoint(cp);
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
this.currentAttr.name += REPLACEMENT_CHARACTER;
break;
}
default: {
this.currentAttr.name += String.fromCodePoint(isAsciiUpper(cp) ? toAsciiLower(cp) : cp);
}
}
}
// After attribute name state
//------------------------------------------------------------------
_stateAfterAttributeName(cp) {
switch (cp) {
case CODE_POINTS.SPACE:
case CODE_POINTS.LINE_FEED:
case CODE_POINTS.TABULATION:
case CODE_POINTS.FORM_FEED: {
// Ignore whitespace
break;
}
case CODE_POINTS.SOLIDUS: {
this.state = State.SELF_CLOSING_START_TAG;
break;
}
case CODE_POINTS.EQUALS_SIGN: {
this.state = State.BEFORE_ATTRIBUTE_VALUE;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this.state = State.DATA;
this.emitCurrentTagToken();
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInTag);
this._emitEOFToken();
break;
}
default: {
this._createAttr('');
this.state = State.ATTRIBUTE_NAME;
this._stateAttributeName(cp);
}
}
}
// Before attribute value state
//------------------------------------------------------------------
_stateBeforeAttributeValue(cp) {
switch (cp) {
case CODE_POINTS.SPACE:
case CODE_POINTS.LINE_FEED:
case CODE_POINTS.TABULATION:
case CODE_POINTS.FORM_FEED: {
// Ignore whitespace
break;
}
case CODE_POINTS.QUOTATION_MARK: {
this.state = State.ATTRIBUTE_VALUE_DOUBLE_QUOTED;
break;
}
case CODE_POINTS.APOSTROPHE: {
this.state = State.ATTRIBUTE_VALUE_SINGLE_QUOTED;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this._err(ERR.missingAttributeValue);
this.state = State.DATA;
this.emitCurrentTagToken();
break;
}
default: {
this.state = State.ATTRIBUTE_VALUE_UNQUOTED;
this._stateAttributeValueUnquoted(cp);
}
}
}
// Attribute value (double-quoted) state
//------------------------------------------------------------------
_stateAttributeValueDoubleQuoted(cp) {
switch (cp) {
case CODE_POINTS.QUOTATION_MARK: {
this.state = State.AFTER_ATTRIBUTE_VALUE_QUOTED;
break;
}
case CODE_POINTS.AMPERSAND: {
this.returnState = State.ATTRIBUTE_VALUE_DOUBLE_QUOTED;
this.state = State.CHARACTER_REFERENCE;
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
this.currentAttr.value += REPLACEMENT_CHARACTER;
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInTag);
this._emitEOFToken();
break;
}
default: {
this.currentAttr.value += String.fromCodePoint(cp);
}
}
}
// Attribute value (single-quoted) state
//------------------------------------------------------------------
_stateAttributeValueSingleQuoted(cp) {
switch (cp) {
case CODE_POINTS.APOSTROPHE: {
this.state = State.AFTER_ATTRIBUTE_VALUE_QUOTED;
break;
}
case CODE_POINTS.AMPERSAND: {
this.returnState = State.ATTRIBUTE_VALUE_SINGLE_QUOTED;
this.state = State.CHARACTER_REFERENCE;
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
this.currentAttr.value += REPLACEMENT_CHARACTER;
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInTag);
this._emitEOFToken();
break;
}
default: {
this.currentAttr.value += String.fromCodePoint(cp);
}
}
}
// Attribute value (unquoted) state
//------------------------------------------------------------------
_stateAttributeValueUnquoted(cp) {
switch (cp) {
case CODE_POINTS.SPACE:
case CODE_POINTS.LINE_FEED:
case CODE_POINTS.TABULATION:
case CODE_POINTS.FORM_FEED: {
this._leaveAttrValue();
this.state = State.BEFORE_ATTRIBUTE_NAME;
break;
}
case CODE_POINTS.AMPERSAND: {
this.returnState = State.ATTRIBUTE_VALUE_UNQUOTED;
this.state = State.CHARACTER_REFERENCE;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this._leaveAttrValue();
this.state = State.DATA;
this.emitCurrentTagToken();
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
this.currentAttr.value += REPLACEMENT_CHARACTER;
break;
}
case CODE_POINTS.QUOTATION_MARK:
case CODE_POINTS.APOSTROPHE:
case CODE_POINTS.LESS_THAN_SIGN:
case CODE_POINTS.EQUALS_SIGN:
case CODE_POINTS.GRAVE_ACCENT: {
this._err(ERR.unexpectedCharacterInUnquotedAttributeValue);
this.currentAttr.value += String.fromCodePoint(cp);
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInTag);
this._emitEOFToken();
break;
}
default: {
this.currentAttr.value += String.fromCodePoint(cp);
}
}
}
// After attribute value (quoted) state
//------------------------------------------------------------------
_stateAfterAttributeValueQuoted(cp) {
switch (cp) {
case CODE_POINTS.SPACE:
case CODE_POINTS.LINE_FEED:
case CODE_POINTS.TABULATION:
case CODE_POINTS.FORM_FEED: {
this._leaveAttrValue();
this.state = State.BEFORE_ATTRIBUTE_NAME;
break;
}
case CODE_POINTS.SOLIDUS: {
this._leaveAttrValue();
this.state = State.SELF_CLOSING_START_TAG;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this._leaveAttrValue();
this.state = State.DATA;
this.emitCurrentTagToken();
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInTag);
this._emitEOFToken();
break;
}
default: {
this._err(ERR.missingWhitespaceBetweenAttributes);
this.state = State.BEFORE_ATTRIBUTE_NAME;
this._stateBeforeAttributeName(cp);
}
}
}
// Self-closing start tag state
//------------------------------------------------------------------
_stateSelfClosingStartTag(cp) {
switch (cp) {
case CODE_POINTS.GREATER_THAN_SIGN: {
const token = this.currentToken;
token.selfClosing = true;
this.state = State.DATA;
this.emitCurrentTagToken();
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInTag);
this._emitEOFToken();
break;
}
default: {
this._err(ERR.unexpectedSolidusInTag);
this.state = State.BEFORE_ATTRIBUTE_NAME;
this._stateBeforeAttributeName(cp);
}
}
}
// Bogus comment state
//------------------------------------------------------------------
_stateBogusComment(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.GREATER_THAN_SIGN: {
this.state = State.DATA;
this.emitCurrentComment(token);
break;
}
case CODE_POINTS.EOF: {
this.emitCurrentComment(token);
this._emitEOFToken();
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
token.data += REPLACEMENT_CHARACTER;
break;
}
default: {
token.data += String.fromCodePoint(cp);
}
}
}
// Markup declaration open state
//------------------------------------------------------------------
_stateMarkupDeclarationOpen(cp) {
if (this._consumeSequenceIfMatch(SEQUENCES.DASH_DASH, true)) {
this._createCommentToken(SEQUENCES.DASH_DASH.length + 1);
this.state = State.COMMENT_START;
}
else if (this._consumeSequenceIfMatch(SEQUENCES.DOCTYPE, false)) {
// NOTE: Doctypes tokens are created without fixed offsets. We keep track of the moment a doctype *might* start here.
this.currentLocation = this.getCurrentLocation(SEQUENCES.DOCTYPE.length + 1);
this.state = State.DOCTYPE;
}
else if (this._consumeSequenceIfMatch(SEQUENCES.CDATA_START, true)) {
if (this.inForeignNode) {
this.state = State.CDATA_SECTION;
}
else {
this._err(ERR.cdataInHtmlContent);
this._createCommentToken(SEQUENCES.CDATA_START.length + 1);
this.currentToken.data = '[CDATA[';
this.state = State.BOGUS_COMMENT;
}
}
//NOTE: Sequence lookups can be abrupted by hibernation. In that case, lookup
//results are no longer valid and we will need to start over.
else if (!this._ensureHibernation()) {
this._err(ERR.incorrectlyOpenedComment);
this._createCommentToken(2);
this.state = State.BOGUS_COMMENT;
this._stateBogusComment(cp);
}
}
// Comment start state
//------------------------------------------------------------------
_stateCommentStart(cp) {
switch (cp) {
case CODE_POINTS.HYPHEN_MINUS: {
this.state = State.COMMENT_START_DASH;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this._err(ERR.abruptClosingOfEmptyComment);
this.state = State.DATA;
const token = this.currentToken;
this.emitCurrentComment(token);
break;
}
default: {
this.state = State.COMMENT;
this._stateComment(cp);
}
}
}
// Comment start dash state
//------------------------------------------------------------------
_stateCommentStartDash(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.HYPHEN_MINUS: {
this.state = State.COMMENT_END;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this._err(ERR.abruptClosingOfEmptyComment);
this.state = State.DATA;
this.emitCurrentComment(token);
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInComment);
this.emitCurrentComment(token);
this._emitEOFToken();
break;
}
default: {
token.data += '-';
this.state = State.COMMENT;
this._stateComment(cp);
}
}
}
// Comment state
//------------------------------------------------------------------
_stateComment(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.HYPHEN_MINUS: {
this.state = State.COMMENT_END_DASH;
break;
}
case CODE_POINTS.LESS_THAN_SIGN: {
token.data += '<';
this.state = State.COMMENT_LESS_THAN_SIGN;
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
token.data += REPLACEMENT_CHARACTER;
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInComment);
this.emitCurrentComment(token);
this._emitEOFToken();
break;
}
default: {
token.data += String.fromCodePoint(cp);
}
}
}
// Comment less-than sign state
//------------------------------------------------------------------
_stateCommentLessThanSign(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.EXCLAMATION_MARK: {
token.data += '!';
this.state = State.COMMENT_LESS_THAN_SIGN_BANG;
break;
}
case CODE_POINTS.LESS_THAN_SIGN: {
token.data += '<';
break;
}
default: {
this.state = State.COMMENT;
this._stateComment(cp);
}
}
}
// Comment less-than sign bang state
//------------------------------------------------------------------
_stateCommentLessThanSignBang(cp) {
if (cp === CODE_POINTS.HYPHEN_MINUS) {
this.state = State.COMMENT_LESS_THAN_SIGN_BANG_DASH;
}
else {
this.state = State.COMMENT;
this._stateComment(cp);
}
}
// Comment less-than sign bang dash state
//------------------------------------------------------------------
_stateCommentLessThanSignBangDash(cp) {
if (cp === CODE_POINTS.HYPHEN_MINUS) {
this.state = State.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH;
}
else {
this.state = State.COMMENT_END_DASH;
this._stateCommentEndDash(cp);
}
}
// Comment less-than sign bang dash dash state
//------------------------------------------------------------------
_stateCommentLessThanSignBangDashDash(cp) {
if (cp !== CODE_POINTS.GREATER_THAN_SIGN && cp !== CODE_POINTS.EOF) {
this._err(ERR.nestedComment);
}
this.state = State.COMMENT_END;
this._stateCommentEnd(cp);
}
// Comment end dash state
//------------------------------------------------------------------
_stateCommentEndDash(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.HYPHEN_MINUS: {
this.state = State.COMMENT_END;
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInComment);
this.emitCurrentComment(token);
this._emitEOFToken();
break;
}
default: {
token.data += '-';
this.state = State.COMMENT;
this._stateComment(cp);
}
}
}
// Comment end state
//------------------------------------------------------------------
_stateCommentEnd(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.GREATER_THAN_SIGN: {
this.state = State.DATA;
this.emitCurrentComment(token);
break;
}
case CODE_POINTS.EXCLAMATION_MARK: {
this.state = State.COMMENT_END_BANG;
break;
}
case CODE_POINTS.HYPHEN_MINUS: {
token.data += '-';
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInComment);
this.emitCurrentComment(token);
this._emitEOFToken();
break;
}
default: {
token.data += '--';
this.state = State.COMMENT;
this._stateComment(cp);
}
}
}
// Comment end bang state
//------------------------------------------------------------------
_stateCommentEndBang(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.HYPHEN_MINUS: {
token.data += '--!';
this.state = State.COMMENT_END_DASH;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this._err(ERR.incorrectlyClosedComment);
this.state = State.DATA;
this.emitCurrentComment(token);
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInComment);
this.emitCurrentComment(token);
this._emitEOFToken();
break;
}
default: {
token.data += '--!';
this.state = State.COMMENT;
this._stateComment(cp);
}
}
}
// DOCTYPE state
//------------------------------------------------------------------
_stateDoctype(cp) {
switch (cp) {
case CODE_POINTS.SPACE:
case CODE_POINTS.LINE_FEED:
case CODE_POINTS.TABULATION:
case CODE_POINTS.FORM_FEED: {
this.state = State.BEFORE_DOCTYPE_NAME;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this.state = State.BEFORE_DOCTYPE_NAME;
this._stateBeforeDoctypeName(cp);
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInDoctype);
this._createDoctypeToken(null);
const token = this.currentToken;
token.forceQuirks = true;
this.emitCurrentDoctype(token);
this._emitEOFToken();
break;
}
default: {
this._err(ERR.missingWhitespaceBeforeDoctypeName);
this.state = State.BEFORE_DOCTYPE_NAME;
this._stateBeforeDoctypeName(cp);
}
}
}
// Before DOCTYPE name state
//------------------------------------------------------------------
_stateBeforeDoctypeName(cp) {
if (isAsciiUpper(cp)) {
this._createDoctypeToken(String.fromCharCode(toAsciiLower(cp)));
this.state = State.DOCTYPE_NAME;
}
else
switch (cp) {
case CODE_POINTS.SPACE:
case CODE_POINTS.LINE_FEED:
case CODE_POINTS.TABULATION:
case CODE_POINTS.FORM_FEED: {
// Ignore whitespace
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
this._createDoctypeToken(REPLACEMENT_CHARACTER);
this.state = State.DOCTYPE_NAME;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this._err(ERR.missingDoctypeName);
this._createDoctypeToken(null);
const token = this.currentToken;
token.forceQuirks = true;
this.emitCurrentDoctype(token);
this.state = State.DATA;
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInDoctype);
this._createDoctypeToken(null);
const token = this.currentToken;
token.forceQuirks = true;
this.emitCurrentDoctype(token);
this._emitEOFToken();
break;
}
default: {
this._createDoctypeToken(String.fromCodePoint(cp));
this.state = State.DOCTYPE_NAME;
}
}
}
// DOCTYPE name state
//------------------------------------------------------------------
_stateDoctypeName(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.SPACE:
case CODE_POINTS.LINE_FEED:
case CODE_POINTS.TABULATION:
case CODE_POINTS.FORM_FEED: {
this.state = State.AFTER_DOCTYPE_NAME;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this.state = State.DATA;
this.emitCurrentDoctype(token);
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
token.name += REPLACEMENT_CHARACTER;
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInDoctype);
token.forceQuirks = true;
this.emitCurrentDoctype(token);
this._emitEOFToken();
break;
}
default: {
token.name += String.fromCodePoint(isAsciiUpper(cp) ? toAsciiLower(cp) : cp);
}
}
}
// After DOCTYPE name state
//------------------------------------------------------------------
_stateAfterDoctypeName(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.SPACE:
case CODE_POINTS.LINE_FEED:
case CODE_POINTS.TABULATION:
case CODE_POINTS.FORM_FEED: {
// Ignore whitespace
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this.state = State.DATA;
this.emitCurrentDoctype(token);
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInDoctype);
token.forceQuirks = true;
this.emitCurrentDoctype(token);
this._emitEOFToken();
break;
}
default:
if (this._consumeSequenceIfMatch(SEQUENCES.PUBLIC, false)) {
this.state = State.AFTER_DOCTYPE_PUBLIC_KEYWORD;
}
else if (this._consumeSequenceIfMatch(SEQUENCES.SYSTEM, false)) {
this.state = State.AFTER_DOCTYPE_SYSTEM_KEYWORD;
}
//NOTE: sequence lookup can be abrupted by hibernation. In that case lookup
//results are no longer valid and we will need to start over.
else if (!this._ensureHibernation()) {
this._err(ERR.invalidCharacterSequenceAfterDoctypeName);
token.forceQuirks = true;
this.state = State.BOGUS_DOCTYPE;
this._stateBogusDoctype(cp);
}
}
}
// After DOCTYPE public keyword state
//------------------------------------------------------------------
_stateAfterDoctypePublicKeyword(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.SPACE:
case CODE_POINTS.LINE_FEED:
case CODE_POINTS.TABULATION:
case CODE_POINTS.FORM_FEED: {
this.state = State.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;
break;
}
case CODE_POINTS.QUOTATION_MARK: {
this._err(ERR.missingWhitespaceAfterDoctypePublicKeyword);
token.publicId = '';
this.state = State.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;
break;
}
case CODE_POINTS.APOSTROPHE: {
this._err(ERR.missingWhitespaceAfterDoctypePublicKeyword);
token.publicId = '';
this.state = State.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this._err(ERR.missingDoctypePublicIdentifier);
token.forceQuirks = true;
this.state = State.DATA;
this.emitCurrentDoctype(token);
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInDoctype);
token.forceQuirks = true;
this.emitCurrentDoctype(token);
this._emitEOFToken();
break;
}
default: {
this._err(ERR.missingQuoteBeforeDoctypePublicIdentifier);
token.forceQuirks = true;
this.state = State.BOGUS_DOCTYPE;
this._stateBogusDoctype(cp);
}
}
}
// Before DOCTYPE public identifier state
//------------------------------------------------------------------
_stateBeforeDoctypePublicIdentifier(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.SPACE:
case CODE_POINTS.LINE_FEED:
case CODE_POINTS.TABULATION:
case CODE_POINTS.FORM_FEED: {
// Ignore whitespace
break;
}
case CODE_POINTS.QUOTATION_MARK: {
token.publicId = '';
this.state = State.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;
break;
}
case CODE_POINTS.APOSTROPHE: {
token.publicId = '';
this.state = State.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this._err(ERR.missingDoctypePublicIdentifier);
token.forceQuirks = true;
this.state = State.DATA;
this.emitCurrentDoctype(token);
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInDoctype);
token.forceQuirks = true;
this.emitCurrentDoctype(token);
this._emitEOFToken();
break;
}
default: {
this._err(ERR.missingQuoteBeforeDoctypePublicIdentifier);
token.forceQuirks = true;
this.state = State.BOGUS_DOCTYPE;
this._stateBogusDoctype(cp);
}
}
}
// DOCTYPE public identifier (double-quoted) state
//------------------------------------------------------------------
_stateDoctypePublicIdentifierDoubleQuoted(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.QUOTATION_MARK: {
this.state = State.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
token.publicId += REPLACEMENT_CHARACTER;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this._err(ERR.abruptDoctypePublicIdentifier);
token.forceQuirks = true;
this.emitCurrentDoctype(token);
this.state = State.DATA;
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInDoctype);
token.forceQuirks = true;
this.emitCurrentDoctype(token);
this._emitEOFToken();
break;
}
default: {
token.publicId += String.fromCodePoint(cp);
}
}
}
// DOCTYPE public identifier (single-quoted) state
//------------------------------------------------------------------
_stateDoctypePublicIdentifierSingleQuoted(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.APOSTROPHE: {
this.state = State.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
token.publicId += REPLACEMENT_CHARACTER;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this._err(ERR.abruptDoctypePublicIdentifier);
token.forceQuirks = true;
this.emitCurrentDoctype(token);
this.state = State.DATA;
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInDoctype);
token.forceQuirks = true;
this.emitCurrentDoctype(token);
this._emitEOFToken();
break;
}
default: {
token.publicId += String.fromCodePoint(cp);
}
}
}
// After DOCTYPE public identifier state
//------------------------------------------------------------------
_stateAfterDoctypePublicIdentifier(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.SPACE:
case CODE_POINTS.LINE_FEED:
case CODE_POINTS.TABULATION:
case CODE_POINTS.FORM_FEED: {
this.state = State.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this.state = State.DATA;
this.emitCurrentDoctype(token);
break;
}
case CODE_POINTS.QUOTATION_MARK: {
this._err(ERR.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers);
token.systemId = '';
this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
break;
}
case CODE_POINTS.APOSTROPHE: {
this._err(ERR.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers);
token.systemId = '';
this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInDoctype);
token.forceQuirks = true;
this.emitCurrentDoctype(token);
this._emitEOFToken();
break;
}
default: {
this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier);
token.forceQuirks = true;
this.state = State.BOGUS_DOCTYPE;
this._stateBogusDoctype(cp);
}
}
}
// Between DOCTYPE public and system identifiers state
//------------------------------------------------------------------
_stateBetweenDoctypePublicAndSystemIdentifiers(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.SPACE:
case CODE_POINTS.LINE_FEED:
case CODE_POINTS.TABULATION:
case CODE_POINTS.FORM_FEED: {
// Ignore whitespace
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this.emitCurrentDoctype(token);
this.state = State.DATA;
break;
}
case CODE_POINTS.QUOTATION_MARK: {
token.systemId = '';
this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
break;
}
case CODE_POINTS.APOSTROPHE: {
token.systemId = '';
this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInDoctype);
token.forceQuirks = true;
this.emitCurrentDoctype(token);
this._emitEOFToken();
break;
}
default: {
this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier);
token.forceQuirks = true;
this.state = State.BOGUS_DOCTYPE;
this._stateBogusDoctype(cp);
}
}
}
// After DOCTYPE system keyword state
//------------------------------------------------------------------
_stateAfterDoctypeSystemKeyword(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.SPACE:
case CODE_POINTS.LINE_FEED:
case CODE_POINTS.TABULATION:
case CODE_POINTS.FORM_FEED: {
this.state = State.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;
break;
}
case CODE_POINTS.QUOTATION_MARK: {
this._err(ERR.missingWhitespaceAfterDoctypeSystemKeyword);
token.systemId = '';
this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
break;
}
case CODE_POINTS.APOSTROPHE: {
this._err(ERR.missingWhitespaceAfterDoctypeSystemKeyword);
token.systemId = '';
this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this._err(ERR.missingDoctypeSystemIdentifier);
token.forceQuirks = true;
this.state = State.DATA;
this.emitCurrentDoctype(token);
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInDoctype);
token.forceQuirks = true;
this.emitCurrentDoctype(token);
this._emitEOFToken();
break;
}
default: {
this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier);
token.forceQuirks = true;
this.state = State.BOGUS_DOCTYPE;
this._stateBogusDoctype(cp);
}
}
}
// Before DOCTYPE system identifier state
//------------------------------------------------------------------
_stateBeforeDoctypeSystemIdentifier(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.SPACE:
case CODE_POINTS.LINE_FEED:
case CODE_POINTS.TABULATION:
case CODE_POINTS.FORM_FEED: {
// Ignore whitespace
break;
}
case CODE_POINTS.QUOTATION_MARK: {
token.systemId = '';
this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
break;
}
case CODE_POINTS.APOSTROPHE: {
token.systemId = '';
this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this._err(ERR.missingDoctypeSystemIdentifier);
token.forceQuirks = true;
this.state = State.DATA;
this.emitCurrentDoctype(token);
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInDoctype);
token.forceQuirks = true;
this.emitCurrentDoctype(token);
this._emitEOFToken();
break;
}
default: {
this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier);
token.forceQuirks = true;
this.state = State.BOGUS_DOCTYPE;
this._stateBogusDoctype(cp);
}
}
}
// DOCTYPE system identifier (double-quoted) state
//------------------------------------------------------------------
_stateDoctypeSystemIdentifierDoubleQuoted(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.QUOTATION_MARK: {
this.state = State.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
token.systemId += REPLACEMENT_CHARACTER;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this._err(ERR.abruptDoctypeSystemIdentifier);
token.forceQuirks = true;
this.emitCurrentDoctype(token);
this.state = State.DATA;
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInDoctype);
token.forceQuirks = true;
this.emitCurrentDoctype(token);
this._emitEOFToken();
break;
}
default: {
token.systemId += String.fromCodePoint(cp);
}
}
}
// DOCTYPE system identifier (single-quoted) state
//------------------------------------------------------------------
_stateDoctypeSystemIdentifierSingleQuoted(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.APOSTROPHE: {
this.state = State.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
token.systemId += REPLACEMENT_CHARACTER;
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this._err(ERR.abruptDoctypeSystemIdentifier);
token.forceQuirks = true;
this.emitCurrentDoctype(token);
this.state = State.DATA;
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInDoctype);
token.forceQuirks = true;
this.emitCurrentDoctype(token);
this._emitEOFToken();
break;
}
default: {
token.systemId += String.fromCodePoint(cp);
}
}
}
// After DOCTYPE system identifier state
//------------------------------------------------------------------
_stateAfterDoctypeSystemIdentifier(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.SPACE:
case CODE_POINTS.LINE_FEED:
case CODE_POINTS.TABULATION:
case CODE_POINTS.FORM_FEED: {
// Ignore whitespace
break;
}
case CODE_POINTS.GREATER_THAN_SIGN: {
this.emitCurrentDoctype(token);
this.state = State.DATA;
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInDoctype);
token.forceQuirks = true;
this.emitCurrentDoctype(token);
this._emitEOFToken();
break;
}
default: {
this._err(ERR.unexpectedCharacterAfterDoctypeSystemIdentifier);
this.state = State.BOGUS_DOCTYPE;
this._stateBogusDoctype(cp);
}
}
}
// Bogus DOCTYPE state
//------------------------------------------------------------------
_stateBogusDoctype(cp) {
const token = this.currentToken;
switch (cp) {
case CODE_POINTS.GREATER_THAN_SIGN: {
this.emitCurrentDoctype(token);
this.state = State.DATA;
break;
}
case CODE_POINTS.NULL: {
this._err(ERR.unexpectedNullCharacter);
break;
}
case CODE_POINTS.EOF: {
this.emitCurrentDoctype(token);
this._emitEOFToken();
break;
}
// Do nothing
}
}
// CDATA section state
//------------------------------------------------------------------
_stateCdataSection(cp) {
switch (cp) {
case CODE_POINTS.RIGHT_SQUARE_BRACKET: {
this.state = State.CDATA_SECTION_BRACKET;
break;
}
case CODE_POINTS.EOF: {
this._err(ERR.eofInCdata);
this._emitEOFToken();
break;
}
default: {
this._emitCodePoint(cp);
}
}
}
// CDATA section bracket state
//------------------------------------------------------------------
_stateCdataSectionBracket(cp) {
if (cp === CODE_POINTS.RIGHT_SQUARE_BRACKET) {
this.state = State.CDATA_SECTION_END;
}
else {
this._emitChars(']');
this.state = State.CDATA_SECTION;
this._stateCdataSection(cp);
}
}
// CDATA section end state
//------------------------------------------------------------------
_stateCdataSectionEnd(cp) {
switch (cp) {
case CODE_POINTS.GREATER_THAN_SIGN: {
this.state = State.DATA;
break;
}
case CODE_POINTS.RIGHT_SQUARE_BRACKET: {
this._emitChars(']');
break;
}
default: {
this._emitChars(']]');
this.state = State.CDATA_SECTION;
this._stateCdataSection(cp);
}
}
}
// Character reference state
//------------------------------------------------------------------
_stateCharacterReference(cp) {
if (cp === CODE_POINTS.NUMBER_SIGN) {
this.state = State.NUMERIC_CHARACTER_REFERENCE;
}
else if (isAsciiAlphaNumeric(cp)) {
this.state = State.NAMED_CHARACTER_REFERENCE;
this._stateNamedCharacterReference(cp);
}
else {
this._flushCodePointConsumedAsCharacterReference(CODE_POINTS.AMPERSAND);
this._reconsumeInState(this.returnState);
}
}
// Named character reference state
//------------------------------------------------------------------
_stateNamedCharacterReference(cp) {
const matchResult = this._matchNamedCharacterReference(cp);
//NOTE: Matching can be abrupted by hibernation. In that case, match
//results are no longer valid and we will need to start over.
if (this._ensureHibernation()) ;
else if (matchResult) {
for (let i = 0; i < matchResult.length; i++) {
this._flushCodePointConsumedAsCharacterReference(matchResult[i]);
}
this.state = this.returnState;
}
else {
this._flushCodePointConsumedAsCharacterReference(CODE_POINTS.AMPERSAND);
this.state = State.AMBIGUOUS_AMPERSAND;
}
}
// Ambiguos ampersand state
//------------------------------------------------------------------
_stateAmbiguousAmpersand(cp) {
if (isAsciiAlphaNumeric(cp)) {
this._flushCodePointConsumedAsCharacterReference(cp);
}
else {
if (cp === CODE_POINTS.SEMICOLON) {
this._err(ERR.unknownNamedCharacterReference);
}
this._reconsumeInState(this.returnState);
}
}
// Numeric character reference state
//------------------------------------------------------------------
_stateNumericCharacterReference(cp) {
this.charRefCode = 0;
if (cp === CODE_POINTS.LATIN_SMALL_X || cp === CODE_POINTS.LATIN_CAPITAL_X) {
this.state = State.HEXADEMICAL_CHARACTER_REFERENCE_START;
}
else {
this.state = State.DECIMAL_CHARACTER_REFERENCE_START;
this._stateDecimalCharacterReferenceStart(cp);
}
}
// Hexademical character reference start state
//------------------------------------------------------------------
_stateHexademicalCharacterReferenceStart(cp) {
if (isAsciiHexDigit(cp)) {
this.state = State.HEXADEMICAL_CHARACTER_REFERENCE;
this._stateHexademicalCharacterReference(cp);
}
else {
this._err(ERR.absenceOfDigitsInNumericCharacterReference);
this._flushCodePointConsumedAsCharacterReference(CODE_POINTS.AMPERSAND);
this._flushCodePointConsumedAsCharacterReference(CODE_POINTS.NUMBER_SIGN);
this._unconsume(2);
this.state = this.returnState;
}
}
// Decimal character reference start state
//------------------------------------------------------------------
_stateDecimalCharacterReferenceStart(cp) {
if (isAsciiDigit(cp)) {
this.state = State.DECIMAL_CHARACTER_REFERENCE;
this._stateDecimalCharacterReference(cp);
}
else {
this._err(ERR.absenceOfDigitsInNumericCharacterReference);
this._flushCodePointConsumedAsCharacterReference(CODE_POINTS.AMPERSAND);
this._flushCodePointConsumedAsCharacterReference(CODE_POINTS.NUMBER_SIGN);
this._reconsumeInState(this.returnState);
}
}
// Hexademical character reference state
//------------------------------------------------------------------
_stateHexademicalCharacterReference(cp) {
if (isAsciiUpperHexDigit(cp)) {
this.charRefCode = this.charRefCode * 16 + cp - 0x37;
}
else if (isAsciiLowerHexDigit(cp)) {
this.charRefCode = this.charRefCode * 16 + cp - 0x57;
}
else if (isAsciiDigit(cp)) {
this.charRefCode = this.charRefCode * 16 + cp - 0x30;
}
else if (cp === CODE_POINTS.SEMICOLON) {
this.state = State.NUMERIC_CHARACTER_REFERENCE_END;
}
else {
this._err(ERR.missingSemicolonAfterCharacterReference);
this.state = State.NUMERIC_CHARACTER_REFERENCE_END;
this._stateNumericCharacterReferenceEnd();
}
}
// Decimal character reference state
//------------------------------------------------------------------
_stateDecimalCharacterReference(cp) {
if (isAsciiDigit(cp)) {
this.charRefCode = this.charRefCode * 10 + cp - 0x30;
}
else if (cp === CODE_POINTS.SEMICOLON) {
this.state = State.NUMERIC_CHARACTER_REFERENCE_END;
}
else {
this._err(ERR.missingSemicolonAfterCharacterReference);
this.state = State.NUMERIC_CHARACTER_REFERENCE_END;
this._stateNumericCharacterReferenceEnd();
}
}
// Numeric character reference end state
//------------------------------------------------------------------
_stateNumericCharacterReferenceEnd() {
if (this.charRefCode === CODE_POINTS.NULL) {
this._err(ERR.nullCharacterReference);
this.charRefCode = CODE_POINTS.REPLACEMENT_CHARACTER;
}
else if (this.charRefCode > 1114111) {
this._err(ERR.characterReferenceOutsideUnicodeRange);
this.charRefCode = CODE_POINTS.REPLACEMENT_CHARACTER;
}
else if (isSurrogate(this.charRefCode)) {
this._err(ERR.surrogateCharacterReference);
this.charRefCode = CODE_POINTS.REPLACEMENT_CHARACTER;
}
else if (isUndefinedCodePoint(this.charRefCode)) {
this._err(ERR.noncharacterCharacterReference);
}
else if (isControlCodePoint(this.charRefCode) || this.charRefCode === CODE_POINTS.CARRIAGE_RETURN) {
this._err(ERR.controlCharacterReference);
const replacement = C1_CONTROLS_REFERENCE_REPLACEMENTS.get(this.charRefCode);
if (replacement !== undefined) {
this.charRefCode = replacement;
}
}
this._flushCodePointConsumedAsCharacterReference(this.charRefCode);
this._reconsumeInState(this.returnState);
}
}
//Element utils
const IMPLICIT_END_TAG_REQUIRED = new Set([TAG_ID.DD, TAG_ID.DT, TAG_ID.LI, TAG_ID.OPTGROUP, TAG_ID.OPTION, TAG_ID.P, TAG_ID.RB, TAG_ID.RP, TAG_ID.RT, TAG_ID.RTC]);
const IMPLICIT_END_TAG_REQUIRED_THOROUGHLY = new Set([
...IMPLICIT_END_TAG_REQUIRED,
TAG_ID.CAPTION,
TAG_ID.COLGROUP,
TAG_ID.TBODY,
TAG_ID.TD,
TAG_ID.TFOOT,
TAG_ID.TH,
TAG_ID.THEAD,
TAG_ID.TR,
]);
const SCOPING_ELEMENT_NS = new Map([
[TAG_ID.APPLET, NS.HTML],
[TAG_ID.CAPTION, NS.HTML],
[TAG_ID.HTML, NS.HTML],
[TAG_ID.MARQUEE, NS.HTML],
[TAG_ID.OBJECT, NS.HTML],
[TAG_ID.TABLE, NS.HTML],
[TAG_ID.TD, NS.HTML],
[TAG_ID.TEMPLATE, NS.HTML],
[TAG_ID.TH, NS.HTML],
[TAG_ID.ANNOTATION_XML, NS.MATHML],
[TAG_ID.MI, NS.MATHML],
[TAG_ID.MN, NS.MATHML],
[TAG_ID.MO, NS.MATHML],
[TAG_ID.MS, NS.MATHML],
[TAG_ID.MTEXT, NS.MATHML],
[TAG_ID.DESC, NS.SVG],
[TAG_ID.FOREIGN_OBJECT, NS.SVG],
[TAG_ID.TITLE, NS.SVG],
]);
const NAMED_HEADERS = [TAG_ID.H1, TAG_ID.H2, TAG_ID.H3, TAG_ID.H4, TAG_ID.H5, TAG_ID.H6];
const TABLE_ROW_CONTEXT = [TAG_ID.TR, TAG_ID.TEMPLATE, TAG_ID.HTML];
const TABLE_BODY_CONTEXT = [TAG_ID.TBODY, TAG_ID.TFOOT, TAG_ID.THEAD, TAG_ID.TEMPLATE, TAG_ID.HTML];
const TABLE_CONTEXT = [TAG_ID.TABLE, TAG_ID.TEMPLATE, TAG_ID.HTML];
const TABLE_CELLS = [TAG_ID.TD, TAG_ID.TH];
//Stack of open elements
class OpenElementStack {
constructor(document, treeAdapter, handler) {
this.treeAdapter = treeAdapter;
this.handler = handler;
this.items = [];
this.tagIDs = [];
this.stackTop = -1;
this.tmplCount = 0;
this.currentTagId = TAG_ID.UNKNOWN;
this.current = document;
}
get currentTmplContentOrNode() {
return this._isInTemplate() ? this.treeAdapter.getTemplateContent(this.current) : this.current;
}
//Index of element
_indexOf(element) {
return this.items.lastIndexOf(element, this.stackTop);
}
//Update current element
_isInTemplate() {
return this.currentTagId === TAG_ID.TEMPLATE && this.treeAdapter.getNamespaceURI(this.current) === NS.HTML;
}
_updateCurrentElement() {
this.current = this.items[this.stackTop];
this.currentTagId = this.tagIDs[this.stackTop];
}
//Mutations
push(element, tagID) {
this.stackTop++;
this.items[this.stackTop] = element;
this.current = element;
this.tagIDs[this.stackTop] = tagID;
this.currentTagId = tagID;
if (this._isInTemplate()) {
this.tmplCount++;
}
this.handler.onItemPush(element, tagID, true);
}
pop() {
const popped = this.current;
if (this.tmplCount > 0 && this._isInTemplate()) {
this.tmplCount--;
}
this.stackTop--;
this._updateCurrentElement();
this.handler.onItemPop(popped, true);
}
replace(oldElement, newElement) {
const idx = this._indexOf(oldElement);
this.items[idx] = newElement;
if (idx === this.stackTop) {
this.current = newElement;
}
}
insertAfter(referenceElement, newElement, newElementID) {
const insertionIdx = this._indexOf(referenceElement) + 1;
this.items.splice(insertionIdx, 0, newElement);
this.tagIDs.splice(insertionIdx, 0, newElementID);
this.stackTop++;
if (insertionIdx === this.stackTop) {
this._updateCurrentElement();
}
this.handler.onItemPush(this.current, this.currentTagId, insertionIdx === this.stackTop);
}
popUntilTagNamePopped(tagName) {
let targetIdx = this.stackTop + 1;
do {
targetIdx = this.tagIDs.lastIndexOf(tagName, targetIdx - 1);
} while (targetIdx > 0 && this.treeAdapter.getNamespaceURI(this.items[targetIdx]) !== NS.HTML);
this.shortenToLength(targetIdx < 0 ? 0 : targetIdx);
}
shortenToLength(idx) {
while (this.stackTop >= idx) {
const popped = this.current;
if (this.tmplCount > 0 && this._isInTemplate()) {
this.tmplCount -= 1;
}
this.stackTop--;
this._updateCurrentElement();
this.handler.onItemPop(popped, this.stackTop < idx);
}
}
popUntilElementPopped(element) {
const idx = this._indexOf(element);
this.shortenToLength(idx < 0 ? 0 : idx);
}
popUntilPopped(tagNames, targetNS) {
const idx = this._indexOfTagNames(tagNames, targetNS);
this.shortenToLength(idx < 0 ? 0 : idx);
}
popUntilNumberedHeaderPopped() {
this.popUntilPopped(NAMED_HEADERS, NS.HTML);
}
popUntilTableCellPopped() {
this.popUntilPopped(TABLE_CELLS, NS.HTML);
}
popAllUpToHtmlElement() {
//NOTE: here we assume that the root <html> element is always first in the open element stack, so
//we perform this fast stack clean up.
this.tmplCount = 0;
this.shortenToLength(1);
}
_indexOfTagNames(tagNames, namespace) {
for (let i = this.stackTop; i >= 0; i--) {
if (tagNames.includes(this.tagIDs[i]) && this.treeAdapter.getNamespaceURI(this.items[i]) === namespace) {
return i;
}
}
return -1;
}
clearBackTo(tagNames, targetNS) {
const idx = this._indexOfTagNames(tagNames, targetNS);
this.shortenToLength(idx + 1);
}
clearBackToTableContext() {
this.clearBackTo(TABLE_CONTEXT, NS.HTML);
}
clearBackToTableBodyContext() {
this.clearBackTo(TABLE_BODY_CONTEXT, NS.HTML);
}
clearBackToTableRowContext() {
this.clearBackTo(TABLE_ROW_CONTEXT, NS.HTML);
}
remove(element) {
const idx = this._indexOf(element);
if (idx >= 0) {
if (idx === this.stackTop) {
this.pop();
}
else {
this.items.splice(idx, 1);
this.tagIDs.splice(idx, 1);
this.stackTop--;
this._updateCurrentElement();
this.handler.onItemPop(element, false);
}
}
}
//Search
tryPeekProperlyNestedBodyElement() {
//Properly nested <body> element (should be second element in stack).
return this.stackTop >= 1 && this.tagIDs[1] === TAG_ID.BODY ? this.items[1] : null;
}
contains(element) {
return this._indexOf(element) > -1;
}
getCommonAncestor(element) {
const elementIdx = this._indexOf(element) - 1;
return elementIdx >= 0 ? this.items[elementIdx] : null;
}
isRootHtmlElementCurrent() {
return this.stackTop === 0 && this.tagIDs[0] === TAG_ID.HTML;
}
//Element in scope
hasInScope(tagName) {
for (let i = this.stackTop; i >= 0; i--) {
const tn = this.tagIDs[i];
const ns = this.treeAdapter.getNamespaceURI(this.items[i]);
if (tn === tagName && ns === NS.HTML) {
return true;
}
if (SCOPING_ELEMENT_NS.get(tn) === ns) {
return false;
}
}
return true;
}
hasNumberedHeaderInScope() {
for (let i = this.stackTop; i >= 0; i--) {
const tn = this.tagIDs[i];
const ns = this.treeAdapter.getNamespaceURI(this.items[i]);
if (isNumberedHeader(tn) && ns === NS.HTML) {
return true;
}
if (SCOPING_ELEMENT_NS.get(tn) === ns) {
return false;
}
}
return true;
}
hasInListItemScope(tagName) {
for (let i = this.stackTop; i >= 0; i--) {
const tn = this.tagIDs[i];
const ns = this.treeAdapter.getNamespaceURI(this.items[i]);
if (tn === tagName && ns === NS.HTML) {
return true;
}
if (((tn === TAG_ID.UL || tn === TAG_ID.OL) && ns === NS.HTML) || SCOPING_ELEMENT_NS.get(tn) === ns) {
return false;
}
}
return true;
}
hasInButtonScope(tagName) {
for (let i = this.stackTop; i >= 0; i--) {
const tn = this.tagIDs[i];
const ns = this.treeAdapter.getNamespaceURI(this.items[i]);
if (tn === tagName && ns === NS.HTML) {
return true;
}
if ((tn === TAG_ID.BUTTON && ns === NS.HTML) || SCOPING_ELEMENT_NS.get(tn) === ns) {
return false;
}
}
return true;
}
hasInTableScope(tagName) {
for (let i = this.stackTop; i >= 0; i--) {
const tn = this.tagIDs[i];
const ns = this.treeAdapter.getNamespaceURI(this.items[i]);
if (ns !== NS.HTML) {
continue;
}
if (tn === tagName) {
return true;
}
if (tn === TAG_ID.TABLE || tn === TAG_ID.TEMPLATE || tn === TAG_ID.HTML) {
return false;
}
}
return true;
}
hasTableBodyContextInTableScope() {
for (let i = this.stackTop; i >= 0; i--) {
const tn = this.tagIDs[i];
const ns = this.treeAdapter.getNamespaceURI(this.items[i]);
if (ns !== NS.HTML) {
continue;
}
if (tn === TAG_ID.TBODY || tn === TAG_ID.THEAD || tn === TAG_ID.TFOOT) {
return true;
}
if (tn === TAG_ID.TABLE || tn === TAG_ID.HTML) {
return false;
}
}
return true;
}
hasInSelectScope(tagName) {
for (let i = this.stackTop; i >= 0; i--) {
const tn = this.tagIDs[i];
const ns = this.treeAdapter.getNamespaceURI(this.items[i]);
if (ns !== NS.HTML) {
continue;
}
if (tn === tagName) {
return true;
}
if (tn !== TAG_ID.OPTION && tn !== TAG_ID.OPTGROUP) {
return false;
}
}
return true;
}
//Implied end tags
generateImpliedEndTags() {
while (IMPLICIT_END_TAG_REQUIRED.has(this.currentTagId)) {
this.pop();
}
}
generateImpliedEndTagsThoroughly() {
while (IMPLICIT_END_TAG_REQUIRED_THOROUGHLY.has(this.currentTagId)) {
this.pop();
}
}
generateImpliedEndTagsWithExclusion(exclusionId) {
while (this.currentTagId !== exclusionId && IMPLICIT_END_TAG_REQUIRED_THOROUGHLY.has(this.currentTagId)) {
this.pop();
}
}
}
//Const
const NOAH_ARK_CAPACITY = 3;
var EntryType;
(function (EntryType) {
EntryType[EntryType["Marker"] = 0] = "Marker";
EntryType[EntryType["Element"] = 1] = "Element";
})(EntryType || (EntryType = {}));
const MARKER = { type: EntryType.Marker };
//List of formatting elements
class FormattingElementList {
constructor(treeAdapter) {
this.treeAdapter = treeAdapter;
this.entries = [];
this.bookmark = null;
}
//Noah Ark's condition
//OPTIMIZATION: at first we try to find possible candidates for exclusion using
//lightweight heuristics without thorough attributes check.
_getNoahArkConditionCandidates(newElement, neAttrs) {
const candidates = [];
const neAttrsLength = neAttrs.length;
const neTagName = this.treeAdapter.getTagName(newElement);
const neNamespaceURI = this.treeAdapter.getNamespaceURI(newElement);
for (let i = 0; i < this.entries.length; i++) {
const entry = this.entries[i];
if (entry.type === EntryType.Marker) {
break;
}
const { element } = entry;
if (this.treeAdapter.getTagName(element) === neTagName &&
this.treeAdapter.getNamespaceURI(element) === neNamespaceURI) {
const elementAttrs = this.treeAdapter.getAttrList(element);
if (elementAttrs.length === neAttrsLength) {
candidates.push({ idx: i, attrs: elementAttrs });
}
}
}
return candidates;
}
_ensureNoahArkCondition(newElement) {
if (this.entries.length < NOAH_ARK_CAPACITY)
return;
const neAttrs = this.treeAdapter.getAttrList(newElement);
const candidates = this._getNoahArkConditionCandidates(newElement, neAttrs);
if (candidates.length < NOAH_ARK_CAPACITY)
return;
//NOTE: build attrs map for the new element, so we can perform fast lookups
const neAttrsMap = new Map(neAttrs.map((neAttr) => [neAttr.name, neAttr.value]));
let validCandidates = 0;
//NOTE: remove bottommost candidates, until Noah's Ark condition will not be met
for (let i = 0; i < candidates.length; i++) {
const candidate = candidates[i];
// We know that `candidate.attrs.length === neAttrs.length`
if (candidate.attrs.every((cAttr) => neAttrsMap.get(cAttr.name) === cAttr.value)) {
validCandidates += 1;
if (validCandidates >= NOAH_ARK_CAPACITY) {
this.entries.splice(candidate.idx, 1);
}
}
}
}
//Mutations
insertMarker() {
this.entries.unshift(MARKER);
}
pushElement(element, token) {
this._ensureNoahArkCondition(element);
this.entries.unshift({
type: EntryType.Element,
element,
token,
});
}
insertElementAfterBookmark(element, token) {
const bookmarkIdx = this.entries.indexOf(this.bookmark);
this.entries.splice(bookmarkIdx, 0, {
type: EntryType.Element,
element,
token,
});
}
removeEntry(entry) {
const entryIndex = this.entries.indexOf(entry);
if (entryIndex >= 0) {
this.entries.splice(entryIndex, 1);
}
}
clearToLastMarker() {
const markerIdx = this.entries.indexOf(MARKER);
if (markerIdx >= 0) {
this.entries.splice(0, markerIdx + 1);
}
else {
this.entries.length = 0;
}
}
//Search
getElementEntryInScopeWithTagName(tagName) {
const entry = this.entries.find((entry) => entry.type === EntryType.Marker || this.treeAdapter.getTagName(entry.element) === tagName);
return entry && entry.type === EntryType.Element ? entry : null;
}
getElementEntry(element) {
return this.entries.find((entry) => entry.type === EntryType.Element && entry.element === element);
}
}
var NodeType;
(function (NodeType) {
NodeType["Document"] = "#document";
NodeType["DocumentFragment"] = "#document-fragment";
NodeType["Comment"] = "#comment";
NodeType["Text"] = "#text";
NodeType["DocumentType"] = "#documentType";
})(NodeType || (NodeType = {}));
function createTextNode(value) {
return {
nodeName: NodeType.Text,
value,
parentNode: null,
};
}
const defaultTreeAdapter = {
//Node construction
createDocument() {
return {
nodeName: NodeType.Document,
mode: DOCUMENT_MODE.NO_QUIRKS,
childNodes: [],
};
},
createDocumentFragment() {
return {
nodeName: NodeType.DocumentFragment,
childNodes: [],
};
},
createElement(tagName, namespaceURI, attrs) {
return {
nodeName: tagName,
tagName,
attrs,
namespaceURI,
childNodes: [],
parentNode: null,
};
},
createCommentNode(data) {
return {
nodeName: NodeType.Comment,
data,
parentNode: null,
};
},
//Tree mutation
appendChild(parentNode, newNode) {
parentNode.childNodes.push(newNode);
newNode.parentNode = parentNode;
},
insertBefore(parentNode, newNode, referenceNode) {
const insertionIdx = parentNode.childNodes.indexOf(referenceNode);
parentNode.childNodes.splice(insertionIdx, 0, newNode);
newNode.parentNode = parentNode;
},
setTemplateContent(templateElement, contentElement) {
templateElement.content = contentElement;
},
getTemplateContent(templateElement) {
return templateElement.content;
},
setDocumentType(document, name, publicId, systemId) {
const doctypeNode = document.childNodes.find((node) => node.nodeName === NodeType.DocumentType);
if (doctypeNode) {
doctypeNode.name = name;
doctypeNode.publicId = publicId;
doctypeNode.systemId = systemId;
}
else {
const node = {
nodeName: NodeType.DocumentType,
name,
publicId,
systemId,
parentNode: null,
};
defaultTreeAdapter.appendChild(document, node);
}
},
setDocumentMode(document, mode) {
document.mode = mode;
},
getDocumentMode(document) {
return document.mode;
},
detachNode(node) {
if (node.parentNode) {
const idx = node.parentNode.childNodes.indexOf(node);
node.parentNode.childNodes.splice(idx, 1);
node.parentNode = null;
}
},
insertText(parentNode, text) {
if (parentNode.childNodes.length > 0) {
const prevNode = parentNode.childNodes[parentNode.childNodes.length - 1];
if (defaultTreeAdapter.isTextNode(prevNode)) {
prevNode.value += text;
return;
}
}
defaultTreeAdapter.appendChild(parentNode, createTextNode(text));
},
insertTextBefore(parentNode, text, referenceNode) {
const prevNode = parentNode.childNodes[parentNode.childNodes.indexOf(referenceNode) - 1];
if (prevNode && defaultTreeAdapter.isTextNode(prevNode)) {
prevNode.value += text;
}
else {
defaultTreeAdapter.insertBefore(parentNode, createTextNode(text), referenceNode);
}
},
adoptAttributes(recipient, attrs) {
const recipientAttrsMap = new Set(recipient.attrs.map((attr) => attr.name));
for (let j = 0; j < attrs.length; j++) {
if (!recipientAttrsMap.has(attrs[j].name)) {
recipient.attrs.push(attrs[j]);
}
}
},
//Tree traversing
getFirstChild(node) {
return node.childNodes[0];
},
getChildNodes(node) {
return node.childNodes;
},
getParentNode(node) {
return node.parentNode;
},
getAttrList(element) {
return element.attrs;
},
//Node data
getTagName(element) {
return element.tagName;
},
getNamespaceURI(element) {
return element.namespaceURI;
},
getTextNodeContent(textNode) {
return textNode.value;
},
getCommentNodeContent(commentNode) {
return commentNode.data;
},
getDocumentTypeNodeName(doctypeNode) {
return doctypeNode.name;
},
getDocumentTypeNodePublicId(doctypeNode) {
return doctypeNode.publicId;
},
getDocumentTypeNodeSystemId(doctypeNode) {
return doctypeNode.systemId;
},
//Node types
isTextNode(node) {
return node.nodeName === '#text';
},
isCommentNode(node) {
return node.nodeName === '#comment';
},
isDocumentTypeNode(node) {
return node.nodeName === NodeType.DocumentType;
},
isElementNode(node) {
return Object.prototype.hasOwnProperty.call(node, 'tagName');
},
// Source code location
setNodeSourceCodeLocation(node, location) {
node.sourceCodeLocation = location;
},
getNodeSourceCodeLocation(node) {
return node.sourceCodeLocation;
},
updateNodeSourceCodeLocation(node, endLocation) {
node.sourceCodeLocation = { ...node.sourceCodeLocation, ...endLocation };
},
};
//Const
const VALID_DOCTYPE_NAME = 'html';
const VALID_SYSTEM_ID = 'about:legacy-compat';
const QUIRKS_MODE_SYSTEM_ID = 'http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd';
const QUIRKS_MODE_PUBLIC_ID_PREFIXES = [
'+//silmaril//dtd html pro v0r11 19970101//',
'-//as//dtd html 3.0 aswedit + extensions//',
'-//advasoft ltd//dtd html 3.0 aswedit + extensions//',
'-//ietf//dtd html 2.0 level 1//',
'-//ietf//dtd html 2.0 level 2//',
'-//ietf//dtd html 2.0 strict level 1//',
'-//ietf//dtd html 2.0 strict level 2//',
'-//ietf//dtd html 2.0 strict//',
'-//ietf//dtd html 2.0//',
'-//ietf//dtd html 2.1e//',
'-//ietf//dtd html 3.0//',
'-//ietf//dtd html 3.2 final//',
'-//ietf//dtd html 3.2//',
'-//ietf//dtd html 3//',
'-//ietf//dtd html level 0//',
'-//ietf//dtd html level 1//',
'-//ietf//dtd html level 2//',
'-//ietf//dtd html level 3//',
'-//ietf//dtd html strict level 0//',
'-//ietf//dtd html strict level 1//',
'-//ietf//dtd html strict level 2//',
'-//ietf//dtd html strict level 3//',
'-//ietf//dtd html strict//',
'-//ietf//dtd html//',
'-//metrius//dtd metrius presentational//',
'-//microsoft//dtd internet explorer 2.0 html strict//',
'-//microsoft//dtd internet explorer 2.0 html//',
'-//microsoft//dtd internet explorer 2.0 tables//',
'-//microsoft//dtd internet explorer 3.0 html strict//',
'-//microsoft//dtd internet explorer 3.0 html//',
'-//microsoft//dtd internet explorer 3.0 tables//',
'-//netscape comm. corp.//dtd html//',
'-//netscape comm. corp.//dtd strict html//',
"-//o'reilly and associates//dtd html 2.0//",
"-//o'reilly and associates//dtd html extended 1.0//",
"-//o'reilly and associates//dtd html extended relaxed 1.0//",
'-//sq//dtd html 2.0 hotmetal + extensions//',
'-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//',
'-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//',
'-//spyglass//dtd html 2.0 extended//',
'-//sun microsystems corp.//dtd hotjava html//',
'-//sun microsystems corp.//dtd hotjava strict html//',
'-//w3c//dtd html 3 1995-03-24//',
'-//w3c//dtd html 3.2 draft//',
'-//w3c//dtd html 3.2 final//',
'-//w3c//dtd html 3.2//',
'-//w3c//dtd html 3.2s draft//',
'-//w3c//dtd html 4.0 frameset//',
'-//w3c//dtd html 4.0 transitional//',
'-//w3c//dtd html experimental 19960712//',
'-//w3c//dtd html experimental 970421//',
'-//w3c//dtd w3 html//',
'-//w3o//dtd w3 html 3.0//',
'-//webtechs//dtd mozilla html 2.0//',
'-//webtechs//dtd mozilla html//',
];
const QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES = [
...QUIRKS_MODE_PUBLIC_ID_PREFIXES,
'-//w3c//dtd html 4.01 frameset//',
'-//w3c//dtd html 4.01 transitional//',
];
const QUIRKS_MODE_PUBLIC_IDS = new Set([
'-//w3o//dtd w3 html strict 3.0//en//',
'-/w3c/dtd html 4.0 transitional/en',
'html',
]);
const LIMITED_QUIRKS_PUBLIC_ID_PREFIXES = ['-//w3c//dtd xhtml 1.0 frameset//', '-//w3c//dtd xhtml 1.0 transitional//'];
const LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES = [
...LIMITED_QUIRKS_PUBLIC_ID_PREFIXES,
'-//w3c//dtd html 4.01 frameset//',
'-//w3c//dtd html 4.01 transitional//',
];
//Utils
function hasPrefix(publicId, prefixes) {
return prefixes.some((prefix) => publicId.startsWith(prefix));
}
//API
function isConforming(token) {
return (token.name === VALID_DOCTYPE_NAME &&
token.publicId === null &&
(token.systemId === null || token.systemId === VALID_SYSTEM_ID));
}
function getDocumentMode(token) {
if (token.name !== VALID_DOCTYPE_NAME) {
return DOCUMENT_MODE.QUIRKS;
}
const { systemId } = token;
if (systemId && systemId.toLowerCase() === QUIRKS_MODE_SYSTEM_ID) {
return DOCUMENT_MODE.QUIRKS;
}
let { publicId } = token;
if (publicId !== null) {
publicId = publicId.toLowerCase();
if (QUIRKS_MODE_PUBLIC_IDS.has(publicId)) {
return DOCUMENT_MODE.QUIRKS;
}
let prefixes = systemId === null ? QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES : QUIRKS_MODE_PUBLIC_ID_PREFIXES;
if (hasPrefix(publicId, prefixes)) {
return DOCUMENT_MODE.QUIRKS;
}
prefixes =
systemId === null ? LIMITED_QUIRKS_PUBLIC_ID_PREFIXES : LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES;
if (hasPrefix(publicId, prefixes)) {
return DOCUMENT_MODE.LIMITED_QUIRKS;
}
}
return DOCUMENT_MODE.NO_QUIRKS;
}
//MIME types
const MIME_TYPES = {
TEXT_HTML: 'text/html',
APPLICATION_XML: 'application/xhtml+xml',
};
//Attributes
const DEFINITION_URL_ATTR = 'definitionurl';
const ADJUSTED_DEFINITION_URL_ATTR = 'definitionURL';
const SVG_ATTRS_ADJUSTMENT_MAP = new Map([
'attributeName',
'attributeType',
'baseFrequency',
'baseProfile',
'calcMode',
'clipPathUnits',
'diffuseConstant',
'edgeMode',
'filterUnits',
'glyphRef',
'gradientTransform',
'gradientUnits',
'kernelMatrix',
'kernelUnitLength',
'keyPoints',
'keySplines',
'keyTimes',
'lengthAdjust',
'limitingConeAngle',
'markerHeight',
'markerUnits',
'markerWidth',
'maskContentUnits',
'maskUnits',
'numOctaves',
'pathLength',
'patternContentUnits',
'patternTransform',
'patternUnits',
'pointsAtX',
'pointsAtY',
'pointsAtZ',
'preserveAlpha',
'preserveAspectRatio',
'primitiveUnits',
'refX',
'refY',
'repeatCount',
'repeatDur',
'requiredExtensions',
'requiredFeatures',
'specularConstant',
'specularExponent',
'spreadMethod',
'startOffset',
'stdDeviation',
'stitchTiles',
'surfaceScale',
'systemLanguage',
'tableValues',
'targetX',
'targetY',
'textLength',
'viewBox',
'viewTarget',
'xChannelSelector',
'yChannelSelector',
'zoomAndPan',
].map((attr) => [attr.toLowerCase(), attr]));
const XML_ATTRS_ADJUSTMENT_MAP = new Map([
['xlink:actuate', { prefix: 'xlink', name: 'actuate', namespace: NS.XLINK }],
['xlink:arcrole', { prefix: 'xlink', name: 'arcrole', namespace: NS.XLINK }],
['xlink:href', { prefix: 'xlink', name: 'href', namespace: NS.XLINK }],
['xlink:role', { prefix: 'xlink', name: 'role', namespace: NS.XLINK }],
['xlink:show', { prefix: 'xlink', name: 'show', namespace: NS.XLINK }],
['xlink:title', { prefix: 'xlink', name: 'title', namespace: NS.XLINK }],
['xlink:type', { prefix: 'xlink', name: 'type', namespace: NS.XLINK }],
['xml:base', { prefix: 'xml', name: 'base', namespace: NS.XML }],
['xml:lang', { prefix: 'xml', name: 'lang', namespace: NS.XML }],
['xml:space', { prefix: 'xml', name: 'space', namespace: NS.XML }],
['xmlns', { prefix: '', name: 'xmlns', namespace: NS.XMLNS }],
['xmlns:xlink', { prefix: 'xmlns', name: 'xlink', namespace: NS.XMLNS }],
]);
//SVG tag names adjustment map
const SVG_TAG_NAMES_ADJUSTMENT_MAP = new Map([
'altGlyph',
'altGlyphDef',
'altGlyphItem',
'animateColor',
'animateMotion',
'animateTransform',
'clipPath',
'feBlend',
'feColorMatrix',
'feComponentTransfer',
'feComposite',
'feConvolveMatrix',
'feDiffuseLighting',
'feDisplacementMap',
'feDistantLight',
'feFlood',
'feFuncA',
'feFuncB',
'feFuncG',
'feFuncR',
'feGaussianBlur',
'feImage',
'feMerge',
'feMergeNode',
'feMorphology',
'feOffset',
'fePointLight',
'feSpecularLighting',
'feSpotLight',
'feTile',
'feTurbulence',
'foreignObject',
'glyphRef',
'linearGradient',
'radialGradient',
'textPath',
].map((tn) => [tn.toLowerCase(), tn]));
//Tags that causes exit from foreign content
const EXITS_FOREIGN_CONTENT = new Set([
TAG_ID.B,
TAG_ID.BIG,
TAG_ID.BLOCKQUOTE,
TAG_ID.BODY,
TAG_ID.BR,
TAG_ID.CENTER,
TAG_ID.CODE,
TAG_ID.DD,
TAG_ID.DIV,
TAG_ID.DL,
TAG_ID.DT,
TAG_ID.EM,
TAG_ID.EMBED,
TAG_ID.H1,
TAG_ID.H2,
TAG_ID.H3,
TAG_ID.H4,
TAG_ID.H5,
TAG_ID.H6,
TAG_ID.HEAD,
TAG_ID.HR,
TAG_ID.I,
TAG_ID.IMG,
TAG_ID.LI,
TAG_ID.LISTING,
TAG_ID.MENU,
TAG_ID.META,
TAG_ID.NOBR,
TAG_ID.OL,
TAG_ID.P,
TAG_ID.PRE,
TAG_ID.RUBY,
TAG_ID.S,
TAG_ID.SMALL,
TAG_ID.SPAN,
TAG_ID.STRONG,
TAG_ID.STRIKE,
TAG_ID.SUB,
TAG_ID.SUP,
TAG_ID.TABLE,
TAG_ID.TT,
TAG_ID.U,
TAG_ID.UL,
TAG_ID.VAR,
]);
//Check exit from foreign content
function causesExit(startTagToken) {
const tn = startTagToken.tagID;
const isFontWithAttrs = tn === TAG_ID.FONT &&
startTagToken.attrs.some(({ name }) => name === ATTRS.COLOR || name === ATTRS.SIZE || name === ATTRS.FACE);
return isFontWithAttrs || EXITS_FOREIGN_CONTENT.has(tn);
}
//Token adjustments
function adjustTokenMathMLAttrs(token) {
for (let i = 0; i < token.attrs.length; i++) {
if (token.attrs[i].name === DEFINITION_URL_ATTR) {
token.attrs[i].name = ADJUSTED_DEFINITION_URL_ATTR;
break;
}
}
}
function adjustTokenSVGAttrs(token) {
for (let i = 0; i < token.attrs.length; i++) {
const adjustedAttrName = SVG_ATTRS_ADJUSTMENT_MAP.get(token.attrs[i].name);
if (adjustedAttrName != null) {
token.attrs[i].name = adjustedAttrName;
}
}
}
function adjustTokenXMLAttrs(token) {
for (let i = 0; i < token.attrs.length; i++) {
const adjustedAttrEntry = XML_ATTRS_ADJUSTMENT_MAP.get(token.attrs[i].name);
if (adjustedAttrEntry) {
token.attrs[i].prefix = adjustedAttrEntry.prefix;
token.attrs[i].name = adjustedAttrEntry.name;
token.attrs[i].namespace = adjustedAttrEntry.namespace;
}
}
}
function adjustTokenSVGTagName(token) {
const adjustedTagName = SVG_TAG_NAMES_ADJUSTMENT_MAP.get(token.tagName);
if (adjustedTagName != null) {
token.tagName = adjustedTagName;
token.tagID = getTagID(token.tagName);
}
}
//Integration points
function isMathMLTextIntegrationPoint(tn, ns) {
return ns === NS.MATHML && (tn === TAG_ID.MI || tn === TAG_ID.MO || tn === TAG_ID.MN || tn === TAG_ID.MS || tn === TAG_ID.MTEXT);
}
function isHtmlIntegrationPoint(tn, ns, attrs) {
if (ns === NS.MATHML && tn === TAG_ID.ANNOTATION_XML) {
for (let i = 0; i < attrs.length; i++) {
if (attrs[i].name === ATTRS.ENCODING) {
const value = attrs[i].value.toLowerCase();
return value === MIME_TYPES.TEXT_HTML || value === MIME_TYPES.APPLICATION_XML;
}
}
}
return ns === NS.SVG && (tn === TAG_ID.FOREIGN_OBJECT || tn === TAG_ID.DESC || tn === TAG_ID.TITLE);
}
function isIntegrationPoint(tn, ns, attrs, foreignNS) {
return (((!foreignNS || foreignNS === NS.HTML) && isHtmlIntegrationPoint(tn, ns, attrs)) ||
((!foreignNS || foreignNS === NS.MATHML) && isMathMLTextIntegrationPoint(tn, ns)));
}
//Misc constants
const HIDDEN_INPUT_TYPE = 'hidden';
//Adoption agency loops iteration count
const AA_OUTER_LOOP_ITER = 8;
const AA_INNER_LOOP_ITER = 3;
//Insertion modes
var InsertionMode;
(function (InsertionMode) {
InsertionMode[InsertionMode["INITIAL"] = 0] = "INITIAL";
InsertionMode[InsertionMode["BEFORE_HTML"] = 1] = "BEFORE_HTML";
InsertionMode[InsertionMode["BEFORE_HEAD"] = 2] = "BEFORE_HEAD";
InsertionMode[InsertionMode["IN_HEAD"] = 3] = "IN_HEAD";
InsertionMode[InsertionMode["IN_HEAD_NO_SCRIPT"] = 4] = "IN_HEAD_NO_SCRIPT";
InsertionMode[InsertionMode["AFTER_HEAD"] = 5] = "AFTER_HEAD";
InsertionMode[InsertionMode["IN_BODY"] = 6] = "IN_BODY";
InsertionMode[InsertionMode["TEXT"] = 7] = "TEXT";
InsertionMode[InsertionMode["IN_TABLE"] = 8] = "IN_TABLE";
InsertionMode[InsertionMode["IN_TABLE_TEXT"] = 9] = "IN_TABLE_TEXT";
InsertionMode[InsertionMode["IN_CAPTION"] = 10] = "IN_CAPTION";
InsertionMode[InsertionMode["IN_COLUMN_GROUP"] = 11] = "IN_COLUMN_GROUP";
InsertionMode[InsertionMode["IN_TABLE_BODY"] = 12] = "IN_TABLE_BODY";
InsertionMode[InsertionMode["IN_ROW"] = 13] = "IN_ROW";
InsertionMode[InsertionMode["IN_CELL"] = 14] = "IN_CELL";
InsertionMode[InsertionMode["IN_SELECT"] = 15] = "IN_SELECT";
InsertionMode[InsertionMode["IN_SELECT_IN_TABLE"] = 16] = "IN_SELECT_IN_TABLE";
InsertionMode[InsertionMode["IN_TEMPLATE"] = 17] = "IN_TEMPLATE";
InsertionMode[InsertionMode["AFTER_BODY"] = 18] = "AFTER_BODY";
InsertionMode[InsertionMode["IN_FRAMESET"] = 19] = "IN_FRAMESET";
InsertionMode[InsertionMode["AFTER_FRAMESET"] = 20] = "AFTER_FRAMESET";
InsertionMode[InsertionMode["AFTER_AFTER_BODY"] = 21] = "AFTER_AFTER_BODY";
InsertionMode[InsertionMode["AFTER_AFTER_FRAMESET"] = 22] = "AFTER_AFTER_FRAMESET";
})(InsertionMode || (InsertionMode = {}));
const BASE_LOC = {
startLine: -1,
startCol: -1,
startOffset: -1,
endLine: -1,
endCol: -1,
endOffset: -1,
};
const TABLE_STRUCTURE_TAGS = new Set([TAG_ID.TABLE, TAG_ID.TBODY, TAG_ID.TFOOT, TAG_ID.THEAD, TAG_ID.TR]);
const defaultParserOptions = {
scriptingEnabled: true,
sourceCodeLocationInfo: false,
treeAdapter: defaultTreeAdapter,
onParseError: null,
};
//Parser
class Parser {
constructor(options, document, fragmentContext = null, scriptHandler = null) {
this.fragmentContext = fragmentContext;
this.scriptHandler = scriptHandler;
this.currentToken = null;
this.stopped = false;
this.insertionMode = InsertionMode.INITIAL;
this.originalInsertionMode = InsertionMode.INITIAL;
this.headElement = null;
this.formElement = null;
/** Indicates that the current node is not an element in the HTML namespace */
this.currentNotInHTML = false;
/**
* The template insertion mode stack is maintained from the left.
* Ie. the topmost element will always have index 0.
*/
this.tmplInsertionModeStack = [];
this.pendingCharacterTokens = [];
this.hasNonWhitespacePendingCharacterToken = false;
this.framesetOk = true;
this.skipNextNewLine = false;
this.fosterParentingEnabled = false;
this.options = {
...defaultParserOptions,
...options,
};
this.treeAdapter = this.options.treeAdapter;
this.onParseError = this.options.onParseError;
// Always enable location info if we report parse errors.
if (this.onParseError) {
this.options.sourceCodeLocationInfo = true;
}
this.document = document !== null && document !== void 0 ? document : this.treeAdapter.createDocument();
this.tokenizer = new Tokenizer(this.options, this);
this.activeFormattingElements = new FormattingElementList(this.treeAdapter);
this.fragmentContextID = fragmentContext ? getTagID(this.treeAdapter.getTagName(fragmentContext)) : TAG_ID.UNKNOWN;
this._setContextModes(fragmentContext !== null && fragmentContext !== void 0 ? fragmentContext : this.document, this.fragmentContextID);
this.openElements = new OpenElementStack(this.document, this.treeAdapter, this);
}
// API
static parse(html, options) {
const parser = new this(options);
parser.tokenizer.write(html, true);
return parser.document;
}
static getFragmentParser(fragmentContext, options) {
const opts = {
...defaultParserOptions,
...options,
};
//NOTE: use a <template> element as the fragment context if no context element was provided,
//so we will parse in a "forgiving" manner
fragmentContext !== null && fragmentContext !== void 0 ? fragmentContext : (fragmentContext = opts.treeAdapter.createElement(TAG_NAMES.TEMPLATE, NS.HTML, []));
//NOTE: create a fake element which will be used as the `document` for fragment parsing.
//This is important for jsdom, where a new `document` cannot be created. This led to
//fragment parsing messing with the main `document`.
const documentMock = opts.treeAdapter.createElement('documentmock', NS.HTML, []);
const parser = new this(opts, documentMock, fragmentContext);
if (parser.fragmentContextID === TAG_ID.TEMPLATE) {
parser.tmplInsertionModeStack.unshift(InsertionMode.IN_TEMPLATE);
}
parser._initTokenizerForFragmentParsing();
parser._insertFakeRootElement();
parser._resetInsertionMode();
parser._findFormInFragmentContext();
return parser;
}
getFragment() {
const rootElement = this.treeAdapter.getFirstChild(this.document);
const fragment = this.treeAdapter.createDocumentFragment();
this._adoptNodes(rootElement, fragment);
return fragment;
}
//Errors
_err(token, code, beforeToken) {
var _a;
if (!this.onParseError)
return;
const loc = (_a = token.location) !== null && _a !== void 0 ? _a : BASE_LOC;
const err = {
code,
startLine: loc.startLine,
startCol: loc.startCol,
startOffset: loc.startOffset,
endLine: beforeToken ? loc.startLine : loc.endLine,
endCol: beforeToken ? loc.startCol : loc.endCol,
endOffset: beforeToken ? loc.startOffset : loc.endOffset,
};
this.onParseError(err);
}
//Stack events
onItemPush(node, tid, isTop) {
var _a, _b;
(_b = (_a = this.treeAdapter).onItemPush) === null || _b === void 0 ? void 0 : _b.call(_a, node);
if (isTop && this.openElements.stackTop > 0)
this._setContextModes(node, tid);
}
onItemPop(node, isTop) {
var _a, _b;
if (this.options.sourceCodeLocationInfo) {
this._setEndLocation(node, this.currentToken);
}
(_b = (_a = this.treeAdapter).onItemPop) === null || _b === void 0 ? void 0 : _b.call(_a, node, this.openElements.current);
if (isTop) {
let current;
let currentTagId;
if (this.openElements.stackTop === 0 && this.fragmentContext) {
current = this.fragmentContext;
currentTagId = this.fragmentContextID;
}
else {
({ current, currentTagId } = this.openElements);
}
this._setContextModes(current, currentTagId);
}
}
_setContextModes(current, tid) {
const isHTML = current === this.document || this.treeAdapter.getNamespaceURI(current) === NS.HTML;
this.currentNotInHTML = !isHTML;
this.tokenizer.inForeignNode = !isHTML && !this._isIntegrationPoint(tid, current);
}
_switchToTextParsing(currentToken, nextTokenizerState) {
this._insertElement(currentToken, NS.HTML);
this.tokenizer.state = nextTokenizerState;
this.originalInsertionMode = this.insertionMode;
this.insertionMode = InsertionMode.TEXT;
}
switchToPlaintextParsing() {
this.insertionMode = InsertionMode.TEXT;
this.originalInsertionMode = InsertionMode.IN_BODY;
this.tokenizer.state = TokenizerMode.PLAINTEXT;
}
//Fragment parsing
_getAdjustedCurrentElement() {
return this.openElements.stackTop === 0 && this.fragmentContext
? this.fragmentContext
: this.openElements.current;
}
_findFormInFragmentContext() {
let node = this.fragmentContext;
while (node) {
if (this.treeAdapter.getTagName(node) === TAG_NAMES.FORM) {
this.formElement = node;
break;
}
node = this.treeAdapter.getParentNode(node);
}
}
_initTokenizerForFragmentParsing() {
if (!this.fragmentContext || this.treeAdapter.getNamespaceURI(this.fragmentContext) !== NS.HTML) {
return;
}
switch (this.fragmentContextID) {
case TAG_ID.TITLE:
case TAG_ID.TEXTAREA: {
this.tokenizer.state = TokenizerMode.RCDATA;
break;
}
case TAG_ID.STYLE:
case TAG_ID.XMP:
case TAG_ID.IFRAME:
case TAG_ID.NOEMBED:
case TAG_ID.NOFRAMES:
case TAG_ID.NOSCRIPT: {
this.tokenizer.state = TokenizerMode.RAWTEXT;
break;
}
case TAG_ID.SCRIPT: {
this.tokenizer.state = TokenizerMode.SCRIPT_DATA;
break;
}
case TAG_ID.PLAINTEXT: {
this.tokenizer.state = TokenizerMode.PLAINTEXT;
break;
}
// Do nothing
}
}
//Tree mutation
_setDocumentType(token) {
const name = token.name || '';
const publicId = token.publicId || '';
const systemId = token.systemId || '';
this.treeAdapter.setDocumentType(this.document, name, publicId, systemId);
if (token.location) {
const documentChildren = this.treeAdapter.getChildNodes(this.document);
const docTypeNode = documentChildren.find((node) => this.treeAdapter.isDocumentTypeNode(node));
if (docTypeNode) {
this.treeAdapter.setNodeSourceCodeLocation(docTypeNode, token.location);
}
}
}
_attachElementToTree(element, location) {
if (this.options.sourceCodeLocationInfo) {
const loc = location && {
...location,
startTag: location,
};
this.treeAdapter.setNodeSourceCodeLocation(element, loc);
}
if (this._shouldFosterParentOnInsertion()) {
this._fosterParentElement(element);
}
else {
const parent = this.openElements.currentTmplContentOrNode;
this.treeAdapter.appendChild(parent, element);
}
}
_appendElement(token, namespaceURI) {
const element = this.treeAdapter.createElement(token.tagName, namespaceURI, token.attrs);
this._attachElementToTree(element, token.location);
}
_insertElement(token, namespaceURI) {
const element = this.treeAdapter.createElement(token.tagName, namespaceURI, token.attrs);
this._attachElementToTree(element, token.location);
this.openElements.push(element, token.tagID);
}
_insertFakeElement(tagName, tagID) {
const element = this.treeAdapter.createElement(tagName, NS.HTML, []);
this._attachElementToTree(element, null);
this.openElements.push(element, tagID);
}
_insertTemplate(token) {
const tmpl = this.treeAdapter.createElement(token.tagName, NS.HTML, token.attrs);
const content = this.treeAdapter.createDocumentFragment();
this.treeAdapter.setTemplateContent(tmpl, content);
this._attachElementToTree(tmpl, token.location);
this.openElements.push(tmpl, token.tagID);
if (this.options.sourceCodeLocationInfo)
this.treeAdapter.setNodeSourceCodeLocation(content, null);
}
_insertFakeRootElement() {
const element = this.treeAdapter.createElement(TAG_NAMES.HTML, NS.HTML, []);
if (this.options.sourceCodeLocationInfo)
this.treeAdapter.setNodeSourceCodeLocation(element, null);
this.treeAdapter.appendChild(this.openElements.current, element);
this.openElements.push(element, TAG_ID.HTML);
}
_appendCommentNode(token, parent) {
const commentNode = this.treeAdapter.createCommentNode(token.data);
this.treeAdapter.appendChild(parent, commentNode);
if (this.options.sourceCodeLocationInfo) {
this.treeAdapter.setNodeSourceCodeLocation(commentNode, token.location);
}
}
_insertCharacters(token) {
let parent;
let beforeElement;
if (this._shouldFosterParentOnInsertion()) {
({ parent, beforeElement } = this._findFosterParentingLocation());
if (beforeElement) {
this.treeAdapter.insertTextBefore(parent, token.chars, beforeElement);
}
else {
this.treeAdapter.insertText(parent, token.chars);
}
}
else {
parent = this.openElements.currentTmplContentOrNode;
this.treeAdapter.insertText(parent, token.chars);
}
if (!token.location)
return;
const siblings = this.treeAdapter.getChildNodes(parent);
const textNodeIdx = beforeElement ? siblings.lastIndexOf(beforeElement) : siblings.length;
const textNode = siblings[textNodeIdx - 1];
//NOTE: if we have a location assigned by another token, then just update the end position
const tnLoc = this.treeAdapter.getNodeSourceCodeLocation(textNode);
if (tnLoc) {
const { endLine, endCol, endOffset } = token.location;
this.treeAdapter.updateNodeSourceCodeLocation(textNode, { endLine, endCol, endOffset });
}
else if (this.options.sourceCodeLocationInfo) {
this.treeAdapter.setNodeSourceCodeLocation(textNode, token.location);
}
}
_adoptNodes(donor, recipient) {
for (let child = this.treeAdapter.getFirstChild(donor); child; child = this.treeAdapter.getFirstChild(donor)) {
this.treeAdapter.detachNode(child);
this.treeAdapter.appendChild(recipient, child);
}
}
_setEndLocation(element, closingToken) {
if (this.treeAdapter.getNodeSourceCodeLocation(element) && closingToken.location) {
const ctLoc = closingToken.location;
const tn = this.treeAdapter.getTagName(element);
const endLoc =
// NOTE: For cases like <p> <p> </p> - First 'p' closes without a closing
// tag and for cases like <td> <p> </td> - 'p' closes without a closing tag.
closingToken.type === TokenType.END_TAG && tn === closingToken.tagName
? {
endTag: { ...ctLoc },
endLine: ctLoc.endLine,
endCol: ctLoc.endCol,
endOffset: ctLoc.endOffset,
}
: {
endLine: ctLoc.startLine,
endCol: ctLoc.startCol,
endOffset: ctLoc.startOffset,
};
this.treeAdapter.updateNodeSourceCodeLocation(element, endLoc);
}
}
//Token processing
shouldProcessStartTagTokenInForeignContent(token) {
// Check that neither current === document, or ns === NS.HTML
if (!this.currentNotInHTML)
return false;
let current;
let currentTagId;
if (this.openElements.stackTop === 0 && this.fragmentContext) {
current = this.fragmentContext;
currentTagId = this.fragmentContextID;
}
else {
({ current, currentTagId } = this.openElements);
}
if (token.tagID === TAG_ID.SVG &&
this.treeAdapter.getTagName(current) === TAG_NAMES.ANNOTATION_XML &&
this.treeAdapter.getNamespaceURI(current) === NS.MATHML) {
return false;
}
return (
// Check that `current` is not an integration point for HTML or MathML elements.
this.tokenizer.inForeignNode ||
// If it _is_ an integration point, then we might have to check that it is not an HTML
// integration point.
((token.tagID === TAG_ID.MGLYPH || token.tagID === TAG_ID.MALIGNMARK) &&
!this._isIntegrationPoint(currentTagId, current, NS.HTML)));
}
_processToken(token) {
switch (token.type) {
case TokenType.CHARACTER: {
this.onCharacter(token);
break;
}
case TokenType.NULL_CHARACTER: {
this.onNullCharacter(token);
break;
}
case TokenType.COMMENT: {
this.onComment(token);
break;
}
case TokenType.DOCTYPE: {
this.onDoctype(token);
break;
}
case TokenType.START_TAG: {
this._processStartTag(token);
break;
}
case TokenType.END_TAG: {
this.onEndTag(token);
break;
}
case TokenType.EOF: {
this.onEof(token);
break;
}
case TokenType.WHITESPACE_CHARACTER: {
this.onWhitespaceCharacter(token);
break;
}
}
}
//Integration points
_isIntegrationPoint(tid, element, foreignNS) {
const ns = this.treeAdapter.getNamespaceURI(element);
const attrs = this.treeAdapter.getAttrList(element);
return isIntegrationPoint(tid, ns, attrs, foreignNS);
}
//Active formatting elements reconstruction
_reconstructActiveFormattingElements() {
const listLength = this.activeFormattingElements.entries.length;
if (listLength) {
const endIndex = this.activeFormattingElements.entries.findIndex((entry) => entry.type === EntryType.Marker || this.openElements.contains(entry.element));
const unopenIdx = endIndex < 0 ? listLength - 1 : endIndex - 1;
for (let i = unopenIdx; i >= 0; i--) {
const entry = this.activeFormattingElements.entries[i];
this._insertElement(entry.token, this.treeAdapter.getNamespaceURI(entry.element));
entry.element = this.openElements.current;
}
}
}
//Close elements
_closeTableCell() {
this.openElements.generateImpliedEndTags();
this.openElements.popUntilTableCellPopped();
this.activeFormattingElements.clearToLastMarker();
this.insertionMode = InsertionMode.IN_ROW;
}
_closePElement() {
this.openElements.generateImpliedEndTagsWithExclusion(TAG_ID.P);
this.openElements.popUntilTagNamePopped(TAG_ID.P);
}
//Insertion modes
_resetInsertionMode() {
for (let i = this.openElements.stackTop; i >= 0; i--) {
//Insertion mode reset map
switch (i === 0 && this.fragmentContext ? this.fragmentContextID : this.openElements.tagIDs[i]) {
case TAG_ID.TR:
this.insertionMode = InsertionMode.IN_ROW;
return;
case TAG_ID.TBODY:
case TAG_ID.THEAD:
case TAG_ID.TFOOT:
this.insertionMode = InsertionMode.IN_TABLE_BODY;
return;
case TAG_ID.CAPTION:
this.insertionMode = InsertionMode.IN_CAPTION;
return;
case TAG_ID.COLGROUP:
this.insertionMode = InsertionMode.IN_COLUMN_GROUP;
return;
case TAG_ID.TABLE:
this.insertionMode = InsertionMode.IN_TABLE;
return;
case TAG_ID.BODY:
this.insertionMode = InsertionMode.IN_BODY;
return;
case TAG_ID.FRAMESET:
this.insertionMode = InsertionMode.IN_FRAMESET;
return;
case TAG_ID.SELECT:
this._resetInsertionModeForSelect(i);
return;
case TAG_ID.TEMPLATE:
this.insertionMode = this.tmplInsertionModeStack[0];
return;
case TAG_ID.HTML:
this.insertionMode = this.headElement ? InsertionMode.AFTER_HEAD : InsertionMode.BEFORE_HEAD;
return;
case TAG_ID.TD:
case TAG_ID.TH:
if (i > 0) {
this.insertionMode = InsertionMode.IN_CELL;
return;
}
break;
case TAG_ID.HEAD:
if (i > 0) {
this.insertionMode = InsertionMode.IN_HEAD;
return;
}
break;
}
}
this.insertionMode = InsertionMode.IN_BODY;
}
_resetInsertionModeForSelect(selectIdx) {
if (selectIdx > 0) {
for (let i = selectIdx - 1; i > 0; i--) {
const tn = this.openElements.tagIDs[i];
if (tn === TAG_ID.TEMPLATE) {
break;
}
else if (tn === TAG_ID.TABLE) {
this.insertionMode = InsertionMode.IN_SELECT_IN_TABLE;
return;
}
}
}
this.insertionMode = InsertionMode.IN_SELECT;
}
//Foster parenting
_isElementCausesFosterParenting(tn) {
return TABLE_STRUCTURE_TAGS.has(tn);
}
_shouldFosterParentOnInsertion() {
return this.fosterParentingEnabled && this._isElementCausesFosterParenting(this.openElements.currentTagId);
}
_findFosterParentingLocation() {
for (let i = this.openElements.stackTop; i >= 0; i--) {
const openElement = this.openElements.items[i];
switch (this.openElements.tagIDs[i]) {
case TAG_ID.TEMPLATE:
if (this.treeAdapter.getNamespaceURI(openElement) === NS.HTML) {
return { parent: this.treeAdapter.getTemplateContent(openElement), beforeElement: null };
}
break;
case TAG_ID.TABLE: {
const parent = this.treeAdapter.getParentNode(openElement);
if (parent) {
return { parent, beforeElement: openElement };
}
return { parent: this.openElements.items[i - 1], beforeElement: null };
}
// Do nothing
}
}
return { parent: this.openElements.items[0], beforeElement: null };
}
_fosterParentElement(element) {
const location = this._findFosterParentingLocation();
if (location.beforeElement) {
this.treeAdapter.insertBefore(location.parent, element, location.beforeElement);
}
else {
this.treeAdapter.appendChild(location.parent, element);
}
}
//Special elements
_isSpecialElement(element, id) {
const ns = this.treeAdapter.getNamespaceURI(element);
return SPECIAL_ELEMENTS[ns].has(id);
}
onCharacter(token) {
this.skipNextNewLine = false;
if (this.tokenizer.inForeignNode) {
characterInForeignContent(this, token);
return;
}
switch (this.insertionMode) {
case InsertionMode.INITIAL:
tokenInInitialMode(this, token);
break;
case InsertionMode.BEFORE_HTML:
tokenBeforeHtml(this, token);
break;
case InsertionMode.BEFORE_HEAD:
tokenBeforeHead(this, token);
break;
case InsertionMode.IN_HEAD:
tokenInHead(this, token);
break;
case InsertionMode.IN_HEAD_NO_SCRIPT:
tokenInHeadNoScript(this, token);
break;
case InsertionMode.AFTER_HEAD:
tokenAfterHead(this, token);
break;
case InsertionMode.IN_BODY:
case InsertionMode.IN_CAPTION:
case InsertionMode.IN_CELL:
case InsertionMode.IN_TEMPLATE:
characterInBody(this, token);
break;
case InsertionMode.TEXT:
case InsertionMode.IN_SELECT:
case InsertionMode.IN_SELECT_IN_TABLE:
this._insertCharacters(token);
break;
case InsertionMode.IN_TABLE:
case InsertionMode.IN_TABLE_BODY:
case InsertionMode.IN_ROW:
characterInTable(this, token);
break;
case InsertionMode.IN_TABLE_TEXT:
characterInTableText(this, token);
break;
case InsertionMode.IN_COLUMN_GROUP:
tokenInColumnGroup(this, token);
break;
case InsertionMode.AFTER_BODY:
tokenAfterBody(this, token);
break;
case InsertionMode.AFTER_AFTER_BODY:
tokenAfterAfterBody(this, token);
break;
// Do nothing
}
}
onNullCharacter(token) {
this.skipNextNewLine = false;
if (this.tokenizer.inForeignNode) {
nullCharacterInForeignContent(this, token);
return;
}
switch (this.insertionMode) {
case InsertionMode.INITIAL:
tokenInInitialMode(this, token);
break;
case InsertionMode.BEFORE_HTML:
tokenBeforeHtml(this, token);
break;
case InsertionMode.BEFORE_HEAD:
tokenBeforeHead(this, token);
break;
case InsertionMode.IN_HEAD:
tokenInHead(this, token);
break;
case InsertionMode.IN_HEAD_NO_SCRIPT:
tokenInHeadNoScript(this, token);
break;
case InsertionMode.AFTER_HEAD:
tokenAfterHead(this, token);
break;
case InsertionMode.TEXT:
this._insertCharacters(token);
break;
case InsertionMode.IN_TABLE:
case InsertionMode.IN_TABLE_BODY:
case InsertionMode.IN_ROW:
characterInTable(this, token);
break;
case InsertionMode.IN_COLUMN_GROUP:
tokenInColumnGroup(this, token);
break;
case InsertionMode.AFTER_BODY:
tokenAfterBody(this, token);
break;
case InsertionMode.AFTER_AFTER_BODY:
tokenAfterAfterBody(this, token);
break;
// Do nothing
}
}
onComment(token) {
this.skipNextNewLine = false;
if (this.currentNotInHTML) {
appendComment(this, token);
return;
}
switch (this.insertionMode) {
case InsertionMode.INITIAL:
case InsertionMode.BEFORE_HTML:
case InsertionMode.BEFORE_HEAD:
case InsertionMode.IN_HEAD:
case InsertionMode.IN_HEAD_NO_SCRIPT:
case InsertionMode.AFTER_HEAD:
case InsertionMode.IN_BODY:
case InsertionMode.IN_TABLE:
case InsertionMode.IN_CAPTION:
case InsertionMode.IN_COLUMN_GROUP:
case InsertionMode.IN_TABLE_BODY:
case InsertionMode.IN_ROW:
case InsertionMode.IN_CELL:
case InsertionMode.IN_SELECT:
case InsertionMode.IN_SELECT_IN_TABLE:
case InsertionMode.IN_TEMPLATE:
case InsertionMode.IN_FRAMESET:
case InsertionMode.AFTER_FRAMESET:
appendComment(this, token);
break;
case InsertionMode.IN_TABLE_TEXT:
tokenInTableText(this, token);
break;
case InsertionMode.AFTER_BODY:
appendCommentToRootHtmlElement(this, token);
break;
case InsertionMode.AFTER_AFTER_BODY:
case InsertionMode.AFTER_AFTER_FRAMESET:
appendCommentToDocument(this, token);
break;
// Do nothing
}
}
onDoctype(token) {
this.skipNextNewLine = false;
switch (this.insertionMode) {
case InsertionMode.INITIAL:
doctypeInInitialMode(this, token);
break;
case InsertionMode.BEFORE_HEAD:
case InsertionMode.IN_HEAD:
case InsertionMode.IN_HEAD_NO_SCRIPT:
case InsertionMode.AFTER_HEAD:
this._err(token, ERR.misplacedDoctype);
break;
case InsertionMode.IN_TABLE_TEXT:
tokenInTableText(this, token);
break;
// Do nothing
}
}
onStartTag(token) {
this.skipNextNewLine = false;
this.currentToken = token;
this._processStartTag(token);
if (token.selfClosing && !token.ackSelfClosing) {
this._err(token, ERR.nonVoidHtmlElementStartTagWithTrailingSolidus);
}
}
/**
* Processes a given start tag.
*
* `onStartTag` checks if a self-closing tag was recognized. When a token
* is moved inbetween multiple insertion modes, this check for self-closing
* could lead to false positives. To avoid this, `_processStartTag` is used
* for nested calls.
*
* @param token The token to process.
*/
_processStartTag(token) {
if (this.shouldProcessStartTagTokenInForeignContent(token)) {
startTagInForeignContent(this, token);
}
else {
this._startTagOutsideForeignContent(token);
}
}
_startTagOutsideForeignContent(token) {
switch (this.insertionMode) {
case InsertionMode.INITIAL:
tokenInInitialMode(this, token);
break;
case InsertionMode.BEFORE_HTML:
startTagBeforeHtml(this, token);
break;
case InsertionMode.BEFORE_HEAD:
startTagBeforeHead(this, token);
break;
case InsertionMode.IN_HEAD:
startTagInHead(this, token);
break;
case InsertionMode.IN_HEAD_NO_SCRIPT:
startTagInHeadNoScript(this, token);
break;
case InsertionMode.AFTER_HEAD:
startTagAfterHead(this, token);
break;
case InsertionMode.IN_BODY:
startTagInBody(this, token);
break;
case InsertionMode.IN_TABLE:
startTagInTable(this, token);
break;
case InsertionMode.IN_TABLE_TEXT:
tokenInTableText(this, token);
break;
case InsertionMode.IN_CAPTION:
startTagInCaption(this, token);
break;
case InsertionMode.IN_COLUMN_GROUP:
startTagInColumnGroup(this, token);
break;
case InsertionMode.IN_TABLE_BODY:
startTagInTableBody(this, token);
break;
case InsertionMode.IN_ROW:
startTagInRow(this, token);
break;
case InsertionMode.IN_CELL:
startTagInCell(this, token);
break;
case InsertionMode.IN_SELECT:
startTagInSelect(this, token);
break;
case InsertionMode.IN_SELECT_IN_TABLE:
startTagInSelectInTable(this, token);
break;
case InsertionMode.IN_TEMPLATE:
startTagInTemplate(this, token);
break;
case InsertionMode.AFTER_BODY:
startTagAfterBody(this, token);
break;
case InsertionMode.IN_FRAMESET:
startTagInFrameset(this, token);
break;
case InsertionMode.AFTER_FRAMESET:
startTagAfterFrameset(this, token);
break;
case InsertionMode.AFTER_AFTER_BODY:
startTagAfterAfterBody(this, token);
break;
case InsertionMode.AFTER_AFTER_FRAMESET:
startTagAfterAfterFrameset(this, token);
break;
// Do nothing
}
}
onEndTag(token) {
this.skipNextNewLine = false;
this.currentToken = token;
if (this.currentNotInHTML) {
endTagInForeignContent(this, token);
}
else {
this._endTagOutsideForeignContent(token);
}
}
_endTagOutsideForeignContent(token) {
switch (this.insertionMode) {
case InsertionMode.INITIAL:
tokenInInitialMode(this, token);
break;
case InsertionMode.BEFORE_HTML:
endTagBeforeHtml(this, token);
break;
case InsertionMode.BEFORE_HEAD:
endTagBeforeHead(this, token);
break;
case InsertionMode.IN_HEAD:
endTagInHead(this, token);
break;
case InsertionMode.IN_HEAD_NO_SCRIPT:
endTagInHeadNoScript(this, token);
break;
case InsertionMode.AFTER_HEAD:
endTagAfterHead(this, token);
break;
case InsertionMode.IN_BODY:
endTagInBody(this, token);
break;
case InsertionMode.TEXT:
endTagInText(this, token);
break;
case InsertionMode.IN_TABLE:
endTagInTable(this, token);
break;
case InsertionMode.IN_TABLE_TEXT:
tokenInTableText(this, token);
break;
case InsertionMode.IN_CAPTION:
endTagInCaption(this, token);
break;
case InsertionMode.IN_COLUMN_GROUP:
endTagInColumnGroup(this, token);
break;
case InsertionMode.IN_TABLE_BODY:
endTagInTableBody(this, token);
break;
case InsertionMode.IN_ROW:
endTagInRow(this, token);
break;
case InsertionMode.IN_CELL:
endTagInCell(this, token);
break;
case InsertionMode.IN_SELECT:
endTagInSelect(this, token);
break;
case InsertionMode.IN_SELECT_IN_TABLE:
endTagInSelectInTable(this, token);
break;
case InsertionMode.IN_TEMPLATE:
endTagInTemplate(this, token);
break;
case InsertionMode.AFTER_BODY:
endTagAfterBody(this, token);
break;
case InsertionMode.IN_FRAMESET:
endTagInFrameset(this, token);
break;
case InsertionMode.AFTER_FRAMESET:
endTagAfterFrameset(this, token);
break;
case InsertionMode.AFTER_AFTER_BODY:
tokenAfterAfterBody(this, token);
break;
// Do nothing
}
}
onEof(token) {
switch (this.insertionMode) {
case InsertionMode.INITIAL:
tokenInInitialMode(this, token);
break;
case InsertionMode.BEFORE_HTML:
tokenBeforeHtml(this, token);
break;
case InsertionMode.BEFORE_HEAD:
tokenBeforeHead(this, token);
break;
case InsertionMode.IN_HEAD:
tokenInHead(this, token);
break;
case InsertionMode.IN_HEAD_NO_SCRIPT:
tokenInHeadNoScript(this, token);
break;
case InsertionMode.AFTER_HEAD:
tokenAfterHead(this, token);
break;
case InsertionMode.IN_BODY:
case InsertionMode.IN_TABLE:
case InsertionMode.IN_CAPTION:
case InsertionMode.IN_COLUMN_GROUP:
case InsertionMode.IN_TABLE_BODY:
case InsertionMode.IN_ROW:
case InsertionMode.IN_CELL:
case InsertionMode.IN_SELECT:
case InsertionMode.IN_SELECT_IN_TABLE:
eofInBody(this, token);
break;
case InsertionMode.TEXT:
eofInText(this, token);
break;
case InsertionMode.IN_TABLE_TEXT:
tokenInTableText(this, token);
break;
case InsertionMode.IN_TEMPLATE:
eofInTemplate(this, token);
break;
case InsertionMode.AFTER_BODY:
case InsertionMode.IN_FRAMESET:
case InsertionMode.AFTER_FRAMESET:
case InsertionMode.AFTER_AFTER_BODY:
case InsertionMode.AFTER_AFTER_FRAMESET:
stopParsing(this, token);
break;
// Do nothing
}
}
onWhitespaceCharacter(token) {
if (this.skipNextNewLine) {
this.skipNextNewLine = false;
if (token.chars.charCodeAt(0) === CODE_POINTS.LINE_FEED) {
if (token.chars.length === 1) {
return;
}
token.chars = token.chars.substr(1);
}
}
if (this.tokenizer.inForeignNode) {
this._insertCharacters(token);
return;
}
switch (this.insertionMode) {
case InsertionMode.IN_HEAD:
case InsertionMode.IN_HEAD_NO_SCRIPT:
case InsertionMode.AFTER_HEAD:
case InsertionMode.TEXT:
case InsertionMode.IN_COLUMN_GROUP:
case InsertionMode.IN_SELECT:
case InsertionMode.IN_SELECT_IN_TABLE:
case InsertionMode.IN_FRAMESET:
case InsertionMode.AFTER_FRAMESET:
this._insertCharacters(token);
break;
case InsertionMode.IN_BODY:
case InsertionMode.IN_CAPTION:
case InsertionMode.IN_CELL:
case InsertionMode.IN_TEMPLATE:
case InsertionMode.AFTER_BODY:
case InsertionMode.AFTER_AFTER_BODY:
case InsertionMode.AFTER_AFTER_FRAMESET:
whitespaceCharacterInBody(this, token);
break;
case InsertionMode.IN_TABLE:
case InsertionMode.IN_TABLE_BODY:
case InsertionMode.IN_ROW:
characterInTable(this, token);
break;
case InsertionMode.IN_TABLE_TEXT:
whitespaceCharacterInTableText(this, token);
break;
// Do nothing
}
}
}
//Adoption agency algorithm
//(see: http://www.whatwg.org/specs/web-apps/current-work/multipage/tree-construction.html#adoptionAgency)
//------------------------------------------------------------------
//Steps 5-8 of the algorithm
function aaObtainFormattingElementEntry(p, token) {
let formattingElementEntry = p.activeFormattingElements.getElementEntryInScopeWithTagName(token.tagName);
if (formattingElementEntry) {
if (!p.openElements.contains(formattingElementEntry.element)) {
p.activeFormattingElements.removeEntry(formattingElementEntry);
formattingElementEntry = null;
}
else if (!p.openElements.hasInScope(token.tagID)) {
formattingElementEntry = null;
}
}
else {
genericEndTagInBody(p, token);
}
return formattingElementEntry;
}
//Steps 9 and 10 of the algorithm
function aaObtainFurthestBlock(p, formattingElementEntry) {
let furthestBlock = null;
let idx = p.openElements.stackTop;
for (; idx >= 0; idx--) {
const element = p.openElements.items[idx];
if (element === formattingElementEntry.element) {
break;
}
if (p._isSpecialElement(element, p.openElements.tagIDs[idx])) {
furthestBlock = element;
}
}
if (!furthestBlock) {
p.openElements.shortenToLength(idx < 0 ? 0 : idx);
p.activeFormattingElements.removeEntry(formattingElementEntry);
}
return furthestBlock;
}
//Step 13 of the algorithm
function aaInnerLoop(p, furthestBlock, formattingElement) {
let lastElement = furthestBlock;
let nextElement = p.openElements.getCommonAncestor(furthestBlock);
for (let i = 0, element = nextElement; element !== formattingElement; i++, element = nextElement) {
//NOTE: store the next element for the next loop iteration (it may be deleted from the stack by step 9.5)
nextElement = p.openElements.getCommonAncestor(element);
const elementEntry = p.activeFormattingElements.getElementEntry(element);
const counterOverflow = elementEntry && i >= AA_INNER_LOOP_ITER;
const shouldRemoveFromOpenElements = !elementEntry || counterOverflow;
if (shouldRemoveFromOpenElements) {
if (counterOverflow) {
p.activeFormattingElements.removeEntry(elementEntry);
}
p.openElements.remove(element);
}
else {
element = aaRecreateElementFromEntry(p, elementEntry);
if (lastElement === furthestBlock) {
p.activeFormattingElements.bookmark = elementEntry;
}
p.treeAdapter.detachNode(lastElement);
p.treeAdapter.appendChild(element, lastElement);
lastElement = element;
}
}
return lastElement;
}
//Step 13.7 of the algorithm
function aaRecreateElementFromEntry(p, elementEntry) {
const ns = p.treeAdapter.getNamespaceURI(elementEntry.element);
const newElement = p.treeAdapter.createElement(elementEntry.token.tagName, ns, elementEntry.token.attrs);
p.openElements.replace(elementEntry.element, newElement);
elementEntry.element = newElement;
return newElement;
}
//Step 14 of the algorithm
function aaInsertLastNodeInCommonAncestor(p, commonAncestor, lastElement) {
const tn = p.treeAdapter.getTagName(commonAncestor);
const tid = getTagID(tn);
if (p._isElementCausesFosterParenting(tid)) {
p._fosterParentElement(lastElement);
}
else {
const ns = p.treeAdapter.getNamespaceURI(commonAncestor);
if (tid === TAG_ID.TEMPLATE && ns === NS.HTML) {
commonAncestor = p.treeAdapter.getTemplateContent(commonAncestor);
}
p.treeAdapter.appendChild(commonAncestor, lastElement);
}
}
//Steps 15-19 of the algorithm
function aaReplaceFormattingElement(p, furthestBlock, formattingElementEntry) {
const ns = p.treeAdapter.getNamespaceURI(formattingElementEntry.element);
const { token } = formattingElementEntry;
const newElement = p.treeAdapter.createElement(token.tagName, ns, token.attrs);
p._adoptNodes(furthestBlock, newElement);
p.treeAdapter.appendChild(furthestBlock, newElement);
p.activeFormattingElements.insertElementAfterBookmark(newElement, token);
p.activeFormattingElements.removeEntry(formattingElementEntry);
p.openElements.remove(formattingElementEntry.element);
p.openElements.insertAfter(furthestBlock, newElement, token.tagID);
}
//Algorithm entry point
function callAdoptionAgency(p, token) {
for (let i = 0; i < AA_OUTER_LOOP_ITER; i++) {
const formattingElementEntry = aaObtainFormattingElementEntry(p, token);
if (!formattingElementEntry) {
break;
}
const furthestBlock = aaObtainFurthestBlock(p, formattingElementEntry);
if (!furthestBlock) {
break;
}
p.activeFormattingElements.bookmark = formattingElementEntry;
const lastElement = aaInnerLoop(p, furthestBlock, formattingElementEntry.element);
const commonAncestor = p.openElements.getCommonAncestor(formattingElementEntry.element);
p.treeAdapter.detachNode(lastElement);
if (commonAncestor)
aaInsertLastNodeInCommonAncestor(p, commonAncestor, lastElement);
aaReplaceFormattingElement(p, furthestBlock, formattingElementEntry);
}
}
//Generic token handlers
//------------------------------------------------------------------
function appendComment(p, token) {
p._appendCommentNode(token, p.openElements.currentTmplContentOrNode);
}
function appendCommentToRootHtmlElement(p, token) {
p._appendCommentNode(token, p.openElements.items[0]);
}
function appendCommentToDocument(p, token) {
p._appendCommentNode(token, p.document);
}
function stopParsing(p, token) {
p.stopped = true;
// NOTE: Set end locations for elements that remain on the open element stack.
if (token.location) {
// NOTE: If we are not in a fragment, `html` and `body` will stay on the stack.
// This is a problem, as we might overwrite their end position here.
const target = p.fragmentContext ? 0 : 2;
for (let i = p.openElements.stackTop; i >= target; i--) {
p._setEndLocation(p.openElements.items[i], token);
}
// Handle `html` and `body`
if (!p.fragmentContext && p.openElements.stackTop >= 0) {
const htmlElement = p.openElements.items[0];
const htmlLocation = p.treeAdapter.getNodeSourceCodeLocation(htmlElement);
if (htmlLocation && !htmlLocation.endTag) {
p._setEndLocation(htmlElement, token);
if (p.openElements.stackTop >= 1) {
const bodyElement = p.openElements.items[1];
const bodyLocation = p.treeAdapter.getNodeSourceCodeLocation(bodyElement);
if (bodyLocation && !bodyLocation.endTag) {
p._setEndLocation(bodyElement, token);
}
}
}
}
}
}
// The "initial" insertion mode
//------------------------------------------------------------------
function doctypeInInitialMode(p, token) {
p._setDocumentType(token);
const mode = token.forceQuirks ? DOCUMENT_MODE.QUIRKS : getDocumentMode(token);
if (!isConforming(token)) {
p._err(token, ERR.nonConformingDoctype);
}
p.treeAdapter.setDocumentMode(p.document, mode);
p.insertionMode = InsertionMode.BEFORE_HTML;
}
function tokenInInitialMode(p, token) {
p._err(token, ERR.missingDoctype, true);
p.treeAdapter.setDocumentMode(p.document, DOCUMENT_MODE.QUIRKS);
p.insertionMode = InsertionMode.BEFORE_HTML;
p._processToken(token);
}
// The "before html" insertion mode
//------------------------------------------------------------------
function startTagBeforeHtml(p, token) {
if (token.tagID === TAG_ID.HTML) {
p._insertElement(token, NS.HTML);
p.insertionMode = InsertionMode.BEFORE_HEAD;
}
else {
tokenBeforeHtml(p, token);
}
}
function endTagBeforeHtml(p, token) {
const tn = token.tagID;
if (tn === TAG_ID.HTML || tn === TAG_ID.HEAD || tn === TAG_ID.BODY || tn === TAG_ID.BR) {
tokenBeforeHtml(p, token);
}
}
function tokenBeforeHtml(p, token) {
p._insertFakeRootElement();
p.insertionMode = InsertionMode.BEFORE_HEAD;
p._processToken(token);
}
// The "before head" insertion mode
//------------------------------------------------------------------
function startTagBeforeHead(p, token) {
switch (token.tagID) {
case TAG_ID.HTML: {
startTagInBody(p, token);
break;
}
case TAG_ID.HEAD: {
p._insertElement(token, NS.HTML);
p.headElement = p.openElements.current;
p.insertionMode = InsertionMode.IN_HEAD;
break;
}
default: {
tokenBeforeHead(p, token);
}
}
}
function endTagBeforeHead(p, token) {
const tn = token.tagID;
if (tn === TAG_ID.HEAD || tn === TAG_ID.BODY || tn === TAG_ID.HTML || tn === TAG_ID.BR) {
tokenBeforeHead(p, token);
}
else {
p._err(token, ERR.endTagWithoutMatchingOpenElement);
}
}
function tokenBeforeHead(p, token) {
p._insertFakeElement(TAG_NAMES.HEAD, TAG_ID.HEAD);
p.headElement = p.openElements.current;
p.insertionMode = InsertionMode.IN_HEAD;
p._processToken(token);
}
// The "in head" insertion mode
//------------------------------------------------------------------
function startTagInHead(p, token) {
switch (token.tagID) {
case TAG_ID.HTML: {
startTagInBody(p, token);
break;
}
case TAG_ID.BASE:
case TAG_ID.BASEFONT:
case TAG_ID.BGSOUND:
case TAG_ID.LINK:
case TAG_ID.META: {
p._appendElement(token, NS.HTML);
token.ackSelfClosing = true;
break;
}
case TAG_ID.TITLE: {
p._switchToTextParsing(token, TokenizerMode.RCDATA);
break;
}
case TAG_ID.NOSCRIPT: {
if (p.options.scriptingEnabled) {
p._switchToTextParsing(token, TokenizerMode.RAWTEXT);
}
else {
p._insertElement(token, NS.HTML);
p.insertionMode = InsertionMode.IN_HEAD_NO_SCRIPT;
}
break;
}
case TAG_ID.NOFRAMES:
case TAG_ID.STYLE: {
p._switchToTextParsing(token, TokenizerMode.RAWTEXT);
break;
}
case TAG_ID.SCRIPT: {
p._switchToTextParsing(token, TokenizerMode.SCRIPT_DATA);
break;
}
case TAG_ID.TEMPLATE: {
p._insertTemplate(token);
p.activeFormattingElements.insertMarker();
p.framesetOk = false;
p.insertionMode = InsertionMode.IN_TEMPLATE;
p.tmplInsertionModeStack.unshift(InsertionMode.IN_TEMPLATE);
break;
}
case TAG_ID.HEAD: {
p._err(token, ERR.misplacedStartTagForHeadElement);
break;
}
default: {
tokenInHead(p, token);
}
}
}
function endTagInHead(p, token) {
switch (token.tagID) {
case TAG_ID.HEAD: {
p.openElements.pop();
p.insertionMode = InsertionMode.AFTER_HEAD;
break;
}
case TAG_ID.BODY:
case TAG_ID.BR:
case TAG_ID.HTML: {
tokenInHead(p, token);
break;
}
case TAG_ID.TEMPLATE: {
if (p.openElements.tmplCount > 0) {
p.openElements.generateImpliedEndTagsThoroughly();
if (p.openElements.currentTagId !== TAG_ID.TEMPLATE) {
p._err(token, ERR.closingOfElementWithOpenChildElements);
}
p.openElements.popUntilTagNamePopped(TAG_ID.TEMPLATE);
p.activeFormattingElements.clearToLastMarker();
p.tmplInsertionModeStack.shift();
p._resetInsertionMode();
}
else {
p._err(token, ERR.endTagWithoutMatchingOpenElement);
}
break;
}
default: {
p._err(token, ERR.endTagWithoutMatchingOpenElement);
}
}
}
function tokenInHead(p, token) {
p.openElements.pop();
p.insertionMode = InsertionMode.AFTER_HEAD;
p._processToken(token);
}
// The "in head no script" insertion mode
//------------------------------------------------------------------
function startTagInHeadNoScript(p, token) {
switch (token.tagID) {
case TAG_ID.HTML: {
startTagInBody(p, token);
break;
}
case TAG_ID.BASEFONT:
case TAG_ID.BGSOUND:
case TAG_ID.HEAD:
case TAG_ID.LINK:
case TAG_ID.META:
case TAG_ID.NOFRAMES:
case TAG_ID.STYLE: {
startTagInHead(p, token);
break;
}
case TAG_ID.NOSCRIPT: {
p._err(token, ERR.nestedNoscriptInHead);
break;
}
default: {
tokenInHeadNoScript(p, token);
}
}
}
function endTagInHeadNoScript(p, token) {
switch (token.tagID) {
case TAG_ID.NOSCRIPT: {
p.openElements.pop();
p.insertionMode = InsertionMode.IN_HEAD;
break;
}
case TAG_ID.BR: {
tokenInHeadNoScript(p, token);
break;
}
default: {
p._err(token, ERR.endTagWithoutMatchingOpenElement);
}
}
}
function tokenInHeadNoScript(p, token) {
const errCode = token.type === TokenType.EOF ? ERR.openElementsLeftAfterEof : ERR.disallowedContentInNoscriptInHead;
p._err(token, errCode);
p.openElements.pop();
p.insertionMode = InsertionMode.IN_HEAD;
p._processToken(token);
}
// The "after head" insertion mode
//------------------------------------------------------------------
function startTagAfterHead(p, token) {
switch (token.tagID) {
case TAG_ID.HTML: {
startTagInBody(p, token);
break;
}
case TAG_ID.BODY: {
p._insertElement(token, NS.HTML);
p.framesetOk = false;
p.insertionMode = InsertionMode.IN_BODY;
break;
}
case TAG_ID.FRAMESET: {
p._insertElement(token, NS.HTML);
p.insertionMode = InsertionMode.IN_FRAMESET;
break;
}
case TAG_ID.BASE:
case TAG_ID.BASEFONT:
case TAG_ID.BGSOUND:
case TAG_ID.LINK:
case TAG_ID.META:
case TAG_ID.NOFRAMES:
case TAG_ID.SCRIPT:
case TAG_ID.STYLE:
case TAG_ID.TEMPLATE:
case TAG_ID.TITLE: {
p._err(token, ERR.abandonedHeadElementChild);
p.openElements.push(p.headElement, TAG_ID.HEAD);
startTagInHead(p, token);
p.openElements.remove(p.headElement);
break;
}
case TAG_ID.HEAD: {
p._err(token, ERR.misplacedStartTagForHeadElement);
break;
}
default: {
tokenAfterHead(p, token);
}
}
}
function endTagAfterHead(p, token) {
switch (token.tagID) {
case TAG_ID.BODY:
case TAG_ID.HTML:
case TAG_ID.BR: {
tokenAfterHead(p, token);
break;
}
case TAG_ID.TEMPLATE: {
endTagInHead(p, token);
break;
}
default: {
p._err(token, ERR.endTagWithoutMatchingOpenElement);
}
}
}
function tokenAfterHead(p, token) {
p._insertFakeElement(TAG_NAMES.BODY, TAG_ID.BODY);
p.insertionMode = InsertionMode.IN_BODY;
modeInBody(p, token);
}
// The "in body" insertion mode
//------------------------------------------------------------------
function modeInBody(p, token) {
switch (token.type) {
case TokenType.CHARACTER: {
characterInBody(p, token);
break;
}
case TokenType.WHITESPACE_CHARACTER: {
whitespaceCharacterInBody(p, token);
break;
}
case TokenType.COMMENT: {
appendComment(p, token);
break;
}
case TokenType.START_TAG: {
startTagInBody(p, token);
break;
}
case TokenType.END_TAG: {
endTagInBody(p, token);
break;
}
case TokenType.EOF: {
eofInBody(p, token);
break;
}
// Do nothing
}
}
function whitespaceCharacterInBody(p, token) {
p._reconstructActiveFormattingElements();
p._insertCharacters(token);
}
function characterInBody(p, token) {
p._reconstructActiveFormattingElements();
p._insertCharacters(token);
p.framesetOk = false;
}
function htmlStartTagInBody(p, token) {
if (p.openElements.tmplCount === 0) {
p.treeAdapter.adoptAttributes(p.openElements.items[0], token.attrs);
}
}
function bodyStartTagInBody(p, token) {
const bodyElement = p.openElements.tryPeekProperlyNestedBodyElement();
if (bodyElement && p.openElements.tmplCount === 0) {
p.framesetOk = false;
p.treeAdapter.adoptAttributes(bodyElement, token.attrs);
}
}
function framesetStartTagInBody(p, token) {
const bodyElement = p.openElements.tryPeekProperlyNestedBodyElement();
if (p.framesetOk && bodyElement) {
p.treeAdapter.detachNode(bodyElement);
p.openElements.popAllUpToHtmlElement();
p._insertElement(token, NS.HTML);
p.insertionMode = InsertionMode.IN_FRAMESET;
}
}
function addressStartTagInBody(p, token) {
if (p.openElements.hasInButtonScope(TAG_ID.P)) {
p._closePElement();
}
p._insertElement(token, NS.HTML);
}
function numberedHeaderStartTagInBody(p, token) {
if (p.openElements.hasInButtonScope(TAG_ID.P)) {
p._closePElement();
}
if (isNumberedHeader(p.openElements.currentTagId)) {
p.openElements.pop();
}
p._insertElement(token, NS.HTML);
}
function preStartTagInBody(p, token) {
if (p.openElements.hasInButtonScope(TAG_ID.P)) {
p._closePElement();
}
p._insertElement(token, NS.HTML);
//NOTE: If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move
//on to the next one. (Newlines at the start of pre blocks are ignored as an authoring convenience.)
p.skipNextNewLine = true;
p.framesetOk = false;
}
function formStartTagInBody(p, token) {
const inTemplate = p.openElements.tmplCount > 0;
if (!p.formElement || inTemplate) {
if (p.openElements.hasInButtonScope(TAG_ID.P)) {
p._closePElement();
}
p._insertElement(token, NS.HTML);
if (!inTemplate) {
p.formElement = p.openElements.current;
}
}
}
function listItemStartTagInBody(p, token) {
p.framesetOk = false;
const tn = token.tagID;
for (let i = p.openElements.stackTop; i >= 0; i--) {
const elementId = p.openElements.tagIDs[i];
if ((tn === TAG_ID.LI && elementId === TAG_ID.LI) ||
((tn === TAG_ID.DD || tn === TAG_ID.DT) && (elementId === TAG_ID.DD || elementId === TAG_ID.DT))) {
p.openElements.generateImpliedEndTagsWithExclusion(elementId);
p.openElements.popUntilTagNamePopped(elementId);
break;
}
if (elementId !== TAG_ID.ADDRESS &&
elementId !== TAG_ID.DIV &&
elementId !== TAG_ID.P &&
p._isSpecialElement(p.openElements.items[i], elementId)) {
break;
}
}
if (p.openElements.hasInButtonScope(TAG_ID.P)) {
p._closePElement();
}
p._insertElement(token, NS.HTML);
}
function plaintextStartTagInBody(p, token) {
if (p.openElements.hasInButtonScope(TAG_ID.P)) {
p._closePElement();
}
p._insertElement(token, NS.HTML);
p.tokenizer.state = TokenizerMode.PLAINTEXT;
}
function buttonStartTagInBody(p, token) {
if (p.openElements.hasInScope(TAG_ID.BUTTON)) {
p.openElements.generateImpliedEndTags();
p.openElements.popUntilTagNamePopped(TAG_ID.BUTTON);
}
p._reconstructActiveFormattingElements();
p._insertElement(token, NS.HTML);
p.framesetOk = false;
}
function aStartTagInBody(p, token) {
const activeElementEntry = p.activeFormattingElements.getElementEntryInScopeWithTagName(TAG_NAMES.A);
if (activeElementEntry) {
callAdoptionAgency(p, token);
p.openElements.remove(activeElementEntry.element);
p.activeFormattingElements.removeEntry(activeElementEntry);
}
p._reconstructActiveFormattingElements();
p._insertElement(token, NS.HTML);
p.activeFormattingElements.pushElement(p.openElements.current, token);
}
function bStartTagInBody(p, token) {
p._reconstructActiveFormattingElements();
p._insertElement(token, NS.HTML);
p.activeFormattingElements.pushElement(p.openElements.current, token);
}
function nobrStartTagInBody(p, token) {
p._reconstructActiveFormattingElements();
if (p.openElements.hasInScope(TAG_ID.NOBR)) {
callAdoptionAgency(p, token);
p._reconstructActiveFormattingElements();
}
p._insertElement(token, NS.HTML);
p.activeFormattingElements.pushElement(p.openElements.current, token);
}
function appletStartTagInBody(p, token) {
p._reconstructActiveFormattingElements();
p._insertElement(token, NS.HTML);
p.activeFormattingElements.insertMarker();
p.framesetOk = false;
}
function tableStartTagInBody(p, token) {
if (p.treeAdapter.getDocumentMode(p.document) !== DOCUMENT_MODE.QUIRKS && p.openElements.hasInButtonScope(TAG_ID.P)) {
p._closePElement();
}
p._insertElement(token, NS.HTML);
p.framesetOk = false;
p.insertionMode = InsertionMode.IN_TABLE;
}
function areaStartTagInBody(p, token) {
p._reconstructActiveFormattingElements();
p._appendElement(token, NS.HTML);
p.framesetOk = false;
token.ackSelfClosing = true;
}
function isHiddenInput(token) {
const inputType = getTokenAttr(token, ATTRS.TYPE);
return inputType != null && inputType.toLowerCase() === HIDDEN_INPUT_TYPE;
}
function inputStartTagInBody(p, token) {
p._reconstructActiveFormattingElements();
p._appendElement(token, NS.HTML);
if (!isHiddenInput(token)) {
p.framesetOk = false;
}
token.ackSelfClosing = true;
}
function paramStartTagInBody(p, token) {
p._appendElement(token, NS.HTML);
token.ackSelfClosing = true;
}
function hrStartTagInBody(p, token) {
if (p.openElements.hasInButtonScope(TAG_ID.P)) {
p._closePElement();
}
p._appendElement(token, NS.HTML);
p.framesetOk = false;
token.ackSelfClosing = true;
}
function imageStartTagInBody(p, token) {
token.tagName = TAG_NAMES.IMG;
token.tagID = TAG_ID.IMG;
areaStartTagInBody(p, token);
}
function textareaStartTagInBody(p, token) {
p._insertElement(token, NS.HTML);
//NOTE: If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move
//on to the next one. (Newlines at the start of textarea elements are ignored as an authoring convenience.)
p.skipNextNewLine = true;
p.tokenizer.state = TokenizerMode.RCDATA;
p.originalInsertionMode = p.insertionMode;
p.framesetOk = false;
p.insertionMode = InsertionMode.TEXT;
}
function xmpStartTagInBody(p, token) {
if (p.openElements.hasInButtonScope(TAG_ID.P)) {
p._closePElement();
}
p._reconstructActiveFormattingElements();
p.framesetOk = false;
p._switchToTextParsing(token, TokenizerMode.RAWTEXT);
}
function iframeStartTagInBody(p, token) {
p.framesetOk = false;
p._switchToTextParsing(token, TokenizerMode.RAWTEXT);
}
//NOTE: here we assume that we always act as an user agent with enabled plugins, so we parse
//<noembed> as rawtext.
function noembedStartTagInBody(p, token) {
p._switchToTextParsing(token, TokenizerMode.RAWTEXT);
}
function selectStartTagInBody(p, token) {
p._reconstructActiveFormattingElements();
p._insertElement(token, NS.HTML);
p.framesetOk = false;
p.insertionMode =
p.insertionMode === InsertionMode.IN_TABLE ||
p.insertionMode === InsertionMode.IN_CAPTION ||
p.insertionMode === InsertionMode.IN_TABLE_BODY ||
p.insertionMode === InsertionMode.IN_ROW ||
p.insertionMode === InsertionMode.IN_CELL
? InsertionMode.IN_SELECT_IN_TABLE
: InsertionMode.IN_SELECT;
}
function optgroupStartTagInBody(p, token) {
if (p.openElements.currentTagId === TAG_ID.OPTION) {
p.openElements.pop();
}
p._reconstructActiveFormattingElements();
p._insertElement(token, NS.HTML);
}
function rbStartTagInBody(p, token) {
if (p.openElements.hasInScope(TAG_ID.RUBY)) {
p.openElements.generateImpliedEndTags();
}
p._insertElement(token, NS.HTML);
}
function rtStartTagInBody(p, token) {
if (p.openElements.hasInScope(TAG_ID.RUBY)) {
p.openElements.generateImpliedEndTagsWithExclusion(TAG_ID.RTC);
}
p._insertElement(token, NS.HTML);
}
function mathStartTagInBody(p, token) {
p._reconstructActiveFormattingElements();
adjustTokenMathMLAttrs(token);
adjustTokenXMLAttrs(token);
if (token.selfClosing) {
p._appendElement(token, NS.MATHML);
}
else {
p._insertElement(token, NS.MATHML);
}
token.ackSelfClosing = true;
}
function svgStartTagInBody(p, token) {
p._reconstructActiveFormattingElements();
adjustTokenSVGAttrs(token);
adjustTokenXMLAttrs(token);
if (token.selfClosing) {
p._appendElement(token, NS.SVG);
}
else {
p._insertElement(token, NS.SVG);
}
token.ackSelfClosing = true;
}
function genericStartTagInBody(p, token) {
p._reconstructActiveFormattingElements();
p._insertElement(token, NS.HTML);
}
function startTagInBody(p, token) {
switch (token.tagID) {
case TAG_ID.I:
case TAG_ID.S:
case TAG_ID.B:
case TAG_ID.U:
case TAG_ID.EM:
case TAG_ID.TT:
case TAG_ID.BIG:
case TAG_ID.CODE:
case TAG_ID.FONT:
case TAG_ID.SMALL:
case TAG_ID.STRIKE:
case TAG_ID.STRONG: {
bStartTagInBody(p, token);
break;
}
case TAG_ID.A: {
aStartTagInBody(p, token);
break;
}
case TAG_ID.H1:
case TAG_ID.H2:
case TAG_ID.H3:
case TAG_ID.H4:
case TAG_ID.H5:
case TAG_ID.H6: {
numberedHeaderStartTagInBody(p, token);
break;
}
case TAG_ID.P:
case TAG_ID.DL:
case TAG_ID.OL:
case TAG_ID.UL:
case TAG_ID.DIV:
case TAG_ID.DIR:
case TAG_ID.NAV:
case TAG_ID.MAIN:
case TAG_ID.MENU:
case TAG_ID.ASIDE:
case TAG_ID.CENTER:
case TAG_ID.FIGURE:
case TAG_ID.FOOTER:
case TAG_ID.HEADER:
case TAG_ID.HGROUP:
case TAG_ID.DIALOG:
case TAG_ID.DETAILS:
case TAG_ID.ADDRESS:
case TAG_ID.ARTICLE:
case TAG_ID.SECTION:
case TAG_ID.SUMMARY:
case TAG_ID.FIELDSET:
case TAG_ID.BLOCKQUOTE:
case TAG_ID.FIGCAPTION: {
addressStartTagInBody(p, token);
break;
}
case TAG_ID.LI:
case TAG_ID.DD:
case TAG_ID.DT: {
listItemStartTagInBody(p, token);
break;
}
case TAG_ID.BR:
case TAG_ID.IMG:
case TAG_ID.WBR:
case TAG_ID.AREA:
case TAG_ID.EMBED:
case TAG_ID.KEYGEN: {
areaStartTagInBody(p, token);
break;
}
case TAG_ID.HR: {
hrStartTagInBody(p, token);
break;
}
case TAG_ID.RB:
case TAG_ID.RTC: {
rbStartTagInBody(p, token);
break;
}
case TAG_ID.RT:
case TAG_ID.RP: {
rtStartTagInBody(p, token);
break;
}
case TAG_ID.PRE:
case TAG_ID.LISTING: {
preStartTagInBody(p, token);
break;
}
case TAG_ID.XMP: {
xmpStartTagInBody(p, token);
break;
}
case TAG_ID.SVG: {
svgStartTagInBody(p, token);
break;
}
case TAG_ID.HTML: {
htmlStartTagInBody(p, token);
break;
}
case TAG_ID.BASE:
case TAG_ID.LINK:
case TAG_ID.META:
case TAG_ID.STYLE:
case TAG_ID.TITLE:
case TAG_ID.SCRIPT:
case TAG_ID.BGSOUND:
case TAG_ID.BASEFONT:
case TAG_ID.TEMPLATE: {
startTagInHead(p, token);
break;
}
case TAG_ID.BODY: {
bodyStartTagInBody(p, token);
break;
}
case TAG_ID.FORM: {
formStartTagInBody(p, token);
break;
}
case TAG_ID.NOBR: {
nobrStartTagInBody(p, token);
break;
}
case TAG_ID.MATH: {
mathStartTagInBody(p, token);
break;
}
case TAG_ID.TABLE: {
tableStartTagInBody(p, token);
break;
}
case TAG_ID.INPUT: {
inputStartTagInBody(p, token);
break;
}
case TAG_ID.PARAM:
case TAG_ID.TRACK:
case TAG_ID.SOURCE: {
paramStartTagInBody(p, token);
break;
}
case TAG_ID.IMAGE: {
imageStartTagInBody(p, token);
break;
}
case TAG_ID.BUTTON: {
buttonStartTagInBody(p, token);
break;
}
case TAG_ID.APPLET:
case TAG_ID.OBJECT:
case TAG_ID.MARQUEE: {
appletStartTagInBody(p, token);
break;
}
case TAG_ID.IFRAME: {
iframeStartTagInBody(p, token);
break;
}
case TAG_ID.SELECT: {
selectStartTagInBody(p, token);
break;
}
case TAG_ID.OPTION:
case TAG_ID.OPTGROUP: {
optgroupStartTagInBody(p, token);
break;
}
case TAG_ID.NOEMBED: {
noembedStartTagInBody(p, token);
break;
}
case TAG_ID.FRAMESET: {
framesetStartTagInBody(p, token);
break;
}
case TAG_ID.TEXTAREA: {
textareaStartTagInBody(p, token);
break;
}
case TAG_ID.NOSCRIPT: {
if (p.options.scriptingEnabled) {
noembedStartTagInBody(p, token);
}
else {
genericStartTagInBody(p, token);
}
break;
}
case TAG_ID.PLAINTEXT: {
plaintextStartTagInBody(p, token);
break;
}
case TAG_ID.COL:
case TAG_ID.TH:
case TAG_ID.TD:
case TAG_ID.TR:
case TAG_ID.HEAD:
case TAG_ID.FRAME:
case TAG_ID.TBODY:
case TAG_ID.TFOOT:
case TAG_ID.THEAD:
case TAG_ID.CAPTION:
case TAG_ID.COLGROUP: {
// Ignore token
break;
}
default: {
genericStartTagInBody(p, token);
}
}
}
function bodyEndTagInBody(p, token) {
if (p.openElements.hasInScope(TAG_ID.BODY)) {
p.insertionMode = InsertionMode.AFTER_BODY;
//NOTE: <body> is never popped from the stack, so we need to updated
//the end location explicitly.
if (p.options.sourceCodeLocationInfo) {
const bodyElement = p.openElements.tryPeekProperlyNestedBodyElement();
if (bodyElement) {
p._setEndLocation(bodyElement, token);
}
}
}
}
function htmlEndTagInBody(p, token) {
if (p.openElements.hasInScope(TAG_ID.BODY)) {
p.insertionMode = InsertionMode.AFTER_BODY;
endTagAfterBody(p, token);
}
}
function addressEndTagInBody(p, token) {
const tn = token.tagID;
if (p.openElements.hasInScope(tn)) {
p.openElements.generateImpliedEndTags();
p.openElements.popUntilTagNamePopped(tn);
}
}
function formEndTagInBody(p) {
const inTemplate = p.openElements.tmplCount > 0;
const { formElement } = p;
if (!inTemplate) {
p.formElement = null;
}
if ((formElement || inTemplate) && p.openElements.hasInScope(TAG_ID.FORM)) {
p.openElements.generateImpliedEndTags();
if (inTemplate) {
p.openElements.popUntilTagNamePopped(TAG_ID.FORM);
}
else if (formElement) {
p.openElements.remove(formElement);
}
}
}
function pEndTagInBody(p) {
if (!p.openElements.hasInButtonScope(TAG_ID.P)) {
p._insertFakeElement(TAG_NAMES.P, TAG_ID.P);
}
p._closePElement();
}
function liEndTagInBody(p) {
if (p.openElements.hasInListItemScope(TAG_ID.LI)) {
p.openElements.generateImpliedEndTagsWithExclusion(TAG_ID.LI);
p.openElements.popUntilTagNamePopped(TAG_ID.LI);
}
}
function ddEndTagInBody(p, token) {
const tn = token.tagID;
if (p.openElements.hasInScope(tn)) {
p.openElements.generateImpliedEndTagsWithExclusion(tn);
p.openElements.popUntilTagNamePopped(tn);
}
}
function numberedHeaderEndTagInBody(p) {
if (p.openElements.hasNumberedHeaderInScope()) {
p.openElements.generateImpliedEndTags();
p.openElements.popUntilNumberedHeaderPopped();
}
}
function appletEndTagInBody(p, token) {
const tn = token.tagID;
if (p.openElements.hasInScope(tn)) {
p.openElements.generateImpliedEndTags();
p.openElements.popUntilTagNamePopped(tn);
p.activeFormattingElements.clearToLastMarker();
}
}
function brEndTagInBody(p) {
p._reconstructActiveFormattingElements();
p._insertFakeElement(TAG_NAMES.BR, TAG_ID.BR);
p.openElements.pop();
p.framesetOk = false;
}
function genericEndTagInBody(p, token) {
const tn = token.tagName;
const tid = token.tagID;
for (let i = p.openElements.stackTop; i > 0; i--) {
const element = p.openElements.items[i];
const elementId = p.openElements.tagIDs[i];
// Compare the tag name here, as the tag might not be a known tag with an ID.
if (tid === elementId && (tid !== TAG_ID.UNKNOWN || p.treeAdapter.getTagName(element) === tn)) {
p.openElements.generateImpliedEndTagsWithExclusion(tid);
if (p.openElements.stackTop >= i)
p.openElements.shortenToLength(i);
break;
}
if (p._isSpecialElement(element, elementId)) {
break;
}
}
}
function endTagInBody(p, token) {
switch (token.tagID) {
case TAG_ID.A:
case TAG_ID.B:
case TAG_ID.I:
case TAG_ID.S:
case TAG_ID.U:
case TAG_ID.EM:
case TAG_ID.TT:
case TAG_ID.BIG:
case TAG_ID.CODE:
case TAG_ID.FONT:
case TAG_ID.NOBR:
case TAG_ID.SMALL:
case TAG_ID.STRIKE:
case TAG_ID.STRONG: {
callAdoptionAgency(p, token);
break;
}
case TAG_ID.P: {
pEndTagInBody(p);
break;
}
case TAG_ID.DL:
case TAG_ID.UL:
case TAG_ID.OL:
case TAG_ID.DIR:
case TAG_ID.DIV:
case TAG_ID.NAV:
case TAG_ID.PRE:
case TAG_ID.MAIN:
case TAG_ID.MENU:
case TAG_ID.ASIDE:
case TAG_ID.CENTER:
case TAG_ID.FIGURE:
case TAG_ID.FOOTER:
case TAG_ID.HEADER:
case TAG_ID.HGROUP:
case TAG_ID.DIALOG:
case TAG_ID.ADDRESS:
case TAG_ID.ARTICLE:
case TAG_ID.DETAILS:
case TAG_ID.SECTION:
case TAG_ID.SUMMARY:
case TAG_ID.LISTING:
case TAG_ID.FIELDSET:
case TAG_ID.BLOCKQUOTE:
case TAG_ID.FIGCAPTION: {
addressEndTagInBody(p, token);
break;
}
case TAG_ID.LI: {
liEndTagInBody(p);
break;
}
case TAG_ID.DD:
case TAG_ID.DT: {
ddEndTagInBody(p, token);
break;
}
case TAG_ID.H1:
case TAG_ID.H2:
case TAG_ID.H3:
case TAG_ID.H4:
case TAG_ID.H5:
case TAG_ID.H6: {
numberedHeaderEndTagInBody(p);
break;
}
case TAG_ID.BR: {
brEndTagInBody(p);
break;
}
case TAG_ID.BODY: {
bodyEndTagInBody(p, token);
break;
}
case TAG_ID.HTML: {
htmlEndTagInBody(p, token);
break;
}
case TAG_ID.FORM: {
formEndTagInBody(p);
break;
}
case TAG_ID.APPLET:
case TAG_ID.OBJECT:
case TAG_ID.MARQUEE: {
appletEndTagInBody(p, token);
break;
}
case TAG_ID.TEMPLATE: {
endTagInHead(p, token);
break;
}
default: {
genericEndTagInBody(p, token);
}
}
}
function eofInBody(p, token) {
if (p.tmplInsertionModeStack.length > 0) {
eofInTemplate(p, token);
}
else {
stopParsing(p, token);
}
}
// The "text" insertion mode
//------------------------------------------------------------------
function endTagInText(p, token) {
var _a;
if (token.tagID === TAG_ID.SCRIPT) {
(_a = p.scriptHandler) === null || _a === void 0 ? void 0 : _a.call(p, p.openElements.current);
}
p.openElements.pop();
p.insertionMode = p.originalInsertionMode;
}
function eofInText(p, token) {
p._err(token, ERR.eofInElementThatCanContainOnlyText);
p.openElements.pop();
p.insertionMode = p.originalInsertionMode;
p.onEof(token);
}
// The "in table" insertion mode
//------------------------------------------------------------------
function characterInTable(p, token) {
if (TABLE_STRUCTURE_TAGS.has(p.openElements.currentTagId)) {
p.pendingCharacterTokens.length = 0;
p.hasNonWhitespacePendingCharacterToken = false;
p.originalInsertionMode = p.insertionMode;
p.insertionMode = InsertionMode.IN_TABLE_TEXT;
switch (token.type) {
case TokenType.CHARACTER: {
characterInTableText(p, token);
break;
}
case TokenType.WHITESPACE_CHARACTER: {
whitespaceCharacterInTableText(p, token);
break;
}
// Ignore null
}
}
else {
tokenInTable(p, token);
}
}
function captionStartTagInTable(p, token) {
p.openElements.clearBackToTableContext();
p.activeFormattingElements.insertMarker();
p._insertElement(token, NS.HTML);
p.insertionMode = InsertionMode.IN_CAPTION;
}
function colgroupStartTagInTable(p, token) {
p.openElements.clearBackToTableContext();
p._insertElement(token, NS.HTML);
p.insertionMode = InsertionMode.IN_COLUMN_GROUP;
}
function colStartTagInTable(p, token) {
p.openElements.clearBackToTableContext();
p._insertFakeElement(TAG_NAMES.COLGROUP, TAG_ID.COLGROUP);
p.insertionMode = InsertionMode.IN_COLUMN_GROUP;
startTagInColumnGroup(p, token);
}
function tbodyStartTagInTable(p, token) {
p.openElements.clearBackToTableContext();
p._insertElement(token, NS.HTML);
p.insertionMode = InsertionMode.IN_TABLE_BODY;
}
function tdStartTagInTable(p, token) {
p.openElements.clearBackToTableContext();
p._insertFakeElement(TAG_NAMES.TBODY, TAG_ID.TBODY);
p.insertionMode = InsertionMode.IN_TABLE_BODY;
startTagInTableBody(p, token);
}
function tableStartTagInTable(p, token) {
if (p.openElements.hasInTableScope(TAG_ID.TABLE)) {
p.openElements.popUntilTagNamePopped(TAG_ID.TABLE);
p._resetInsertionMode();
p._processStartTag(token);
}
}
function inputStartTagInTable(p, token) {
if (isHiddenInput(token)) {
p._appendElement(token, NS.HTML);
}
else {
tokenInTable(p, token);
}
token.ackSelfClosing = true;
}
function formStartTagInTable(p, token) {
if (!p.formElement && p.openElements.tmplCount === 0) {
p._insertElement(token, NS.HTML);
p.formElement = p.openElements.current;
p.openElements.pop();
}
}
function startTagInTable(p, token) {
switch (token.tagID) {
case TAG_ID.TD:
case TAG_ID.TH:
case TAG_ID.TR: {
tdStartTagInTable(p, token);
break;
}
case TAG_ID.STYLE:
case TAG_ID.SCRIPT:
case TAG_ID.TEMPLATE: {
startTagInHead(p, token);
break;
}
case TAG_ID.COL: {
colStartTagInTable(p, token);
break;
}
case TAG_ID.FORM: {
formStartTagInTable(p, token);
break;
}
case TAG_ID.TABLE: {
tableStartTagInTable(p, token);
break;
}
case TAG_ID.TBODY:
case TAG_ID.TFOOT:
case TAG_ID.THEAD: {
tbodyStartTagInTable(p, token);
break;
}
case TAG_ID.INPUT: {
inputStartTagInTable(p, token);
break;
}
case TAG_ID.CAPTION: {
captionStartTagInTable(p, token);
break;
}
case TAG_ID.COLGROUP: {
colgroupStartTagInTable(p, token);
break;
}
default: {
tokenInTable(p, token);
}
}
}
function endTagInTable(p, token) {
switch (token.tagID) {
case TAG_ID.TABLE: {
if (p.openElements.hasInTableScope(TAG_ID.TABLE)) {
p.openElements.popUntilTagNamePopped(TAG_ID.TABLE);
p._resetInsertionMode();
}
break;
}
case TAG_ID.TEMPLATE: {
endTagInHead(p, token);
break;
}
case TAG_ID.BODY:
case TAG_ID.CAPTION:
case TAG_ID.COL:
case TAG_ID.COLGROUP:
case TAG_ID.HTML:
case TAG_ID.TBODY:
case TAG_ID.TD:
case TAG_ID.TFOOT:
case TAG_ID.TH:
case TAG_ID.THEAD:
case TAG_ID.TR: {
// Ignore token
break;
}
default: {
tokenInTable(p, token);
}
}
}
function tokenInTable(p, token) {
const savedFosterParentingState = p.fosterParentingEnabled;
p.fosterParentingEnabled = true;
// Process token in `In Body` mode
modeInBody(p, token);
p.fosterParentingEnabled = savedFosterParentingState;
}
// The "in table text" insertion mode
//------------------------------------------------------------------
function whitespaceCharacterInTableText(p, token) {
p.pendingCharacterTokens.push(token);
}
function characterInTableText(p, token) {
p.pendingCharacterTokens.push(token);
p.hasNonWhitespacePendingCharacterToken = true;
}
function tokenInTableText(p, token) {
let i = 0;
if (p.hasNonWhitespacePendingCharacterToken) {
for (; i < p.pendingCharacterTokens.length; i++) {
tokenInTable(p, p.pendingCharacterTokens[i]);
}
}
else {
for (; i < p.pendingCharacterTokens.length; i++) {
p._insertCharacters(p.pendingCharacterTokens[i]);
}
}
p.insertionMode = p.originalInsertionMode;
p._processToken(token);
}
// The "in caption" insertion mode
//------------------------------------------------------------------
const TABLE_VOID_ELEMENTS = new Set([TAG_ID.CAPTION, TAG_ID.COL, TAG_ID.COLGROUP, TAG_ID.TBODY, TAG_ID.TD, TAG_ID.TFOOT, TAG_ID.TH, TAG_ID.THEAD, TAG_ID.TR]);
function startTagInCaption(p, token) {
const tn = token.tagID;
if (TABLE_VOID_ELEMENTS.has(tn)) {
if (p.openElements.hasInTableScope(TAG_ID.CAPTION)) {
p.openElements.generateImpliedEndTags();
p.openElements.popUntilTagNamePopped(TAG_ID.CAPTION);
p.activeFormattingElements.clearToLastMarker();
p.insertionMode = InsertionMode.IN_TABLE;
startTagInTable(p, token);
}
}
else {
startTagInBody(p, token);
}
}
function endTagInCaption(p, token) {
const tn = token.tagID;
switch (tn) {
case TAG_ID.CAPTION:
case TAG_ID.TABLE: {
if (p.openElements.hasInTableScope(TAG_ID.CAPTION)) {
p.openElements.generateImpliedEndTags();
p.openElements.popUntilTagNamePopped(TAG_ID.CAPTION);
p.activeFormattingElements.clearToLastMarker();
p.insertionMode = InsertionMode.IN_TABLE;
if (tn === TAG_ID.TABLE) {
endTagInTable(p, token);
}
}
break;
}
case TAG_ID.BODY:
case TAG_ID.COL:
case TAG_ID.COLGROUP:
case TAG_ID.HTML:
case TAG_ID.TBODY:
case TAG_ID.TD:
case TAG_ID.TFOOT:
case TAG_ID.TH:
case TAG_ID.THEAD:
case TAG_ID.TR: {
// Ignore token
break;
}
default: {
endTagInBody(p, token);
}
}
}
// The "in column group" insertion mode
//------------------------------------------------------------------
function startTagInColumnGroup(p, token) {
switch (token.tagID) {
case TAG_ID.HTML: {
startTagInBody(p, token);
break;
}
case TAG_ID.COL: {
p._appendElement(token, NS.HTML);
token.ackSelfClosing = true;
break;
}
case TAG_ID.TEMPLATE: {
startTagInHead(p, token);
break;
}
default: {
tokenInColumnGroup(p, token);
}
}
}
function endTagInColumnGroup(p, token) {
switch (token.tagID) {
case TAG_ID.COLGROUP: {
if (p.openElements.currentTagId === TAG_ID.COLGROUP) {
p.openElements.pop();
p.insertionMode = InsertionMode.IN_TABLE;
}
break;
}
case TAG_ID.TEMPLATE: {
endTagInHead(p, token);
break;
}
case TAG_ID.COL: {
// Ignore token
break;
}
default: {
tokenInColumnGroup(p, token);
}
}
}
function tokenInColumnGroup(p, token) {
if (p.openElements.currentTagId === TAG_ID.COLGROUP) {
p.openElements.pop();
p.insertionMode = InsertionMode.IN_TABLE;
p._processToken(token);
}
}
// The "in table body" insertion mode
//------------------------------------------------------------------
function startTagInTableBody(p, token) {
switch (token.tagID) {
case TAG_ID.TR: {
p.openElements.clearBackToTableBodyContext();
p._insertElement(token, NS.HTML);
p.insertionMode = InsertionMode.IN_ROW;
break;
}
case TAG_ID.TH:
case TAG_ID.TD: {
p.openElements.clearBackToTableBodyContext();
p._insertFakeElement(TAG_NAMES.TR, TAG_ID.TR);
p.insertionMode = InsertionMode.IN_ROW;
startTagInRow(p, token);
break;
}
case TAG_ID.CAPTION:
case TAG_ID.COL:
case TAG_ID.COLGROUP:
case TAG_ID.TBODY:
case TAG_ID.TFOOT:
case TAG_ID.THEAD: {
if (p.openElements.hasTableBodyContextInTableScope()) {
p.openElements.clearBackToTableBodyContext();
p.openElements.pop();
p.insertionMode = InsertionMode.IN_TABLE;
startTagInTable(p, token);
}
break;
}
default: {
startTagInTable(p, token);
}
}
}
function endTagInTableBody(p, token) {
const tn = token.tagID;
switch (token.tagID) {
case TAG_ID.TBODY:
case TAG_ID.TFOOT:
case TAG_ID.THEAD: {
if (p.openElements.hasInTableScope(tn)) {
p.openElements.clearBackToTableBodyContext();
p.openElements.pop();
p.insertionMode = InsertionMode.IN_TABLE;
}
break;
}
case TAG_ID.TABLE: {
if (p.openElements.hasTableBodyContextInTableScope()) {
p.openElements.clearBackToTableBodyContext();
p.openElements.pop();
p.insertionMode = InsertionMode.IN_TABLE;
endTagInTable(p, token);
}
break;
}
case TAG_ID.BODY:
case TAG_ID.CAPTION:
case TAG_ID.COL:
case TAG_ID.COLGROUP:
case TAG_ID.HTML:
case TAG_ID.TD:
case TAG_ID.TH:
case TAG_ID.TR: {
// Ignore token
break;
}
default: {
endTagInTable(p, token);
}
}
}
// The "in row" insertion mode
//------------------------------------------------------------------
function startTagInRow(p, token) {
switch (token.tagID) {
case TAG_ID.TH:
case TAG_ID.TD: {
p.openElements.clearBackToTableRowContext();
p._insertElement(token, NS.HTML);
p.insertionMode = InsertionMode.IN_CELL;
p.activeFormattingElements.insertMarker();
break;
}
case TAG_ID.CAPTION:
case TAG_ID.COL:
case TAG_ID.COLGROUP:
case TAG_ID.TBODY:
case TAG_ID.TFOOT:
case TAG_ID.THEAD:
case TAG_ID.TR: {
if (p.openElements.hasInTableScope(TAG_ID.TR)) {
p.openElements.clearBackToTableRowContext();
p.openElements.pop();
p.insertionMode = InsertionMode.IN_TABLE_BODY;
startTagInTableBody(p, token);
}
break;
}
default: {
startTagInTable(p, token);
}
}
}
function endTagInRow(p, token) {
switch (token.tagID) {
case TAG_ID.TR: {
if (p.openElements.hasInTableScope(TAG_ID.TR)) {
p.openElements.clearBackToTableRowContext();
p.openElements.pop();
p.insertionMode = InsertionMode.IN_TABLE_BODY;
}
break;
}
case TAG_ID.TABLE: {
if (p.openElements.hasInTableScope(TAG_ID.TR)) {
p.openElements.clearBackToTableRowContext();
p.openElements.pop();
p.insertionMode = InsertionMode.IN_TABLE_BODY;
endTagInTableBody(p, token);
}
break;
}
case TAG_ID.TBODY:
case TAG_ID.TFOOT:
case TAG_ID.THEAD: {
if (p.openElements.hasInTableScope(token.tagID) || p.openElements.hasInTableScope(TAG_ID.TR)) {
p.openElements.clearBackToTableRowContext();
p.openElements.pop();
p.insertionMode = InsertionMode.IN_TABLE_BODY;
endTagInTableBody(p, token);
}
break;
}
case TAG_ID.BODY:
case TAG_ID.CAPTION:
case TAG_ID.COL:
case TAG_ID.COLGROUP:
case TAG_ID.HTML:
case TAG_ID.TD:
case TAG_ID.TH: {
// Ignore end tag
break;
}
default:
endTagInTable(p, token);
}
}
// The "in cell" insertion mode
//------------------------------------------------------------------
function startTagInCell(p, token) {
const tn = token.tagID;
if (TABLE_VOID_ELEMENTS.has(tn)) {
if (p.openElements.hasInTableScope(TAG_ID.TD) || p.openElements.hasInTableScope(TAG_ID.TH)) {
p._closeTableCell();
startTagInRow(p, token);
}
}
else {
startTagInBody(p, token);
}
}
function endTagInCell(p, token) {
const tn = token.tagID;
switch (tn) {
case TAG_ID.TD:
case TAG_ID.TH: {
if (p.openElements.hasInTableScope(tn)) {
p.openElements.generateImpliedEndTags();
p.openElements.popUntilTagNamePopped(tn);
p.activeFormattingElements.clearToLastMarker();
p.insertionMode = InsertionMode.IN_ROW;
}
break;
}
case TAG_ID.TABLE:
case TAG_ID.TBODY:
case TAG_ID.TFOOT:
case TAG_ID.THEAD:
case TAG_ID.TR: {
if (p.openElements.hasInTableScope(tn)) {
p._closeTableCell();
endTagInRow(p, token);
}
break;
}
case TAG_ID.BODY:
case TAG_ID.CAPTION:
case TAG_ID.COL:
case TAG_ID.COLGROUP:
case TAG_ID.HTML: {
// Ignore token
break;
}
default: {
endTagInBody(p, token);
}
}
}
// The "in select" insertion mode
//------------------------------------------------------------------
function startTagInSelect(p, token) {
switch (token.tagID) {
case TAG_ID.HTML: {
startTagInBody(p, token);
break;
}
case TAG_ID.OPTION: {
if (p.openElements.currentTagId === TAG_ID.OPTION) {
p.openElements.pop();
}
p._insertElement(token, NS.HTML);
break;
}
case TAG_ID.OPTGROUP: {
if (p.openElements.currentTagId === TAG_ID.OPTION) {
p.openElements.pop();
}
if (p.openElements.currentTagId === TAG_ID.OPTGROUP) {
p.openElements.pop();
}
p._insertElement(token, NS.HTML);
break;
}
case TAG_ID.INPUT:
case TAG_ID.KEYGEN:
case TAG_ID.TEXTAREA:
case TAG_ID.SELECT: {
if (p.openElements.hasInSelectScope(TAG_ID.SELECT)) {
p.openElements.popUntilTagNamePopped(TAG_ID.SELECT);
p._resetInsertionMode();
if (token.tagID !== TAG_ID.SELECT) {
p._processStartTag(token);
}
}
break;
}
case TAG_ID.SCRIPT:
case TAG_ID.TEMPLATE: {
startTagInHead(p, token);
break;
}
// Do nothing
}
}
function endTagInSelect(p, token) {
switch (token.tagID) {
case TAG_ID.OPTGROUP: {
if (p.openElements.stackTop > 0 &&
p.openElements.currentTagId === TAG_ID.OPTION &&
p.openElements.tagIDs[p.openElements.stackTop - 1] === TAG_ID.OPTGROUP) {
p.openElements.pop();
}
if (p.openElements.currentTagId === TAG_ID.OPTGROUP) {
p.openElements.pop();
}
break;
}
case TAG_ID.OPTION: {
if (p.openElements.currentTagId === TAG_ID.OPTION) {
p.openElements.pop();
}
break;
}
case TAG_ID.SELECT: {
if (p.openElements.hasInSelectScope(TAG_ID.SELECT)) {
p.openElements.popUntilTagNamePopped(TAG_ID.SELECT);
p._resetInsertionMode();
}
break;
}
case TAG_ID.TEMPLATE: {
endTagInHead(p, token);
break;
}
// Do nothing
}
}
// The "in select in table" insertion mode
//------------------------------------------------------------------
function startTagInSelectInTable(p, token) {
const tn = token.tagID;
if (tn === TAG_ID.CAPTION ||
tn === TAG_ID.TABLE ||
tn === TAG_ID.TBODY ||
tn === TAG_ID.TFOOT ||
tn === TAG_ID.THEAD ||
tn === TAG_ID.TR ||
tn === TAG_ID.TD ||
tn === TAG_ID.TH) {
p.openElements.popUntilTagNamePopped(TAG_ID.SELECT);
p._resetInsertionMode();
p._processStartTag(token);
}
else {
startTagInSelect(p, token);
}
}
function endTagInSelectInTable(p, token) {
const tn = token.tagID;
if (tn === TAG_ID.CAPTION ||
tn === TAG_ID.TABLE ||
tn === TAG_ID.TBODY ||
tn === TAG_ID.TFOOT ||
tn === TAG_ID.THEAD ||
tn === TAG_ID.TR ||
tn === TAG_ID.TD ||
tn === TAG_ID.TH) {
if (p.openElements.hasInTableScope(tn)) {
p.openElements.popUntilTagNamePopped(TAG_ID.SELECT);
p._resetInsertionMode();
p.onEndTag(token);
}
}
else {
endTagInSelect(p, token);
}
}
// The "in template" insertion mode
//------------------------------------------------------------------
function startTagInTemplate(p, token) {
switch (token.tagID) {
// First, handle tags that can start without a mode change
case TAG_ID.BASE:
case TAG_ID.BASEFONT:
case TAG_ID.BGSOUND:
case TAG_ID.LINK:
case TAG_ID.META:
case TAG_ID.NOFRAMES:
case TAG_ID.SCRIPT:
case TAG_ID.STYLE:
case TAG_ID.TEMPLATE:
case TAG_ID.TITLE:
startTagInHead(p, token);
break;
// Re-process the token in the appropriate mode
case TAG_ID.CAPTION:
case TAG_ID.COLGROUP:
case TAG_ID.TBODY:
case TAG_ID.TFOOT:
case TAG_ID.THEAD:
p.tmplInsertionModeStack[0] = InsertionMode.IN_TABLE;
p.insertionMode = InsertionMode.IN_TABLE;
startTagInTable(p, token);
break;
case TAG_ID.COL:
p.tmplInsertionModeStack[0] = InsertionMode.IN_COLUMN_GROUP;
p.insertionMode = InsertionMode.IN_COLUMN_GROUP;
startTagInColumnGroup(p, token);
break;
case TAG_ID.TR:
p.tmplInsertionModeStack[0] = InsertionMode.IN_TABLE_BODY;
p.insertionMode = InsertionMode.IN_TABLE_BODY;
startTagInTableBody(p, token);
break;
case TAG_ID.TD:
case TAG_ID.TH:
p.tmplInsertionModeStack[0] = InsertionMode.IN_ROW;
p.insertionMode = InsertionMode.IN_ROW;
startTagInRow(p, token);
break;
default:
p.tmplInsertionModeStack[0] = InsertionMode.IN_BODY;
p.insertionMode = InsertionMode.IN_BODY;
startTagInBody(p, token);
}
}
function endTagInTemplate(p, token) {
if (token.tagID === TAG_ID.TEMPLATE) {
endTagInHead(p, token);
}
}
function eofInTemplate(p, token) {
if (p.openElements.tmplCount > 0) {
p.openElements.popUntilTagNamePopped(TAG_ID.TEMPLATE);
p.activeFormattingElements.clearToLastMarker();
p.tmplInsertionModeStack.shift();
p._resetInsertionMode();
p.onEof(token);
}
else {
stopParsing(p, token);
}
}
// The "after body" insertion mode
//------------------------------------------------------------------
function startTagAfterBody(p, token) {
if (token.tagID === TAG_ID.HTML) {
startTagInBody(p, token);
}
else {
tokenAfterBody(p, token);
}
}
function endTagAfterBody(p, token) {
var _a;
if (token.tagID === TAG_ID.HTML) {
if (!p.fragmentContext) {
p.insertionMode = InsertionMode.AFTER_AFTER_BODY;
}
//NOTE: <html> is never popped from the stack, so we need to updated
//the end location explicitly.
if (p.options.sourceCodeLocationInfo && p.openElements.tagIDs[0] === TAG_ID.HTML) {
p._setEndLocation(p.openElements.items[0], token);
// Update the body element, if it doesn't have an end tag
const bodyElement = p.openElements.items[1];
if (bodyElement && !((_a = p.treeAdapter.getNodeSourceCodeLocation(bodyElement)) === null || _a === void 0 ? void 0 : _a.endTag)) {
p._setEndLocation(bodyElement, token);
}
}
}
else {
tokenAfterBody(p, token);
}
}
function tokenAfterBody(p, token) {
p.insertionMode = InsertionMode.IN_BODY;
modeInBody(p, token);
}
// The "in frameset" insertion mode
//------------------------------------------------------------------
function startTagInFrameset(p, token) {
switch (token.tagID) {
case TAG_ID.HTML: {
startTagInBody(p, token);
break;
}
case TAG_ID.FRAMESET: {
p._insertElement(token, NS.HTML);
break;
}
case TAG_ID.FRAME: {
p._appendElement(token, NS.HTML);
token.ackSelfClosing = true;
break;
}
case TAG_ID.NOFRAMES: {
startTagInHead(p, token);
break;
}
// Do nothing
}
}
function endTagInFrameset(p, token) {
if (token.tagID === TAG_ID.FRAMESET && !p.openElements.isRootHtmlElementCurrent()) {
p.openElements.pop();
if (!p.fragmentContext && p.openElements.currentTagId !== TAG_ID.FRAMESET) {
p.insertionMode = InsertionMode.AFTER_FRAMESET;
}
}
}
// The "after frameset" insertion mode
//------------------------------------------------------------------
function startTagAfterFrameset(p, token) {
switch (token.tagID) {
case TAG_ID.HTML: {
startTagInBody(p, token);
break;
}
case TAG_ID.NOFRAMES: {
startTagInHead(p, token);
break;
}
// Do nothing
}
}
function endTagAfterFrameset(p, token) {
if (token.tagID === TAG_ID.HTML) {
p.insertionMode = InsertionMode.AFTER_AFTER_FRAMESET;
}
}
// The "after after body" insertion mode
//------------------------------------------------------------------
function startTagAfterAfterBody(p, token) {
if (token.tagID === TAG_ID.HTML) {
startTagInBody(p, token);
}
else {
tokenAfterAfterBody(p, token);
}
}
function tokenAfterAfterBody(p, token) {
p.insertionMode = InsertionMode.IN_BODY;
modeInBody(p, token);
}
// The "after after frameset" insertion mode
//------------------------------------------------------------------
function startTagAfterAfterFrameset(p, token) {
switch (token.tagID) {
case TAG_ID.HTML: {
startTagInBody(p, token);
break;
}
case TAG_ID.NOFRAMES: {
startTagInHead(p, token);
break;
}
// Do nothing
}
}
// The rules for parsing tokens in foreign content
//------------------------------------------------------------------
function nullCharacterInForeignContent(p, token) {
token.chars = REPLACEMENT_CHARACTER;
p._insertCharacters(token);
}
function characterInForeignContent(p, token) {
p._insertCharacters(token);
p.framesetOk = false;
}
function popUntilHtmlOrIntegrationPoint(p) {
while (p.treeAdapter.getNamespaceURI(p.openElements.current) !== NS.HTML &&
!p._isIntegrationPoint(p.openElements.currentTagId, p.openElements.current)) {
p.openElements.pop();
}
}
function startTagInForeignContent(p, token) {
if (causesExit(token)) {
popUntilHtmlOrIntegrationPoint(p);
p._startTagOutsideForeignContent(token);
}
else {
const current = p._getAdjustedCurrentElement();
const currentNs = p.treeAdapter.getNamespaceURI(current);
if (currentNs === NS.MATHML) {
adjustTokenMathMLAttrs(token);
}
else if (currentNs === NS.SVG) {
adjustTokenSVGTagName(token);
adjustTokenSVGAttrs(token);
}
adjustTokenXMLAttrs(token);
if (token.selfClosing) {
p._appendElement(token, currentNs);
}
else {
p._insertElement(token, currentNs);
}
token.ackSelfClosing = true;
}
}
function endTagInForeignContent(p, token) {
if (token.tagID === TAG_ID.P || token.tagID === TAG_ID.BR) {
popUntilHtmlOrIntegrationPoint(p);
p._endTagOutsideForeignContent(token);
return;
}
for (let i = p.openElements.stackTop; i > 0; i--) {
const element = p.openElements.items[i];
if (p.treeAdapter.getNamespaceURI(element) === NS.HTML) {
p._endTagOutsideForeignContent(token);
break;
}
const tagName = p.treeAdapter.getTagName(element);
if (tagName.toLowerCase() === token.tagName) {
//NOTE: update the token tag name for `_setEndLocation`.
token.tagName = tagName;
p.openElements.shortenToLength(i);
break;
}
}
}
var _escape = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.escapeText = exports.escapeAttribute = exports.escapeUTF8 = exports.escape = exports.encodeXML = exports.getCodePoint = exports.xmlReplacer = void 0;
exports.xmlReplacer = /["&'<>$\x80-\uFFFF]/g;
var xmlCodeMap = new Map([
[34, "&quot;"],
[38, "&amp;"],
[39, "&apos;"],
[60, "&lt;"],
[62, "&gt;"],
]);
// For compatibility with node < 4, we wrap `codePointAt`
exports.getCodePoint =
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
String.prototype.codePointAt != null
? function (str, index) { return str.codePointAt(index); }
: // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
function (c, index) {
return (c.charCodeAt(index) & 0xfc00) === 0xd800
? (c.charCodeAt(index) - 0xd800) * 0x400 +
c.charCodeAt(index + 1) -
0xdc00 +
0x10000
: c.charCodeAt(index);
};
/**
* Encodes all non-ASCII characters, as well as characters not valid in XML
* documents using XML entities.
*
* If a character has no equivalent entity, a
* numeric hexadecimal reference (eg. `&#xfc;`) will be used.
*/
function encodeXML(str) {
var ret = "";
var lastIdx = 0;
var match;
while ((match = exports.xmlReplacer.exec(str)) !== null) {
var i = match.index;
var char = str.charCodeAt(i);
var next = xmlCodeMap.get(char);
if (next !== undefined) {
ret += str.substring(lastIdx, i) + next;
lastIdx = i + 1;
}
else {
ret += "".concat(str.substring(lastIdx, i), "&#x").concat((0, exports.getCodePoint)(str, i).toString(16), ";");
// Increase by 1 if we have a surrogate pair
lastIdx = exports.xmlReplacer.lastIndex += Number((char & 0xfc00) === 0xd800);
}
}
return ret + str.substr(lastIdx);
}
exports.encodeXML = encodeXML;
/**
* Encodes all non-ASCII characters, as well as characters not valid in XML
* documents using numeric hexadecimal reference (eg. `&#xfc;`).
*
* Have a look at `escapeUTF8` if you want a more concise output at the expense
* of reduced transportability.
*
* @param data String to escape.
*/
exports.escape = encodeXML;
function getEscaper(regex, map) {
return function escape(data) {
var match;
var lastIdx = 0;
var result = "";
while ((match = regex.exec(data))) {
if (lastIdx !== match.index) {
result += data.substring(lastIdx, match.index);
}
// We know that this chararcter will be in the map.
result += map.get(match[0].charCodeAt(0));
// Every match will be of length 1
lastIdx = match.index + 1;
}
return result + data.substring(lastIdx);
};
}
/**
* Encodes all characters not valid in XML documents using XML entities.
*
* Note that the output will be character-set dependent.
*
* @param data String to escape.
*/
exports.escapeUTF8 = getEscaper(/[&<>'"]/g, xmlCodeMap);
/**
* Encodes all characters that have to be escaped in HTML attributes,
* following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
*
* @param data String to escape.
*/
exports.escapeAttribute = getEscaper(/["&\u00A0]/g, new Map([
[34, "&quot;"],
[38, "&amp;"],
[160, "&nbsp;"],
]));
/**
* Encodes all characters that have to be escaped in HTML text,
* following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
*
* @param data String to escape.
*/
exports.escapeText = getEscaper(/[&<>\u00A0]/g, new Map([
[38, "&amp;"],
[60, "&lt;"],
[62, "&gt;"],
[160, "&nbsp;"],
]));
});
unwrapExports(_escape);
var _escape_1 = _escape.escapeText;
var _escape_2 = _escape.escapeAttribute;
var _escape_3 = _escape.escapeUTF8;
var _escape_4 = _escape.escape;
var _escape_5 = _escape.encodeXML;
var _escape_6 = _escape.getCodePoint;
var _escape_7 = _escape.xmlReplacer;
// Sets
const VOID_ELEMENTS = new Set([
TAG_NAMES.AREA,
TAG_NAMES.BASE,
TAG_NAMES.BASEFONT,
TAG_NAMES.BGSOUND,
TAG_NAMES.BR,
TAG_NAMES.COL,
TAG_NAMES.EMBED,
TAG_NAMES.FRAME,
TAG_NAMES.HR,
TAG_NAMES.IMG,
TAG_NAMES.INPUT,
TAG_NAMES.KEYGEN,
TAG_NAMES.LINK,
TAG_NAMES.META,
TAG_NAMES.PARAM,
TAG_NAMES.SOURCE,
TAG_NAMES.TRACK,
TAG_NAMES.WBR,
]);
function isVoidElement(node, options) {
return (options.treeAdapter.isElementNode(node) &&
options.treeAdapter.getNamespaceURI(node) === NS.HTML &&
VOID_ELEMENTS.has(options.treeAdapter.getTagName(node)));
}
const defaultOpts$2 = { treeAdapter: defaultTreeAdapter, scriptingEnabled: true };
/**
* Serializes an AST element node to an HTML string, including the element node.
*
* @example
*
* ```js
* const parse5 = require('parse5');
*
* const document = parse5.parseFragment('<div>Hello, <b>world</b>!</div>');
*
* // Serializes the <div> element.
* const html = parse5.serializeOuter(document.childNodes[0]);
*
* console.log(str); //> '<div>Hello, <b>world</b>!</div>'
* ```
*
* @param node Node to serialize.
* @param options Serialization options.
*/
function serializeOuter(node, options) {
const opts = { ...defaultOpts$2, ...options };
return serializeNode(node, opts);
}
function serializeChildNodes(parentNode, options) {
let html = '';
// Get container of the child nodes
const container = options.treeAdapter.isElementNode(parentNode) &&
options.treeAdapter.getTagName(parentNode) === TAG_NAMES.TEMPLATE &&
options.treeAdapter.getNamespaceURI(parentNode) === NS.HTML
? options.treeAdapter.getTemplateContent(parentNode)
: parentNode;
const childNodes = options.treeAdapter.getChildNodes(container);
if (childNodes) {
for (const currentNode of childNodes) {
html += serializeNode(currentNode, options);
}
}
return html;
}
function serializeNode(node, options) {
if (options.treeAdapter.isElementNode(node)) {
return serializeElement(node, options);
}
if (options.treeAdapter.isTextNode(node)) {
return serializeTextNode(node, options);
}
if (options.treeAdapter.isCommentNode(node)) {
return serializeCommentNode(node, options);
}
if (options.treeAdapter.isDocumentTypeNode(node)) {
return serializeDocumentTypeNode(node, options);
}
// Return an empty string for unknown nodes
return '';
}
function serializeElement(node, options) {
const tn = options.treeAdapter.getTagName(node);
return `<${tn}${serializeAttributes(node, options)}>${isVoidElement(node, options) ? '' : `${serializeChildNodes(node, options)}</${tn}>`}`;
}
function serializeAttributes(node, { treeAdapter }) {
let html = '';
for (const attr of treeAdapter.getAttrList(node)) {
html += ' ';
if (!attr.namespace) {
html += attr.name;
}
else
switch (attr.namespace) {
case NS.XML: {
html += `xml:${attr.name}`;
break;
}
case NS.XMLNS: {
if (attr.name !== 'xmlns') {
html += 'xmlns:';
}
html += attr.name;
break;
}
case NS.XLINK: {
html += `xlink:${attr.name}`;
break;
}
default: {
html += `${attr.prefix}:${attr.name}`;
}
}
html += `="${_escape_2(attr.value)}"`;
}
return html;
}
function serializeTextNode(node, options) {
const { treeAdapter } = options;
const content = treeAdapter.getTextNodeContent(node);
const parent = treeAdapter.getParentNode(node);
const parentTn = parent && treeAdapter.isElementNode(parent) && treeAdapter.getTagName(parent);
return parentTn &&
treeAdapter.getNamespaceURI(parent) === NS.HTML &&
hasUnescapedText(parentTn, options.scriptingEnabled)
? content
: _escape_1(content);
}
function serializeCommentNode(node, { treeAdapter }) {
return `<!--${treeAdapter.getCommentNodeContent(node)}-->`;
}
function serializeDocumentTypeNode(node, { treeAdapter }) {
return `<!DOCTYPE ${treeAdapter.getDocumentTypeNodeName(node)}>`;
}
// Shorthands
/**
* Parses an HTML string.
*
* @param html Input HTML string.
* @param options Parsing options.
* @returns Document
*
* @example
*
* ```js
* const parse5 = require('parse5');
*
* const document = parse5.parse('<!DOCTYPE html><html><head></head><body>Hi there!</body></html>');
*
* console.log(document.childNodes[1].tagName); //> 'html'
*```
*/
function parse$3(html, options) {
return Parser.parse(html, options);
}
function parseFragment(fragmentContext, html, options) {
if (typeof fragmentContext === 'string') {
options = html;
html = fragmentContext;
fragmentContext = null;
}
const parser = Parser.getFragmentParser(fragmentContext, options);
parser.tokenizer.write(html, true);
return parser.getFragment();
}
// `Set` constructor
// https://tc39.es/ecma262/#sec-set-objects
collection('Set', function (init) {
return function Set() { return init(this, arguments.length ? arguments[0] : undefined); };
}, collectionStrong);
var set$2 = path.Set;
var set$3 = set$2;
var set$4 = set$3;
/* eslint-disable es-x/no-array-prototype-lastindexof -- safe */
var min$4 = Math.min;
var $lastIndexOf = [].lastIndexOf;
var NEGATIVE_ZERO$1 = !!$lastIndexOf && 1 / [1].lastIndexOf(1, -0) < 0;
var STRICT_METHOD$5 = arrayMethodIsStrict('lastIndexOf');
var FORCED$6 = NEGATIVE_ZERO$1 || !STRICT_METHOD$5;
// `Array.prototype.lastIndexOf` method implementation
// https://tc39.es/ecma262/#sec-array.prototype.lastindexof
var arrayLastIndexOf = FORCED$6 ? function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) {
// convert -0 to +0
if (NEGATIVE_ZERO$1) return functionApply($lastIndexOf, this, arguments) || 0;
var O = toIndexedObject(this);
var length = lengthOfArrayLike(O);
var index = length - 1;
if (arguments.length > 1) index = min$4(index, toIntegerOrInfinity(arguments[1]));
if (index < 0) index = length + index;
for (;index >= 0; index--) if (index in O && O[index] === searchElement) return index || 0;
return -1;
} : $lastIndexOf;
// `Array.prototype.lastIndexOf` method
// https://tc39.es/ecma262/#sec-array.prototype.lastindexof
// eslint-disable-next-line es-x/no-array-prototype-lastindexof -- required for testing
_export({ target: 'Array', proto: true, forced: arrayLastIndexOf !== [].lastIndexOf }, {
lastIndexOf: arrayLastIndexOf
});
var lastIndexOf = entryVirtual('Array').lastIndexOf;
var entries$3 = entryVirtual('Array').entries;
var map$b = map$5;
var UNDEFINED_CODE_POINTS$1 = new set$4([65534, 65535, 131070, 131071, 196606, 196607, 262142, 262143, 327678, 327679, 393214, 393215, 458750, 458751, 524286, 524287, 589822, 589823, 655358, 655359, 720894, 720895, 786430, 786431, 851966, 851967, 917502, 917503, 983038, 983039, 1048574, 1048575, 1114110, 1114111]);
var CODE_POINTS$1;
(function (CODE_POINTS) {
CODE_POINTS[CODE_POINTS["EOF"] = -1] = "EOF";
CODE_POINTS[CODE_POINTS["NULL"] = 0] = "NULL";
CODE_POINTS[CODE_POINTS["TABULATION"] = 9] = "TABULATION";
CODE_POINTS[CODE_POINTS["CARRIAGE_RETURN"] = 13] = "CARRIAGE_RETURN";
CODE_POINTS[CODE_POINTS["LINE_FEED"] = 10] = "LINE_FEED";
CODE_POINTS[CODE_POINTS["FORM_FEED"] = 12] = "FORM_FEED";
CODE_POINTS[CODE_POINTS["SPACE"] = 32] = "SPACE";
CODE_POINTS[CODE_POINTS["EXCLAMATION_MARK"] = 33] = "EXCLAMATION_MARK";
CODE_POINTS[CODE_POINTS["QUOTATION_MARK"] = 34] = "QUOTATION_MARK";
CODE_POINTS[CODE_POINTS["NUMBER_SIGN"] = 35] = "NUMBER_SIGN";
CODE_POINTS[CODE_POINTS["AMPERSAND"] = 38] = "AMPERSAND";
CODE_POINTS[CODE_POINTS["APOSTROPHE"] = 39] = "APOSTROPHE";
CODE_POINTS[CODE_POINTS["HYPHEN_MINUS"] = 45] = "HYPHEN_MINUS";
CODE_POINTS[CODE_POINTS["SOLIDUS"] = 47] = "SOLIDUS";
CODE_POINTS[CODE_POINTS["DIGIT_0"] = 48] = "DIGIT_0";
CODE_POINTS[CODE_POINTS["DIGIT_9"] = 57] = "DIGIT_9";
CODE_POINTS[CODE_POINTS["SEMICOLON"] = 59] = "SEMICOLON";
CODE_POINTS[CODE_POINTS["LESS_THAN_SIGN"] = 60] = "LESS_THAN_SIGN";
CODE_POINTS[CODE_POINTS["EQUALS_SIGN"] = 61] = "EQUALS_SIGN";
CODE_POINTS[CODE_POINTS["GREATER_THAN_SIGN"] = 62] = "GREATER_THAN_SIGN";
CODE_POINTS[CODE_POINTS["QUESTION_MARK"] = 63] = "QUESTION_MARK";
CODE_POINTS[CODE_POINTS["LATIN_CAPITAL_A"] = 65] = "LATIN_CAPITAL_A";
CODE_POINTS[CODE_POINTS["LATIN_CAPITAL_F"] = 70] = "LATIN_CAPITAL_F";
CODE_POINTS[CODE_POINTS["LATIN_CAPITAL_X"] = 88] = "LATIN_CAPITAL_X";
CODE_POINTS[CODE_POINTS["LATIN_CAPITAL_Z"] = 90] = "LATIN_CAPITAL_Z";
CODE_POINTS[CODE_POINTS["RIGHT_SQUARE_BRACKET"] = 93] = "RIGHT_SQUARE_BRACKET";
CODE_POINTS[CODE_POINTS["GRAVE_ACCENT"] = 96] = "GRAVE_ACCENT";
CODE_POINTS[CODE_POINTS["LATIN_SMALL_A"] = 97] = "LATIN_SMALL_A";
CODE_POINTS[CODE_POINTS["LATIN_SMALL_F"] = 102] = "LATIN_SMALL_F";
CODE_POINTS[CODE_POINTS["LATIN_SMALL_X"] = 120] = "LATIN_SMALL_X";
CODE_POINTS[CODE_POINTS["LATIN_SMALL_Z"] = 122] = "LATIN_SMALL_Z";
CODE_POINTS[CODE_POINTS["REPLACEMENT_CHARACTER"] = 65533] = "REPLACEMENT_CHARACTER";
})(CODE_POINTS$1 || (CODE_POINTS$1 = {}));
var ERR$1;
(function (ERR) {
ERR["controlCharacterInInputStream"] = "control-character-in-input-stream";
ERR["noncharacterInInputStream"] = "noncharacter-in-input-stream";
ERR["surrogateInInputStream"] = "surrogate-in-input-stream";
ERR["nonVoidHtmlElementStartTagWithTrailingSolidus"] = "non-void-html-element-start-tag-with-trailing-solidus";
ERR["endTagWithAttributes"] = "end-tag-with-attributes";
ERR["endTagWithTrailingSolidus"] = "end-tag-with-trailing-solidus";
ERR["unexpectedSolidusInTag"] = "unexpected-solidus-in-tag";
ERR["unexpectedNullCharacter"] = "unexpected-null-character";
ERR["unexpectedQuestionMarkInsteadOfTagName"] = "unexpected-question-mark-instead-of-tag-name";
ERR["invalidFirstCharacterOfTagName"] = "invalid-first-character-of-tag-name";
ERR["unexpectedEqualsSignBeforeAttributeName"] = "unexpected-equals-sign-before-attribute-name";
ERR["missingEndTagName"] = "missing-end-tag-name";
ERR["unexpectedCharacterInAttributeName"] = "unexpected-character-in-attribute-name";
ERR["unknownNamedCharacterReference"] = "unknown-named-character-reference";
ERR["missingSemicolonAfterCharacterReference"] = "missing-semicolon-after-character-reference";
ERR["unexpectedCharacterAfterDoctypeSystemIdentifier"] = "unexpected-character-after-doctype-system-identifier";
ERR["unexpectedCharacterInUnquotedAttributeValue"] = "unexpected-character-in-unquoted-attribute-value";
ERR["eofBeforeTagName"] = "eof-before-tag-name";
ERR["eofInTag"] = "eof-in-tag";
ERR["missingAttributeValue"] = "missing-attribute-value";
ERR["missingWhitespaceBetweenAttributes"] = "missing-whitespace-between-attributes";
ERR["missingWhitespaceAfterDoctypePublicKeyword"] = "missing-whitespace-after-doctype-public-keyword";
ERR["missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers"] = "missing-whitespace-between-doctype-public-and-system-identifiers";
ERR["missingWhitespaceAfterDoctypeSystemKeyword"] = "missing-whitespace-after-doctype-system-keyword";
ERR["missingQuoteBeforeDoctypePublicIdentifier"] = "missing-quote-before-doctype-public-identifier";
ERR["missingQuoteBeforeDoctypeSystemIdentifier"] = "missing-quote-before-doctype-system-identifier";
ERR["missingDoctypePublicIdentifier"] = "missing-doctype-public-identifier";
ERR["missingDoctypeSystemIdentifier"] = "missing-doctype-system-identifier";
ERR["abruptDoctypePublicIdentifier"] = "abrupt-doctype-public-identifier";
ERR["abruptDoctypeSystemIdentifier"] = "abrupt-doctype-system-identifier";
ERR["cdataInHtmlContent"] = "cdata-in-html-content";
ERR["incorrectlyOpenedComment"] = "incorrectly-opened-comment";
ERR["eofInScriptHtmlCommentLikeText"] = "eof-in-script-html-comment-like-text";
ERR["eofInDoctype"] = "eof-in-doctype";
ERR["nestedComment"] = "nested-comment";
ERR["abruptClosingOfEmptyComment"] = "abrupt-closing-of-empty-comment";
ERR["eofInComment"] = "eof-in-comment";
ERR["incorrectlyClosedComment"] = "incorrectly-closed-comment";
ERR["eofInCdata"] = "eof-in-cdata";
ERR["absenceOfDigitsInNumericCharacterReference"] = "absence-of-digits-in-numeric-character-reference";
ERR["nullCharacterReference"] = "null-character-reference";
ERR["surrogateCharacterReference"] = "surrogate-character-reference";
ERR["characterReferenceOutsideUnicodeRange"] = "character-reference-outside-unicode-range";
ERR["controlCharacterReference"] = "control-character-reference";
ERR["noncharacterCharacterReference"] = "noncharacter-character-reference";
ERR["missingWhitespaceBeforeDoctypeName"] = "missing-whitespace-before-doctype-name";
ERR["missingDoctypeName"] = "missing-doctype-name";
ERR["invalidCharacterSequenceAfterDoctypeName"] = "invalid-character-sequence-after-doctype-name";
ERR["duplicateAttribute"] = "duplicate-attribute";
ERR["nonConformingDoctype"] = "non-conforming-doctype";
ERR["missingDoctype"] = "missing-doctype";
ERR["misplacedDoctype"] = "misplaced-doctype";
ERR["endTagWithoutMatchingOpenElement"] = "end-tag-without-matching-open-element";
ERR["closingOfElementWithOpenChildElements"] = "closing-of-element-with-open-child-elements";
ERR["disallowedContentInNoscriptInHead"] = "disallowed-content-in-noscript-in-head";
ERR["openElementsLeftAfterEof"] = "open-elements-left-after-eof";
ERR["abandonedHeadElementChild"] = "abandoned-head-element-child";
ERR["misplacedStartTagForHeadElement"] = "misplaced-start-tag-for-head-element";
ERR["nestedNoscriptInHead"] = "nested-noscript-in-head";
ERR["eofInElementThatCanContainOnlyText"] = "eof-in-element-that-can-contain-only-text";
})(ERR$1 || (ERR$1 = {}));
var TokenType$1;
(function (TokenType) {
TokenType[TokenType["CHARACTER"] = 0] = "CHARACTER";
TokenType[TokenType["NULL_CHARACTER"] = 1] = "NULL_CHARACTER";
TokenType[TokenType["WHITESPACE_CHARACTER"] = 2] = "WHITESPACE_CHARACTER";
TokenType[TokenType["START_TAG"] = 3] = "START_TAG";
TokenType[TokenType["END_TAG"] = 4] = "END_TAG";
TokenType[TokenType["COMMENT"] = 5] = "COMMENT";
TokenType[TokenType["DOCTYPE"] = 6] = "DOCTYPE";
TokenType[TokenType["EOF"] = 7] = "EOF";
TokenType[TokenType["HIBERNATION"] = 8] = "HIBERNATION";
})(TokenType$1 || (TokenType$1 = {}));
var _SPECIAL_ELEMENTS;
/** All valid namespaces in HTML. */
var NS$1;
(function (NS) {
NS["HTML"] = "http://www.w3.org/1999/xhtml";
NS["MATHML"] = "http://www.w3.org/1998/Math/MathML";
NS["SVG"] = "http://www.w3.org/2000/svg";
NS["XLINK"] = "http://www.w3.org/1999/xlink";
NS["XML"] = "http://www.w3.org/XML/1998/namespace";
NS["XMLNS"] = "http://www.w3.org/2000/xmlns/";
})(NS$1 || (NS$1 = {}));
var ATTRS$1;
(function (ATTRS) {
ATTRS["TYPE"] = "type";
ATTRS["ACTION"] = "action";
ATTRS["ENCODING"] = "encoding";
ATTRS["PROMPT"] = "prompt";
ATTRS["NAME"] = "name";
ATTRS["COLOR"] = "color";
ATTRS["FACE"] = "face";
ATTRS["SIZE"] = "size";
})(ATTRS$1 || (ATTRS$1 = {}));
/**
* The mode of the document.
*
* @see {@link https://dom.spec.whatwg.org/#concept-document-limited-quirks}
*/
var DOCUMENT_MODE$1;
(function (DOCUMENT_MODE) {
DOCUMENT_MODE["NO_QUIRKS"] = "no-quirks";
DOCUMENT_MODE["QUIRKS"] = "quirks";
DOCUMENT_MODE["LIMITED_QUIRKS"] = "limited-quirks";
})(DOCUMENT_MODE$1 || (DOCUMENT_MODE$1 = {}));
var TAG_NAMES$1;
(function (TAG_NAMES) {
TAG_NAMES["A"] = "a";
TAG_NAMES["ADDRESS"] = "address";
TAG_NAMES["ANNOTATION_XML"] = "annotation-xml";
TAG_NAMES["APPLET"] = "applet";
TAG_NAMES["AREA"] = "area";
TAG_NAMES["ARTICLE"] = "article";
TAG_NAMES["ASIDE"] = "aside";
TAG_NAMES["B"] = "b";
TAG_NAMES["BASE"] = "base";
TAG_NAMES["BASEFONT"] = "basefont";
TAG_NAMES["BGSOUND"] = "bgsound";
TAG_NAMES["BIG"] = "big";
TAG_NAMES["BLOCKQUOTE"] = "blockquote";
TAG_NAMES["BODY"] = "body";
TAG_NAMES["BR"] = "br";
TAG_NAMES["BUTTON"] = "button";
TAG_NAMES["CAPTION"] = "caption";
TAG_NAMES["CENTER"] = "center";
TAG_NAMES["CODE"] = "code";
TAG_NAMES["COL"] = "col";
TAG_NAMES["COLGROUP"] = "colgroup";
TAG_NAMES["DD"] = "dd";
TAG_NAMES["DESC"] = "desc";
TAG_NAMES["DETAILS"] = "details";
TAG_NAMES["DIALOG"] = "dialog";
TAG_NAMES["DIR"] = "dir";
TAG_NAMES["DIV"] = "div";
TAG_NAMES["DL"] = "dl";
TAG_NAMES["DT"] = "dt";
TAG_NAMES["EM"] = "em";
TAG_NAMES["EMBED"] = "embed";
TAG_NAMES["FIELDSET"] = "fieldset";
TAG_NAMES["FIGCAPTION"] = "figcaption";
TAG_NAMES["FIGURE"] = "figure";
TAG_NAMES["FONT"] = "font";
TAG_NAMES["FOOTER"] = "footer";
TAG_NAMES["FOREIGN_OBJECT"] = "foreignObject";
TAG_NAMES["FORM"] = "form";
TAG_NAMES["FRAME"] = "frame";
TAG_NAMES["FRAMESET"] = "frameset";
TAG_NAMES["H1"] = "h1";
TAG_NAMES["H2"] = "h2";
TAG_NAMES["H3"] = "h3";
TAG_NAMES["H4"] = "h4";
TAG_NAMES["H5"] = "h5";
TAG_NAMES["H6"] = "h6";
TAG_NAMES["HEAD"] = "head";
TAG_NAMES["HEADER"] = "header";
TAG_NAMES["HGROUP"] = "hgroup";
TAG_NAMES["HR"] = "hr";
TAG_NAMES["HTML"] = "html";
TAG_NAMES["I"] = "i";
TAG_NAMES["IMG"] = "img";
TAG_NAMES["IMAGE"] = "image";
TAG_NAMES["INPUT"] = "input";
TAG_NAMES["IFRAME"] = "iframe";
TAG_NAMES["KEYGEN"] = "keygen";
TAG_NAMES["LABEL"] = "label";
TAG_NAMES["LI"] = "li";
TAG_NAMES["LINK"] = "link";
TAG_NAMES["LISTING"] = "listing";
TAG_NAMES["MAIN"] = "main";
TAG_NAMES["MALIGNMARK"] = "malignmark";
TAG_NAMES["MARQUEE"] = "marquee";
TAG_NAMES["MATH"] = "math";
TAG_NAMES["MENU"] = "menu";
TAG_NAMES["META"] = "meta";
TAG_NAMES["MGLYPH"] = "mglyph";
TAG_NAMES["MI"] = "mi";
TAG_NAMES["MO"] = "mo";
TAG_NAMES["MN"] = "mn";
TAG_NAMES["MS"] = "ms";
TAG_NAMES["MTEXT"] = "mtext";
TAG_NAMES["NAV"] = "nav";
TAG_NAMES["NOBR"] = "nobr";
TAG_NAMES["NOFRAMES"] = "noframes";
TAG_NAMES["NOEMBED"] = "noembed";
TAG_NAMES["NOSCRIPT"] = "noscript";
TAG_NAMES["OBJECT"] = "object";
TAG_NAMES["OL"] = "ol";
TAG_NAMES["OPTGROUP"] = "optgroup";
TAG_NAMES["OPTION"] = "option";
TAG_NAMES["P"] = "p";
TAG_NAMES["PARAM"] = "param";
TAG_NAMES["PLAINTEXT"] = "plaintext";
TAG_NAMES["PRE"] = "pre";
TAG_NAMES["RB"] = "rb";
TAG_NAMES["RP"] = "rp";
TAG_NAMES["RT"] = "rt";
TAG_NAMES["RTC"] = "rtc";
TAG_NAMES["RUBY"] = "ruby";
TAG_NAMES["S"] = "s";
TAG_NAMES["SCRIPT"] = "script";
TAG_NAMES["SECTION"] = "section";
TAG_NAMES["SELECT"] = "select";
TAG_NAMES["SOURCE"] = "source";
TAG_NAMES["SMALL"] = "small";
TAG_NAMES["SPAN"] = "span";
TAG_NAMES["STRIKE"] = "strike";
TAG_NAMES["STRONG"] = "strong";
TAG_NAMES["STYLE"] = "style";
TAG_NAMES["SUB"] = "sub";
TAG_NAMES["SUMMARY"] = "summary";
TAG_NAMES["SUP"] = "sup";
TAG_NAMES["TABLE"] = "table";
TAG_NAMES["TBODY"] = "tbody";
TAG_NAMES["TEMPLATE"] = "template";
TAG_NAMES["TEXTAREA"] = "textarea";
TAG_NAMES["TFOOT"] = "tfoot";
TAG_NAMES["TD"] = "td";
TAG_NAMES["TH"] = "th";
TAG_NAMES["THEAD"] = "thead";
TAG_NAMES["TITLE"] = "title";
TAG_NAMES["TR"] = "tr";
TAG_NAMES["TRACK"] = "track";
TAG_NAMES["TT"] = "tt";
TAG_NAMES["U"] = "u";
TAG_NAMES["UL"] = "ul";
TAG_NAMES["SVG"] = "svg";
TAG_NAMES["VAR"] = "var";
TAG_NAMES["WBR"] = "wbr";
TAG_NAMES["XMP"] = "xmp";
})(TAG_NAMES$1 || (TAG_NAMES$1 = {}));
/**
* Tag IDs are numeric IDs for known tag names.
*
* We use tag IDs to improve the performance of tag name comparisons.
*/
var TAG_ID$1;
(function (TAG_ID) {
TAG_ID[TAG_ID["UNKNOWN"] = 0] = "UNKNOWN";
TAG_ID[TAG_ID["A"] = 1] = "A";
TAG_ID[TAG_ID["ADDRESS"] = 2] = "ADDRESS";
TAG_ID[TAG_ID["ANNOTATION_XML"] = 3] = "ANNOTATION_XML";
TAG_ID[TAG_ID["APPLET"] = 4] = "APPLET";
TAG_ID[TAG_ID["AREA"] = 5] = "AREA";
TAG_ID[TAG_ID["ARTICLE"] = 6] = "ARTICLE";
TAG_ID[TAG_ID["ASIDE"] = 7] = "ASIDE";
TAG_ID[TAG_ID["B"] = 8] = "B";
TAG_ID[TAG_ID["BASE"] = 9] = "BASE";
TAG_ID[TAG_ID["BASEFONT"] = 10] = "BASEFONT";
TAG_ID[TAG_ID["BGSOUND"] = 11] = "BGSOUND";
TAG_ID[TAG_ID["BIG"] = 12] = "BIG";
TAG_ID[TAG_ID["BLOCKQUOTE"] = 13] = "BLOCKQUOTE";
TAG_ID[TAG_ID["BODY"] = 14] = "BODY";
TAG_ID[TAG_ID["BR"] = 15] = "BR";
TAG_ID[TAG_ID["BUTTON"] = 16] = "BUTTON";
TAG_ID[TAG_ID["CAPTION"] = 17] = "CAPTION";
TAG_ID[TAG_ID["CENTER"] = 18] = "CENTER";
TAG_ID[TAG_ID["CODE"] = 19] = "CODE";
TAG_ID[TAG_ID["COL"] = 20] = "COL";
TAG_ID[TAG_ID["COLGROUP"] = 21] = "COLGROUP";
TAG_ID[TAG_ID["DD"] = 22] = "DD";
TAG_ID[TAG_ID["DESC"] = 23] = "DESC";
TAG_ID[TAG_ID["DETAILS"] = 24] = "DETAILS";
TAG_ID[TAG_ID["DIALOG"] = 25] = "DIALOG";
TAG_ID[TAG_ID["DIR"] = 26] = "DIR";
TAG_ID[TAG_ID["DIV"] = 27] = "DIV";
TAG_ID[TAG_ID["DL"] = 28] = "DL";
TAG_ID[TAG_ID["DT"] = 29] = "DT";
TAG_ID[TAG_ID["EM"] = 30] = "EM";
TAG_ID[TAG_ID["EMBED"] = 31] = "EMBED";
TAG_ID[TAG_ID["FIELDSET"] = 32] = "FIELDSET";
TAG_ID[TAG_ID["FIGCAPTION"] = 33] = "FIGCAPTION";
TAG_ID[TAG_ID["FIGURE"] = 34] = "FIGURE";
TAG_ID[TAG_ID["FONT"] = 35] = "FONT";
TAG_ID[TAG_ID["FOOTER"] = 36] = "FOOTER";
TAG_ID[TAG_ID["FOREIGN_OBJECT"] = 37] = "FOREIGN_OBJECT";
TAG_ID[TAG_ID["FORM"] = 38] = "FORM";
TAG_ID[TAG_ID["FRAME"] = 39] = "FRAME";
TAG_ID[TAG_ID["FRAMESET"] = 40] = "FRAMESET";
TAG_ID[TAG_ID["H1"] = 41] = "H1";
TAG_ID[TAG_ID["H2"] = 42] = "H2";
TAG_ID[TAG_ID["H3"] = 43] = "H3";
TAG_ID[TAG_ID["H4"] = 44] = "H4";
TAG_ID[TAG_ID["H5"] = 45] = "H5";
TAG_ID[TAG_ID["H6"] = 46] = "H6";
TAG_ID[TAG_ID["HEAD"] = 47] = "HEAD";
TAG_ID[TAG_ID["HEADER"] = 48] = "HEADER";
TAG_ID[TAG_ID["HGROUP"] = 49] = "HGROUP";
TAG_ID[TAG_ID["HR"] = 50] = "HR";
TAG_ID[TAG_ID["HTML"] = 51] = "HTML";
TAG_ID[TAG_ID["I"] = 52] = "I";
TAG_ID[TAG_ID["IMG"] = 53] = "IMG";
TAG_ID[TAG_ID["IMAGE"] = 54] = "IMAGE";
TAG_ID[TAG_ID["INPUT"] = 55] = "INPUT";
TAG_ID[TAG_ID["IFRAME"] = 56] = "IFRAME";
TAG_ID[TAG_ID["KEYGEN"] = 57] = "KEYGEN";
TAG_ID[TAG_ID["LABEL"] = 58] = "LABEL";
TAG_ID[TAG_ID["LI"] = 59] = "LI";
TAG_ID[TAG_ID["LINK"] = 60] = "LINK";
TAG_ID[TAG_ID["LISTING"] = 61] = "LISTING";
TAG_ID[TAG_ID["MAIN"] = 62] = "MAIN";
TAG_ID[TAG_ID["MALIGNMARK"] = 63] = "MALIGNMARK";
TAG_ID[TAG_ID["MARQUEE"] = 64] = "MARQUEE";
TAG_ID[TAG_ID["MATH"] = 65] = "MATH";
TAG_ID[TAG_ID["MENU"] = 66] = "MENU";
TAG_ID[TAG_ID["META"] = 67] = "META";
TAG_ID[TAG_ID["MGLYPH"] = 68] = "MGLYPH";
TAG_ID[TAG_ID["MI"] = 69] = "MI";
TAG_ID[TAG_ID["MO"] = 70] = "MO";
TAG_ID[TAG_ID["MN"] = 71] = "MN";
TAG_ID[TAG_ID["MS"] = 72] = "MS";
TAG_ID[TAG_ID["MTEXT"] = 73] = "MTEXT";
TAG_ID[TAG_ID["NAV"] = 74] = "NAV";
TAG_ID[TAG_ID["NOBR"] = 75] = "NOBR";
TAG_ID[TAG_ID["NOFRAMES"] = 76] = "NOFRAMES";
TAG_ID[TAG_ID["NOEMBED"] = 77] = "NOEMBED";
TAG_ID[TAG_ID["NOSCRIPT"] = 78] = "NOSCRIPT";
TAG_ID[TAG_ID["OBJECT"] = 79] = "OBJECT";
TAG_ID[TAG_ID["OL"] = 80] = "OL";
TAG_ID[TAG_ID["OPTGROUP"] = 81] = "OPTGROUP";
TAG_ID[TAG_ID["OPTION"] = 82] = "OPTION";
TAG_ID[TAG_ID["P"] = 83] = "P";
TAG_ID[TAG_ID["PARAM"] = 84] = "PARAM";
TAG_ID[TAG_ID["PLAINTEXT"] = 85] = "PLAINTEXT";
TAG_ID[TAG_ID["PRE"] = 86] = "PRE";
TAG_ID[TAG_ID["RB"] = 87] = "RB";
TAG_ID[TAG_ID["RP"] = 88] = "RP";
TAG_ID[TAG_ID["RT"] = 89] = "RT";
TAG_ID[TAG_ID["RTC"] = 90] = "RTC";
TAG_ID[TAG_ID["RUBY"] = 91] = "RUBY";
TAG_ID[TAG_ID["S"] = 92] = "S";
TAG_ID[TAG_ID["SCRIPT"] = 93] = "SCRIPT";
TAG_ID[TAG_ID["SECTION"] = 94] = "SECTION";
TAG_ID[TAG_ID["SELECT"] = 95] = "SELECT";
TAG_ID[TAG_ID["SOURCE"] = 96] = "SOURCE";
TAG_ID[TAG_ID["SMALL"] = 97] = "SMALL";
TAG_ID[TAG_ID["SPAN"] = 98] = "SPAN";
TAG_ID[TAG_ID["STRIKE"] = 99] = "STRIKE";
TAG_ID[TAG_ID["STRONG"] = 100] = "STRONG";
TAG_ID[TAG_ID["STYLE"] = 101] = "STYLE";
TAG_ID[TAG_ID["SUB"] = 102] = "SUB";
TAG_ID[TAG_ID["SUMMARY"] = 103] = "SUMMARY";
TAG_ID[TAG_ID["SUP"] = 104] = "SUP";
TAG_ID[TAG_ID["TABLE"] = 105] = "TABLE";
TAG_ID[TAG_ID["TBODY"] = 106] = "TBODY";
TAG_ID[TAG_ID["TEMPLATE"] = 107] = "TEMPLATE";
TAG_ID[TAG_ID["TEXTAREA"] = 108] = "TEXTAREA";
TAG_ID[TAG_ID["TFOOT"] = 109] = "TFOOT";
TAG_ID[TAG_ID["TD"] = 110] = "TD";
TAG_ID[TAG_ID["TH"] = 111] = "TH";
TAG_ID[TAG_ID["THEAD"] = 112] = "THEAD";
TAG_ID[TAG_ID["TITLE"] = 113] = "TITLE";
TAG_ID[TAG_ID["TR"] = 114] = "TR";
TAG_ID[TAG_ID["TRACK"] = 115] = "TRACK";
TAG_ID[TAG_ID["TT"] = 116] = "TT";
TAG_ID[TAG_ID["U"] = 117] = "U";
TAG_ID[TAG_ID["UL"] = 118] = "UL";
TAG_ID[TAG_ID["SVG"] = 119] = "SVG";
TAG_ID[TAG_ID["VAR"] = 120] = "VAR";
TAG_ID[TAG_ID["WBR"] = 121] = "WBR";
TAG_ID[TAG_ID["XMP"] = 122] = "XMP";
})(TAG_ID$1 || (TAG_ID$1 = {}));
var TAG_NAME_TO_ID$1 = new map$b([[TAG_NAMES$1.A, TAG_ID$1.A], [TAG_NAMES$1.ADDRESS, TAG_ID$1.ADDRESS], [TAG_NAMES$1.ANNOTATION_XML, TAG_ID$1.ANNOTATION_XML], [TAG_NAMES$1.APPLET, TAG_ID$1.APPLET], [TAG_NAMES$1.AREA, TAG_ID$1.AREA], [TAG_NAMES$1.ARTICLE, TAG_ID$1.ARTICLE], [TAG_NAMES$1.ASIDE, TAG_ID$1.ASIDE], [TAG_NAMES$1.B, TAG_ID$1.B], [TAG_NAMES$1.BASE, TAG_ID$1.BASE], [TAG_NAMES$1.BASEFONT, TAG_ID$1.BASEFONT], [TAG_NAMES$1.BGSOUND, TAG_ID$1.BGSOUND], [TAG_NAMES$1.BIG, TAG_ID$1.BIG], [TAG_NAMES$1.BLOCKQUOTE, TAG_ID$1.BLOCKQUOTE], [TAG_NAMES$1.BODY, TAG_ID$1.BODY], [TAG_NAMES$1.BR, TAG_ID$1.BR], [TAG_NAMES$1.BUTTON, TAG_ID$1.BUTTON], [TAG_NAMES$1.CAPTION, TAG_ID$1.CAPTION], [TAG_NAMES$1.CENTER, TAG_ID$1.CENTER], [TAG_NAMES$1.CODE, TAG_ID$1.CODE], [TAG_NAMES$1.COL, TAG_ID$1.COL], [TAG_NAMES$1.COLGROUP, TAG_ID$1.COLGROUP], [TAG_NAMES$1.DD, TAG_ID$1.DD], [TAG_NAMES$1.DESC, TAG_ID$1.DESC], [TAG_NAMES$1.DETAILS, TAG_ID$1.DETAILS], [TAG_NAMES$1.DIALOG, TAG_ID$1.DIALOG], [TAG_NAMES$1.DIR, TAG_ID$1.DIR], [TAG_NAMES$1.DIV, TAG_ID$1.DIV], [TAG_NAMES$1.DL, TAG_ID$1.DL], [TAG_NAMES$1.DT, TAG_ID$1.DT], [TAG_NAMES$1.EM, TAG_ID$1.EM], [TAG_NAMES$1.EMBED, TAG_ID$1.EMBED], [TAG_NAMES$1.FIELDSET, TAG_ID$1.FIELDSET], [TAG_NAMES$1.FIGCAPTION, TAG_ID$1.FIGCAPTION], [TAG_NAMES$1.FIGURE, TAG_ID$1.FIGURE], [TAG_NAMES$1.FONT, TAG_ID$1.FONT], [TAG_NAMES$1.FOOTER, TAG_ID$1.FOOTER], [TAG_NAMES$1.FOREIGN_OBJECT, TAG_ID$1.FOREIGN_OBJECT], [TAG_NAMES$1.FORM, TAG_ID$1.FORM], [TAG_NAMES$1.FRAME, TAG_ID$1.FRAME], [TAG_NAMES$1.FRAMESET, TAG_ID$1.FRAMESET], [TAG_NAMES$1.H1, TAG_ID$1.H1], [TAG_NAMES$1.H2, TAG_ID$1.H2], [TAG_NAMES$1.H3, TAG_ID$1.H3], [TAG_NAMES$1.H4, TAG_ID$1.H4], [TAG_NAMES$1.H5, TAG_ID$1.H5], [TAG_NAMES$1.H6, TAG_ID$1.H6], [TAG_NAMES$1.HEAD, TAG_ID$1.HEAD], [TAG_NAMES$1.HEADER, TAG_ID$1.HEADER], [TAG_NAMES$1.HGROUP, TAG_ID$1.HGROUP], [TAG_NAMES$1.HR, TAG_ID$1.HR], [TAG_NAMES$1.HTML, TAG_ID$1.HTML], [TAG_NAMES$1.I, TAG_ID$1.I], [TAG_NAMES$1.IMG, TAG_ID$1.IMG], [TAG_NAMES$1.IMAGE, TAG_ID$1.IMAGE], [TAG_NAMES$1.INPUT, TAG_ID$1.INPUT], [TAG_NAMES$1.IFRAME, TAG_ID$1.IFRAME], [TAG_NAMES$1.KEYGEN, TAG_ID$1.KEYGEN], [TAG_NAMES$1.LABEL, TAG_ID$1.LABEL], [TAG_NAMES$1.LI, TAG_ID$1.LI], [TAG_NAMES$1.LINK, TAG_ID$1.LINK], [TAG_NAMES$1.LISTING, TAG_ID$1.LISTING], [TAG_NAMES$1.MAIN, TAG_ID$1.MAIN], [TAG_NAMES$1.MALIGNMARK, TAG_ID$1.MALIGNMARK], [TAG_NAMES$1.MARQUEE, TAG_ID$1.MARQUEE], [TAG_NAMES$1.MATH, TAG_ID$1.MATH], [TAG_NAMES$1.MENU, TAG_ID$1.MENU], [TAG_NAMES$1.META, TAG_ID$1.META], [TAG_NAMES$1.MGLYPH, TAG_ID$1.MGLYPH], [TAG_NAMES$1.MI, TAG_ID$1.MI], [TAG_NAMES$1.MO, TAG_ID$1.MO], [TAG_NAMES$1.MN, TAG_ID$1.MN], [TAG_NAMES$1.MS, TAG_ID$1.MS], [TAG_NAMES$1.MTEXT, TAG_ID$1.MTEXT], [TAG_NAMES$1.NAV, TAG_ID$1.NAV], [TAG_NAMES$1.NOBR, TAG_ID$1.NOBR], [TAG_NAMES$1.NOFRAMES, TAG_ID$1.NOFRAMES], [TAG_NAMES$1.NOEMBED, TAG_ID$1.NOEMBED], [TAG_NAMES$1.NOSCRIPT, TAG_ID$1.NOSCRIPT], [TAG_NAMES$1.OBJECT, TAG_ID$1.OBJECT], [TAG_NAMES$1.OL, TAG_ID$1.OL], [TAG_NAMES$1.OPTGROUP, TAG_ID$1.OPTGROUP], [TAG_NAMES$1.OPTION, TAG_ID$1.OPTION], [TAG_NAMES$1.P, TAG_ID$1.P], [TAG_NAMES$1.PARAM, TAG_ID$1.PARAM], [TAG_NAMES$1.PLAINTEXT, TAG_ID$1.PLAINTEXT], [TAG_NAMES$1.PRE, TAG_ID$1.PRE], [TAG_NAMES$1.RB, TAG_ID$1.RB], [TAG_NAMES$1.RP, TAG_ID$1.RP], [TAG_NAMES$1.RT, TAG_ID$1.RT], [TAG_NAMES$1.RTC, TAG_ID$1.RTC], [TAG_NAMES$1.RUBY, TAG_ID$1.RUBY], [TAG_NAMES$1.S, TAG_ID$1.S], [TAG_NAMES$1.SCRIPT, TAG_ID$1.SCRIPT], [TAG_NAMES$1.SECTION, TAG_ID$1.SECTION], [TAG_NAMES$1.SELECT, TAG_ID$1.SELECT], [TAG_NAMES$1.SOURCE, TAG_ID$1.SOURCE], [TAG_NAMES$1.SMALL, TAG_ID$1.SMALL], [TAG_NAMES$1.SPAN, TAG_ID$1.SPAN], [TAG_NAMES$1.STRIKE, TAG_ID$1.STRIKE], [TAG_NAMES$1.STRONG, TAG_ID$1.STRONG], [TAG_NAMES$1.STYLE, TAG_ID$1.STYLE], [TAG_NAMES$1.SUB, TAG_ID$1.SUB], [TAG_NAMES$1.SUMMARY, TAG_ID$1.SUMMARY], [TAG_NAMES$1.SUP, TAG_ID$1.SUP], [TAG_NAMES$1.TABLE, TAG_ID$1.TABLE], [TAG_NAMES$1.TBODY, TAG_ID$1.TBODY], [TAG_NAMES$1.TEMPLATE, TAG_ID$1.TEMPLATE], [TAG_NAMES$1.TEXTAREA, TAG_ID$1.TEXTAREA], [TAG_NAMES$1.TFOOT, TAG_ID$1.TFOOT], [TAG_NAMES$1.TD, TAG_ID$1.TD], [TAG_NAMES$1.TH, TAG_ID$1.TH], [TAG_NAMES$1.THEAD, TAG_ID$1.THEAD], [TAG_NAMES$1.TITLE, TAG_ID$1.TITLE], [TAG_NAMES$1.TR, TAG_ID$1.TR], [TAG_NAMES$1.TRACK, TAG_ID$1.TRACK], [TAG_NAMES$1.TT, TAG_ID$1.TT], [TAG_NAMES$1.U, TAG_ID$1.U], [TAG_NAMES$1.UL, TAG_ID$1.UL], [TAG_NAMES$1.SVG, TAG_ID$1.SVG], [TAG_NAMES$1.VAR, TAG_ID$1.VAR], [TAG_NAMES$1.WBR, TAG_ID$1.WBR], [TAG_NAMES$1.XMP, TAG_ID$1.XMP]]);
var $$1 = TAG_ID$1;
var SPECIAL_ELEMENTS$1 = (_SPECIAL_ELEMENTS = {}, _defineProperty(_SPECIAL_ELEMENTS, NS$1.HTML, new set$4([$$1.ADDRESS, $$1.APPLET, $$1.AREA, $$1.ARTICLE, $$1.ASIDE, $$1.BASE, $$1.BASEFONT, $$1.BGSOUND, $$1.BLOCKQUOTE, $$1.BODY, $$1.BR, $$1.BUTTON, $$1.CAPTION, $$1.CENTER, $$1.COL, $$1.COLGROUP, $$1.DD, $$1.DETAILS, $$1.DIR, $$1.DIV, $$1.DL, $$1.DT, $$1.EMBED, $$1.FIELDSET, $$1.FIGCAPTION, $$1.FIGURE, $$1.FOOTER, $$1.FORM, $$1.FRAME, $$1.FRAMESET, $$1.H1, $$1.H2, $$1.H3, $$1.H4, $$1.H5, $$1.H6, $$1.HEAD, $$1.HEADER, $$1.HGROUP, $$1.HR, $$1.HTML, $$1.IFRAME, $$1.IMG, $$1.INPUT, $$1.LI, $$1.LINK, $$1.LISTING, $$1.MAIN, $$1.MARQUEE, $$1.MENU, $$1.META, $$1.NAV, $$1.NOEMBED, $$1.NOFRAMES, $$1.NOSCRIPT, $$1.OBJECT, $$1.OL, $$1.P, $$1.PARAM, $$1.PLAINTEXT, $$1.PRE, $$1.SCRIPT, $$1.SECTION, $$1.SELECT, $$1.SOURCE, $$1.STYLE, $$1.SUMMARY, $$1.TABLE, $$1.TBODY, $$1.TD, $$1.TEMPLATE, $$1.TEXTAREA, $$1.TFOOT, $$1.TH, $$1.THEAD, $$1.TITLE, $$1.TR, $$1.TRACK, $$1.UL, $$1.WBR, $$1.XMP])), _defineProperty(_SPECIAL_ELEMENTS, NS$1.MATHML, new set$4([$$1.MI, $$1.MO, $$1.MN, $$1.MS, $$1.MTEXT, $$1.ANNOTATION_XML])), _defineProperty(_SPECIAL_ELEMENTS, NS$1.SVG, new set$4([$$1.TITLE, $$1.FOREIGN_OBJECT, $$1.DESC])), _defineProperty(_SPECIAL_ELEMENTS, NS$1.XLINK, new set$4()), _defineProperty(_SPECIAL_ELEMENTS, NS$1.XML, new set$4()), _defineProperty(_SPECIAL_ELEMENTS, NS$1.XMLNS, new set$4()), _SPECIAL_ELEMENTS);
var UNESCAPED_TEXT$1 = new set$4([TAG_NAMES$1.STYLE, TAG_NAMES$1.SCRIPT, TAG_NAMES$1.XMP, TAG_NAMES$1.IFRAME, TAG_NAMES$1.NOEMBED, TAG_NAMES$1.NOFRAMES, TAG_NAMES$1.PLAINTEXT]);
var C1_CONTROLS_REFERENCE_REPLACEMENTS$1 = new map$b([[0x80, 8364], [0x82, 8218], [0x83, 402], [0x84, 8222], [0x85, 8230], [0x86, 8224], [0x87, 8225], [0x88, 710], [0x89, 8240], [0x8a, 352], [0x8b, 8249], [0x8c, 338], [0x8e, 381], [0x91, 8216], [0x92, 8217], [0x93, 8220], [0x94, 8221], [0x95, 8226], [0x96, 8211], [0x97, 8212], [0x98, 732], [0x99, 8482], [0x9a, 353], [0x9b, 8250], [0x9c, 339], [0x9e, 382], [0x9f, 376]]); //States
var State$1;
(function (State) {
State[State["DATA"] = 0] = "DATA";
State[State["RCDATA"] = 1] = "RCDATA";
State[State["RAWTEXT"] = 2] = "RAWTEXT";
State[State["SCRIPT_DATA"] = 3] = "SCRIPT_DATA";
State[State["PLAINTEXT"] = 4] = "PLAINTEXT";
State[State["TAG_OPEN"] = 5] = "TAG_OPEN";
State[State["END_TAG_OPEN"] = 6] = "END_TAG_OPEN";
State[State["TAG_NAME"] = 7] = "TAG_NAME";
State[State["RCDATA_LESS_THAN_SIGN"] = 8] = "RCDATA_LESS_THAN_SIGN";
State[State["RCDATA_END_TAG_OPEN"] = 9] = "RCDATA_END_TAG_OPEN";
State[State["RCDATA_END_TAG_NAME"] = 10] = "RCDATA_END_TAG_NAME";
State[State["RAWTEXT_LESS_THAN_SIGN"] = 11] = "RAWTEXT_LESS_THAN_SIGN";
State[State["RAWTEXT_END_TAG_OPEN"] = 12] = "RAWTEXT_END_TAG_OPEN";
State[State["RAWTEXT_END_TAG_NAME"] = 13] = "RAWTEXT_END_TAG_NAME";
State[State["SCRIPT_DATA_LESS_THAN_SIGN"] = 14] = "SCRIPT_DATA_LESS_THAN_SIGN";
State[State["SCRIPT_DATA_END_TAG_OPEN"] = 15] = "SCRIPT_DATA_END_TAG_OPEN";
State[State["SCRIPT_DATA_END_TAG_NAME"] = 16] = "SCRIPT_DATA_END_TAG_NAME";
State[State["SCRIPT_DATA_ESCAPE_START"] = 17] = "SCRIPT_DATA_ESCAPE_START";
State[State["SCRIPT_DATA_ESCAPE_START_DASH"] = 18] = "SCRIPT_DATA_ESCAPE_START_DASH";
State[State["SCRIPT_DATA_ESCAPED"] = 19] = "SCRIPT_DATA_ESCAPED";
State[State["SCRIPT_DATA_ESCAPED_DASH"] = 20] = "SCRIPT_DATA_ESCAPED_DASH";
State[State["SCRIPT_DATA_ESCAPED_DASH_DASH"] = 21] = "SCRIPT_DATA_ESCAPED_DASH_DASH";
State[State["SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN"] = 22] = "SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN";
State[State["SCRIPT_DATA_ESCAPED_END_TAG_OPEN"] = 23] = "SCRIPT_DATA_ESCAPED_END_TAG_OPEN";
State[State["SCRIPT_DATA_ESCAPED_END_TAG_NAME"] = 24] = "SCRIPT_DATA_ESCAPED_END_TAG_NAME";
State[State["SCRIPT_DATA_DOUBLE_ESCAPE_START"] = 25] = "SCRIPT_DATA_DOUBLE_ESCAPE_START";
State[State["SCRIPT_DATA_DOUBLE_ESCAPED"] = 26] = "SCRIPT_DATA_DOUBLE_ESCAPED";
State[State["SCRIPT_DATA_DOUBLE_ESCAPED_DASH"] = 27] = "SCRIPT_DATA_DOUBLE_ESCAPED_DASH";
State[State["SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH"] = 28] = "SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH";
State[State["SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN"] = 29] = "SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN";
State[State["SCRIPT_DATA_DOUBLE_ESCAPE_END"] = 30] = "SCRIPT_DATA_DOUBLE_ESCAPE_END";
State[State["BEFORE_ATTRIBUTE_NAME"] = 31] = "BEFORE_ATTRIBUTE_NAME";
State[State["ATTRIBUTE_NAME"] = 32] = "ATTRIBUTE_NAME";
State[State["AFTER_ATTRIBUTE_NAME"] = 33] = "AFTER_ATTRIBUTE_NAME";
State[State["BEFORE_ATTRIBUTE_VALUE"] = 34] = "BEFORE_ATTRIBUTE_VALUE";
State[State["ATTRIBUTE_VALUE_DOUBLE_QUOTED"] = 35] = "ATTRIBUTE_VALUE_DOUBLE_QUOTED";
State[State["ATTRIBUTE_VALUE_SINGLE_QUOTED"] = 36] = "ATTRIBUTE_VALUE_SINGLE_QUOTED";
State[State["ATTRIBUTE_VALUE_UNQUOTED"] = 37] = "ATTRIBUTE_VALUE_UNQUOTED";
State[State["AFTER_ATTRIBUTE_VALUE_QUOTED"] = 38] = "AFTER_ATTRIBUTE_VALUE_QUOTED";
State[State["SELF_CLOSING_START_TAG"] = 39] = "SELF_CLOSING_START_TAG";
State[State["BOGUS_COMMENT"] = 40] = "BOGUS_COMMENT";
State[State["MARKUP_DECLARATION_OPEN"] = 41] = "MARKUP_DECLARATION_OPEN";
State[State["COMMENT_START"] = 42] = "COMMENT_START";
State[State["COMMENT_START_DASH"] = 43] = "COMMENT_START_DASH";
State[State["COMMENT"] = 44] = "COMMENT";
State[State["COMMENT_LESS_THAN_SIGN"] = 45] = "COMMENT_LESS_THAN_SIGN";
State[State["COMMENT_LESS_THAN_SIGN_BANG"] = 46] = "COMMENT_LESS_THAN_SIGN_BANG";
State[State["COMMENT_LESS_THAN_SIGN_BANG_DASH"] = 47] = "COMMENT_LESS_THAN_SIGN_BANG_DASH";
State[State["COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH"] = 48] = "COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH";
State[State["COMMENT_END_DASH"] = 49] = "COMMENT_END_DASH";
State[State["COMMENT_END"] = 50] = "COMMENT_END";
State[State["COMMENT_END_BANG"] = 51] = "COMMENT_END_BANG";
State[State["DOCTYPE"] = 52] = "DOCTYPE";
State[State["BEFORE_DOCTYPE_NAME"] = 53] = "BEFORE_DOCTYPE_NAME";
State[State["DOCTYPE_NAME"] = 54] = "DOCTYPE_NAME";
State[State["AFTER_DOCTYPE_NAME"] = 55] = "AFTER_DOCTYPE_NAME";
State[State["AFTER_DOCTYPE_PUBLIC_KEYWORD"] = 56] = "AFTER_DOCTYPE_PUBLIC_KEYWORD";
State[State["BEFORE_DOCTYPE_PUBLIC_IDENTIFIER"] = 57] = "BEFORE_DOCTYPE_PUBLIC_IDENTIFIER";
State[State["DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED"] = 58] = "DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED";
State[State["DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED"] = 59] = "DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED";
State[State["AFTER_DOCTYPE_PUBLIC_IDENTIFIER"] = 60] = "AFTER_DOCTYPE_PUBLIC_IDENTIFIER";
State[State["BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS"] = 61] = "BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS";
State[State["AFTER_DOCTYPE_SYSTEM_KEYWORD"] = 62] = "AFTER_DOCTYPE_SYSTEM_KEYWORD";
State[State["BEFORE_DOCTYPE_SYSTEM_IDENTIFIER"] = 63] = "BEFORE_DOCTYPE_SYSTEM_IDENTIFIER";
State[State["DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED"] = 64] = "DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED";
State[State["DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED"] = 65] = "DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED";
State[State["AFTER_DOCTYPE_SYSTEM_IDENTIFIER"] = 66] = "AFTER_DOCTYPE_SYSTEM_IDENTIFIER";
State[State["BOGUS_DOCTYPE"] = 67] = "BOGUS_DOCTYPE";
State[State["CDATA_SECTION"] = 68] = "CDATA_SECTION";
State[State["CDATA_SECTION_BRACKET"] = 69] = "CDATA_SECTION_BRACKET";
State[State["CDATA_SECTION_END"] = 70] = "CDATA_SECTION_END";
State[State["CHARACTER_REFERENCE"] = 71] = "CHARACTER_REFERENCE";
State[State["NAMED_CHARACTER_REFERENCE"] = 72] = "NAMED_CHARACTER_REFERENCE";
State[State["AMBIGUOUS_AMPERSAND"] = 73] = "AMBIGUOUS_AMPERSAND";
State[State["NUMERIC_CHARACTER_REFERENCE"] = 74] = "NUMERIC_CHARACTER_REFERENCE";
State[State["HEXADEMICAL_CHARACTER_REFERENCE_START"] = 75] = "HEXADEMICAL_CHARACTER_REFERENCE_START";
State[State["DECIMAL_CHARACTER_REFERENCE_START"] = 76] = "DECIMAL_CHARACTER_REFERENCE_START";
State[State["HEXADEMICAL_CHARACTER_REFERENCE"] = 77] = "HEXADEMICAL_CHARACTER_REFERENCE";
State[State["DECIMAL_CHARACTER_REFERENCE"] = 78] = "DECIMAL_CHARACTER_REFERENCE";
State[State["NUMERIC_CHARACTER_REFERENCE_END"] = 79] = "NUMERIC_CHARACTER_REFERENCE_END";
})(State$1 || (State$1 = {})); //Tokenizer initial states for different modes
var TokenizerMode$1 = {
DATA: State$1.DATA,
RCDATA: State$1.RCDATA,
RAWTEXT: State$1.RAWTEXT,
SCRIPT_DATA: State$1.SCRIPT_DATA,
PLAINTEXT: State$1.PLAINTEXT,
CDATA_SECTION: State$1.CDATA_SECTION
}; //Utils
var _context$1;
var IMPLICIT_END_TAG_REQUIRED$1 = new set$4([TAG_ID$1.DD, TAG_ID$1.DT, TAG_ID$1.LI, TAG_ID$1.OPTGROUP, TAG_ID$1.OPTION, TAG_ID$1.P, TAG_ID$1.RB, TAG_ID$1.RP, TAG_ID$1.RT, TAG_ID$1.RTC]);
var IMPLICIT_END_TAG_REQUIRED_THOROUGHLY$1 = new set$4(concat$5(_context$1 = []).call(_context$1, _toConsumableArray(IMPLICIT_END_TAG_REQUIRED$1), [TAG_ID$1.CAPTION, TAG_ID$1.COLGROUP, TAG_ID$1.TBODY, TAG_ID$1.TD, TAG_ID$1.TFOOT, TAG_ID$1.TH, TAG_ID$1.THEAD, TAG_ID$1.TR]));
var SCOPING_ELEMENT_NS$1 = new map$b([[TAG_ID$1.APPLET, NS$1.HTML], [TAG_ID$1.CAPTION, NS$1.HTML], [TAG_ID$1.HTML, NS$1.HTML], [TAG_ID$1.MARQUEE, NS$1.HTML], [TAG_ID$1.OBJECT, NS$1.HTML], [TAG_ID$1.TABLE, NS$1.HTML], [TAG_ID$1.TD, NS$1.HTML], [TAG_ID$1.TEMPLATE, NS$1.HTML], [TAG_ID$1.TH, NS$1.HTML], [TAG_ID$1.ANNOTATION_XML, NS$1.MATHML], [TAG_ID$1.MI, NS$1.MATHML], [TAG_ID$1.MN, NS$1.MATHML], [TAG_ID$1.MO, NS$1.MATHML], [TAG_ID$1.MS, NS$1.MATHML], [TAG_ID$1.MTEXT, NS$1.MATHML], [TAG_ID$1.DESC, NS$1.SVG], [TAG_ID$1.FOREIGN_OBJECT, NS$1.SVG], [TAG_ID$1.TITLE, NS$1.SVG]]);
var NAMED_HEADERS$1 = [TAG_ID$1.H1, TAG_ID$1.H2, TAG_ID$1.H3, TAG_ID$1.H4, TAG_ID$1.H5, TAG_ID$1.H6];
var TABLE_ROW_CONTEXT$1 = [TAG_ID$1.TR, TAG_ID$1.TEMPLATE, TAG_ID$1.HTML];
var TABLE_BODY_CONTEXT$1 = [TAG_ID$1.TBODY, TAG_ID$1.TFOOT, TAG_ID$1.THEAD, TAG_ID$1.TEMPLATE, TAG_ID$1.HTML];
var TABLE_CONTEXT$1 = [TAG_ID$1.TABLE, TAG_ID$1.TEMPLATE, TAG_ID$1.HTML];
var TABLE_CELLS$1 = [TAG_ID$1.TD, TAG_ID$1.TH]; //Stack of open elements
var EntryType$1;
(function (EntryType) {
EntryType[EntryType["Marker"] = 0] = "Marker";
EntryType[EntryType["Element"] = 1] = "Element";
})(EntryType$1 || (EntryType$1 = {}));
var MARKER$1 = {
type: EntryType$1.Marker
}; //List of formatting elements
var NodeType$1;
(function (NodeType) {
NodeType["Document"] = "#document";
NodeType["DocumentFragment"] = "#document-fragment";
NodeType["Comment"] = "#comment";
NodeType["Text"] = "#text";
NodeType["DocumentType"] = "#documentType";
})(NodeType$1 || (NodeType$1 = {}));
var _context$2, _context2$1;
var QUIRKS_MODE_PUBLIC_ID_PREFIXES$1 = ['+//silmaril//dtd html pro v0r11 19970101//', '-//as//dtd html 3.0 aswedit + extensions//', '-//advasoft ltd//dtd html 3.0 aswedit + extensions//', '-//ietf//dtd html 2.0 level 1//', '-//ietf//dtd html 2.0 level 2//', '-//ietf//dtd html 2.0 strict level 1//', '-//ietf//dtd html 2.0 strict level 2//', '-//ietf//dtd html 2.0 strict//', '-//ietf//dtd html 2.0//', '-//ietf//dtd html 2.1e//', '-//ietf//dtd html 3.0//', '-//ietf//dtd html 3.2 final//', '-//ietf//dtd html 3.2//', '-//ietf//dtd html 3//', '-//ietf//dtd html level 0//', '-//ietf//dtd html level 1//', '-//ietf//dtd html level 2//', '-//ietf//dtd html level 3//', '-//ietf//dtd html strict level 0//', '-//ietf//dtd html strict level 1//', '-//ietf//dtd html strict level 2//', '-//ietf//dtd html strict level 3//', '-//ietf//dtd html strict//', '-//ietf//dtd html//', '-//metrius//dtd metrius presentational//', '-//microsoft//dtd internet explorer 2.0 html strict//', '-//microsoft//dtd internet explorer 2.0 html//', '-//microsoft//dtd internet explorer 2.0 tables//', '-//microsoft//dtd internet explorer 3.0 html strict//', '-//microsoft//dtd internet explorer 3.0 html//', '-//microsoft//dtd internet explorer 3.0 tables//', '-//netscape comm. corp.//dtd html//', '-//netscape comm. corp.//dtd strict html//', "-//o'reilly and associates//dtd html 2.0//", "-//o'reilly and associates//dtd html extended 1.0//", "-//o'reilly and associates//dtd html extended relaxed 1.0//", '-//sq//dtd html 2.0 hotmetal + extensions//', '-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//', '-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//', '-//spyglass//dtd html 2.0 extended//', '-//sun microsystems corp.//dtd hotjava html//', '-//sun microsystems corp.//dtd hotjava strict html//', '-//w3c//dtd html 3 1995-03-24//', '-//w3c//dtd html 3.2 draft//', '-//w3c//dtd html 3.2 final//', '-//w3c//dtd html 3.2//', '-//w3c//dtd html 3.2s draft//', '-//w3c//dtd html 4.0 frameset//', '-//w3c//dtd html 4.0 transitional//', '-//w3c//dtd html experimental 19960712//', '-//w3c//dtd html experimental 970421//', '-//w3c//dtd w3 html//', '-//w3o//dtd w3 html 3.0//', '-//webtechs//dtd mozilla html 2.0//', '-//webtechs//dtd mozilla html//'];
var QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES$1 = concat$5(_context$2 = []).call(_context$2, QUIRKS_MODE_PUBLIC_ID_PREFIXES$1, ['-//w3c//dtd html 4.01 frameset//', '-//w3c//dtd html 4.01 transitional//']);
var QUIRKS_MODE_PUBLIC_IDS$1 = new set$4(['-//w3o//dtd w3 html strict 3.0//en//', '-/w3c/dtd html 4.0 transitional/en', 'html']);
var LIMITED_QUIRKS_PUBLIC_ID_PREFIXES$1 = ['-//w3c//dtd xhtml 1.0 frameset//', '-//w3c//dtd xhtml 1.0 transitional//'];
var LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES$1 = concat$5(_context2$1 = []).call(_context2$1, LIMITED_QUIRKS_PUBLIC_ID_PREFIXES$1, ['-//w3c//dtd html 4.01 frameset//', '-//w3c//dtd html 4.01 transitional//']); //Utils
var _context$3, _context2$2;
var SVG_ATTRS_ADJUSTMENT_MAP$1 = new map$b(map$3(_context$3 = ['attributeName', 'attributeType', 'baseFrequency', 'baseProfile', 'calcMode', 'clipPathUnits', 'diffuseConstant', 'edgeMode', 'filterUnits', 'glyphRef', 'gradientTransform', 'gradientUnits', 'kernelMatrix', 'kernelUnitLength', 'keyPoints', 'keySplines', 'keyTimes', 'lengthAdjust', 'limitingConeAngle', 'markerHeight', 'markerUnits', 'markerWidth', 'maskContentUnits', 'maskUnits', 'numOctaves', 'pathLength', 'patternContentUnits', 'patternTransform', 'patternUnits', 'pointsAtX', 'pointsAtY', 'pointsAtZ', 'preserveAlpha', 'preserveAspectRatio', 'primitiveUnits', 'refX', 'refY', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'specularConstant', 'specularExponent', 'spreadMethod', 'startOffset', 'stdDeviation', 'stitchTiles', 'surfaceScale', 'systemLanguage', 'tableValues', 'targetX', 'targetY', 'textLength', 'viewBox', 'viewTarget', 'xChannelSelector', 'yChannelSelector', 'zoomAndPan']).call(_context$3, function (attr) {
return [attr.toLowerCase(), attr];
}));
var XML_ATTRS_ADJUSTMENT_MAP$1 = new map$b([['xlink:actuate', {
prefix: 'xlink',
name: 'actuate',
namespace: NS$1.XLINK
}], ['xlink:arcrole', {
prefix: 'xlink',
name: 'arcrole',
namespace: NS$1.XLINK
}], ['xlink:href', {
prefix: 'xlink',
name: 'href',
namespace: NS$1.XLINK
}], ['xlink:role', {
prefix: 'xlink',
name: 'role',
namespace: NS$1.XLINK
}], ['xlink:show', {
prefix: 'xlink',
name: 'show',
namespace: NS$1.XLINK
}], ['xlink:title', {
prefix: 'xlink',
name: 'title',
namespace: NS$1.XLINK
}], ['xlink:type', {
prefix: 'xlink',
name: 'type',
namespace: NS$1.XLINK
}], ['xml:base', {
prefix: 'xml',
name: 'base',
namespace: NS$1.XML
}], ['xml:lang', {
prefix: 'xml',
name: 'lang',
namespace: NS$1.XML
}], ['xml:space', {
prefix: 'xml',
name: 'space',
namespace: NS$1.XML
}], ['xmlns', {
prefix: '',
name: 'xmlns',
namespace: NS$1.XMLNS
}], ['xmlns:xlink', {
prefix: 'xmlns',
name: 'xlink',
namespace: NS$1.XMLNS
}]]); //SVG tag names adjustment map
var SVG_TAG_NAMES_ADJUSTMENT_MAP$1 = new map$b(map$3(_context2$2 = ['altGlyph', 'altGlyphDef', 'altGlyphItem', 'animateColor', 'animateMotion', 'animateTransform', 'clipPath', 'feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence', 'foreignObject', 'glyphRef', 'linearGradient', 'radialGradient', 'textPath']).call(_context2$2, function (tn) {
return [tn.toLowerCase(), tn];
})); //Tags that causes exit from foreign content
var EXITS_FOREIGN_CONTENT$1 = new set$4([TAG_ID$1.B, TAG_ID$1.BIG, TAG_ID$1.BLOCKQUOTE, TAG_ID$1.BODY, TAG_ID$1.BR, TAG_ID$1.CENTER, TAG_ID$1.CODE, TAG_ID$1.DD, TAG_ID$1.DIV, TAG_ID$1.DL, TAG_ID$1.DT, TAG_ID$1.EM, TAG_ID$1.EMBED, TAG_ID$1.H1, TAG_ID$1.H2, TAG_ID$1.H3, TAG_ID$1.H4, TAG_ID$1.H5, TAG_ID$1.H6, TAG_ID$1.HEAD, TAG_ID$1.HR, TAG_ID$1.I, TAG_ID$1.IMG, TAG_ID$1.LI, TAG_ID$1.LISTING, TAG_ID$1.MENU, TAG_ID$1.META, TAG_ID$1.NOBR, TAG_ID$1.OL, TAG_ID$1.P, TAG_ID$1.PRE, TAG_ID$1.RUBY, TAG_ID$1.S, TAG_ID$1.SMALL, TAG_ID$1.SPAN, TAG_ID$1.STRONG, TAG_ID$1.STRIKE, TAG_ID$1.SUB, TAG_ID$1.SUP, TAG_ID$1.TABLE, TAG_ID$1.TT, TAG_ID$1.U, TAG_ID$1.UL, TAG_ID$1.VAR]); //Check exit from foreign content
var InsertionMode$1;
(function (InsertionMode) {
InsertionMode[InsertionMode["INITIAL"] = 0] = "INITIAL";
InsertionMode[InsertionMode["BEFORE_HTML"] = 1] = "BEFORE_HTML";
InsertionMode[InsertionMode["BEFORE_HEAD"] = 2] = "BEFORE_HEAD";
InsertionMode[InsertionMode["IN_HEAD"] = 3] = "IN_HEAD";
InsertionMode[InsertionMode["IN_HEAD_NO_SCRIPT"] = 4] = "IN_HEAD_NO_SCRIPT";
InsertionMode[InsertionMode["AFTER_HEAD"] = 5] = "AFTER_HEAD";
InsertionMode[InsertionMode["IN_BODY"] = 6] = "IN_BODY";
InsertionMode[InsertionMode["TEXT"] = 7] = "TEXT";
InsertionMode[InsertionMode["IN_TABLE"] = 8] = "IN_TABLE";
InsertionMode[InsertionMode["IN_TABLE_TEXT"] = 9] = "IN_TABLE_TEXT";
InsertionMode[InsertionMode["IN_CAPTION"] = 10] = "IN_CAPTION";
InsertionMode[InsertionMode["IN_COLUMN_GROUP"] = 11] = "IN_COLUMN_GROUP";
InsertionMode[InsertionMode["IN_TABLE_BODY"] = 12] = "IN_TABLE_BODY";
InsertionMode[InsertionMode["IN_ROW"] = 13] = "IN_ROW";
InsertionMode[InsertionMode["IN_CELL"] = 14] = "IN_CELL";
InsertionMode[InsertionMode["IN_SELECT"] = 15] = "IN_SELECT";
InsertionMode[InsertionMode["IN_SELECT_IN_TABLE"] = 16] = "IN_SELECT_IN_TABLE";
InsertionMode[InsertionMode["IN_TEMPLATE"] = 17] = "IN_TEMPLATE";
InsertionMode[InsertionMode["AFTER_BODY"] = 18] = "AFTER_BODY";
InsertionMode[InsertionMode["IN_FRAMESET"] = 19] = "IN_FRAMESET";
InsertionMode[InsertionMode["AFTER_FRAMESET"] = 20] = "AFTER_FRAMESET";
InsertionMode[InsertionMode["AFTER_AFTER_BODY"] = 21] = "AFTER_AFTER_BODY";
InsertionMode[InsertionMode["AFTER_AFTER_FRAMESET"] = 22] = "AFTER_AFTER_FRAMESET";
})(InsertionMode$1 || (InsertionMode$1 = {}));
var TABLE_STRUCTURE_TAGS$1 = new set$4([TAG_ID$1.TABLE, TAG_ID$1.TBODY, TAG_ID$1.TFOOT, TAG_ID$1.THEAD, TAG_ID$1.TR]);
//------------------------------------------------------------------
var TABLE_VOID_ELEMENTS$1 = new set$4([TAG_ID$1.CAPTION, TAG_ID$1.COL, TAG_ID$1.COLGROUP, TAG_ID$1.TBODY, TAG_ID$1.TD, TAG_ID$1.TFOOT, TAG_ID$1.TH, TAG_ID$1.THEAD, TAG_ID$1.TR]);
var VOID_ELEMENTS$1 = new set$4([TAG_NAMES$1.AREA, TAG_NAMES$1.BASE, TAG_NAMES$1.BASEFONT, TAG_NAMES$1.BGSOUND, TAG_NAMES$1.BR, TAG_NAMES$1.COL, TAG_NAMES$1.EMBED, TAG_NAMES$1.FRAME, TAG_NAMES$1.HR, TAG_NAMES$1.IMG, TAG_NAMES$1.INPUT, TAG_NAMES$1.KEYGEN, TAG_NAMES$1.LINK, TAG_NAMES$1.META, TAG_NAMES$1.PARAM, TAG_NAMES$1.SOURCE, TAG_NAMES$1.TRACK, TAG_NAMES$1.WBR]);
function ownKeys$8(object, enumerableOnly) { var keys = keys$3(object); if (getOwnPropertySymbols$2) { var symbols = getOwnPropertySymbols$2(object); enumerableOnly && (symbols = filter$3(symbols).call(symbols, function (sym) { return getOwnPropertyDescriptor$3(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$7(target) { for (var i = 1; i < arguments.length; i++) { var _context7, _context8; var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? forEach$3(_context7 = ownKeys$8(Object(source), !0)).call(_context7, function (key) { _defineProperty(target, key, source[key]); }) : getOwnPropertyDescriptors$2 ? defineProperties$2(target, getOwnPropertyDescriptors$2(source)) : forEach$3(_context8 = ownKeys$8(Object(source))).call(_context8, function (key) { defineProperty$5(target, key, getOwnPropertyDescriptor$3(source, key)); }); } return target; }
function createTextNode$1(value) {
return new Text$1(value);
}
function enquoteDoctypeId(id) {
var quote = includes$4(id).call(id, '"') ? "'" : '"';
return quote + id + quote;
}
/** @internal */
function serializeDoctypeContent(name, publicId, systemId) {
var str = '!DOCTYPE ';
if (name) {
str += name;
}
if (publicId) {
str += " PUBLIC ".concat(enquoteDoctypeId(publicId));
} else if (systemId) {
str += ' SYSTEM';
}
if (systemId) {
str += " ".concat(enquoteDoctypeId(systemId));
}
return str;
}
var adapter = {
// Re-exports from domhandler
isCommentNode: isComment,
isElementNode: isTag$1,
isTextNode: isText,
//Node construction
createDocument: function createDocument() {
var node = new Document([]);
node['x-mode'] = DOCUMENT_MODE$1.NO_QUIRKS;
return node;
},
createDocumentFragment: function createDocumentFragment() {
return new Document([]);
},
createElement: function createElement(tagName, namespaceURI, attrs) {
var attribs = create$6(null);
var attribsNamespace = create$6(null);
var attribsPrefix = create$6(null);
for (var i = 0; i < attrs.length; i++) {
var attrName = attrs[i].name;
attribs[attrName] = attrs[i].value;
attribsNamespace[attrName] = attrs[i].namespace;
attribsPrefix[attrName] = attrs[i].prefix;
}
var node = new Element(tagName, attribs, []);
node.namespace = namespaceURI;
node['x-attribsNamespace'] = attribsNamespace;
node['x-attribsPrefix'] = attribsPrefix;
return node;
},
createCommentNode: function createCommentNode(data) {
return new Comment$1(data);
},
//Tree mutation
appendChild: function appendChild(parentNode, newNode) {
var prev = parentNode.children[parentNode.children.length - 1];
if (prev) {
prev.next = newNode;
newNode.prev = prev;
}
parentNode.children.push(newNode);
newNode.parent = parentNode;
},
insertBefore: function insertBefore(parentNode, newNode, referenceNode) {
var _context, _context2;
var insertionIdx = indexOf$8(_context = parentNode.children).call(_context, referenceNode);
var prev = referenceNode.prev;
if (prev) {
prev.next = newNode;
newNode.prev = prev;
}
referenceNode.prev = newNode;
newNode.next = referenceNode;
splice$4(_context2 = parentNode.children).call(_context2, insertionIdx, 0, newNode);
newNode.parent = parentNode;
},
setTemplateContent: function setTemplateContent(templateElement, contentElement) {
adapter.appendChild(templateElement, contentElement);
},
getTemplateContent: function getTemplateContent(templateElement) {
return templateElement.children[0];
},
setDocumentType: function setDocumentType(document, name, publicId, systemId) {
var _context3;
var data = serializeDoctypeContent(name, publicId, systemId);
var doctypeNode = find$3(_context3 = document.children).call(_context3, function (node) {
return isDirective(node) && node.name === '!doctype';
});
if (doctypeNode) {
doctypeNode.data = data !== null && data !== void 0 ? data : null;
} else {
doctypeNode = new ProcessingInstruction('!doctype', data);
adapter.appendChild(document, doctypeNode);
}
doctypeNode['x-name'] = name !== null && name !== void 0 ? name : undefined;
doctypeNode['x-publicId'] = publicId !== null && publicId !== void 0 ? publicId : undefined;
doctypeNode['x-systemId'] = systemId !== null && systemId !== void 0 ? systemId : undefined;
},
setDocumentMode: function setDocumentMode(document, mode) {
document['x-mode'] = mode;
},
getDocumentMode: function getDocumentMode(document) {
return document['x-mode'];
},
detachNode: function detachNode(node) {
if (node.parent) {
var _context4, _context5;
var idx = indexOf$8(_context4 = node.parent.children).call(_context4, node);
var prev = node.prev,
next = node.next;
node.prev = null;
node.next = null;
if (prev) {
prev.next = next;
}
if (next) {
next.prev = prev;
}
splice$4(_context5 = node.parent.children).call(_context5, idx, 1);
node.parent = null;
}
},
insertText: function insertText(parentNode, text) {
var lastChild = parentNode.children[parentNode.children.length - 1];
if (lastChild && isText(lastChild)) {
lastChild.data += text;
} else {
adapter.appendChild(parentNode, createTextNode$1(text));
}
},
insertTextBefore: function insertTextBefore(parentNode, text, referenceNode) {
var _context6;
var prevNode = parentNode.children[indexOf$8(_context6 = parentNode.children).call(_context6, referenceNode) - 1];
if (prevNode && isText(prevNode)) {
prevNode.data += text;
} else {
adapter.insertBefore(parentNode, createTextNode$1(text), referenceNode);
}
},
adoptAttributes: function adoptAttributes(recipient, attrs) {
for (var i = 0; i < attrs.length; i++) {
var attrName = attrs[i].name;
if (typeof recipient.attribs[attrName] === 'undefined') {
recipient.attribs[attrName] = attrs[i].value;
recipient['x-attribsNamespace'][attrName] = attrs[i].namespace;
recipient['x-attribsPrefix'][attrName] = attrs[i].prefix;
}
}
},
//Tree traversing
getFirstChild: function getFirstChild(node) {
return node.children[0];
},
getChildNodes: function getChildNodes(node) {
return node.children;
},
getParentNode: function getParentNode(node) {
return node.parent;
},
getAttrList: function getAttrList(element) {
return element.attributes;
},
//Node data
getTagName: function getTagName(element) {
return element.name;
},
getNamespaceURI: function getNamespaceURI(element) {
return element.namespace;
},
getTextNodeContent: function getTextNodeContent(textNode) {
return textNode.data;
},
getCommentNodeContent: function getCommentNodeContent(commentNode) {
return commentNode.data;
},
getDocumentTypeNodeName: function getDocumentTypeNodeName(doctypeNode) {
var _a;
return (_a = doctypeNode['x-name']) !== null && _a !== void 0 ? _a : '';
},
getDocumentTypeNodePublicId: function getDocumentTypeNodePublicId(doctypeNode) {
var _a;
return (_a = doctypeNode['x-publicId']) !== null && _a !== void 0 ? _a : '';
},
getDocumentTypeNodeSystemId: function getDocumentTypeNodeSystemId(doctypeNode) {
var _a;
return (_a = doctypeNode['x-systemId']) !== null && _a !== void 0 ? _a : '';
},
//Node types
isDocumentTypeNode: function isDocumentTypeNode(node) {
return isDirective(node) && node.name === '!doctype';
},
// Source code location
setNodeSourceCodeLocation: function setNodeSourceCodeLocation(node, location) {
if (location) {
node.startIndex = location.startOffset;
node.endIndex = location.endOffset;
}
node.sourceCodeLocation = location;
},
getNodeSourceCodeLocation: function getNodeSourceCodeLocation(node) {
return node.sourceCodeLocation;
},
updateNodeSourceCodeLocation: function updateNodeSourceCodeLocation(node, endLocation) {
if (endLocation.endOffset != null) node.endIndex = endLocation.endOffset;
node.sourceCodeLocation = _objectSpread$7(_objectSpread$7({}, node.sourceCodeLocation), endLocation);
}
};
/**
* Parse the content with `parse5` in the context of the given `ParentNode`.
*
* @param content - The content to parse.
* @param options - A set of options to use to parse.
* @param isDocument - Whether to parse the content as a full HTML document.
* @param context - The context in which to parse the content.
* @returns The parsed content.
*/
function parseWithParse5(content, options, isDocument, context) {
const opts = {
scriptingEnabled: typeof options.scriptingEnabled === 'boolean'
? options.scriptingEnabled
: true,
treeAdapter: adapter,
sourceCodeLocationInfo: options.sourceCodeLocationInfo,
};
return isDocument
? parse$3(content, opts)
: parseFragment(context, content, opts);
}
const renderOpts = { treeAdapter: adapter };
/**
* Renders the given DOM tree with `parse5` and returns the result as a string.
*
* @param dom - The DOM tree to render.
* @returns The rendered document.
*/
function renderWithParse5(dom) {
/*
* `dom-serializer` passes over the special "root" node and renders the
* node's children in its place. To mimic this behavior with `parse5`, an
* equivalent operation must be applied to the input array.
*/
const nodes = 'length' in dom ? dom : [dom];
for (let index = 0; index < nodes.length; index += 1) {
const node = nodes[index];
if (isDocument(node)) {
Array.prototype.splice.call(nodes, index, 1, ...node.children);
}
}
let result = '';
for (let index = 0; index < nodes.length; index += 1) {
const node = nodes[index];
result += serializeOuter(node, renderOpts);
}
return result;
}
var CharCodes;
(function (CharCodes) {
CharCodes[CharCodes["Tab"] = 9] = "Tab";
CharCodes[CharCodes["NewLine"] = 10] = "NewLine";
CharCodes[CharCodes["FormFeed"] = 12] = "FormFeed";
CharCodes[CharCodes["CarriageReturn"] = 13] = "CarriageReturn";
CharCodes[CharCodes["Space"] = 32] = "Space";
CharCodes[CharCodes["ExclamationMark"] = 33] = "ExclamationMark";
CharCodes[CharCodes["Num"] = 35] = "Num";
CharCodes[CharCodes["Amp"] = 38] = "Amp";
CharCodes[CharCodes["SingleQuote"] = 39] = "SingleQuote";
CharCodes[CharCodes["DoubleQuote"] = 34] = "DoubleQuote";
CharCodes[CharCodes["Dash"] = 45] = "Dash";
CharCodes[CharCodes["Slash"] = 47] = "Slash";
CharCodes[CharCodes["Zero"] = 48] = "Zero";
CharCodes[CharCodes["Nine"] = 57] = "Nine";
CharCodes[CharCodes["Semi"] = 59] = "Semi";
CharCodes[CharCodes["Lt"] = 60] = "Lt";
CharCodes[CharCodes["Eq"] = 61] = "Eq";
CharCodes[CharCodes["Gt"] = 62] = "Gt";
CharCodes[CharCodes["Questionmark"] = 63] = "Questionmark";
CharCodes[CharCodes["UpperA"] = 65] = "UpperA";
CharCodes[CharCodes["LowerA"] = 97] = "LowerA";
CharCodes[CharCodes["UpperF"] = 70] = "UpperF";
CharCodes[CharCodes["LowerF"] = 102] = "LowerF";
CharCodes[CharCodes["UpperZ"] = 90] = "UpperZ";
CharCodes[CharCodes["LowerZ"] = 122] = "LowerZ";
CharCodes[CharCodes["LowerX"] = 120] = "LowerX";
CharCodes[CharCodes["OpeningSquareBracket"] = 91] = "OpeningSquareBracket";
})(CharCodes || (CharCodes = {}));
/** All the states the tokenizer can be in. */
var State$2;
(function (State) {
State[State["Text"] = 1] = "Text";
State[State["BeforeTagName"] = 2] = "BeforeTagName";
State[State["InTagName"] = 3] = "InTagName";
State[State["InSelfClosingTag"] = 4] = "InSelfClosingTag";
State[State["BeforeClosingTagName"] = 5] = "BeforeClosingTagName";
State[State["InClosingTagName"] = 6] = "InClosingTagName";
State[State["AfterClosingTagName"] = 7] = "AfterClosingTagName";
// Attributes
State[State["BeforeAttributeName"] = 8] = "BeforeAttributeName";
State[State["InAttributeName"] = 9] = "InAttributeName";
State[State["AfterAttributeName"] = 10] = "AfterAttributeName";
State[State["BeforeAttributeValue"] = 11] = "BeforeAttributeValue";
State[State["InAttributeValueDq"] = 12] = "InAttributeValueDq";
State[State["InAttributeValueSq"] = 13] = "InAttributeValueSq";
State[State["InAttributeValueNq"] = 14] = "InAttributeValueNq";
// Declarations
State[State["BeforeDeclaration"] = 15] = "BeforeDeclaration";
State[State["InDeclaration"] = 16] = "InDeclaration";
// Processing instructions
State[State["InProcessingInstruction"] = 17] = "InProcessingInstruction";
// Comments & CDATA
State[State["BeforeComment"] = 18] = "BeforeComment";
State[State["CDATASequence"] = 19] = "CDATASequence";
State[State["InSpecialComment"] = 20] = "InSpecialComment";
State[State["InCommentLike"] = 21] = "InCommentLike";
// Special tags
State[State["BeforeSpecialS"] = 22] = "BeforeSpecialS";
State[State["SpecialStartSequence"] = 23] = "SpecialStartSequence";
State[State["InSpecialTag"] = 24] = "InSpecialTag";
State[State["BeforeEntity"] = 25] = "BeforeEntity";
State[State["BeforeNumericEntity"] = 26] = "BeforeNumericEntity";
State[State["InNamedEntity"] = 27] = "InNamedEntity";
State[State["InNumericEntity"] = 28] = "InNumericEntity";
State[State["InHexEntity"] = 29] = "InHexEntity";
})(State$2 || (State$2 = {}));
function isWhitespace$2(c) {
return (c === CharCodes.Space ||
c === CharCodes.NewLine ||
c === CharCodes.Tab ||
c === CharCodes.FormFeed ||
c === CharCodes.CarriageReturn);
}
function isEndOfTagSection(c) {
return c === CharCodes.Slash || c === CharCodes.Gt || isWhitespace$2(c);
}
function isNumber$1(c) {
return c >= CharCodes.Zero && c <= CharCodes.Nine;
}
function isASCIIAlpha(c) {
return ((c >= CharCodes.LowerA && c <= CharCodes.LowerZ) ||
(c >= CharCodes.UpperA && c <= CharCodes.UpperZ));
}
function isHexDigit(c) {
return ((c >= CharCodes.UpperA && c <= CharCodes.UpperF) ||
(c >= CharCodes.LowerA && c <= CharCodes.LowerF));
}
var QuoteType;
(function (QuoteType) {
QuoteType[QuoteType["NoValue"] = 0] = "NoValue";
QuoteType[QuoteType["Unquoted"] = 1] = "Unquoted";
QuoteType[QuoteType["Single"] = 2] = "Single";
QuoteType[QuoteType["Double"] = 3] = "Double";
})(QuoteType || (QuoteType = {}));
/**
* Sequences used to match longer strings.
*
* We don't have `Script`, `Style`, or `Title` here. Instead, we re-use the *End
* sequences with an increased offset.
*/
const Sequences = {
Cdata: new Uint8Array([0x43, 0x44, 0x41, 0x54, 0x41, 0x5b]),
CdataEnd: new Uint8Array([0x5d, 0x5d, 0x3e]),
CommentEnd: new Uint8Array([0x2d, 0x2d, 0x3e]),
ScriptEnd: new Uint8Array([0x3c, 0x2f, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74]),
StyleEnd: new Uint8Array([0x3c, 0x2f, 0x73, 0x74, 0x79, 0x6c, 0x65]),
TitleEnd: new Uint8Array([0x3c, 0x2f, 0x74, 0x69, 0x74, 0x6c, 0x65]), // `</title`
};
class Tokenizer$1 {
constructor({ xmlMode = false, decodeEntities = true, }, cbs) {
this.cbs = cbs;
/** The current state the tokenizer is in. */
this.state = State$2.Text;
/** The read buffer. */
this.buffer = "";
/** The beginning of the section that is currently being read. */
this.sectionStart = 0;
/** The index within the buffer that we are currently looking at. */
this.index = 0;
/** Some behavior, eg. when decoding entities, is done while we are in another state. This keeps track of the other state type. */
this.baseState = State$2.Text;
/** For special parsing behavior inside of script and style tags. */
this.isSpecial = false;
/** Indicates whether the tokenizer has been paused. */
this.running = true;
/** The offset of the current buffer. */
this.offset = 0;
this.sequenceIndex = 0;
this.trieIndex = 0;
this.trieCurrent = 0;
/** For named entities, the index of the value. For numeric entities, the code point. */
this.entityResult = 0;
this.entityExcess = 0;
this.xmlMode = xmlMode;
this.decodeEntities = decodeEntities;
this.entityTrie = xmlMode ? decode_9 : decode_10;
}
reset() {
this.state = State$2.Text;
this.buffer = "";
this.sectionStart = 0;
this.index = 0;
this.baseState = State$2.Text;
this.currentSequence = undefined;
this.running = true;
this.offset = 0;
}
write(chunk) {
this.offset += this.buffer.length;
this.buffer = chunk;
this.parse();
}
end() {
if (this.running)
this.finish();
}
pause() {
this.running = false;
}
resume() {
this.running = true;
if (this.index < this.buffer.length + this.offset) {
this.parse();
}
}
/**
* The current index within all of the written data.
*/
getIndex() {
return this.index;
}
/**
* The start of the current section.
*/
getSectionStart() {
return this.sectionStart;
}
stateText(c) {
if (c === CharCodes.Lt ||
(!this.decodeEntities && this.fastForwardTo(CharCodes.Lt))) {
if (this.index > this.sectionStart) {
this.cbs.ontext(this.sectionStart, this.index);
}
this.state = State$2.BeforeTagName;
this.sectionStart = this.index;
}
else if (this.decodeEntities && c === CharCodes.Amp) {
this.state = State$2.BeforeEntity;
}
}
stateSpecialStartSequence(c) {
const isEnd = this.sequenceIndex === this.currentSequence.length;
const isMatch = isEnd
? // If we are at the end of the sequence, make sure the tag name has ended
isEndOfTagSection(c)
: // Otherwise, do a case-insensitive comparison
(c | 0x20) === this.currentSequence[this.sequenceIndex];
if (!isMatch) {
this.isSpecial = false;
}
else if (!isEnd) {
this.sequenceIndex++;
return;
}
this.sequenceIndex = 0;
this.state = State$2.InTagName;
this.stateInTagName(c);
}
/** Look for an end tag. For <title> tags, also decode entities. */
stateInSpecialTag(c) {
if (this.sequenceIndex === this.currentSequence.length) {
if (c === CharCodes.Gt || isWhitespace$2(c)) {
const endOfText = this.index - this.currentSequence.length;
if (this.sectionStart < endOfText) {
// Spoof the index so that reported locations match up.
const actualIndex = this.index;
this.index = endOfText;
this.cbs.ontext(this.sectionStart, endOfText);
this.index = actualIndex;
}
this.isSpecial = false;
this.sectionStart = endOfText + 2; // Skip over the `</`
this.stateInClosingTagName(c);
return; // We are done; skip the rest of the function.
}
this.sequenceIndex = 0;
}
if ((c | 0x20) === this.currentSequence[this.sequenceIndex]) {
this.sequenceIndex += 1;
}
else if (this.sequenceIndex === 0) {
if (this.currentSequence === Sequences.TitleEnd) {
// We have to parse entities in <title> tags.
if (this.decodeEntities && c === CharCodes.Amp) {
this.state = State$2.BeforeEntity;
}
}
else if (this.fastForwardTo(CharCodes.Lt)) {
// Outside of <title> tags, we can fast-forward.
this.sequenceIndex = 1;
}
}
else {
// If we see a `<`, set the sequence index to 1; useful for eg. `<</script>`.
this.sequenceIndex = Number(c === CharCodes.Lt);
}
}
stateCDATASequence(c) {
if (c === Sequences.Cdata[this.sequenceIndex]) {
if (++this.sequenceIndex === Sequences.Cdata.length) {
this.state = State$2.InCommentLike;
this.currentSequence = Sequences.CdataEnd;
this.sequenceIndex = 0;
this.sectionStart = this.index + 1;
}
}
else {
this.sequenceIndex = 0;
this.state = State$2.InDeclaration;
this.stateInDeclaration(c); // Reconsume the character
}
}
/**
* When we wait for one specific character, we can speed things up
* by skipping through the buffer until we find it.
*
* @returns Whether the character was found.
*/
fastForwardTo(c) {
while (++this.index < this.buffer.length + this.offset) {
if (this.buffer.charCodeAt(this.index - this.offset) === c) {
return true;
}
}
/*
* We increment the index at the end of the `parse` loop,
* so set it to `buffer.length - 1` here.
*
* TODO: Refactor `parse` to increment index before calling states.
*/
this.index = this.buffer.length + this.offset - 1;
return false;
}
/**
* Comments and CDATA end with `-->` and `]]>`.
*
* Their common qualities are:
* - Their end sequences have a distinct character they start with.
* - That character is then repeated, so we have to check multiple repeats.
* - All characters but the start character of the sequence can be skipped.
*/
stateInCommentLike(c) {
if (c === this.currentSequence[this.sequenceIndex]) {
if (++this.sequenceIndex === this.currentSequence.length) {
if (this.currentSequence === Sequences.CdataEnd) {
this.cbs.oncdata(this.sectionStart, this.index, 2);
}
else {
this.cbs.oncomment(this.sectionStart, this.index, 2);
}
this.sequenceIndex = 0;
this.sectionStart = this.index + 1;
this.state = State$2.Text;
}
}
else if (this.sequenceIndex === 0) {
// Fast-forward to the first character of the sequence
if (this.fastForwardTo(this.currentSequence[0])) {
this.sequenceIndex = 1;
}
}
else if (c !== this.currentSequence[this.sequenceIndex - 1]) {
// Allow long sequences, eg. --->, ]]]>
this.sequenceIndex = 0;
}
}
/**
* HTML only allows ASCII alpha characters (a-z and A-Z) at the beginning of a tag name.
*
* XML allows a lot more characters here (@see https://www.w3.org/TR/REC-xml/#NT-NameStartChar).
* We allow anything that wouldn't end the tag.
*/
isTagStartChar(c) {
return this.xmlMode ? !isEndOfTagSection(c) : isASCIIAlpha(c);
}
startSpecial(sequence, offset) {
this.isSpecial = true;
this.currentSequence = sequence;
this.sequenceIndex = offset;
this.state = State$2.SpecialStartSequence;
}
stateBeforeTagName(c) {
if (c === CharCodes.ExclamationMark) {
this.state = State$2.BeforeDeclaration;
this.sectionStart = this.index + 1;
}
else if (c === CharCodes.Questionmark) {
this.state = State$2.InProcessingInstruction;
this.sectionStart = this.index + 1;
}
else if (this.isTagStartChar(c)) {
const lower = c | 0x20;
this.sectionStart = this.index;
if (!this.xmlMode && lower === Sequences.TitleEnd[2]) {
this.startSpecial(Sequences.TitleEnd, 3);
}
else {
this.state =
!this.xmlMode && lower === Sequences.ScriptEnd[2]
? State$2.BeforeSpecialS
: State$2.InTagName;
}
}
else if (c === CharCodes.Slash) {
this.state = State$2.BeforeClosingTagName;
}
else {
this.state = State$2.Text;
this.stateText(c);
}
}
stateInTagName(c) {
if (isEndOfTagSection(c)) {
this.cbs.onopentagname(this.sectionStart, this.index);
this.sectionStart = -1;
this.state = State$2.BeforeAttributeName;
this.stateBeforeAttributeName(c);
}
}
stateBeforeClosingTagName(c) {
if (isWhitespace$2(c)) ;
else if (c === CharCodes.Gt) {
this.state = State$2.Text;
}
else {
this.state = this.isTagStartChar(c)
? State$2.InClosingTagName
: State$2.InSpecialComment;
this.sectionStart = this.index;
}
}
stateInClosingTagName(c) {
if (c === CharCodes.Gt || isWhitespace$2(c)) {
this.cbs.onclosetag(this.sectionStart, this.index);
this.sectionStart = -1;
this.state = State$2.AfterClosingTagName;
this.stateAfterClosingTagName(c);
}
}
stateAfterClosingTagName(c) {
// Skip everything until ">"
if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) {
this.state = State$2.Text;
this.sectionStart = this.index + 1;
}
}
stateBeforeAttributeName(c) {
if (c === CharCodes.Gt) {
this.cbs.onopentagend(this.index);
if (this.isSpecial) {
this.state = State$2.InSpecialTag;
this.sequenceIndex = 0;
}
else {
this.state = State$2.Text;
}
this.baseState = this.state;
this.sectionStart = this.index + 1;
}
else if (c === CharCodes.Slash) {
this.state = State$2.InSelfClosingTag;
}
else if (!isWhitespace$2(c)) {
this.state = State$2.InAttributeName;
this.sectionStart = this.index;
}
}
stateInSelfClosingTag(c) {
if (c === CharCodes.Gt) {
this.cbs.onselfclosingtag(this.index);
this.state = State$2.Text;
this.baseState = State$2.Text;
this.sectionStart = this.index + 1;
this.isSpecial = false; // Reset special state, in case of self-closing special tags
}
else if (!isWhitespace$2(c)) {
this.state = State$2.BeforeAttributeName;
this.stateBeforeAttributeName(c);
}
}
stateInAttributeName(c) {
if (c === CharCodes.Eq || isEndOfTagSection(c)) {
this.cbs.onattribname(this.sectionStart, this.index);
this.sectionStart = -1;
this.state = State$2.AfterAttributeName;
this.stateAfterAttributeName(c);
}
}
stateAfterAttributeName(c) {
if (c === CharCodes.Eq) {
this.state = State$2.BeforeAttributeValue;
}
else if (c === CharCodes.Slash || c === CharCodes.Gt) {
this.cbs.onattribend(QuoteType.NoValue, this.index);
this.state = State$2.BeforeAttributeName;
this.stateBeforeAttributeName(c);
}
else if (!isWhitespace$2(c)) {
this.cbs.onattribend(QuoteType.NoValue, this.index);
this.state = State$2.InAttributeName;
this.sectionStart = this.index;
}
}
stateBeforeAttributeValue(c) {
if (c === CharCodes.DoubleQuote) {
this.state = State$2.InAttributeValueDq;
this.sectionStart = this.index + 1;
}
else if (c === CharCodes.SingleQuote) {
this.state = State$2.InAttributeValueSq;
this.sectionStart = this.index + 1;
}
else if (!isWhitespace$2(c)) {
this.sectionStart = this.index;
this.state = State$2.InAttributeValueNq;
this.stateInAttributeValueNoQuotes(c); // Reconsume token
}
}
handleInAttributeValue(c, quote) {
if (c === quote ||
(!this.decodeEntities && this.fastForwardTo(quote))) {
this.cbs.onattribdata(this.sectionStart, this.index);
this.sectionStart = -1;
this.cbs.onattribend(quote === CharCodes.DoubleQuote
? QuoteType.Double
: QuoteType.Single, this.index);
this.state = State$2.BeforeAttributeName;
}
else if (this.decodeEntities && c === CharCodes.Amp) {
this.baseState = this.state;
this.state = State$2.BeforeEntity;
}
}
stateInAttributeValueDoubleQuotes(c) {
this.handleInAttributeValue(c, CharCodes.DoubleQuote);
}
stateInAttributeValueSingleQuotes(c) {
this.handleInAttributeValue(c, CharCodes.SingleQuote);
}
stateInAttributeValueNoQuotes(c) {
if (isWhitespace$2(c) || c === CharCodes.Gt) {
this.cbs.onattribdata(this.sectionStart, this.index);
this.sectionStart = -1;
this.cbs.onattribend(QuoteType.Unquoted, this.index);
this.state = State$2.BeforeAttributeName;
this.stateBeforeAttributeName(c);
}
else if (this.decodeEntities && c === CharCodes.Amp) {
this.baseState = this.state;
this.state = State$2.BeforeEntity;
}
}
stateBeforeDeclaration(c) {
if (c === CharCodes.OpeningSquareBracket) {
this.state = State$2.CDATASequence;
this.sequenceIndex = 0;
}
else {
this.state =
c === CharCodes.Dash
? State$2.BeforeComment
: State$2.InDeclaration;
}
}
stateInDeclaration(c) {
if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) {
this.cbs.ondeclaration(this.sectionStart, this.index);
this.state = State$2.Text;
this.sectionStart = this.index + 1;
}
}
stateInProcessingInstruction(c) {
if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) {
this.cbs.onprocessinginstruction(this.sectionStart, this.index);
this.state = State$2.Text;
this.sectionStart = this.index + 1;
}
}
stateBeforeComment(c) {
if (c === CharCodes.Dash) {
this.state = State$2.InCommentLike;
this.currentSequence = Sequences.CommentEnd;
// Allow short comments (eg. <!-->)
this.sequenceIndex = 2;
this.sectionStart = this.index + 1;
}
else {
this.state = State$2.InDeclaration;
}
}
stateInSpecialComment(c) {
if (c === CharCodes.Gt || this.fastForwardTo(CharCodes.Gt)) {
this.cbs.oncomment(this.sectionStart, this.index, 0);
this.state = State$2.Text;
this.sectionStart = this.index + 1;
}
}
stateBeforeSpecialS(c) {
const lower = c | 0x20;
if (lower === Sequences.ScriptEnd[3]) {
this.startSpecial(Sequences.ScriptEnd, 4);
}
else if (lower === Sequences.StyleEnd[3]) {
this.startSpecial(Sequences.StyleEnd, 4);
}
else {
this.state = State$2.InTagName;
this.stateInTagName(c); // Consume the token again
}
}
stateBeforeEntity(c) {
// Start excess with 1 to include the '&'
this.entityExcess = 1;
this.entityResult = 0;
if (c === CharCodes.Num) {
this.state = State$2.BeforeNumericEntity;
}
else if (c === CharCodes.Amp) ;
else {
this.trieIndex = 0;
this.trieCurrent = this.entityTrie[0];
this.state = State$2.InNamedEntity;
this.stateInNamedEntity(c);
}
}
stateInNamedEntity(c) {
this.entityExcess += 1;
this.trieIndex = decode_4(this.entityTrie, this.trieCurrent, this.trieIndex + 1, c);
if (this.trieIndex < 0) {
this.emitNamedEntity();
this.index--;
return;
}
this.trieCurrent = this.entityTrie[this.trieIndex];
const masked = this.trieCurrent & decode_5.VALUE_LENGTH;
// If the branch is a value, store it and continue
if (masked) {
// The mask is the number of bytes of the value, including the current byte.
const valueLength = (masked >> 14) - 1;
// If we have a legacy entity while parsing strictly, just skip the number of bytes
if (!this.allowLegacyEntity() && c !== CharCodes.Semi) {
this.trieIndex += valueLength;
}
else {
// Add 1 as we have already incremented the excess
const entityStart = this.index - this.entityExcess + 1;
if (entityStart > this.sectionStart) {
this.emitPartial(this.sectionStart, entityStart);
}
// If this is a surrogate pair, consume the next two bytes
this.entityResult = this.trieIndex;
this.trieIndex += valueLength;
this.entityExcess = 0;
this.sectionStart = this.index + 1;
if (valueLength === 0) {
this.emitNamedEntity();
}
}
}
}
emitNamedEntity() {
this.state = this.baseState;
if (this.entityResult === 0) {
return;
}
const valueLength = (this.entityTrie[this.entityResult] & decode_5.VALUE_LENGTH) >>
14;
switch (valueLength) {
case 1:
this.emitCodePoint(this.entityTrie[this.entityResult] &
~decode_5.VALUE_LENGTH);
break;
case 2:
this.emitCodePoint(this.entityTrie[this.entityResult + 1]);
break;
case 3: {
this.emitCodePoint(this.entityTrie[this.entityResult + 1]);
this.emitCodePoint(this.entityTrie[this.entityResult + 2]);
}
}
}
stateBeforeNumericEntity(c) {
if ((c | 0x20) === CharCodes.LowerX) {
this.entityExcess++;
this.state = State$2.InHexEntity;
}
else {
this.state = State$2.InNumericEntity;
this.stateInNumericEntity(c);
}
}
emitNumericEntity(strict) {
const entityStart = this.index - this.entityExcess - 1;
const numberStart = entityStart + 2 + Number(this.state === State$2.InHexEntity);
if (numberStart !== this.index) {
// Emit leading data if any
if (entityStart > this.sectionStart) {
this.emitPartial(this.sectionStart, entityStart);
}
this.sectionStart = this.index + Number(strict);
this.emitCodePoint(decode_7(this.entityResult));
}
this.state = this.baseState;
}
stateInNumericEntity(c) {
if (c === CharCodes.Semi) {
this.emitNumericEntity(true);
}
else if (isNumber$1(c)) {
this.entityResult = this.entityResult * 10 + (c - CharCodes.Zero);
this.entityExcess++;
}
else {
if (this.allowLegacyEntity()) {
this.emitNumericEntity(false);
}
else {
this.state = this.baseState;
}
this.index--;
}
}
stateInHexEntity(c) {
if (c === CharCodes.Semi) {
this.emitNumericEntity(true);
}
else if (isNumber$1(c)) {
this.entityResult = this.entityResult * 16 + (c - CharCodes.Zero);
this.entityExcess++;
}
else if (isHexDigit(c)) {
this.entityResult =
this.entityResult * 16 + ((c | 0x20) - CharCodes.LowerA + 10);
this.entityExcess++;
}
else {
if (this.allowLegacyEntity()) {
this.emitNumericEntity(false);
}
else {
this.state = this.baseState;
}
this.index--;
}
}
allowLegacyEntity() {
return (!this.xmlMode &&
(this.baseState === State$2.Text ||
this.baseState === State$2.InSpecialTag));
}
/**
* Remove data that has already been consumed from the buffer.
*/
cleanup() {
// If we are inside of text or attributes, emit what we already have.
if (this.running && this.sectionStart !== this.index) {
if (this.state === State$2.Text ||
(this.state === State$2.InSpecialTag && this.sequenceIndex === 0)) {
this.cbs.ontext(this.sectionStart, this.index);
this.sectionStart = this.index;
}
else if (this.state === State$2.InAttributeValueDq ||
this.state === State$2.InAttributeValueSq ||
this.state === State$2.InAttributeValueNq) {
this.cbs.onattribdata(this.sectionStart, this.index);
this.sectionStart = this.index;
}
}
}
shouldContinue() {
return this.index < this.buffer.length + this.offset && this.running;
}
/**
* Iterates through the buffer, calling the function corresponding to the current state.
*
* States that are more likely to be hit are higher up, as a performance improvement.
*/
parse() {
while (this.shouldContinue()) {
const c = this.buffer.charCodeAt(this.index - this.offset);
if (this.state === State$2.Text) {
this.stateText(c);
}
else if (this.state === State$2.SpecialStartSequence) {
this.stateSpecialStartSequence(c);
}
else if (this.state === State$2.InSpecialTag) {
this.stateInSpecialTag(c);
}
else if (this.state === State$2.CDATASequence) {
this.stateCDATASequence(c);
}
else if (this.state === State$2.InAttributeValueDq) {
this.stateInAttributeValueDoubleQuotes(c);
}
else if (this.state === State$2.InAttributeName) {
this.stateInAttributeName(c);
}
else if (this.state === State$2.InCommentLike) {
this.stateInCommentLike(c);
}
else if (this.state === State$2.InSpecialComment) {
this.stateInSpecialComment(c);
}
else if (this.state === State$2.BeforeAttributeName) {
this.stateBeforeAttributeName(c);
}
else if (this.state === State$2.InTagName) {
this.stateInTagName(c);
}
else if (this.state === State$2.InClosingTagName) {
this.stateInClosingTagName(c);
}
else if (this.state === State$2.BeforeTagName) {
this.stateBeforeTagName(c);
}
else if (this.state === State$2.AfterAttributeName) {
this.stateAfterAttributeName(c);
}
else if (this.state === State$2.InAttributeValueSq) {
this.stateInAttributeValueSingleQuotes(c);
}
else if (this.state === State$2.BeforeAttributeValue) {
this.stateBeforeAttributeValue(c);
}
else if (this.state === State$2.BeforeClosingTagName) {
this.stateBeforeClosingTagName(c);
}
else if (this.state === State$2.AfterClosingTagName) {
this.stateAfterClosingTagName(c);
}
else if (this.state === State$2.BeforeSpecialS) {
this.stateBeforeSpecialS(c);
}
else if (this.state === State$2.InAttributeValueNq) {
this.stateInAttributeValueNoQuotes(c);
}
else if (this.state === State$2.InSelfClosingTag) {
this.stateInSelfClosingTag(c);
}
else if (this.state === State$2.InDeclaration) {
this.stateInDeclaration(c);
}
else if (this.state === State$2.BeforeDeclaration) {
this.stateBeforeDeclaration(c);
}
else if (this.state === State$2.BeforeComment) {
this.stateBeforeComment(c);
}
else if (this.state === State$2.InProcessingInstruction) {
this.stateInProcessingInstruction(c);
}
else if (this.state === State$2.InNamedEntity) {
this.stateInNamedEntity(c);
}
else if (this.state === State$2.BeforeEntity) {
this.stateBeforeEntity(c);
}
else if (this.state === State$2.InHexEntity) {
this.stateInHexEntity(c);
}
else if (this.state === State$2.InNumericEntity) {
this.stateInNumericEntity(c);
}
else {
// `this._state === State.BeforeNumericEntity`
this.stateBeforeNumericEntity(c);
}
this.index++;
}
this.cleanup();
}
finish() {
if (this.state === State$2.InNamedEntity) {
this.emitNamedEntity();
}
// If there is remaining data, emit it in a reasonable way
if (this.sectionStart < this.index) {
this.handleTrailingData();
}
this.cbs.onend();
}
/** Handle any trailing data. */
handleTrailingData() {
const endIndex = this.buffer.length + this.offset;
if (this.state === State$2.InCommentLike) {
if (this.currentSequence === Sequences.CdataEnd) {
this.cbs.oncdata(this.sectionStart, endIndex, 0);
}
else {
this.cbs.oncomment(this.sectionStart, endIndex, 0);
}
}
else if (this.state === State$2.InNumericEntity &&
this.allowLegacyEntity()) {
this.emitNumericEntity(false);
// All trailing data will have been consumed
}
else if (this.state === State$2.InHexEntity &&
this.allowLegacyEntity()) {
this.emitNumericEntity(false);
// All trailing data will have been consumed
}
else if (this.state === State$2.InTagName ||
this.state === State$2.BeforeAttributeName ||
this.state === State$2.BeforeAttributeValue ||
this.state === State$2.AfterAttributeName ||
this.state === State$2.InAttributeName ||
this.state === State$2.InAttributeValueSq ||
this.state === State$2.InAttributeValueDq ||
this.state === State$2.InAttributeValueNq ||
this.state === State$2.InClosingTagName) ;
else {
this.cbs.ontext(this.sectionStart, endIndex);
}
}
emitPartial(start, endIndex) {
if (this.baseState !== State$2.Text &&
this.baseState !== State$2.InSpecialTag) {
this.cbs.onattribdata(start, endIndex);
}
else {
this.cbs.ontext(start, endIndex);
}
}
emitCodePoint(cp) {
if (this.baseState !== State$2.Text &&
this.baseState !== State$2.InSpecialTag) {
this.cbs.onattribentity(cp);
}
else {
this.cbs.ontextentity(cp);
}
}
}
const formTags = new Set([
"input",
"option",
"optgroup",
"select",
"button",
"datalist",
"textarea",
]);
const pTag = new Set(["p"]);
const tableSectionTags = new Set(["thead", "tbody"]);
const ddtTags = new Set(["dd", "dt"]);
const rtpTags = new Set(["rt", "rp"]);
const openImpliesClose = new Map([
["tr", new Set(["tr", "th", "td"])],
["th", new Set(["th"])],
["td", new Set(["thead", "th", "td"])],
["body", new Set(["head", "link", "script"])],
["li", new Set(["li"])],
["p", pTag],
["h1", pTag],
["h2", pTag],
["h3", pTag],
["h4", pTag],
["h5", pTag],
["h6", pTag],
["select", formTags],
["input", formTags],
["output", formTags],
["button", formTags],
["datalist", formTags],
["textarea", formTags],
["option", new Set(["option"])],
["optgroup", new Set(["optgroup", "option"])],
["dd", ddtTags],
["dt", ddtTags],
["address", pTag],
["article", pTag],
["aside", pTag],
["blockquote", pTag],
["details", pTag],
["div", pTag],
["dl", pTag],
["fieldset", pTag],
["figcaption", pTag],
["figure", pTag],
["footer", pTag],
["form", pTag],
["header", pTag],
["hr", pTag],
["main", pTag],
["nav", pTag],
["ol", pTag],
["pre", pTag],
["section", pTag],
["table", pTag],
["ul", pTag],
["rt", rtpTags],
["rp", rtpTags],
["tbody", tableSectionTags],
["tfoot", tableSectionTags],
]);
const voidElements = new Set([
"area",
"base",
"basefont",
"br",
"col",
"command",
"embed",
"frame",
"hr",
"img",
"input",
"isindex",
"keygen",
"link",
"meta",
"param",
"source",
"track",
"wbr",
]);
const foreignContextElements = new Set(["math", "svg"]);
const htmlIntegrationElements = new Set([
"mi",
"mo",
"mn",
"ms",
"mtext",
"annotation-xml",
"foreignobject",
"desc",
"title",
]);
const reNameEnd = /\s|\//;
class Parser$1 {
constructor(cbs, options = {}) {
var _a, _b, _c, _d, _e;
this.options = options;
/** The start index of the last event. */
this.startIndex = 0;
/** The end index of the last event. */
this.endIndex = 0;
/**
* Store the start index of the current open tag,
* so we can update the start index for attributes.
*/
this.openTagStart = 0;
this.tagname = "";
this.attribname = "";
this.attribvalue = "";
this.attribs = null;
this.stack = [];
this.foreignContext = [];
this.buffers = [];
this.bufferOffset = 0;
/** The index of the last written buffer. Used when resuming after a `pause()`. */
this.writeIndex = 0;
/** Indicates whether the parser has finished running / `.end` has been called. */
this.ended = false;
this.cbs = cbs !== null && cbs !== void 0 ? cbs : {};
this.lowerCaseTagNames = (_a = options.lowerCaseTags) !== null && _a !== void 0 ? _a : !options.xmlMode;
this.lowerCaseAttributeNames =
(_b = options.lowerCaseAttributeNames) !== null && _b !== void 0 ? _b : !options.xmlMode;
this.tokenizer = new ((_c = options.Tokenizer) !== null && _c !== void 0 ? _c : Tokenizer$1)(this.options, this);
(_e = (_d = this.cbs).onparserinit) === null || _e === void 0 ? void 0 : _e.call(_d, this);
}
// Tokenizer event handlers
/** @internal */
ontext(start, endIndex) {
var _a, _b;
const data = this.getSlice(start, endIndex);
this.endIndex = endIndex - 1;
(_b = (_a = this.cbs).ontext) === null || _b === void 0 ? void 0 : _b.call(_a, data);
this.startIndex = endIndex;
}
/** @internal */
ontextentity(cp) {
var _a, _b;
/*
* Entities can be emitted on the character, or directly after.
* We use the section start here to get accurate indices.
*/
const idx = this.tokenizer.getSectionStart();
this.endIndex = idx - 1;
(_b = (_a = this.cbs).ontext) === null || _b === void 0 ? void 0 : _b.call(_a, decode_6(cp));
this.startIndex = idx;
}
isVoidElement(name) {
return !this.options.xmlMode && voidElements.has(name);
}
/** @internal */
onopentagname(start, endIndex) {
this.endIndex = endIndex;
let name = this.getSlice(start, endIndex);
if (this.lowerCaseTagNames) {
name = name.toLowerCase();
}
this.emitOpenTag(name);
}
emitOpenTag(name) {
var _a, _b, _c, _d;
this.openTagStart = this.startIndex;
this.tagname = name;
const impliesClose = !this.options.xmlMode && openImpliesClose.get(name);
if (impliesClose) {
while (this.stack.length > 0 &&
impliesClose.has(this.stack[this.stack.length - 1])) {
const el = this.stack.pop();
(_b = (_a = this.cbs).onclosetag) === null || _b === void 0 ? void 0 : _b.call(_a, el, true);
}
}
if (!this.isVoidElement(name)) {
this.stack.push(name);
if (foreignContextElements.has(name)) {
this.foreignContext.push(true);
}
else if (htmlIntegrationElements.has(name)) {
this.foreignContext.push(false);
}
}
(_d = (_c = this.cbs).onopentagname) === null || _d === void 0 ? void 0 : _d.call(_c, name);
if (this.cbs.onopentag)
this.attribs = {};
}
endOpenTag(isImplied) {
var _a, _b;
this.startIndex = this.openTagStart;
if (this.attribs) {
(_b = (_a = this.cbs).onopentag) === null || _b === void 0 ? void 0 : _b.call(_a, this.tagname, this.attribs, isImplied);
this.attribs = null;
}
if (this.cbs.onclosetag && this.isVoidElement(this.tagname)) {
this.cbs.onclosetag(this.tagname, true);
}
this.tagname = "";
}
/** @internal */
onopentagend(endIndex) {
this.endIndex = endIndex;
this.endOpenTag(false);
// Set `startIndex` for next node
this.startIndex = endIndex + 1;
}
/** @internal */
onclosetag(start, endIndex) {
var _a, _b, _c, _d, _e, _f;
this.endIndex = endIndex;
let name = this.getSlice(start, endIndex);
if (this.lowerCaseTagNames) {
name = name.toLowerCase();
}
if (foreignContextElements.has(name) ||
htmlIntegrationElements.has(name)) {
this.foreignContext.pop();
}
if (!this.isVoidElement(name)) {
const pos = this.stack.lastIndexOf(name);
if (pos !== -1) {
if (this.cbs.onclosetag) {
let count = this.stack.length - pos;
while (count--) {
// We know the stack has sufficient elements.
this.cbs.onclosetag(this.stack.pop(), count !== 0);
}
}
else
this.stack.length = pos;
}
else if (!this.options.xmlMode && name === "p") {
// Implicit open before close
this.emitOpenTag("p");
this.closeCurrentTag(true);
}
}
else if (!this.options.xmlMode && name === "br") {
// We can't use `emitOpenTag` for implicit open, as `br` would be implicitly closed.
(_b = (_a = this.cbs).onopentagname) === null || _b === void 0 ? void 0 : _b.call(_a, "br");
(_d = (_c = this.cbs).onopentag) === null || _d === void 0 ? void 0 : _d.call(_c, "br", {}, true);
(_f = (_e = this.cbs).onclosetag) === null || _f === void 0 ? void 0 : _f.call(_e, "br", false);
}
// Set `startIndex` for next node
this.startIndex = endIndex + 1;
}
/** @internal */
onselfclosingtag(endIndex) {
this.endIndex = endIndex;
if (this.options.xmlMode ||
this.options.recognizeSelfClosing ||
this.foreignContext[this.foreignContext.length - 1]) {
this.closeCurrentTag(false);
// Set `startIndex` for next node
this.startIndex = endIndex + 1;
}
else {
// Ignore the fact that the tag is self-closing.
this.onopentagend(endIndex);
}
}
closeCurrentTag(isOpenImplied) {
var _a, _b;
const name = this.tagname;
this.endOpenTag(isOpenImplied);
// Self-closing tags will be on the top of the stack
if (this.stack[this.stack.length - 1] === name) {
// If the opening tag isn't implied, the closing tag has to be implied.
(_b = (_a = this.cbs).onclosetag) === null || _b === void 0 ? void 0 : _b.call(_a, name, !isOpenImplied);
this.stack.pop();
}
}
/** @internal */
onattribname(start, endIndex) {
this.startIndex = start;
const name = this.getSlice(start, endIndex);
this.attribname = this.lowerCaseAttributeNames
? name.toLowerCase()
: name;
}
/** @internal */
onattribdata(start, endIndex) {
this.attribvalue += this.getSlice(start, endIndex);
}
/** @internal */
onattribentity(cp) {
this.attribvalue += decode_6(cp);
}
/** @internal */
onattribend(quote, endIndex) {
var _a, _b;
this.endIndex = endIndex;
(_b = (_a = this.cbs).onattribute) === null || _b === void 0 ? void 0 : _b.call(_a, this.attribname, this.attribvalue, quote === QuoteType.Double
? '"'
: quote === QuoteType.Single
? "'"
: quote === QuoteType.NoValue
? undefined
: null);
if (this.attribs &&
!Object.prototype.hasOwnProperty.call(this.attribs, this.attribname)) {
this.attribs[this.attribname] = this.attribvalue;
}
this.attribvalue = "";
}
getInstructionName(value) {
const idx = value.search(reNameEnd);
let name = idx < 0 ? value : value.substr(0, idx);
if (this.lowerCaseTagNames) {
name = name.toLowerCase();
}
return name;
}
/** @internal */
ondeclaration(start, endIndex) {
this.endIndex = endIndex;
const value = this.getSlice(start, endIndex);
if (this.cbs.onprocessinginstruction) {
const name = this.getInstructionName(value);
this.cbs.onprocessinginstruction(`!${name}`, `!${value}`);
}
// Set `startIndex` for next node
this.startIndex = endIndex + 1;
}
/** @internal */
onprocessinginstruction(start, endIndex) {
this.endIndex = endIndex;
const value = this.getSlice(start, endIndex);
if (this.cbs.onprocessinginstruction) {
const name = this.getInstructionName(value);
this.cbs.onprocessinginstruction(`?${name}`, `?${value}`);
}
// Set `startIndex` for next node
this.startIndex = endIndex + 1;
}
/** @internal */
oncomment(start, endIndex, offset) {
var _a, _b, _c, _d;
this.endIndex = endIndex;
(_b = (_a = this.cbs).oncomment) === null || _b === void 0 ? void 0 : _b.call(_a, this.getSlice(start, endIndex - offset));
(_d = (_c = this.cbs).oncommentend) === null || _d === void 0 ? void 0 : _d.call(_c);
// Set `startIndex` for next node
this.startIndex = endIndex + 1;
}
/** @internal */
oncdata(start, endIndex, offset) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
this.endIndex = endIndex;
const value = this.getSlice(start, endIndex - offset);
if (this.options.xmlMode || this.options.recognizeCDATA) {
(_b = (_a = this.cbs).oncdatastart) === null || _b === void 0 ? void 0 : _b.call(_a);
(_d = (_c = this.cbs).ontext) === null || _d === void 0 ? void 0 : _d.call(_c, value);
(_f = (_e = this.cbs).oncdataend) === null || _f === void 0 ? void 0 : _f.call(_e);
}
else {
(_h = (_g = this.cbs).oncomment) === null || _h === void 0 ? void 0 : _h.call(_g, `[CDATA[${value}]]`);
(_k = (_j = this.cbs).oncommentend) === null || _k === void 0 ? void 0 : _k.call(_j);
}
// Set `startIndex` for next node
this.startIndex = endIndex + 1;
}
/** @internal */
onend() {
var _a, _b;
if (this.cbs.onclosetag) {
// Set the end index for all remaining tags
this.endIndex = this.startIndex;
for (let i = this.stack.length; i > 0; this.cbs.onclosetag(this.stack[--i], true))
;
}
(_b = (_a = this.cbs).onend) === null || _b === void 0 ? void 0 : _b.call(_a);
}
/**
* Resets the parser to a blank state, ready to parse a new HTML document
*/
reset() {
var _a, _b, _c, _d;
(_b = (_a = this.cbs).onreset) === null || _b === void 0 ? void 0 : _b.call(_a);
this.tokenizer.reset();
this.tagname = "";
this.attribname = "";
this.attribs = null;
this.stack.length = 0;
this.startIndex = 0;
this.endIndex = 0;
(_d = (_c = this.cbs).onparserinit) === null || _d === void 0 ? void 0 : _d.call(_c, this);
this.buffers.length = 0;
this.bufferOffset = 0;
this.writeIndex = 0;
this.ended = false;
}
/**
* Resets the parser, then parses a complete document and
* pushes it to the handler.
*
* @param data Document to parse.
*/
parseComplete(data) {
this.reset();
this.end(data);
}
getSlice(start, end) {
while (start - this.bufferOffset >= this.buffers[0].length) {
this.shiftBuffer();
}
let str = this.buffers[0].slice(start - this.bufferOffset, end - this.bufferOffset);
while (end - this.bufferOffset > this.buffers[0].length) {
this.shiftBuffer();
str += this.buffers[0].slice(0, end - this.bufferOffset);
}
return str;
}
shiftBuffer() {
this.bufferOffset += this.buffers[0].length;
this.writeIndex--;
this.buffers.shift();
}
/**
* Parses a chunk of data and calls the corresponding callbacks.
*
* @param chunk Chunk to parse.
*/
write(chunk) {
var _a, _b;
if (this.ended) {
(_b = (_a = this.cbs).onerror) === null || _b === void 0 ? void 0 : _b.call(_a, new Error(".write() after done!"));
return;
}
this.buffers.push(chunk);
if (this.tokenizer.running) {
this.tokenizer.write(chunk);
this.writeIndex++;
}
}
/**
* Parses the end of the buffer and clears the stack, calls onend.
*
* @param chunk Optional final chunk to parse.
*/
end(chunk) {
var _a, _b;
if (this.ended) {
(_b = (_a = this.cbs).onerror) === null || _b === void 0 ? void 0 : _b.call(_a, Error(".end() after done!"));
return;
}
if (chunk)
this.write(chunk);
this.ended = true;
this.tokenizer.end();
}
/**
* Pauses parsing. The parser won't emit events until `resume` is called.
*/
pause() {
this.tokenizer.pause();
}
/**
* Resumes parsing after `pause` was called.
*/
resume() {
this.tokenizer.resume();
while (this.tokenizer.running &&
this.writeIndex < this.buffers.length) {
this.tokenizer.write(this.buffers[this.writeIndex++]);
}
if (this.ended)
this.tokenizer.end();
}
/**
* Alias of `write`, for backwards compatibility.
*
* @param chunk Chunk to parse.
* @deprecated
*/
parseChunk(chunk) {
this.write(chunk);
}
/**
* Alias of `end`, for backwards compatibility.
*
* @param chunk Optional final chunk to parse.
* @deprecated
*/
done(chunk) {
this.end(chunk);
}
}
// Helper methods
/**
* Parses the data, returns the resulting document.
*
* @param data The data that should be parsed.
* @param options Optional options for the parser and DOM builder.
*/
function parseDocument(data, options) {
const handler = new DomHandler(undefined, options);
new Parser$1(handler, options).end(data);
return handler.root;
}
/**
* Types used in signatures of Cheerio methods.
*
* @category Cheerio
*/
const parse$4 = getParse((content, options, isDocument, context) => options.xmlMode || options._useHtmlParser2
? parseDocument(content, options)
: parseWithParse5(content, options, isDocument, context));
// Duplicate docs due to https://github.com/TypeStrong/typedoc/issues/1616
/**
* Create a querying function, bound to a document created from the provided markup.
*
* Note that similar to web browser contexts, this operation may introduce
* `<html>`, `<head>`, and `<body>` elements; set `isDocument` to `false` to
* switch to fragment mode and disable this.
*
* @param content - Markup to be loaded.
* @param options - Options for the created instance.
* @param isDocument - Allows parser to be switched to fragment mode.
* @returns The loaded document.
* @see {@link https://cheerio.js.org#loading} for additional usage information.
*/
const load = getLoad(parse$4, (dom, options) => options.xmlMode || options._useHtmlParser2
? render(dom, options)
: renderWithParse5(dom));
/**
* The default cheerio instance.
*
* @deprecated Use the function returned by `load` instead.
*/
var cheerio = load([]);
var debug_1 = createCommonjsModule(function (module, exports) {
exports = module.exports = debug;
function debug(label) {
return _debug.bind(null, label);
}
function _debug(label) {
var args = [].slice.call(arguments, 1);
args.unshift('[' + label + ']');
process.stderr.write(args.join(' ') + '\n');
}
});
var lexer = createCommonjsModule(function (module, exports) {
var debug = debug_1('lex');
exports = module.exports = lex;
/**
* Convert a CSS string into an array of lexical tokens.
*
* @param {String} css CSS
* @returns {Array} lexical tokens
*/
function lex(css) {
var buffer = ''; // Character accumulator
var ch; // Current character
var column = 0; // Current source column number
var cursor = -1; // Current source cursor position
var depth = 0; // Current nesting depth
var line = 1; // Current source line number
var state = 'before-selector'; // Current state
var stack = [state]; // State stack
var token = {}; // Current token
var tokens = []; // Token accumulator
// Supported @-rules, in roughly descending order of usage probability.
var atRules = [
'media',
'keyframes',
{ name: '-webkit-keyframes', type: 'keyframes', prefix: '-webkit-' },
{ name: '-moz-keyframes', type: 'keyframes', prefix: '-moz-' },
{ name: '-ms-keyframes', type: 'keyframes', prefix: '-ms-' },
{ name: '-o-keyframes', type: 'keyframes', prefix: '-o-' },
'font-face',
{ name: 'import', state: 'before-at-value' },
{ name: 'charset', state: 'before-at-value' },
'supports',
'viewport',
{ name: 'namespace', state: 'before-at-value' },
'document',
{ name: '-moz-document', type: 'document', prefix: '-moz-' },
'page'
];
// -- Functions ------------------------------------------------------------
/**
* Advance the character cursor and return the next character.
*
* @returns {String} The next character.
*/
function getCh() {
skip();
return css[cursor];
}
/**
* Return the state at the given index in the stack.
* The stack is LIFO so indexing is from the right.
*
* @param {Number} [index=0] Index to return.
* @returns {String} state
*/
function getState(index) {
return index ? stack[stack.length - 1 - index] : state;
}
/**
* Look ahead for a string beginning from the next position. The string
* being looked for must start at the next position.
*
* @param {String} str The string to look for.
* @returns {Boolean} Whether the string was found.
*/
function isNextString(str) {
var start = cursor + 1;
return (str === css.slice(start, start + str.length));
}
/**
* Find the start position of a substring beginning from the next
* position. The string being looked for may begin anywhere.
*
* @param {String} str The substring to look for.
* @returns {Number|false} The position, or `false` if not found.
*/
function find(str) {
var pos = css.slice(cursor).indexOf(str);
return pos > 0 ? pos : false;
}
/**
* Determine whether a character is next.
*
* @param {String} ch Character.
* @returns {Boolean} Whether the character is next.
*/
function isNextChar(ch) {
return ch === peek(1);
}
/**
* Return the character at the given cursor offset. The offset is relative
* to the cursor, so negative values move backwards.
*
* @param {Number} [offset=1] Cursor offset.
* @returns {String} Character.
*/
function peek(offset) {
return css[cursor + (offset || 1)];
}
/**
* Remove the current state from the stack and set the new current state.
*
* @returns {String} The removed state.
*/
function popState() {
var removed = stack.pop();
state = stack[stack.length - 1];
return removed;
}
/**
* Set the current state and add it to the stack.
*
* @param {String} newState The new state.
* @returns {Number} The new stack length.
*/
function pushState(newState) {
state = newState;
stack.push(state);
return stack.length;
}
/**
* Replace the current state with a new state.
*
* @param {String} newState The new state.
* @returns {String} The replaced state.
*/
function replaceState(newState) {
var previousState = state;
stack[stack.length - 1] = state = newState;
return previousState;
}
/**
* Move the character cursor. Positive numbers move the cursor forward.
* Negative numbers are not supported!
*
* @param {Number} [n=1] Number of characters to skip.
*/
function skip(n) {
if ((n || 1) == 1) {
if (css[cursor] == '\n') {
line++;
column = 1;
} else {
column++;
}
cursor++;
} else {
var skipStr = css.slice(cursor, cursor + n).split('\n');
if (skipStr.length > 1) {
line += skipStr.length - 1;
column = 1;
}
column += skipStr[skipStr.length - 1].length;
cursor = cursor + n;
}
}
/**
* Add the current token to the pile and reset the buffer.
*/
function addToken() {
token.end = {
line: line,
col: column
};
tokens.push(token);
buffer = '';
token = {};
}
/**
* Set the current token.
*
* @param {String} type Token type.
*/
function initializeToken(type) {
token = {
type: type,
start: {
line: line,
col : column
}
};
}
while (ch = getCh()) {
// column += 1;
switch (ch) {
// Space
case ' ':
switch (getState()) {
case 'selector':
case 'value':
case 'value-paren':
case 'at-group':
case 'at-value':
case 'comment':
case 'double-string':
case 'single-string':
buffer += ch;
break;
}
break;
// Newline or tab
case '\n':
case '\t':
case '\r':
case '\f':
switch (getState()) {
case 'value':
case 'value-paren':
case 'at-group':
case 'comment':
case 'single-string':
case 'double-string':
case 'selector':
buffer += ch;
break;
case 'at-value':
// Tokenize an @-rule if a semi-colon was omitted.
if ('\n' === ch) {
token.value = buffer.trim();
addToken();
popState();
}
break;
}
// if ('\n' === ch) {
// column = 0;
// line += 1;
// }
break;
case ':':
switch (getState()) {
case 'name':
token.name = buffer.trim();
buffer = '';
replaceState('before-value');
break;
case 'before-selector':
buffer += ch;
initializeToken('selector');
pushState('selector');
break;
case 'before-value':
replaceState('value');
buffer += ch;
break;
default:
buffer += ch;
break;
}
break;
case ';':
switch (getState()) {
case 'name':
case 'before-value':
case 'value':
// Tokenize a declaration
// if value is empty skip the declaration
if (buffer.trim().length > 0) {
token.value = buffer.trim(),
addToken();
}
replaceState('before-name');
break;
case 'value-paren':
// Insignificant semi-colon
buffer += ch;
break;
case 'at-value':
// Tokenize an @-rule
token.value = buffer.trim();
addToken();
popState();
break;
case 'before-name':
// Extraneous semi-colon
break;
default:
buffer += ch;
break;
}
break;
case '{':
switch (getState()) {
case 'selector':
// If the sequence is `\{` then assume that the brace should be escaped.
if (peek(-1) === '\\') {
buffer += ch;
break;
}
// Tokenize a selector
token.text = buffer.trim();
addToken();
replaceState('before-name');
depth = depth + 1;
break;
case 'at-group':
// Tokenize an @-group
token.name = buffer.trim();
// XXX: @-rules are starting to get hairy
switch (token.type) {
case 'font-face':
case 'viewport' :
case 'page' :
pushState('before-name');
break;
default:
pushState('before-selector');
}
addToken();
depth = depth + 1;
break;
case 'name':
case 'at-rule':
// Tokenize a declaration or an @-rule
token.name = buffer.trim();
addToken();
pushState('before-name');
depth = depth + 1;
break;
case 'comment':
case 'double-string':
case 'single-string':
// Ignore braces in comments and strings
buffer += ch;
break;
case 'before-value':
replaceState('value');
buffer += ch;
break;
}
break;
case '}':
switch (getState()) {
case 'before-name':
case 'name':
case 'before-value':
case 'value':
// If the buffer contains anything, it is a value
if (buffer) {
token.value = buffer.trim();
}
// If the current token has a name and a value it should be tokenized.
if (token.name && token.value) {
addToken();
}
// Leave the block
initializeToken('end');
addToken();
popState();
// We might need to leave again.
// XXX: What about 3 levels deep?
if ('at-group' === getState()) {
initializeToken('at-group-end');
addToken();
popState();
}
if (depth > 0) {
depth = depth - 1;
}
break;
case 'at-group':
case 'before-selector':
case 'selector':
// If the sequence is `\}` then assume that the brace should be escaped.
if (peek(-1) === '\\') {
buffer += ch;
break;
}
if (depth > 0) {
// Leave block if in an at-group
if ('at-group' === getState(1)) {
initializeToken('at-group-end');
addToken();
}
}
if (depth > 1) {
popState();
}
if (depth > 0) {
depth = depth - 1;
}
break;
case 'double-string':
case 'single-string':
case 'comment':
// Ignore braces in comments and strings.
buffer += ch;
break;
}
break;
// Strings
case '"':
case "'":
switch (getState()) {
case 'double-string':
if ('"' === ch && '\\' !== peek(-1)) {
popState();
}
break;
case 'single-string':
if ("'" === ch && '\\' !== peek(-1)) {
popState();
}
break;
case 'before-at-value':
replaceState('at-value');
pushState('"' === ch ? 'double-string' : 'single-string');
break;
case 'before-value':
replaceState('value');
pushState('"' === ch ? 'double-string' : 'single-string');
break;
case 'comment':
// Ignore strings within comments.
break;
default:
if ('\\' !== peek(-1)) {
pushState('"' === ch ? 'double-string' : 'single-string');
}
}
buffer += ch;
break;
// Comments
case '/':
switch (getState()) {
case 'comment':
case 'double-string':
case 'single-string':
// Ignore
buffer += ch;
break;
case 'before-value':
case 'selector':
case 'name':
case 'value':
if (isNextChar('*')) {
// Ignore comments in selectors, properties and values. They are
// difficult to represent in the AST.
var pos = find('*/');
if (pos) {
skip(pos + 1);
}
} else {
if (getState() == 'before-value') replaceState('value');
buffer += ch;
}
break;
default:
if (isNextChar('*')) {
// Create a comment token
initializeToken('comment');
pushState('comment');
skip();
}
else {
buffer += ch;
}
break;
}
break;
// Comment end or universal selector
case '*':
switch (getState()) {
case 'comment':
if (isNextChar('/')) {
// Tokenize a comment
token.text = buffer; // Don't trim()!
skip();
addToken();
popState();
}
else {
buffer += ch;
}
break;
case 'before-selector':
buffer += ch;
initializeToken('selector');
pushState('selector');
break;
case 'before-value':
replaceState('value');
buffer += ch;
break;
default:
buffer += ch;
}
break;
// @-rules
case '@':
switch (getState()) {
case 'comment':
case 'double-string':
case 'single-string':
buffer += ch;
break;
case 'before-value':
replaceState('value');
buffer += ch;
break;
default:
// Iterate over the supported @-rules and attempt to tokenize one.
var tokenized = false;
var name;
var rule;
for (var j = 0, len = atRules.length; !tokenized && j < len; ++j) {
rule = atRules[j];
name = rule.name || rule;
if (!isNextString(name)) { continue; }
tokenized = true;
initializeToken(name);
pushState(rule.state || 'at-group');
skip(name.length);
if (rule.prefix) {
token.prefix = rule.prefix;
}
if (rule.type) {
token.type = rule.type;
}
}
if (!tokenized) {
// Keep on truckin' America!
buffer += ch;
}
break;
}
break;
// Parentheses are tracked to disambiguate semi-colons, such as within a
// data URI.
case '(':
switch (getState()) {
case 'value':
pushState('value-paren');
break;
case 'before-value':
replaceState('value');
break;
}
buffer += ch;
break;
case ')':
switch (getState()) {
case 'value-paren':
popState();
break;
case 'before-value':
replaceState('value');
break;
}
buffer += ch;
break;
default:
switch (getState()) {
case 'before-selector':
initializeToken('selector');
pushState('selector');
break;
case 'before-name':
initializeToken('property');
replaceState('name');
break;
case 'before-value':
replaceState('value');
break;
case 'before-at-value':
replaceState('at-value');
break;
}
buffer += ch;
break;
}
}
return tokens;
}
});
var parser = createCommonjsModule(function (module, exports) {
var debug = debug_1('parse');
exports = module.exports = parse;
var _comments; // Whether comments are allowed.
var _depth; // Current block nesting depth.
var _position; // Whether to include line/column position.
var _tokens; // Array of lexical tokens.
/**
* Convert a CSS string or array of lexical tokens into a `stringify`-able AST.
*
* @param {String} css CSS string or array of lexical token
* @param {Object} [options]
* @param {Boolean} [options.comments=false] allow comment nodes in the AST
* @returns {Object} `stringify`-able AST
*/
function parse(css, options) {
options || (options = {});
_comments = !!options.comments;
_position = !!options.position;
_depth = 0;
// Operate on a copy of the given tokens, or the lex()'d CSS string.
_tokens = Array.isArray(css) ? css.slice() : lexer(css);
var rule;
var rules = [];
var token;
while ((token = next())) {
rule = parseToken(token);
rule && rules.push(rule);
}
return {
type: "stylesheet",
stylesheet: {
rules: rules
}
};
}
// -- Functions --------------------------------------------------------------
/**
* Build an AST node from a lexical token.
*
* @param {Object} token lexical token
* @param {Object} [override] object hash of properties that override those
* already in the token, or that will be added to the token.
* @returns {Object} AST node
*/
function astNode(token, override) {
override || (override = {});
var key;
var keys = ['type', 'name', 'value'];
var node = {};
// Avoiding [].forEach for performance reasons.
for (var i = 0; i < keys.length; ++i) {
key = keys[i];
if (token[key]) {
node[key] = override[key] || token[key];
}
}
keys = Object.keys(override);
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (!node[key]) {
node[key] = override[key];
}
}
if (_position) {
node.position = {
start: token.start,
end: token.end
};
}
return node;
}
/**
* Remove a lexical token from the stack and return the removed token.
*
* @returns {Object} lexical token
*/
function next() {
var token = _tokens.shift();
return token;
}
// -- Parse* Functions ---------------------------------------------------------
/**
* Convert an @-group lexical token to an AST node.
*
* @param {Object} token @-group lexical token
* @returns {Object} @-group AST node
*/
function parseAtGroup(token) {
_depth = _depth + 1;
// As the @-group token is assembled, relevant token values are captured here
// temporarily. They will later be used as `tokenize()` overrides.
var overrides = {};
switch (token.type) {
case 'font-face':
case 'viewport' :
overrides.declarations = parseDeclarations();
break;
case 'page':
overrides.prefix = token.prefix;
overrides.declarations = parseDeclarations();
break;
default:
overrides.prefix = token.prefix;
overrides.rules = parseRules();
}
return astNode(token, overrides);
}
/**
* Convert an @import lexical token to an AST node.
*
* @param {Object} token @import lexical token
* @returns {Object} @import AST node
*/
function parseAtImport(token) {
return astNode(token);
}
/**
* Convert an @charset token to an AST node.
*
* @param {Object} token @charset lexical token
* @returns {Object} @charset node
*/
function parseCharset(token) {
return astNode(token);
}
/**
* Convert a comment token to an AST Node.
*
* @param {Object} token comment lexical token
* @returns {Object} comment node
*/
function parseComment(token) {
return astNode(token, {text: token.text});
}
function parseNamespace(token) {
return astNode(token);
}
/**
* Convert a property lexical token to a property AST node.
*
* @returns {Object} property node
*/
function parseProperty(token) {
return astNode(token);
}
/**
* Convert a selector lexical token to a selector AST node.
*
* @param {Object} token selector lexical token
* @returns {Object} selector node
*/
function parseSelector(token) {
function trim(str) {
return str.trim();
}
return astNode(token, {
type: 'rule',
selectors: token.text.split(',').map(trim),
declarations: parseDeclarations()
});
}
/**
* Convert a lexical token to an AST node.
*
* @returns {Object|undefined} AST node
*/
function parseToken(token) {
switch (token.type) {
// Cases are listed in roughly descending order of probability.
case 'property': return parseProperty(token);
case 'selector': return parseSelector(token);
case 'at-group-end': _depth = _depth - 1; return;
case 'media' :
case 'keyframes' :return parseAtGroup(token);
case 'comment': if (_comments) { return parseComment(token); } break;
case 'charset': return parseCharset(token);
case 'import': return parseAtImport(token);
case 'namespace': return parseNamespace(token);
case 'font-face':
case 'supports' :
case 'viewport' :
case 'document' :
case 'page' : return parseAtGroup(token);
}
}
// -- Parse Helper Functions ---------------------------------------------------
/**
* Iteratively parses lexical tokens from the stack into AST nodes until a
* conditional function returns `false`, at which point iteration terminates
* and any AST nodes collected are returned.
*
* @param {Function} conditionFn
* @param {Object} token the lexical token being parsed
* @returns {Boolean} `true` if the token should be parsed, `false` otherwise
* @return {Array} AST nodes
*/
function parseTokensWhile(conditionFn) {
var node;
var nodes = [];
var token;
while ((token = next()) && (conditionFn && conditionFn(token))) {
node = parseToken(token);
node && nodes.push(node);
}
// Place an unused non-`end` lexical token back onto the stack.
if (token && token.type !== 'end') {
_tokens.unshift(token);
}
return nodes;
}
/**
* Convert a series of tokens into a sequence of declaration AST nodes.
*
* @returns {Array} declaration nodes
*/
function parseDeclarations() {
return parseTokensWhile(function (token) {
return (token.type === 'property' || token.type === 'comment');
});
}
/**
* Convert a series of tokens into a sequence of rule nodes.
*
* @returns {Array} rule nodes
*/
function parseRules() {
return parseTokensWhile(function () { return _depth; });
}
});
var stringify_1 = createCommonjsModule(function (module, exports) {
var debug = debug_1('stringify');
var _comments; // Whether comments are allowed in the stringified CSS.
var _compress; // Whether the stringified CSS should be compressed.
var _indentation; // Indentation option value.
var _level; // Current indentation level.
var _n; // Compression-aware newline character.
var _s; // Compression-aware space character.
exports = module.exports = stringify;
/**
* Convert a `stringify`-able AST into a CSS string.
*
* @param {Object} `stringify`-able AST
* @param {Object} [options]
* @param {Boolean} [options.comments=false] allow comments in the CSS
* @param {Boolean} [options.compress=false] compress whitespace
* @param {String} [options.indentation=''] indentation sequence
* @returns {String} CSS
*/
function stringify(ast, options) {
options || (options = {});
_indentation = options.indentation || '';
_compress = !!options.compress;
_comments = !!options.comments;
_level = 1;
if (_compress) {
_n = _s = '';
} else {
_n = '\n';
_s = ' ';
}
var css = reduce(ast.stylesheet.rules, stringifyNode).join('\n').trim();
return css;
}
// -- Functions --------------------------------------------------------------
/**
* Modify the indentation level, or return a compression-aware sequence of
* spaces equal to the current indentation level.
*
* @param {Number} [level=undefined] indentation level modifier
* @returns {String} sequence of spaces
*/
function indent(level) {
if (level) {
_level += level;
return;
}
if (_compress) { return ''; }
return Array(_level).join(_indentation || '');
}
// -- Stringify Functions ------------------------------------------------------
/**
* Stringify an @-rule AST node.
*
* Use `stringifyAtGroup()` when dealing with @-groups that may contain blocks
* such as @media.
*
* @param {String} type @-rule type. E.g., import, charset
* @returns {String} Stringified @-rule
*/
function stringifyAtRule(node) {
return '@' + node.type + ' ' + node.value + ';' + _n;
}
/**
* Stringify an @-group AST node.
*
* Use `stringifyAtRule()` when dealing with @-rules that may not contain blocks
* such as @import.
*
* @param {Object} node @-group AST node
* @returns {String}
*/
function stringifyAtGroup(node) {
var label = '';
var prefix = node.prefix || '';
if (node.name) {
label = ' ' + node.name;
}
// FIXME: @-rule conditional logic is leaking everywhere.
var chomp = node.type !== 'page';
return '@' + prefix + node.type + label + _s + stringifyBlock(node, chomp) + _n;
}
/**
* Stringify a comment AST node.
*
* @param {Object} node comment AST node
* @returns {String}
*/
function stringifyComment(node) {
if (!_comments) { return ''; }
return '/*' + (node.text || '') + '*/' + _n;
}
/**
* Stringify a rule AST node.
*
* @param {Object} node rule AST node
* @returns {String}
*/
function stringifyRule(node) {
var label;
if (node.selectors) {
label = node.selectors.join(',' + _n);
} else {
label = '@' + node.type;
label += node.name ? ' ' + node.name : '';
}
return indent() + label + _s + stringifyBlock(node) + _n;
}
// -- Stringify Helper Functions -----------------------------------------------
/**
* Reduce an array by applying a function to each item and retaining the truthy
* results.
*
* When `item.type` is `'comment'` `stringifyComment` will be applied instead.
*
* @param {Array} items array to reduce
* @param {Function} fn function to call for each item in the array
* @returns {Mixed} Truthy values will be retained, falsy values omitted
* @returns {Array} retained results
*/
function reduce(items, fn) {
return items.reduce(function (results, item) {
var result = (item.type === 'comment') ? stringifyComment(item) : fn(item);
result && results.push(result);
return results;
}, []);
}
/**
* Stringify an AST node with the assumption that it represents a block of
* declarations or other @-group contents.
*
* @param {Object} node AST node
* @returns {String}
*/
// FIXME: chomp should not be a magic boolean parameter
function stringifyBlock(node, chomp) {
var children = node.declarations;
var fn = stringifyDeclaration;
if (node.rules) {
children = node.rules;
fn = stringifyRule;
}
children = stringifyChildren(children, fn);
children && (children = _n + children + (chomp ? '' : _n));
return '{' + children + indent() + '}';
}
/**
* Stringify an array of child AST nodes by calling the given stringify function
* once for each child, and concatenating the results.
*
* @param {Array} children `node.rules` or `node.declarations`
* @param {Function} fn stringify function
* @returns {String}
*/
function stringifyChildren(children, fn) {
if (!children) { return ''; }
indent(1);
var results = reduce(children, fn);
indent(-1);
if (!results.length) { return ''; }
return results.join(_n);
}
/**
* Stringify a declaration AST node.
*
* @param {Object} node declaration AST node
* @returns {String}
*/
function stringifyDeclaration(node) {
if (node.type === 'property') {
return stringifyProperty(node);
}
}
/**
* Stringify an AST node.
*
* @param {Object} node AST node
* @returns {String}
*/
function stringifyNode(node) {
switch (node.type) {
// Cases are listed in roughly descending order of probability.
case 'rule': return stringifyRule(node);
case 'media' :
case 'keyframes': return stringifyAtGroup(node);
case 'comment': return stringifyComment(node);
case 'import' :
case 'charset' :
case 'namespace': return stringifyAtRule(node);
case 'font-face':
case 'supports' :
case 'viewport' :
case 'document' :
case 'page' : return stringifyAtGroup(node);
}
}
/**
* Stringify an AST property node.
*
* @param {Object} node AST property node
* @returns {String}
*/
function stringifyProperty(node) {
var name = node.name ? node.name + ':' + _s : '';
return indent() + name + node.value + ';';
}
});
var mensch = {
lex : lexer,
parse: parser,
stringify: stringify_1
};
// Notable changes from Slick.Parser 1.0.x
// The parser now uses 2 classes: Expressions and Expression
// `new Expressions` produces an array-like object containing a list of Expression objects
// - Expressions::toString() produces a cleaned up expressions string
// `new Expression` produces an array-like object
// - Expression::toString() produces a cleaned up expression string
// The only exposed method is parse, which produces a (cached) `new Expressions` instance
// parsed.raw is no longer present, use .toString()
// parsed.expression is now useless, just use the indices
// parsed.reverse() has been removed for now, due to its apparent uselessness
// Other changes in the Expressions object:
// - classNames are now unique, and save both escaped and unescaped values
// - attributes now save both escaped and unescaped values
// - pseudos now save both escaped and unescaped values
var escapeRe = /([-.*+?^${}()|[\]\/\\])/g,
unescapeRe = /\\/g;
var escape$1 = function(string){
// XRegExp v2.0.0-beta-3
// « https://github.com/slevithan/XRegExp/blob/master/src/xregexp.js
return (string + "").replace(escapeRe, '\\$1')
};
var unescape$1 = function(string){
return (string + "").replace(unescapeRe, '')
};
var slickRe = RegExp(
/*
#!/usr/bin/env ruby
puts "\t\t" + DATA.read.gsub(/\(\?x\)|\s+#.*$|\s+|\\$|\\n/,'')
__END__
"(?x)^(?:\
\\s* ( , ) \\s* # Separator \n\
| \\s* ( <combinator>+ ) \\s* # Combinator \n\
| ( \\s+ ) # CombinatorChildren \n\
| ( <unicode>+ | \\* ) # Tag \n\
| \\# ( <unicode>+ ) # ID \n\
| \\. ( <unicode>+ ) # ClassName \n\
| # Attribute \n\
\\[ \
\\s* (<unicode1>+) (?: \
\\s* ([*^$!~|]?=) (?: \
\\s* (?:\
([\"']?)(.*?)\\9 \
)\
) \
)? \\s* \
\\](?!\\]) \n\
| :+ ( <unicode>+ )(?:\
\\( (?:\
(?:([\"'])([^\\12]*)\\12)|((?:\\([^)]+\\)|[^()]*)+)\
) \\)\
)?\
)"
*/
"^(?:\\s*(,)\\s*|\\s*(<combinator>+)\\s*|(\\s+)|(<unicode>+|\\*)|\\#(<unicode>+)|\\.(<unicode>+)|\\[\\s*(<unicode1>+)(?:\\s*([*^$!~|]?=)(?:\\s*(?:([\"']?)(.*?)\\9)))?\\s*\\](?!\\])|(:+)(<unicode>+)(?:\\((?:(?:([\"'])([^\\13]*)\\13)|((?:\\([^)]+\\)|[^()]*)+))\\))?)"
.replace(/<combinator>/, '[' + escape$1(">+~`!@$%^&={}\\;</") + ']')
.replace(/<unicode>/g, '(?:[\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])')
.replace(/<unicode1>/g, '(?:[:\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])')
);
// Part
var Part = function Part(combinator){
this.combinator = combinator || " ";
this.tag = "*";
};
Part.prototype.toString = function(){
if (!this.raw){
var xpr = "", k, part;
xpr += this.tag || "*";
if (this.id) xpr += "#" + this.id;
if (this.classes) xpr += "." + this.classList.join(".");
if (this.attributes) for (k = 0; part = this.attributes[k++];){
xpr += "[" + part.name + (part.operator ? part.operator + '"' + part.value + '"' : '') + "]";
}
if (this.pseudos) for (k = 0; part = this.pseudos[k++];){
xpr += ":" + part.name;
if (part.value) xpr += "(" + part.value + ")";
}
this.raw = xpr;
}
return this.raw
};
// Expression
var Expression = function Expression(){
this.length = 0;
};
Expression.prototype.toString = function(){
if (!this.raw){
var xpr = "";
for (var j = 0, bit; bit = this[j++];){
if (j !== 1) xpr += " ";
if (bit.combinator !== " ") xpr += bit.combinator + " ";
xpr += bit;
}
this.raw = xpr;
}
return this.raw
};
var replacer$1 = function(
rawMatch,
separator,
combinator,
combinatorChildren,
tagName,
id,
className,
attributeKey,
attributeOperator,
attributeQuote,
attributeValue,
pseudoMarker,
pseudoClass,
pseudoQuote,
pseudoClassQuotedValue,
pseudoClassValue
){
var expression, current;
if (separator || !this.length){
expression = this[this.length++] = new Expression;
if (separator) return ''
}
if (!expression) expression = this[this.length - 1];
if (combinator || combinatorChildren || !expression.length){
current = expression[expression.length++] = new Part(combinator);
}
if (!current) current = expression[expression.length - 1];
if (tagName){
current.tag = unescape$1(tagName);
} else if (id){
current.id = unescape$1(id);
} else if (className){
var unescaped = unescape$1(className);
var classes = current.classes || (current.classes = {});
if (!classes[unescaped]){
classes[unescaped] = escape$1(className);
var classList = current.classList || (current.classList = []);
classList.push(unescaped);
classList.sort();
}
} else if (pseudoClass){
pseudoClassValue = pseudoClassValue || pseudoClassQuotedValue
;(current.pseudos || (current.pseudos = [])).push({
type : pseudoMarker.length == 1 ? 'class' : 'element',
name : unescape$1(pseudoClass),
escapedName : escape$1(pseudoClass),
value : pseudoClassValue ? unescape$1(pseudoClassValue) : null,
escapedValue : pseudoClassValue ? escape$1(pseudoClassValue) : null
});
} else if (attributeKey){
attributeValue = attributeValue ? escape$1(attributeValue) : null
;(current.attributes || (current.attributes = [])).push({
operator : attributeOperator,
name : unescape$1(attributeKey),
escapedName : escape$1(attributeKey),
value : attributeValue ? unescape$1(attributeValue) : null,
escapedValue : attributeValue ? escape$1(attributeValue) : null
});
}
return ''
};
// Expressions
var Expressions = function Expressions(expression){
this.length = 0;
var self = this;
var original = expression, replaced;
while (expression){
replaced = expression.replace(slickRe, function(){
return replacer$1.apply(self, arguments)
});
if (replaced === expression) throw new Error(original + ' is an invalid expression')
expression = replaced;
}
};
Expressions.prototype.toString = function(){
if (!this.raw){
var expressions = [];
for (var i = 0, expression; expression = this[i++];) expressions.push(expression);
this.raw = expressions.join(", ");
}
return this.raw
};
var cache = {};
var parse$5 = function(expression){
if (expression == null) return null
expression = ('' + expression).replace(/^\s+|\s+$/g, '');
return cache[expression] || (cache[expression] = new Expressions(expression))
};
var parser$1 = parse$5;
var selector = createCommonjsModule(function (module, exports) {
module.exports = exports = Selector;
/**
* CSS selector constructor.
*
* @param {String} selector text
* @param {Array} optionally, precalculated specificity
* @api public
*/
function Selector(text, styleAttribute) {
this.text = text;
this.spec = undefined;
this.styleAttribute = styleAttribute || false;
}
/**
* Get parsed selector.
*
* @api public
*/
Selector.prototype.parsed = function() {
if (!this.tokens) { this.tokens = parse(this.text); }
return this.tokens;
};
/**
* Lazy specificity getter
*
* @api public
*/
Selector.prototype.specificity = function() {
var styleAttribute = this.styleAttribute;
if (!this.spec) { this.spec = specificity(this.text, this.parsed()); }
return this.spec;
function specificity(text, parsed) {
var expressions = parsed || parse(text);
var spec = [styleAttribute ? 1 : 0, 0, 0, 0];
var nots = [];
for (var i = 0; i < expressions.length; i++) {
var expression = expressions[i];
var pseudos = expression.pseudos;
// id awards a point in the second column
if (expression.id) { spec[1]++; }
// classes and attributes award a point each in the third column
if (expression.attributes) { spec[2] += expression.attributes.length; }
if (expression.classList) { spec[2] += expression.classList.length; }
// tag awards a point in the fourth column
if (expression.tag && expression.tag !== '*') { spec[3]++; }
// pseudos award a point each in the fourth column
if (pseudos) {
spec[3] += pseudos.length;
for (var p = 0; p < pseudos.length; p++) {
if (pseudos[p].name === 'not') {
nots.push(pseudos[p].value);
spec[3]--;
}
}
}
}
for (var ii = nots.length; ii--;) {
var not = specificity(nots[ii]);
for (var jj = 4; jj--;) { spec[jj] += not[jj]; }
}
return spec;
}
};
/**
* Parses a selector and returns the tokens.
*
* @param {String} selector
* @api private.
*/
function parse(text) {
try {
return parser$1(text)[0];
} catch (e) {
return [];
}
}
});
var property = createCommonjsModule(function (module, exports) {
module.exports = exports = Property;
/**
* Module dependencies.
*/
/**
* CSS property constructor.
*
* @param {String} property
* @param {String} value
* @param {Selector} selector the property originates from
* @param {Integer} priority 0 for normal properties, 2 for !important properties.
* @param {Array} additional array of integers representing more detailed priorities (sorting)
* @api public
*/
function Property(prop, value, selector, priority, additionalPriority) {
this.prop = prop;
this.value = value;
this.selector = selector;
this.priority = priority || 0;
this.additionalPriority = additionalPriority || [];
}
/**
* Compares with another Property based on Selector#specificity.
*
* @api public
*/
Property.prototype.compareFunc = function(property) {
var a = [];
a.push.apply(a, this.selector.specificity());
a.push.apply(a, this.additionalPriority);
a[0] += this.priority;
var b = [];
b.push.apply(b, property.selector.specificity());
b.push.apply(b, property.additionalPriority);
b[0] += property.priority;
return utils$1.compareFunc(a, b);
};
Property.prototype.compare = function(property) {
var winner = this.compareFunc(property);
if (winner === 1) {
return this;
}
return property;
};
/**
* Returns CSS property
*
* @api public
*/
Property.prototype.toString = function() {
return this.prop + ': ' + this.value.replace(/['"]+/g, '') + ';';
};
});
var utils$1 = createCommonjsModule(function (module, exports) {
/**
* Module dependencies.
*/
exports.Selector = selector;
exports.Property = property;
/**
* Returns an array of the selectors.
*
* @license Sizzle CSS Selector Engine - MIT
* @param {String} selectorText from mensch
* @api public
*/
exports.extract = function extract(selectorText) {
var attr = 0;
var sels = [];
var sel = '';
for (var i = 0, l = selectorText.length; i < l; i++) {
var c = selectorText.charAt(i);
if (attr) {
if (']' === c || ')' === c) { attr--; }
sel += c;
} else {
if (',' === c) {
sels.push(sel);
sel = '';
} else {
if ('[' === c || '(' === c) { attr++; }
if (sel.length || (c !== ',' && c !== '\n' && c !== ' ')) { sel += c; }
}
}
}
if (sel.length) {
sels.push(sel);
}
return sels;
};
/**
* Returns a parse tree for a CSS source.
* If it encounters multiple selectors separated by a comma, it splits the
* tree.
*
* @param {String} css source
* @api public
*/
exports.parseCSS = function(css) {
var parsed = mensch.parse(css, {position: true, comments: true});
var rules = typeof parsed.stylesheet != 'undefined' && parsed.stylesheet.rules ? parsed.stylesheet.rules : [];
var ret = [];
for (var i = 0, l = rules.length; i < l; i++) {
if (rules[i].type == 'rule') {
var rule = rules[i];
var selectors = rule.selectors;
for (var ii = 0, ll = selectors.length; ii < ll; ii++) {
ret.push([selectors[ii], rule.declarations]);
}
}
}
return ret;
};
/**
* Returns preserved text for a CSS source.
*
* @param {String} css source
* @param {Object} options
* @api public
*/
exports.getPreservedText = function(css, options, ignoredPseudos) {
var parsed = mensch.parse(css, {position: true, comments: true});
var rules = typeof parsed.stylesheet != 'undefined' && parsed.stylesheet.rules ? parsed.stylesheet.rules : [];
var preserved = [];
var lastStart = null;
for (var i = rules.length - 1; i >= 0; i--) {
if ((options.fontFaces && rules[i].type === 'font-face') ||
(options.mediaQueries && rules[i].type === 'media') ||
(options.keyFrames && rules[i].type === 'keyframes') ||
(options.pseudos && rules[i].selectors && this.matchesPseudo(rules[i].selectors[0], ignoredPseudos))) {
preserved.unshift(
mensch.stringify(
{ stylesheet: { rules: [ rules[i] ] }},
{ comments: false, indentation: ' ' }
)
);
}
lastStart = rules[i].position.start;
}
if (preserved.length === 0) {
return false;
}
return '\n' + preserved.join('\n') + '\n';
};
exports.normalizeLineEndings = function(text) {
return text.replace(/\r\n/g, '\n').replace(/\n/g, '\r\n');
};
exports.matchesPseudo = function(needle, haystack) {
return haystack.find(function (element) {
return needle.indexOf(element) > -1;
})
};
/**
* Compares two specificity vectors, returning the winning one.
*
* @param {Array} vector a
* @param {Array} vector b
* @return {Array}
* @api public
*/
exports.compareFunc = function(a, b) {
var min = Math.min(a.length, b.length);
for (var i = 0; i < min; i++) {
if (a[i] === b[i]) { continue; }
if (a[i] > b[i]) { return 1; }
return -1;
}
return a.length - b.length;
};
exports.compare = function(a, b) {
return exports.compareFunc(a, b) == 1 ? a : b;
};
exports.getDefaultOptions = function(options) {
var result = Object.assign({
extraCss: '',
insertPreservedExtraCss: true,
applyStyleTags: true,
removeStyleTags: true,
preserveMediaQueries: true,
preserveFontFaces: true,
preserveKeyFrames: true,
preservePseudos: true,
applyWidthAttributes: true,
applyHeightAttributes: true,
applyAttributesTableElements: true,
url: ''
}, options);
result.webResources = result.webResources || {};
return result;
};
});
var utils_1 = utils$1.Selector;
var utils_2 = utils$1.Property;
var utils_3 = utils$1.extract;
var utils_4 = utils$1.parseCSS;
var utils_5 = utils$1.getPreservedText;
var utils_6 = utils$1.normalizeLineEndings;
var utils_7 = utils$1.matchesPseudo;
var utils_8 = utils$1.compareFunc;
var utils_9 = utils$1.compare;
var utils_10 = utils$1.getDefaultOptions;
var cheerio_1 = createCommonjsModule(function (module) {
/**
* Module dependencies.
*/
var cheerioLoad = function(html, options, encodeEntities) {
options = Object.assign({decodeEntities: false, _useHtmlParser2:true}, options);
html = encodeEntities(html);
return cheerio.load(html, options);
};
var createEntityConverters = function () {
var codeBlockLookup = [];
var encodeCodeBlocks = function(html) {
var blocks = module.exports.codeBlocks;
Object.keys(blocks).forEach(function(key) {
var re = new RegExp(blocks[key].start + '([\\S\\s]*?)' + blocks[key].end, 'g');
html = html.replace(re, function(match, subMatch) {
codeBlockLookup.push(match);
return 'JUICE_CODE_BLOCK_' + (codeBlockLookup.length - 1) + '_';
});
});
return html;
};
var decodeCodeBlocks = function(html) {
for(var index = 0; index < codeBlockLookup.length; index++) {
var re = new RegExp('JUICE_CODE_BLOCK_' + index + '_(="")?', 'gi');
html = html.replace(re, function() {
return codeBlockLookup[index];
});
}
return html;
};
return {
encodeEntities: encodeCodeBlocks,
decodeEntities: decodeCodeBlocks,
};
};
/**
* Parses the input, calls the callback on the parsed DOM, and generates the output
*
* @param {String} html input html to be processed
* @param {Object} options for the parser
* @param {Function} callback to be invoked on the DOM
* @param {Array} callbackExtraArguments to be passed to the callback
* @return {String} resulting html
*/
module.exports = function(html, options, callback, callbackExtraArguments) {
var entityConverters = createEntityConverters();
var $ = cheerioLoad(html, options, entityConverters.encodeEntities);
var args = [ $ ];
args.push.apply(args, callbackExtraArguments);
var doc = callback.apply(undefined, args) || $;
if (options && options.xmlMode) {
return entityConverters.decodeEntities(doc.xml());
}
return entityConverters.decodeEntities(doc.html());
};
module.exports.codeBlocks = {
EJS: { start: '<%', end: '%>' },
HBS: { start: '{{', end: '}}' }
};
});
var cheerio_2 = cheerio_1.codeBlocks;
/**
* Converts a decimal number to roman numeral.
* https://stackoverflow.com/questions/9083037/convert-a-number-into-a-roman-numeral-in-javascript
*
* @param {Number} number
* @api private.
*/
var romanize = function(num) {
if (isNaN(num))
return NaN;
var digits = String(+num).split(""),
key = ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM",
"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC",
"","I","II","III","IV","V","VI","VII","VIII","IX"],
roman = "",
i = 3;
while (i--)
roman = (key[+digits.pop() + (i * 10)] || "") + roman;
return Array(+digits.join("") + 1).join("M") + roman;
};
/**
* Converts a decimal number to alphanumeric numeral.
* https://stackoverflow.com/questions/45787459/convert-number-to-alphabet-string-javascript
*
* @param {Number} number
* @api private.
*/
var alphanumeric = function(num) {
var s = '', t;
while (num > 0) {
t = (num - 1) % 26;
s = String.fromCharCode(65 + t) + s;
num = (num - t)/26 | 0;
}
return s || undefined;
};
var numbers = {
romanize: romanize,
alphanumeric: alphanumeric
};
var inline = function makeJuiceClient(juiceClient) {
juiceClient.ignoredPseudos = ['hover', 'active', 'focus', 'visited', 'link'];
juiceClient.widthElements = ['TABLE', 'TD', 'TH', 'IMG'];
juiceClient.heightElements = ['TABLE', 'TD', 'TH', 'IMG'];
juiceClient.tableElements = ['TABLE', 'TH', 'TR', 'TD', 'CAPTION', 'COLGROUP', 'COL', 'THEAD', 'TBODY', 'TFOOT'];
juiceClient.nonVisualElements = [ 'HEAD', 'TITLE', 'BASE', 'LINK', 'STYLE', 'META', 'SCRIPT', 'NOSCRIPT' ];
juiceClient.styleToAttribute = {
'background-color': 'bgcolor',
'background-image': 'background',
'text-align': 'align',
'vertical-align': 'valign'
};
juiceClient.excludedProperties = [];
juiceClient.juiceDocument = juiceDocument;
juiceClient.inlineDocument = inlineDocument;
function inlineDocument($, css, options) {
options = options || {};
var rules = utils$1.parseCSS(css);
var editedElements = [];
var styleAttributeName = 'style';
var counters = {};
if (options.styleAttributeName) {
styleAttributeName = options.styleAttributeName;
}
rules.forEach(handleRule);
editedElements.forEach(setStyleAttrs);
if (options.inlinePseudoElements) {
editedElements.forEach(inlinePseudoElements);
}
if (options.applyWidthAttributes) {
editedElements.forEach(function(el) {
setDimensionAttrs(el, 'width');
});
}
if (options.applyHeightAttributes) {
editedElements.forEach(function(el) {
setDimensionAttrs(el, 'height');
});
}
if (options.applyAttributesTableElements) {
editedElements.forEach(setAttributesOnTableElements);
}
if (options.insertPreservedExtraCss && options.extraCss) {
var preservedText = utils$1.getPreservedText(options.extraCss, {
mediaQueries: options.preserveMediaQueries,
fontFaces: options.preserveFontFaces,
keyFrames: options.preserveKeyFrames
});
if (preservedText) {
var $appendTo = null;
if (options.insertPreservedExtraCss !== true) {
$appendTo = $(options.insertPreservedExtraCss);
} else {
$appendTo = $('head');
if (!$appendTo.length) { $appendTo = $('body'); }
if (!$appendTo.length) { $appendTo = $.root(); }
}
$appendTo.first().append('<style>' + preservedText + '</style>');
}
}
function handleRule(rule) {
var sel = rule[0];
var style = rule[1];
var selector = new utils$1.Selector(sel);
var parsedSelector = selector.parsed();
if (!parsedSelector) {
return;
}
var pseudoElementType = getPseudoElementType(parsedSelector);
// skip rule if the selector has any pseudos which are ignored
for (var i = 0; i < parsedSelector.length; ++i) {
var subSel = parsedSelector[i];
if (subSel.pseudos) {
for (var j = 0; j < subSel.pseudos.length; ++j) {
var subSelPseudo = subSel.pseudos[j];
if (juiceClient.ignoredPseudos.indexOf(subSelPseudo.name) >= 0) {
return;
}
}
}
}
if (pseudoElementType) {
var last = parsedSelector[parsedSelector.length - 1];
var pseudos = last.pseudos;
last.pseudos = filterElementPseudos(last.pseudos);
sel = parsedSelector.toString();
last.pseudos = pseudos;
}
var els;
try {
els = $(sel);
} catch (err) {
// skip invalid selector
return;
}
els.each(function() {
var el = this;
if (el.name && juiceClient.nonVisualElements.indexOf(el.name.toUpperCase()) >= 0) {
return;
}
if (pseudoElementType) {
var pseudoElPropName = 'pseudo' + pseudoElementType;
var pseudoEl = el[pseudoElPropName];
if (!pseudoEl) {
pseudoEl = el[pseudoElPropName] = $('<span />').get(0);
pseudoEl.pseudoElementType = pseudoElementType;
pseudoEl.pseudoElementParent = el;
pseudoEl.counterProps = el.counterProps;
el[pseudoElPropName] = pseudoEl;
}
el = pseudoEl;
}
if (!el.styleProps) {
el.styleProps = {};
// if the element has inline styles, fake selector with topmost specificity
if ($(el).attr(styleAttributeName)) {
var cssText = '* { ' + $(el).attr(styleAttributeName) + ' } ';
addProps(utils$1.parseCSS(cssText)[0][1], new utils$1.Selector('<style>', true));
}
// store reference to an element we need to compile style="" attr for
editedElements.push(el);
}
if (!el.counterProps) {
el.counterProps = el.parent && el.parent.counterProps
? Object.create(el.parent.counterProps)
: {};
}
function resetCounter(el, value) {
var tokens = value.split(/\s+/);
for (var j = 0; j < tokens.length; j++) {
var counter = tokens[j];
var resetval = parseInt(tokens[j+1], 10);
isNaN(resetval)
? el.counterProps[counter] = counters[counter] = 0
: el.counterProps[counter] = counters[tokens[j++]] = resetval;
}
}
function incrementCounter(el, value) {
var tokens = value.split(/\s+/);
for (var j = 0; j < tokens.length; j++) {
var counter = tokens[j];
if (el.counterProps[counter] === undefined) {
continue;
}
var incrval = parseInt(tokens[j+1], 10);
isNaN(incrval)
? el.counterProps[counter] = counters[counter] += 1
: el.counterProps[counter] = counters[tokens[j++]] += incrval;
}
}
// go through the properties
function addProps(style, selector) {
for (var i = 0, l = style.length; i < l; i++) {
if (style[i].type == 'property') {
var name = style[i].name;
var value = style[i].value;
if (name === 'counter-reset') {
resetCounter(el, value);
}
if (name === 'counter-increment') {
incrementCounter(el, value);
}
var important = value.match(/!important$/) !== null;
if (important && !options.preserveImportant) value = removeImportant(value);
// adds line number and column number for the properties as "additionalPriority" to the
// properties because in CSS the position directly affect the priority.
var additionalPriority = [style[i].position.start.line, style[i].position.start.col];
var prop = new utils$1.Property(name, value, selector, important ? 2 : 0, additionalPriority);
var existing = el.styleProps[name];
// if property name is not in the excluded properties array
if (juiceClient.excludedProperties.indexOf(name) < 0) {
if (existing && existing.compare(prop) === prop || !existing) {
// deleting a property let us change the order (move it to the end in the setStyleAttrs loop)
if (existing && existing.selector !== selector) {
delete el.styleProps[name];
} else if (existing) {
// make "prop" a special composed property.
prop.nextProp = existing;
}
el.styleProps[name] = prop;
}
}
}
}
}
addProps(style, selector);
});
}
function setStyleAttrs(el) {
var l = Object.keys(el.styleProps).length;
var props = [];
// Here we loop each property and make sure to "expand"
// linked "nextProp" properties happening when the same property
// is declared multiple times in the same selector.
Object.keys(el.styleProps).forEach(function(key) {
var np = el.styleProps[key];
while (typeof np !== 'undefined') {
props.push(np);
np = np.nextProp;
}
});
// sort properties by their originating selector's specificity so that
// props like "padding" and "padding-bottom" are resolved as expected.
props.sort(function(a, b) {
return a.compareFunc(b);
});
var string = props
.filter(function(prop) {
// Content becomes the innerHTML of pseudo elements, not used as a
// style property
return prop.prop !== 'content';
})
.map(function(prop) {
return prop.prop + ': ' + prop.value.replace(/["]/g, '\'') + ';';
})
.join(' ');
if (string) {
$(el).attr(styleAttributeName, string);
}
}
function inlinePseudoElements(el) {
if (el.pseudoElementType && el.styleProps.content) {
var parsed = parseContent(el);
if (parsed.img) {
el.name = 'img';
$(el).attr('src', parsed.img);
} else {
$(el).text(parsed);
}
var parent = el.pseudoElementParent;
if (el.pseudoElementType === 'before') {
$(parent).prepend(el);
} else {
$(parent).append(el);
}
}
}
function setDimensionAttrs(el, dimension) {
if (!el.name) { return; }
var elName = el.name.toUpperCase();
if (juiceClient[dimension + 'Elements'].indexOf(elName) > -1) {
for (var i in el.styleProps) {
if (el.styleProps[i].prop === dimension) {
var value = el.styleProps[i].value;
if (options.preserveImportant) {
value = removeImportant(value);
}
if (value.match(/px/)) {
var pxSize = value.replace('px', '');
$(el).attr(dimension, pxSize);
return;
}
if (juiceClient.tableElements.indexOf(elName) > -1 && value.match(/\%/)) {
$(el).attr(dimension, value);
return;
}
}
}
}
}
function extractBackgroundUrl(value) {
return value.indexOf('url(') !== 0
? value
: value.replace(/^url\((["'])?([^"']+)\1\)$/, '$2');
}
function setAttributesOnTableElements(el) {
if (!el.name) { return; }
var elName = el.name.toUpperCase();
var styleProps = Object.keys(juiceClient.styleToAttribute);
if (juiceClient.tableElements.indexOf(elName) > -1) {
for (var i in el.styleProps) {
if (styleProps.indexOf(el.styleProps[i].prop) > -1) {
var prop = juiceClient.styleToAttribute[el.styleProps[i].prop];
var value = el.styleProps[i].value;
if (options.preserveImportant) {
value = removeImportant(value);
}
if (prop === 'background') {
value = extractBackgroundUrl(value);
}
if (/(linear|radial)-gradient\(/i.test(value)) {
continue;
}
$(el).attr(prop, value);
}
}
}
}
}
function removeImportant(value) {
return value.replace(/\s*!important$/, '')
}
function findVariableValue(el, variable) {
while (el) {
if (variable in el.styleProps) {
return el.styleProps[variable].value;
}
var el = el.parent || el.pseudoElementParent;
}
}
function applyCounterStyle(counter, style) {
switch (style) {
case 'lower-roman':
return numbers.romanize(counter).toLowerCase();
case 'upper-roman':
return numbers.romanize(counter);
case 'lower-latin':
case 'lower-alpha':
return numbers.alphanumeric(counter).toLowerCase();
case 'upper-latin':
case 'upper-alpha':
return numbers.alphanumeric(counter);
// TODO support more counter styles
default:
return counter.toString();
}
}
function parseContent(el) {
var content = el.styleProps.content.value;
if (content === 'none' || content === 'normal') {
return '';
}
var imageUrlMatch = content.match(/^\s*url\s*\(\s*(.*?)\s*\)\s*$/i);
if (imageUrlMatch) {
var url = imageUrlMatch[1].replace(/^['"]|['"]$/g, '');
return { img: url };
}
var parsed = [];
var tokens = content.split(/['"]/);
for (var i = 0; i < tokens.length; i++) {
if (tokens[i] === '') continue;
var varMatch = tokens[i].match(/var\s*\(\s*(.*?)\s*(,\s*(.*?)\s*)?\s*\)/i);
if (varMatch) {
var variable = findVariableValue(el, varMatch[1]) || varMatch[2];
parsed.push(variable.replace(/^['"]|['"]$/g, ''));
continue;
}
var counterMatch = tokens[i].match(/counter\s*\(\s*(.*?)\s*(,\s*(.*?)\s*)?\s*\)/i);
if (counterMatch && counterMatch[1] in el.counterProps) {
var counter = el.counterProps[counterMatch[1]];
parsed.push(applyCounterStyle(counter, counterMatch[3]));
continue;
}
var attrMatch = tokens[i].match(/attr\s*\(\s*(.*?)\s*\)/i);
if (attrMatch) {
var attr = attrMatch[1];
parsed.push(el.pseudoElementParent
? el.pseudoElementParent.attribs[attr]
: el.attribs[attr]
);
continue;
}
parsed.push(tokens[i]);
}
content = parsed.join('');
// Naive unescape, assume no unicode char codes
content = content.replace(/\\/g, '');
return content;
}
// Return "before" or "after" if the given selector is a pseudo element (e.g.,
// a::after).
function getPseudoElementType(selector) {
if (selector.length === 0) {
return;
}
var pseudos = selector[selector.length - 1].pseudos;
if (!pseudos) {
return;
}
for (var i = 0; i < pseudos.length; i++) {
if (isPseudoElementName(pseudos[i])) {
return pseudos[i].name;
}
}
}
function isPseudoElementName(pseudo) {
return pseudo.name === 'before' || pseudo.name === 'after';
}
function filterElementPseudos(pseudos) {
return pseudos.filter(function(pseudo) {
return !isPseudoElementName(pseudo);
});
}
function juiceDocument($, options) {
options = utils$1.getDefaultOptions(options);
var css = extractCssFromDocument($, options);
css += '\n' + options.extraCss;
inlineDocument($, css, options);
return $;
}
function getStylesData($, options) {
var results = [];
var stylesList = $('style');
var styleDataList, styleData, styleElement;
stylesList.each(function() {
styleElement = this;
// the API for Cheerio using parse5 (default) and htmlparser2 are slightly different
// detect this by checking if .childNodes exist (as opposed to .children)
var usingParse5 = !!styleElement.childNodes;
styleDataList = usingParse5 ? styleElement.childNodes : styleElement.children;
if (styleDataList.length !== 1) {
if (options.removeStyleTags) {
$(styleElement).remove();
}
return;
}
styleData = styleDataList[0].data;
if (options.applyStyleTags && $(styleElement).attr('data-embed') === undefined) {
results.push(styleData);
}
if (options.removeStyleTags && $(styleElement).attr('data-embed') === undefined) {
var text = usingParse5 ? styleElement.childNodes[0].nodeValue : styleElement.children[0].data;
var preservedText = utils$1.getPreservedText(text, {
mediaQueries: options.preserveMediaQueries,
fontFaces: options.preserveFontFaces,
keyFrames: options.preserveKeyFrames,
pseudos: options.preservePseudos
}, juiceClient.ignoredPseudos);
if (preservedText) {
if (usingParse5) {
styleElement.childNodes[0].nodeValue = preservedText;
} else {
styleElement.children[0].data = preservedText;
}
} else {
$(styleElement).remove();
}
}
$(styleElement).removeAttr('data-embed');
});
return results;
}
function extractCssFromDocument($, options) {
var results = getStylesData($, options);
var css = results.join('\n');
return css;
}
return juiceClient;
};
/**
* Note that makeJuiceClient will take a base object (in this case a function) and enhance it
* with a lot of useful properties and functions.
*
* This client adopts cheerio as a DOM parser and adds an "inlineContent" function that let
* users to specify the CSS to be inlined instead of extracting it from the html.
*
* The weird "makeJuiceClient" behaviour is there in order to keep backward API compatibility.
*/
var juiceClient = inline(function(html,options) {
return cheerio_1(html, { xmlMode: options && options.xmlMode}, juiceDocument, [options]);
});
var juiceDocument = function(html, options) {
return juiceClient.juiceDocument(html, options);
};
juiceClient.inlineContent = function(html, css, options) {
return cheerio_1(html, { xmlMode: options && options.xmlMode}, juiceClient.inlineDocument, [css, options]);
};
var client = juiceClient;
function _createSuper$1j(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1j(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1j() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 复制按钮用来复制预览区的html内容
* 该操作会将预览区的css样式以行内样式的形式插入到html内容里从而保证粘贴时样式一致
*/
var Copy = /*#__PURE__*/function (_MenuBase) {
_inherits(Copy, _MenuBase);
var _super = _createSuper$1j(Copy);
function Copy($cherry) {
var _this;
_classCallCheck(this, Copy);
_this = _super.call(this, $cherry);
_this.previewer = $cherry.previewer;
_this.isLoading = false;
_this.updateMarkdown = false;
_this.setName('copy', 'copy');
return _this;
}
_createClass(Copy, [{
key: "adaptWechat",
value: function () {
var _adaptWechat = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(rawHtml) {
var figureRegex, html, imgRegex, promises, urls;
return regenerator.wrap(function _callee$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
// 转化链接
// Array.from(document.querySelectorAll('a')).forEach((item) => {
// item.removeAttribute('href');
// });
// 防止echarts标签被转成p时丢失样式
figureRegex = /(<figure data-lines=.+?<)div(.+?<\/)div(>.*?<\/figure>)/g;
html = rawHtml.replace(figureRegex, function (match, prefix, content, suffix) {
var _context, _context2;
return concat$5(_context = concat$5(_context2 = "".concat(prefix, "p")).call(_context2, content, "p")).call(_context, suffix);
}); // 图片转base64防止无法自动上传
imgRegex = /(<img.+?src=")(.+?)(".*?>)/g;
/** @type {(Promise<string>)[]} */
promises = [];
html.replace(imgRegex, function (match, prefix, src) {
promises.push(convertImgToBase64(src));
});
_context3.next = 7;
return promise$7.all(promises);
case 7:
urls = _context3.sent;
return _context3.abrupt("return", html.replace(imgRegex, function (match, prefix, src, suffix) {
return prefix + urls.shift() + suffix;
}));
case 9:
case "end":
return _context3.stop();
}
}
}, _callee);
}));
function adaptWechat(_x) {
return _adaptWechat.apply(this, arguments);
}
return adaptWechat;
}()
}, {
key: "getStyleFromSheets",
value: function getStyleFromSheets(keyword) {
var _context4;
var sheets = filter$3(_context4 = from_1$2(document.styleSheets)).call(_context4, function (item) {
var _context5;
return indexOf$8(_context5 = item.cssRules[0].cssText).call(_context5, keyword) > -1;
});
return "<style>".concat(reduce$3(sheets).call(sheets, function (html, sheet) {
var _context6;
return html + reduce$3(_context6 = from_1$2(sheet.cssRules)).call(_context6, function (html, rule) {
return html + rule.cssText;
}, '');
}, ''), "</style>");
}
}, {
key: "computeStyle",
value: function computeStyle() {
// 计算需要append进富文本的style
var mathStyle = this.getStyleFromSheets('mjx-container');
var cherryStyle = this.getStyleFromSheets('cherry');
var echartStyle = '<style>figure>p{overflow:hidden;position:relative;width:500px;height:300px;background:transparent;}</style>';
return {
mathStyle: mathStyle,
echartStyle: echartStyle,
cherryStyle: cherryStyle
};
}
/**
* 由于复制操作会随着预览区域的内容增加而耗时变长,所以需要增加“正在复制”的状态回显
* 同时该状态也用于限频
*/
}, {
key: "toggleLoading",
value: function toggleLoading() {
// 切换loading状态
if (this.isLoading) {
var loadingButton = document.querySelector('.icon-loading');
loadingButton.outerHTML = "<i class=\"ch-icon ch-icon-copy\" title=\"".concat(this.locale.copy, "\"></i>");
} else {
var copyButton = document.querySelector('.ch-icon-copy');
copyButton.outerHTML = '<div class="icon-loading loading"></div>';
}
this.isLoading = !this.isLoading;
}
/**
* 响应点击事件
* 该按钮不会引发编辑区域的内容改动,所以不用处理用户在编辑区域的选中内容
* @param {Event} e 点击事件
*/
}, {
key: "onClick",
value: function onClick(e) {
var _this2 = this;
this.toggleLoading();
var inlineCodeTheme = document.querySelector('.cherry').getAttribute('data-inline-code-theme');
var codeBlockTheme = document.querySelector('.cherry').getAttribute('data-code-block-theme');
var _this$computeStyle = this.computeStyle(),
mathStyle = _this$computeStyle.mathStyle,
echartStyle = _this$computeStyle.echartStyle,
cherryStyle = _this$computeStyle.cherryStyle;
var html = this.previewer.isPreviewerHidden() ? this.previewer.options.previewerCache.html : this.previewer.getValue(); // 将css样式以行内样式的形式插入到html内容里
this.adaptWechat(html).then(function (html) {
var _context7, _context8, _context9;
copyToClip(client(concat$5(_context7 = concat$5(_context8 = concat$5(_context9 = "<div data-inline-code-theme=\"".concat(inlineCodeTheme, "\" data-code-block-theme=\"")).call(_context9, codeBlockTheme, "\">\n <div class=\"cherry-markdown\">")).call(_context8, html, "</div>\n </div>")).call(_context7, mathStyle + echartStyle + cherryStyle)));
_this2.toggleLoading();
});
}
}]);
return Copy;
}(MenuBase);
function convertImgToBase64(url, callback, outputFormat) {
return new promise$7(function (resolve) {
var canvas =
/** @type {HTMLCanvasElement}*/
document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function () {
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL(outputFormat || 'image/png');
resolve(dataURL);
canvas = null;
};
img.src = url;
});
}
function _createSuper$1k(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1k(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1k() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入面板
*/
var Panel$1 = /*#__PURE__*/function (_MenuBase) {
_inherits(Panel, _MenuBase);
var _super = _createSuper$1k(Panel);
function Panel($cherry) {
var _context, _context2, _context3, _context4, _context5;
var _this;
_classCallCheck(this, Panel);
_this = _super.call(this, $cherry);
_this.setName('panel', 'tips');
_this.panelRule = getPanelRule().reg;
_this.subMenuConfig = [{
iconName: 'tips',
name: 'tips',
onclick: bind$5(_context = _this.bindSubClick).call(_context, _assertThisInitialized(_this), 'primary')
}, {
iconName: 'info',
name: 'info',
onclick: bind$5(_context2 = _this.bindSubClick).call(_context2, _assertThisInitialized(_this), 'info')
}, {
iconName: 'warning',
name: 'warning',
onclick: bind$5(_context3 = _this.bindSubClick).call(_context3, _assertThisInitialized(_this), 'warning')
}, {
iconName: 'danger',
name: 'danger',
onclick: bind$5(_context4 = _this.bindSubClick).call(_context4, _assertThisInitialized(_this), 'danger')
}, {
iconName: 'success',
name: 'success',
onclick: bind$5(_context5 = _this.bindSubClick).call(_context5, _assertThisInitialized(_this), 'success')
}];
return _this;
}
/**
* 从字符串中找打面板的name
* @param {string} str
* @returns {string | false}
*/
_createClass(Panel, [{
key: "$getNameFromStr",
value: function $getNameFromStr(str) {
var ret = false;
this.panelRule.lastIndex = 0;
str.replace(this.panelRule, function (match, preLines, name, content) {
var $name = /\s/.test(trim$3(name).call(name)) ? trim$3(name).call(name).replace(/\s.*$/, '') : name;
ret = $name ? trim$3($name).call($name).toLowerCase() : '';
return match;
});
return ret;
}
}, {
key: "$getTitle",
value: function $getTitle(str) {
this.panelRule.lastIndex = 0;
str.replace(this.panelRule, function (match, preLines, name, content) {
var $name = trim$3(name).call(name);
return /\s/.test($name) ? $name.replace(/[^\s]+\s/, '') : '';
});
return '';
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @param {string} shortKey 快捷键参数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
}, {
key: "onClick",
value: function onClick(selection) {
var _this2 = this,
_context9,
_context10;
var shortKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var $selection = getSelection(this.editor.editor, selection, 'line', true) || '内容';
var currentName = this.$getNameFromStr($selection);
var title = this.$getTitle($selection);
if (currentName === false) {
// 如果没有命中面板语法,则尝试扩大选区
this.getMoreSelection('::: ', '\n', function () {
var newSelection = _this2.editor.editor.getSelection();
var isMatch = _this2.$getNameFromStr(newSelection);
if (isMatch !== false) {
$selection = newSelection;
currentName = isMatch;
title = _this2.$getTitle(newSelection);
}
return isMatch !== false;
});
}
if (currentName !== false) {
// 如果命中了面板语法,则尝试去掉语法或者变更语法
if (currentName === shortKey) {
// 去掉面板语法
this.panelRule.lastIndex = 0;
return $selection.replace(this.panelRule, function (match, preLines, name, content) {
var _context6;
var $name = trim$3(name).call(name);
var $title = /\s/.test($name) ? $name.replace(/[^\s]+\s/, '') : '';
return concat$5(_context6 = "".concat($title, "\n")).call(_context6, content);
});
} // 修改name
this.registerAfterClickCb(function () {
_this2.setLessSelection('::: ', '\n');
});
this.panelRule.lastIndex = 0;
return $selection.replace(this.panelRule, function (match, preLines, name, content) {
var _context7, _context8;
var $name = trim$3(name).call(name);
var $title = /\s/.test($name) ? $name.replace(/[^\s]+\s/, '') : '';
return concat$5(_context7 = concat$5(_context8 = "::: ".concat(shortKey, " ")).call(_context8, $title, "\n")).call(_context7, content.replace(/\n+$/, ''), "\n:::");
});
}
this.registerAfterClickCb(function () {
_this2.setLessSelection('::: ', '\n');
});
$selection = $selection.replace(/^\n+/, '');
if (/\n/.test($selection)) {
if (!title) {
title = $selection.replace(/\n[\w\W]+$/, '');
$selection = $selection.replace(/^[^\n]+\n/, '');
}
} else {
title = title ? title : '标题';
}
return concat$5(_context9 = concat$5(_context10 = "::: ".concat(shortKey, " ")).call(_context10, title, "\n")).call(_context9, $selection, "\n:::").replace(/\n{2,}:::/g, '\n:::');
}
}]);
return Panel;
}(MenuBase);
function _createSuper$1l(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1l(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1l() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入对齐方式
*/
var Justify = /*#__PURE__*/function (_Panel) {
_inherits(Justify, _Panel);
var _super = _createSuper$1l(Justify);
function Justify($cherry) {
var _context, _context2, _context3;
var _this;
_classCallCheck(this, Justify);
_this = _super.call(this, $cherry);
_this.setName('justify', 'justify');
_this.panelRule = getPanelRule().reg;
_this.subMenuConfig = [{
iconName: 'justifyLeft',
name: '左对齐',
onclick: bind$5(_context = _this.bindSubClick).call(_context, _assertThisInitialized(_this), 'left')
}, {
iconName: 'justifyCenter',
name: '居中',
onclick: bind$5(_context2 = _this.bindSubClick).call(_context2, _assertThisInitialized(_this), 'center')
}, {
iconName: 'justifyRight',
name: '右对齐',
onclick: bind$5(_context3 = _this.bindSubClick).call(_context3, _assertThisInitialized(_this), 'right')
}];
return _this;
}
_createClass(Justify, [{
key: "$getTitle",
value: function $getTitle() {
return ' ';
}
}]);
return Justify;
}(Panel$1);
function _createSuper$1m(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1m(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1m() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 插入手风琴
*/
var Detail$1 = /*#__PURE__*/function (_MenuBase) {
_inherits(Detail, _MenuBase);
var _super = _createSuper$1m(Detail);
function Detail($cherry) {
var _this;
_classCallCheck(this, Detail);
_this = _super.call(this, $cherry);
_this.setName('detail', 'insertFlow');
_this.detailRule = getDetailRule().reg;
return _this;
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(Detail, [{
key: "onClick",
value: function onClick(selection) {
var _this2 = this;
var $selection = getSelection(this.editor.editor, selection, 'line', true) || '点击展开更多\n内容\n++- 默认展开\n内容\n++ 默认收起\n内容';
this.detailRule.lastIndex = 0;
if (!this.detailRule.test($selection)) {
// 如果没有命中手风琴语法,则尝试扩大选区
this.getMoreSelection('+++ ', '\n', function () {
var newSelection = _this2.editor.editor.getSelection();
_this2.detailRule.lastIndex = 0;
var isMatch = _this2.detailRule.test(newSelection);
if (isMatch !== false) {
$selection = newSelection;
}
return isMatch !== false;
});
}
this.detailRule.lastIndex = 0;
if (this.detailRule.test($selection)) {
// 如果命中了手风琴语法,则去掉手风琴语法
this.detailRule.lastIndex = 0;
return $selection.replace(this.detailRule, function (match, preLines, isOpen, title, content) {
var _context;
return concat$5(_context = "".concat(title, "\n")).call(_context, content);
});
} // 去掉开头的空格
$selection = $selection.replace(/^\s+/, ''); // 如果选中的内容不包含换行,则强制增加一个换行
if (!/\n/.test($selection)) {
var _context2;
$selection = concat$5(_context2 = "".concat($selection, "\n")).call(_context2, $selection);
}
this.registerAfterClickCb(function () {
_this2.setLessSelection('+++ ', '\n');
});
return "+++ ".concat($selection, "\n+++").replace(/\n{2,}\+\+\+/g, '\n+++');
}
}]);
return Detail;
}(MenuBase);
function _createSuper$1n(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1n(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1n() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 打开draw.io画图对话框点击确定后向编辑器插入图片语法
*/
var DrawIo = /*#__PURE__*/function (_MenuBase) {
_inherits(DrawIo, _MenuBase);
var _super = _createSuper$1n(DrawIo);
function DrawIo($cherry) {
var _this;
_classCallCheck(this, DrawIo);
_this = _super.call(this, $cherry);
_this.setName('draw.io', 'draw.io');
_this.noIcon = true;
_this.drawioIframeUrl = $cherry.options.drawioIframeUrl;
return _this;
}
/**
* 响应点击事件
* @param {string} selection 被用户选中的文本内容
* @param {string} shortKey 快捷键参数,本函数不处理这个参数
* @returns {string} 回填到编辑器光标位置/选中文本区域的内容
*/
_createClass(DrawIo, [{
key: "onClick",
value: function onClick(selection) {
var _this2 = this;
if (!this.drawioIframeUrl) {
// 如果没有配置drawio的编辑页URL则直接失效
return selection;
}
if (this.hasCacheOnce()) {
var _context;
// @ts-ignore
var _this$getAndCleanCach = this.getAndCleanCacheOnce(),
xmlData = _this$getAndCleanCach.xmlData,
base64 = _this$getAndCleanCach.base64;
var begin = '![';
var end = concat$5(_context = "](".concat(base64, "){data-type=drawio data-xml=")).call(_context, encodeURI(xmlData), "}");
this.registerAfterClickCb(function () {
_this2.setLessSelection(begin, end);
});
return "".concat(begin, "\u5728\u9884\u89C8\u533A\u70B9\u51FB\u56FE\u7247\u91CD\u65B0\u7F16\u8F91draw.io").concat(end);
} // 插入图片,调用上传文件逻辑
drawioDialog(this.drawioIframeUrl, '', function (data) {
_this2.setCacheOnce(data);
_this2.fire(null);
});
this.updateMarkdown = false;
return selection;
}
}]);
return DrawIo;
}(MenuBase);
// 目前不支持按需动态加载
// 如果对CherryMarkdown构建后的文件大小有比较严格的要求可以根据实际情况删减hook
var HookList = {
bold: Bold,
italic: Italic,
'|': Split,
strikethrough: Strikethrough$1,
sub: Sub$1,
sup: Sup$1,
header: Header$1,
insert: Insert,
list: List$1,
ol: Ol,
ul: Ul,
checklist: Checklist,
graph: Graph,
size: Size$1,
h1: H1,
h2: H2,
h3: H3,
color: Color$1,
quote: Quote,
quickTable: QuickTable,
togglePreview: TogglePreview,
code: Code,
codeTheme: CodeTheme,
"export": Export,
settings: Settings,
fullScreen: FullScreen,
mobilePreview: MobilePreview,
copy: Copy,
undo: Undo,
redo: Redo,
underline: Underline$1,
switchModel: SwitchModel,
image: Image$2,
audio: Audio,
video: Video,
br: Br$1,
hr: Hr$1,
formula: Formula,
link: Link$1,
table: Table$1,
toc: Toc$1,
lineTable: LineTable,
barTable: BrTable,
pdf: Pdf,
word: Word,
ruby: Ruby$1,
theme: Theme,
file: File,
panel: Panel$1,
justify: Justify,
detail: Detail$1,
drawIo: DrawIo,
chatgpt: ChatGpt
};
var HookCenter$1 = /*#__PURE__*/function () {
function HookCenter(toolbar) {
_classCallCheck(this, HookCenter);
this.toolbar = toolbar;
/**
* @type {{[key: string]: import('@/toolbars/MenuBase').default}} 保存所有菜单实例
*/
this.hooks = {};
/**
* @type {string[]} 所有注册的菜单名称
*/
this.allMenusName = [];
/**
* @type {string[]} 一级菜单的名称
*/
this.level1MenusName = [];
/**
* @type {{ [parentName: string]: string[]}} 二级菜单的名称, e.g. {一级菜单名称: [二级菜单名称1, 二级菜单名称2]}
*/
this.level2MenusName = {};
this.init();
}
_createClass(HookCenter, [{
key: "$newMenu",
value: function $newMenu(name) {
if (this.hooks[name]) {
return;
}
var _this$toolbar$options = this.toolbar.options,
$cherry = _this$toolbar$options.$cherry,
customMenu = _this$toolbar$options.customMenu;
if (HookList[name]) {
this.allMenusName.push(name);
this.hooks[name] = new HookList[name]($cherry);
} else if (customMenu !== undefined && customMenu !== null && customMenu[name]) {
this.allMenusName.push(name); // 如果是自定义菜单,传参兼容旧版
this.hooks[name] = new customMenu[name]($cherry);
}
}
/**
* 根据配置动态渲染、绑定工具栏
* @returns
*/
}, {
key: "init",
value: function init() {
var _this = this;
var buttonConfig = this.toolbar.options.buttonConfig;
forEach$3(buttonConfig).call(buttonConfig, function (item) {
if (typeof item === 'string') {
_this.level1MenusName.push(item);
_this.$newMenu(item);
} else if (_typeof(item) === 'object') {
var keys = keys$3(item);
if (keys.length === 1) {
var _context;
// 只接受形如{ name: [ subMenu ] }的参数
var _keys = _slicedToArray(keys, 1),
name = _keys[0];
_this.level1MenusName.push(name);
_this.$newMenu(name);
_this.level2MenusName[name] = item[name];
forEach$3(_context = item[name]).call(_context, function (subItem) {
_this.$newMenu(subItem);
});
}
}
});
}
}]);
return HookCenter;
}();
var Toolbar = /*#__PURE__*/function () {
/**
* @type {Record<string, any>} 外部获取 toolbarHandler
*/
function Toolbar(options) {
_classCallCheck(this, Toolbar);
_defineProperty(this, "toolbarHandlers", {});
// 存储所有菜单的实例
this.menus = {}; // 存储所有快捷键的影射 {快捷键: 菜单名称}
this.shortcutKeyMap = {}; // 存储所有二级菜单面板
this.subMenus = {}; // 默认的菜单配置
this.options = {
dom: document.createElement('div'),
buttonConfig: ['bold'],
customMenu: [],
buttonRightConfig: []
};
assign$2(this.options, options);
this.$cherry = this.options.$cherry;
this.instanceId = this.$cherry.instanceId;
this.menus = new HookCenter$1(this);
this.drawMenus();
this.init();
}
_createClass(Toolbar, [{
key: "init",
value: function init() {
var _this = this;
this.collectShortcutKey();
this.collectToolbarHandler();
Event$1.on(this.instanceId, Event$1.Events.cleanAllSubMenus, function () {
return _this.hideAllSubMenu();
});
}
}, {
key: "previewOnly",
value: function previewOnly() {
this.options.dom.classList.add('preview-only');
Event$1.emit(this.instanceId, Event$1.Events.toolbarHide);
}
}, {
key: "showToolbar",
value: function showToolbar() {
this.options.dom.classList.remove('preview-only');
Event$1.emit(this.instanceId, Event$1.Events.toolbarShow);
}
}, {
key: "isHasLevel2Menu",
value: function isHasLevel2Menu(name) {
// FIXME: return boolean
return this.menus.level2MenusName[name];
}
}, {
key: "isHasConfigMenu",
value: function isHasConfigMenu(name) {
// FIXME: return boolean
return this.menus.hooks[name].subMenuConfig || [];
}
/**
* 判断是否有子菜单目前有两种子菜单配置方式1、通过`subMenuConfig`属性 2、通过`buttonConfig`配置属性
* @param {string} name
* @returns {boolean} 是否有子菜单
*/
}, {
key: "isHasSubMenu",
value: function isHasSubMenu(name) {
return Boolean(this.isHasLevel2Menu(name) || this.isHasConfigMenu(name).length > 0);
}
/**
* 根据配置画出来一级工具栏
*/
}, {
key: "drawMenus",
value: function drawMenus() {
var _context,
_this2 = this,
_this$options$buttonR;
var fragLeft = document.createDocumentFragment();
var toolbarLeft = createElement('div', 'toolbar-left');
forEach$3(_context = this.menus.level1MenusName).call(_context, function (name) {
var btn = _this2.menus.hooks[name].createBtn();
btn.addEventListener('click', function (event) {
_this2.onClick(event, name);
}, false);
if (_this2.isHasSubMenu(name)) {
btn.classList.add('cherry-toolbar-dropdown');
}
fragLeft.appendChild(btn);
});
toolbarLeft.appendChild(fragLeft);
this.options.dom.appendChild(toolbarLeft);
(_this$options$buttonR = this.options.buttonRightConfig) !== null && _this$options$buttonR !== void 0 && _this$options$buttonR.length ? this.drawRightMenus(this.options.buttonRightConfig) : null;
}
/**
* 根据配置画出来右侧一级工具栏
*/
}, {
key: "drawRightMenus",
value: function drawRightMenus(buttonRightConfig) {
var _context2;
var toolbarRight = createElement('div', 'toolbar-right');
var fragRight = document.createDocumentFragment();
var rightOptions = {
options: {
$cherry: this.$cherry,
buttonConfig: buttonRightConfig,
customMenu: []
}
};
var rightMenus = new HookCenter$1(rightOptions);
forEach$3(_context2 = rightMenus.level1MenusName).call(_context2, function (name) {
var btn = rightMenus.hooks[name].createBtn();
btn.addEventListener('click', function (event) {
console.log('第一次点击');
rightMenus.hooks[name].fire(event, name);
}, false);
fragRight.appendChild(btn);
});
toolbarRight.appendChild(fragRight);
this.options.dom.appendChild(toolbarRight);
}
}, {
key: "setSubMenuPosition",
value: function setSubMenuPosition(menuObj, subMenuObj) {
var pos = menuObj.getMenuPosition();
subMenuObj.style.left = "".concat(pos.left + pos.width / 2, "px");
subMenuObj.style.top = "".concat(pos.top + pos.height, "px");
subMenuObj.style.position = menuObj.positionModel;
}
}, {
key: "drawSubMenus",
value: function drawSubMenus(name) {
var _this3 = this;
this.subMenus[name] = createElement('div', 'cherry-dropdown', {
name: name
});
this.setSubMenuPosition(this.menus.hooks[name], this.subMenus[name]); // 如果有配置的二级菜单
var level2MenusName = this.isHasLevel2Menu(name);
if (level2MenusName) {
forEach$3(level2MenusName).call(level2MenusName, function (level2Name) {
var subMenu = _this3.menus.hooks[level2Name];
if (subMenu !== undefined && typeof subMenu.createBtn === 'function') {
var btn = subMenu.createBtn(true); // 二级菜单的dom认定为一级菜单的
subMenu.dom = subMenu.dom ? subMenu.dom : _this3.menus.hooks[name].dom;
btn.addEventListener('click', function (event) {
return _this3.onClick(event, level2Name, true);
}, false);
_this3.subMenus[name].appendChild(btn);
}
});
} // 兼容旧版本配置的二级菜单
var subMenuConfig = this.isHasConfigMenu(name);
if (subMenuConfig.length > 0) {
forEach$3(subMenuConfig).call(subMenuConfig, function (config) {
var btn = _this3.menus.hooks[name].createSubBtnByConfig(config);
btn.addEventListener('click', function () {
return _this3.hideAllSubMenu();
}, false);
_this3.subMenus[name].appendChild(btn);
});
}
this.$cherry.wrapperDom.appendChild(this.subMenus[name]);
}
/**
* 处理点击事件
*/
}, {
key: "onClick",
value: function onClick(event, name) {
var focusEvent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var menu = this.menus.hooks[name];
if (!menu) {
return;
}
if (this.isHasSubMenu(name) && !focusEvent) {
this.toggleSubMenu(name);
} else {
this.hideAllSubMenu();
menu.fire(event, name);
}
}
/**
* 展开/收起二级菜单
*/
}, {
key: "toggleSubMenu",
value: function toggleSubMenu(name) {
if (!this.subMenus[name]) {
// 如果没有二级菜单,则先画出来,然后再显示
this.hideAllSubMenu();
this.drawSubMenus(name);
this.subMenus[name].style.display = 'block';
return;
}
if (this.subMenus[name].style.display === 'none') {
// 如果是隐藏的,则先隐藏所有二级菜单,再显示当前二级菜单
this.hideAllSubMenu();
this.subMenus[name].style.display = 'block';
this.setSubMenuPosition(this.menus.hooks[name], this.subMenus[name]);
} else {
// 如果是显示的,则隐藏当前二级菜单
this.subMenus[name].style.display = 'none';
}
}
/**
* 隐藏所有的二级菜单
*/
}, {
key: "hideAllSubMenu",
value: function hideAllSubMenu() {
var _context3;
forEach$3(_context3 = this.$cherry.wrapperDom.querySelectorAll('.cherry-dropdown')).call(_context3, function (dom) {
dom.style.display = 'none';
});
}
/**
* 收集快捷键
*/
}, {
key: "collectShortcutKey",
value: function collectShortcutKey() {
var _context4,
_this4 = this;
forEach$3(_context4 = this.menus.allMenusName).call(_context4, function (name) {
var _this4$menus$hooks$na;
(_this4$menus$hooks$na = _this4.menus.hooks[name].shortcutKeys) === null || _this4$menus$hooks$na === void 0 ? void 0 : forEach$3(_this4$menus$hooks$na).call(_this4$menus$hooks$na, function (key) {
_this4.shortcutKeyMap[key] = name;
});
});
}
}, {
key: "collectToolbarHandler",
value: function collectToolbarHandler() {
var _context5,
_this5 = this;
this.toolbarHandlers = reduce$3(_context5 = this.menus.allMenusName).call(_context5, function (handlerMap, name) {
var menuHook = _this5.menus.hooks[name];
if (!menuHook) {
return handlerMap;
}
handlerMap[name] = function (shortcut, _callback) {
if (typeof _callback === 'function') {
Logger.warn('MenuBase#onClick param callback is no longer supported. Please register the callback via MenuBase#registerAfterClickCb instead.');
}
menuHook.fire.call(menuHook, undefined, shortcut);
};
return handlerMap;
}, {});
}
/**
* 监测是否有对应的快捷键
* @param {KeyboardEvent} evt keydown 事件
* @returns {boolean} 是否有对应的快捷键
*/
}, {
key: "matchShortcutKey",
value: function matchShortcutKey(evt) {
return !!this.shortcutKeyMap[this.getCurrentKey(evt)];
}
/**
* 触发对应快捷键的事件
* @param {KeyboardEvent} evt
*/
}, {
key: "fireShortcutKey",
value: function fireShortcutKey(evt) {
var _this$menus$hooks$thi;
var currentKey = this.getCurrentKey(evt);
(_this$menus$hooks$thi = this.menus.hooks[this.shortcutKeyMap[currentKey]]) === null || _this$menus$hooks$thi === void 0 ? void 0 : _this$menus$hooks$thi.fire(evt, currentKey);
}
/**
* 格式化当前按键mac下的command按键转换为ctrl
* @param {KeyboardEvent} event
* @returns
*/
}, {
key: "getCurrentKey",
value: function getCurrentKey(event) {
var key = '';
if (event.ctrlKey) {
key += 'Ctrl-';
}
if (event.altKey) {
key += 'Alt-';
}
if (event.metaKey && mac) {
key += 'Ctrl-';
} // 如果存在shift键
if (event.shiftKey) {
key += "Shift-";
} // 如果还有第三个键 且不是 shift键
if (event.key && event.key.toLowerCase() !== 'shift') {
key += event.key.toLowerCase();
}
return key;
}
}]);
return Toolbar;
}();
function _createSuper$1o(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1o(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1o() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 在编辑区域选中文本时浮现的bubble工具栏
*/
var Bubble = /*#__PURE__*/function (_Toolbar) {
_inherits(Bubble, _Toolbar);
var _super = _createSuper$1o(Bubble);
function Bubble() {
_classCallCheck(this, Bubble);
return _super.apply(this, arguments);
}
_createClass(Bubble, [{
key: "visible",
get: function get() {
var bubbleStyle = window.getComputedStyle(this.bubbleDom);
return bubbleStyle.display !== 'none' && bubbleStyle.visibility !== 'hidden';
},
set:
/**
* @type {'flex' | 'block'}
*/
// constructor(options) {
// super(options);
// }
function set(visible) {
var bubbleStyle = window.getComputedStyle(this.bubbleDom);
if (visible) {
bubbleStyle.display === 'none' && (this.bubbleDom.style.display = Bubble.displayType); // bubbleStyle.visibility !== 'visible' && (this.bubbleBottom.style.visibility = 'visible');
} else {
bubbleStyle.display !== 'none' && (this.bubbleDom.style.display = 'none'); // bubbleStyle.visibility !== 'hidden' && (this.bubbleBottom.style.visibility = 'hidden');
}
}
}, {
key: "init",
value: function init() {
this.options.editor = this.$cherry.editor;
this.addSelectionChangeListener();
this.bubbleDom = this.options.dom;
this.editorDom = this.options.editor.getEditorDom();
this.initBubbleDom();
this.editorDom.querySelector('.CodeMirror').appendChild(this.bubbleDom);
}
/**
* 计算编辑区域的偏移量
* @returns {number} 编辑区域的滚动区域
*/
}, {
key: "getScrollTop",
value: function getScrollTop() {
return this.options.editor.editor.getScrollInfo().top;
}
/**
* 当编辑区域滚动的时候自动隐藏bubble工具栏和子工具栏
*/
}, {
key: "updatePositionWhenScroll",
value: function updatePositionWhenScroll() {
if (this.bubbleDom.style.display === Bubble.displayType) {
this.bubbleDom.style.marginTop = "".concat(_parseFloat$2(this.bubbleDom.dataset.scrollTop) - this.getScrollTop(), "px");
}
}
/**
* 根据高度计算bubble工具栏出现的位置的高度
* 根据宽度计算bubble工具栏出现的位置的left值以及bubble工具栏三角箭头的left值
* @param {number} top 高度
* @param {number} width 选中文本内容的宽度
*/
}, {
key: "showBubble",
value: function showBubble(top, width) {
if (!this.visible) {
this.visible = true;
this.bubbleDom.style.marginTop = '0';
this.bubbleDom.dataset.scrollTop = String(this.getScrollTop());
}
var positionLimit = this.editorDom.querySelector('.CodeMirror-lines').firstChild.getBoundingClientRect();
var editorPosition = this.editorDom.getBoundingClientRect();
var minLeft = positionLimit.left - editorPosition.left;
var maxLeft = positionLimit.width + minLeft;
var minTop = this.bubbleDom.offsetHeight * 2;
var $top = top;
if ($top < minTop) {
// 如果高度小于编辑器的顶部则让bubble工具栏出现在选中文本的下放
$top += this.bubbleDom.offsetHeight - this.bubbleTop.getBoundingClientRect().height;
this.bubbleTop.style.display = 'block';
this.bubbleBottom.style.display = 'none';
} else {
// 反之出现在选中文本内容的上方
$top -= this.bubbleDom.offsetHeight + 2 * this.bubbleBottom.getBoundingClientRect().height;
this.bubbleTop.style.display = 'none';
this.bubbleBottom.style.display = 'block';
}
this.bubbleDom.style.top = "".concat($top, "px");
var left = width - this.bubbleDom.offsetWidth / 2;
if (left < minLeft) {
// 如果位置超过了编辑器的最左边则控制bubble工具栏不超出编辑器最左边
// 同时bubble工具栏上的箭头尽量指向选中文本内容的中间位置
left = minLeft;
this.$setBubbleCursorPosition("".concat(width - minLeft, "px"));
} else if (left + this.bubbleDom.offsetWidth > maxLeft) {
// 如果位置超过了编辑器的最右边则控制bubble工具栏不超出编辑器最右边
// 同时bubble工具栏上的箭头尽量指向选中文本内容的中间位置
left = maxLeft - this.bubbleDom.offsetWidth;
this.$setBubbleCursorPosition("".concat(width - left, "px"));
} else {
// 让bubble工具栏的箭头处于工具栏的中间位置
this.$setBubbleCursorPosition('50%');
} // 安全边距 20px
this.bubbleDom.style.left = "".concat(Math.max(20, left), "px");
}
}, {
key: "hideBubble",
value: function hideBubble() {
this.visible = false;
}
/**
* 控制bubble工具栏的箭头的位置
* @param {string} left 左偏移量
*/
}, {
key: "$setBubbleCursorPosition",
value: function $setBubbleCursorPosition() {
var left = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '50%';
if (left === '50%') {
this.bubbleTop.style.left = '50%';
this.bubbleBottom.style.left = '50%';
} else {
var $left = _parseFloat$2(left) < 10 ? '10px' : left;
this.bubbleTop.style.left = $left;
this.bubbleBottom.style.left = $left;
}
}
}, {
key: "initBubbleDom",
value: function initBubbleDom() {
var top = document.createElement('div');
top.className = 'cherry-bubble-top';
var bottom = document.createElement('div');
bottom.className = 'cherry-bubble-bottom';
this.bubbleTop = top;
this.bubbleBottom = bottom;
this.bubbleDom.appendChild(top);
this.bubbleDom.appendChild(bottom); // 默认不可见
this.visible = false;
}
}, {
key: "getBubbleDom",
value: function getBubbleDom() {
return this.bubbleDom;
}
}, {
key: "addSelectionChangeListener",
value: function addSelectionChangeListener() {
var _this = this;
this.options.editor.addListener('change', function (codemirror) {
// 当编辑区内容变更时自动隐藏bubble工具栏
_this.hideBubble();
});
this.options.editor.addListener('refresh', function (codemirror) {
// 当编辑区内容刷新时自动隐藏bubble工具栏
_this.hideBubble();
});
this.options.editor.addListener('scroll', function (codemirror) {
// 当编辑区滚动时需要实时同步bubble工具栏的位置
_this.updatePositionWhenScroll();
});
this.options.editor.addListener('beforeSelectionChange', function (codemirror, info) {
// 当编辑区选中内容改变时,需要展示/隐藏bubble工具栏并计算工具栏位置
if (info.origin !== '*mouse' && (info.origin !== null || typeof info.origin === 'undefined')) {
return true;
}
if (!info.ranges[0]) {
return true;
}
var anchor = info.ranges[0].anchor.line * 1000000 + info.ranges[0].anchor.ch;
var head = info.ranges[0].head.line * 1000000 + info.ranges[0].head.ch;
var direction = 'asc';
if (anchor > head) {
direction = 'desc';
}
setTimeout$3(function () {
var selections = codemirror.getSelections();
if (selections.join('').length <= 0) {
_this.hideBubble();
return;
}
var selectedObjs = codemirror.getWrapperElement().getElementsByClassName('CodeMirror-selected');
var editorPosition = _this.editorDom.getBoundingClientRect();
var width = 0;
var top = 0;
if (_typeof(selectedObjs) !== 'object' || selectedObjs.length <= 0) {
_this.hideBubble();
return;
}
for (var key = 0; key < selectedObjs.length; key++) {
var one = selectedObjs[key];
var position = one.getBoundingClientRect();
var targetTop = position.top - editorPosition.top;
if (direction === 'asc') {
if (targetTop >= top) {
top = targetTop;
width = position.left - editorPosition.left + position.width / 2;
}
} else {
if (targetTop <= top || top <= 0) {
top = targetTop;
width = position.left - editorPosition.left + position.width / 2;
}
}
}
_this.showBubble(top, width);
}, 10);
});
}
}]);
return Bubble;
}(Toolbar);
_defineProperty(Bubble, "displayType", 'flex');
function _createSuper$1p(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1p(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1p() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 当光标处于编辑器新行起始位置时出现的浮动工具栏
*/
var FloatMenu = /*#__PURE__*/function (_Toolbar) {
_inherits(FloatMenu, _Toolbar);
var _super = _createSuper$1p(FloatMenu);
function FloatMenu() {
_classCallCheck(this, FloatMenu);
return _super.apply(this, arguments);
}
_createClass(FloatMenu, [{
key: "init",
value: // constructor(options) {
// super(options);
// }
function init() {
this.editor = this.$cherry.editor;
this.editorDom = this.editor.getEditorDom();
this.editorDom.querySelector('.CodeMirror-scroll').appendChild(this.options.dom);
this.initAction();
}
}, {
key: "initAction",
value: function initAction() {
var self = this;
this.editor.addListener('cursorActivity', function (codemirror, evt) {
// 当编辑区光标位置改变时触发
self.cursorActivity(evt, codemirror);
});
this.editor.addListener('update', function (codemirror, evt) {
// 当编辑区内容改变时触发
self.cursorActivity(evt, codemirror);
});
this.editor.addListener('refresh', function (codemirror, evt) {
// 当编辑器刷新时触发
setTimeout$3(function () {
self.cursorActivity(evt, codemirror);
}, 0);
});
}
}, {
key: "update",
value: function update(evt, codeMirror) {
var pos = codeMirror.getCursor();
if (this.isHidden(pos.line, codeMirror)) {
this.options.dom.style.display = 'none';
return false;
}
this.options.dom.style.display = 'inline-block';
}
/**
* 当光标激活时触发当光标处于行起始位置时展示float工具栏反之隐藏
* @param {Event} evt
* @param {CodeMirror.Editor} codeMirror
* @returns
*/
}, {
key: "cursorActivity",
value: function cursorActivity(evt, codeMirror) {
var pos = codeMirror.getCursor();
var codeMirrorLines = document.querySelector('.cherry-editor .CodeMirror-lines');
if (!codeMirrorLines) {
return false;
}
var computedLinesStyle = getComputedStyle(codeMirrorLines);
var codeWrapPaddingLeft = _parseFloat$2(computedLinesStyle.paddingLeft);
var codeWrapPaddingTop = _parseFloat$2(computedLinesStyle.paddingTop); // const cursorHandle = codeMirror.getLineHandle(pos.line);
// const verticalMiddle = cursorHandle.height * 1 / 2;
if (this.isHidden(pos.line, codeMirror)) {
this.options.dom.style.display = 'none';
return false;
}
this.options.dom.style.display = 'inline-block';
this.options.dom.style.left = "".concat(codeWrapPaddingLeft, "px");
this.options.dom.style.top = "".concat(this.getLineHeight(pos.line, codeMirror) + codeWrapPaddingTop, "px");
}
/**
* 判断是否需要隐藏Float工具栏
* 有选中内容或者光标所在行有内容时隐藏float 工具栏
* @param {number} line
* @param {CodeMirror.Editor} codeMirror
* @returns {boolean} 是否需要隐藏float工具栏true需要隐藏
*/
}, {
key: "isHidden",
value: function isHidden(line, codeMirror) {
var selections = codeMirror.getSelections();
if (selections.length > 1) {
return true;
}
var selection = codeMirror.getSelection();
if (selection.length > 0) {
return true;
}
if (codeMirror.getLine(line)) {
return true;
}
return false;
}
/**
* 获取对应行的行高度用来让float 工具栏在该行保持垂直居中
* @param {number} line
* @param {CodeMirror.Editor} codeMirror
* @returns
*/
}, {
key: "getLineHeight",
value: function getLineHeight(line, codeMirror) {
var height = 0;
codeMirror.getDoc().eachLine(0, line, function (line) {
height += line.height;
});
return height;
}
}]);
return FloatMenu;
}(Toolbar);
function _createSuper$1q(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1q(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1q() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/**
* 预览区域右侧悬浮的工具栏
* 推荐放置跟编辑区域完全无关的工具栏
* 比如复制预览区域内容、修改预览区域主题等
*/
var Sidebar = /*#__PURE__*/function (_Toolbar) {
_inherits(Sidebar, _Toolbar);
var _super = _createSuper$1q(Sidebar);
function Sidebar() {
_classCallCheck(this, Sidebar);
return _super.apply(this, arguments);
}
return _createClass(Sidebar);
}(Toolbar);
/**
* This library modifies the diff-patch-match library by Neil Fraser
* by removing the patch and match functionality and certain advanced
* options in the diff function. The original license is as follows:
*
* ===
*
* Diff Match and Patch
*
* Copyright 2006 Google Inc.
* http://code.google.com/p/google-diff-match-patch/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* The data structure representing a diff is an array of tuples:
* [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
* which means: delete 'Hello', add 'Goodbye' and keep ' world.'
*/
var DIFF_DELETE = -1;
var DIFF_INSERT = 1;
var DIFF_EQUAL = 0;
/**
* Find the differences between two texts. Simplifies the problem by stripping
* any common prefix or suffix off the texts before diffing.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {Int|Object} [cursor_pos] Edit position in text1 or object with more info
* @return {Array} Array of diff tuples.
*/
function diff_main(text1, text2, cursor_pos, _fix_unicode) {
// Check for equality
if (text1 === text2) {
if (text1) {
return [[DIFF_EQUAL, text1]];
}
return [];
}
if (cursor_pos != null) {
var editdiff = find_cursor_edit_diff(text1, text2, cursor_pos);
if (editdiff) {
return editdiff;
}
}
// Trim off common prefix (speedup).
var commonlength = diff_commonPrefix(text1, text2);
var commonprefix = text1.substring(0, commonlength);
text1 = text1.substring(commonlength);
text2 = text2.substring(commonlength);
// Trim off common suffix (speedup).
commonlength = diff_commonSuffix(text1, text2);
var commonsuffix = text1.substring(text1.length - commonlength);
text1 = text1.substring(0, text1.length - commonlength);
text2 = text2.substring(0, text2.length - commonlength);
// Compute the diff on the middle block.
var diffs = diff_compute_(text1, text2);
// Restore the prefix and suffix.
if (commonprefix) {
diffs.unshift([DIFF_EQUAL, commonprefix]);
}
if (commonsuffix) {
diffs.push([DIFF_EQUAL, commonsuffix]);
}
diff_cleanupMerge(diffs, _fix_unicode);
return diffs;
}
/**
* Find the differences between two texts. Assumes that the texts do not
* have any common prefix or suffix.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @return {Array} Array of diff tuples.
*/
function diff_compute_(text1, text2) {
var diffs;
if (!text1) {
// Just add some text (speedup).
return [[DIFF_INSERT, text2]];
}
if (!text2) {
// Just delete some text (speedup).
return [[DIFF_DELETE, text1]];
}
var longtext = text1.length > text2.length ? text1 : text2;
var shorttext = text1.length > text2.length ? text2 : text1;
var i = longtext.indexOf(shorttext);
if (i !== -1) {
// Shorter text is inside the longer text (speedup).
diffs = [
[DIFF_INSERT, longtext.substring(0, i)],
[DIFF_EQUAL, shorttext],
[DIFF_INSERT, longtext.substring(i + shorttext.length)]
];
// Swap insertions for deletions if diff is reversed.
if (text1.length > text2.length) {
diffs[0][0] = diffs[2][0] = DIFF_DELETE;
}
return diffs;
}
if (shorttext.length === 1) {
// Single character string.
// After the previous speedup, the character can't be an equality.
return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
}
// Check to see if the problem can be split in two.
var hm = diff_halfMatch_(text1, text2);
if (hm) {
// A half-match was found, sort out the return data.
var text1_a = hm[0];
var text1_b = hm[1];
var text2_a = hm[2];
var text2_b = hm[3];
var mid_common = hm[4];
// Send both pairs off for separate processing.
var diffs_a = diff_main(text1_a, text2_a);
var diffs_b = diff_main(text1_b, text2_b);
// Merge the results.
return diffs_a.concat([[DIFF_EQUAL, mid_common]], diffs_b);
}
return diff_bisect_(text1, text2);
}
/**
* Find the 'middle snake' of a diff, split the problem in two
* and return the recursively constructed diff.
* See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @return {Array} Array of diff tuples.
* @private
*/
function diff_bisect_(text1, text2) {
// Cache the text lengths to prevent multiple calls.
var text1_length = text1.length;
var text2_length = text2.length;
var max_d = Math.ceil((text1_length + text2_length) / 2);
var v_offset = max_d;
var v_length = 2 * max_d;
var v1 = new Array(v_length);
var v2 = new Array(v_length);
// Setting all elements to -1 is faster in Chrome & Firefox than mixing
// integers and undefined.
for (var x = 0; x < v_length; x++) {
v1[x] = -1;
v2[x] = -1;
}
v1[v_offset + 1] = 0;
v2[v_offset + 1] = 0;
var delta = text1_length - text2_length;
// If the total number of characters is odd, then the front path will collide
// with the reverse path.
var front = (delta % 2 !== 0);
// Offsets for start and end of k loop.
// Prevents mapping of space beyond the grid.
var k1start = 0;
var k1end = 0;
var k2start = 0;
var k2end = 0;
for (var d = 0; d < max_d; d++) {
// Walk the front path one step.
for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
var k1_offset = v_offset + k1;
var x1;
if (k1 === -d || (k1 !== d && v1[k1_offset - 1] < v1[k1_offset + 1])) {
x1 = v1[k1_offset + 1];
} else {
x1 = v1[k1_offset - 1] + 1;
}
var y1 = x1 - k1;
while (
x1 < text1_length && y1 < text2_length &&
text1.charAt(x1) === text2.charAt(y1)
) {
x1++;
y1++;
}
v1[k1_offset] = x1;
if (x1 > text1_length) {
// Ran off the right of the graph.
k1end += 2;
} else if (y1 > text2_length) {
// Ran off the bottom of the graph.
k1start += 2;
} else if (front) {
var k2_offset = v_offset + delta - k1;
if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] !== -1) {
// Mirror x2 onto top-left coordinate system.
var x2 = text1_length - v2[k2_offset];
if (x1 >= x2) {
// Overlap detected.
return diff_bisectSplit_(text1, text2, x1, y1);
}
}
}
}
// Walk the reverse path one step.
for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
var k2_offset = v_offset + k2;
var x2;
if (k2 === -d || (k2 !== d && v2[k2_offset - 1] < v2[k2_offset + 1])) {
x2 = v2[k2_offset + 1];
} else {
x2 = v2[k2_offset - 1] + 1;
}
var y2 = x2 - k2;
while (
x2 < text1_length && y2 < text2_length &&
text1.charAt(text1_length - x2 - 1) === text2.charAt(text2_length - y2 - 1)
) {
x2++;
y2++;
}
v2[k2_offset] = x2;
if (x2 > text1_length) {
// Ran off the left of the graph.
k2end += 2;
} else if (y2 > text2_length) {
// Ran off the top of the graph.
k2start += 2;
} else if (!front) {
var k1_offset = v_offset + delta - k2;
if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] !== -1) {
var x1 = v1[k1_offset];
var y1 = v_offset + x1 - k1_offset;
// Mirror x2 onto top-left coordinate system.
x2 = text1_length - x2;
if (x1 >= x2) {
// Overlap detected.
return diff_bisectSplit_(text1, text2, x1, y1);
}
}
}
}
}
// Diff took too long and hit the deadline or
// number of diffs equals number of characters, no commonality at all.
return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
}
/**
* Given the location of the 'middle snake', split the diff in two parts
* and recurse.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} x Index of split point in text1.
* @param {number} y Index of split point in text2.
* @return {Array} Array of diff tuples.
*/
function diff_bisectSplit_(text1, text2, x, y) {
var text1a = text1.substring(0, x);
var text2a = text2.substring(0, y);
var text1b = text1.substring(x);
var text2b = text2.substring(y);
// Compute both diffs serially.
var diffs = diff_main(text1a, text2a);
var diffsb = diff_main(text1b, text2b);
return diffs.concat(diffsb);
}
/**
* Determine the common prefix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the start of each
* string.
*/
function diff_commonPrefix(text1, text2) {
// Quick check for common null cases.
if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) {
return 0;
}
// Binary search.
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
var pointermin = 0;
var pointermax = Math.min(text1.length, text2.length);
var pointermid = pointermax;
var pointerstart = 0;
while (pointermin < pointermid) {
if (
text1.substring(pointerstart, pointermid) ==
text2.substring(pointerstart, pointermid)
) {
pointermin = pointermid;
pointerstart = pointermin;
} else {
pointermax = pointermid;
}
pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
}
if (is_surrogate_pair_start(text1.charCodeAt(pointermid - 1))) {
pointermid--;
}
return pointermid;
}
/**
* Determine the common suffix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of each string.
*/
function diff_commonSuffix(text1, text2) {
// Quick check for common null cases.
if (!text1 || !text2 || text1.slice(-1) !== text2.slice(-1)) {
return 0;
}
// Binary search.
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
var pointermin = 0;
var pointermax = Math.min(text1.length, text2.length);
var pointermid = pointermax;
var pointerend = 0;
while (pointermin < pointermid) {
if (
text1.substring(text1.length - pointermid, text1.length - pointerend) ==
text2.substring(text2.length - pointermid, text2.length - pointerend)
) {
pointermin = pointermid;
pointerend = pointermin;
} else {
pointermax = pointermid;
}
pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
}
if (is_surrogate_pair_end(text1.charCodeAt(text1.length - pointermid))) {
pointermid--;
}
return pointermid;
}
/**
* Do the two texts share a substring which is at least half the length of the
* longer text?
* This speedup can produce non-minimal diffs.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {Array.<string>} Five element Array, containing the prefix of
* text1, the suffix of text1, the prefix of text2, the suffix of
* text2 and the common middle. Or null if there was no match.
*/
function diff_halfMatch_(text1, text2) {
var longtext = text1.length > text2.length ? text1 : text2;
var shorttext = text1.length > text2.length ? text2 : text1;
if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
return null; // Pointless.
}
/**
* Does a substring of shorttext exist within longtext such that the substring
* is at least half the length of longtext?
* Closure, but does not reference any external variables.
* @param {string} longtext Longer string.
* @param {string} shorttext Shorter string.
* @param {number} i Start index of quarter length substring within longtext.
* @return {Array.<string>} Five element Array, containing the prefix of
* longtext, the suffix of longtext, the prefix of shorttext, the suffix
* of shorttext and the common middle. Or null if there was no match.
* @private
*/
function diff_halfMatchI_(longtext, shorttext, i) {
// Start with a 1/4 length substring at position i as a seed.
var seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
var j = -1;
var best_common = '';
var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b;
while ((j = shorttext.indexOf(seed, j + 1)) !== -1) {
var prefixLength = diff_commonPrefix(
longtext.substring(i), shorttext.substring(j));
var suffixLength = diff_commonSuffix(
longtext.substring(0, i), shorttext.substring(0, j));
if (best_common.length < suffixLength + prefixLength) {
best_common = shorttext.substring(
j - suffixLength, j) + shorttext.substring(j, j + prefixLength);
best_longtext_a = longtext.substring(0, i - suffixLength);
best_longtext_b = longtext.substring(i + prefixLength);
best_shorttext_a = shorttext.substring(0, j - suffixLength);
best_shorttext_b = shorttext.substring(j + prefixLength);
}
}
if (best_common.length * 2 >= longtext.length) {
return [
best_longtext_a, best_longtext_b,
best_shorttext_a, best_shorttext_b, best_common
];
} else {
return null;
}
}
// First check if the second quarter is the seed for a half-match.
var hm1 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 4));
// Check again based on the third quarter.
var hm2 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 2));
var hm;
if (!hm1 && !hm2) {
return null;
} else if (!hm2) {
hm = hm1;
} else if (!hm1) {
hm = hm2;
} else {
// Both matched. Select the longest.
hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
}
// A half-match was found, sort out the return data.
var text1_a, text1_b, text2_a, text2_b;
if (text1.length > text2.length) {
text1_a = hm[0];
text1_b = hm[1];
text2_a = hm[2];
text2_b = hm[3];
} else {
text2_a = hm[0];
text2_b = hm[1];
text1_a = hm[2];
text1_b = hm[3];
}
var mid_common = hm[4];
return [text1_a, text1_b, text2_a, text2_b, mid_common];
}
/**
* Reorder and merge like edit sections. Merge equalities.
* Any edit section can move as long as it doesn't cross an equality.
* @param {Array} diffs Array of diff tuples.
* @param {boolean} fix_unicode Whether to normalize to a unicode-correct diff
*/
function diff_cleanupMerge(diffs, fix_unicode) {
diffs.push([DIFF_EQUAL, '']); // Add a dummy entry at the end.
var pointer = 0;
var count_delete = 0;
var count_insert = 0;
var text_delete = '';
var text_insert = '';
var commonlength;
while (pointer < diffs.length) {
if (pointer < diffs.length - 1 && !diffs[pointer][1]) {
diffs.splice(pointer, 1);
continue;
}
switch (diffs[pointer][0]) {
case DIFF_INSERT:
count_insert++;
text_insert += diffs[pointer][1];
pointer++;
break;
case DIFF_DELETE:
count_delete++;
text_delete += diffs[pointer][1];
pointer++;
break;
case DIFF_EQUAL:
var previous_equality = pointer - count_insert - count_delete - 1;
if (fix_unicode) {
// prevent splitting of unicode surrogate pairs. when fix_unicode is true,
// we assume that the old and new text in the diff are complete and correct
// unicode-encoded JS strings, but the tuple boundaries may fall between
// surrogate pairs. we fix this by shaving off stray surrogates from the end
// of the previous equality and the beginning of this equality. this may create
// empty equalities or a common prefix or suffix. for example, if AB and AC are
// emojis, `[[0, 'A'], [-1, 'BA'], [0, 'C']]` would turn into deleting 'ABAC' and
// inserting 'AC', and then the common suffix 'AC' will be eliminated. in this
// particular case, both equalities go away, we absorb any previous inequalities,
// and we keep scanning for the next equality before rewriting the tuples.
if (previous_equality >= 0 && ends_with_pair_start(diffs[previous_equality][1])) {
var stray = diffs[previous_equality][1].slice(-1);
diffs[previous_equality][1] = diffs[previous_equality][1].slice(0, -1);
text_delete = stray + text_delete;
text_insert = stray + text_insert;
if (!diffs[previous_equality][1]) {
// emptied out previous equality, so delete it and include previous delete/insert
diffs.splice(previous_equality, 1);
pointer--;
var k = previous_equality - 1;
if (diffs[k] && diffs[k][0] === DIFF_INSERT) {
count_insert++;
text_insert = diffs[k][1] + text_insert;
k--;
}
if (diffs[k] && diffs[k][0] === DIFF_DELETE) {
count_delete++;
text_delete = diffs[k][1] + text_delete;
k--;
}
previous_equality = k;
}
}
if (starts_with_pair_end(diffs[pointer][1])) {
var stray = diffs[pointer][1].charAt(0);
diffs[pointer][1] = diffs[pointer][1].slice(1);
text_delete += stray;
text_insert += stray;
}
}
if (pointer < diffs.length - 1 && !diffs[pointer][1]) {
// for empty equality not at end, wait for next equality
diffs.splice(pointer, 1);
break;
}
if (text_delete.length > 0 || text_insert.length > 0) {
// note that diff_commonPrefix and diff_commonSuffix are unicode-aware
if (text_delete.length > 0 && text_insert.length > 0) {
// Factor out any common prefixes.
commonlength = diff_commonPrefix(text_insert, text_delete);
if (commonlength !== 0) {
if (previous_equality >= 0) {
diffs[previous_equality][1] += text_insert.substring(0, commonlength);
} else {
diffs.splice(0, 0, [DIFF_EQUAL, text_insert.substring(0, commonlength)]);
pointer++;
}
text_insert = text_insert.substring(commonlength);
text_delete = text_delete.substring(commonlength);
}
// Factor out any common suffixes.
commonlength = diff_commonSuffix(text_insert, text_delete);
if (commonlength !== 0) {
diffs[pointer][1] =
text_insert.substring(text_insert.length - commonlength) + diffs[pointer][1];
text_insert = text_insert.substring(0, text_insert.length - commonlength);
text_delete = text_delete.substring(0, text_delete.length - commonlength);
}
}
// Delete the offending records and add the merged ones.
var n = count_insert + count_delete;
if (text_delete.length === 0 && text_insert.length === 0) {
diffs.splice(pointer - n, n);
pointer = pointer - n;
} else if (text_delete.length === 0) {
diffs.splice(pointer - n, n, [DIFF_INSERT, text_insert]);
pointer = pointer - n + 1;
} else if (text_insert.length === 0) {
diffs.splice(pointer - n, n, [DIFF_DELETE, text_delete]);
pointer = pointer - n + 1;
} else {
diffs.splice(pointer - n, n, [DIFF_DELETE, text_delete], [DIFF_INSERT, text_insert]);
pointer = pointer - n + 2;
}
}
if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) {
// Merge this equality with the previous one.
diffs[pointer - 1][1] += diffs[pointer][1];
diffs.splice(pointer, 1);
} else {
pointer++;
}
count_insert = 0;
count_delete = 0;
text_delete = '';
text_insert = '';
break;
}
}
if (diffs[diffs.length - 1][1] === '') {
diffs.pop(); // Remove the dummy entry at the end.
}
// Second pass: look for single edits surrounded on both sides by equalities
// which can be shifted sideways to eliminate an equality.
// e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
var changes = false;
pointer = 1;
// Intentionally ignore the first and last element (don't need checking).
while (pointer < diffs.length - 1) {
if (diffs[pointer - 1][0] === DIFF_EQUAL &&
diffs[pointer + 1][0] === DIFF_EQUAL) {
// This is a single edit surrounded by equalities.
if (diffs[pointer][1].substring(diffs[pointer][1].length -
diffs[pointer - 1][1].length) === diffs[pointer - 1][1]) {
// Shift the edit over the previous equality.
diffs[pointer][1] = diffs[pointer - 1][1] +
diffs[pointer][1].substring(0, diffs[pointer][1].length -
diffs[pointer - 1][1].length);
diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
diffs.splice(pointer - 1, 1);
changes = true;
} else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) ==
diffs[pointer + 1][1]) {
// Shift the edit over the next equality.
diffs[pointer - 1][1] += diffs[pointer + 1][1];
diffs[pointer][1] =
diffs[pointer][1].substring(diffs[pointer + 1][1].length) +
diffs[pointer + 1][1];
diffs.splice(pointer + 1, 1);
changes = true;
}
}
pointer++;
}
// If shifts were made, the diff needs reordering and another shift sweep.
if (changes) {
diff_cleanupMerge(diffs, fix_unicode);
}
}
function is_surrogate_pair_start(charCode) {
return charCode >= 0xD800 && charCode <= 0xDBFF;
}
function is_surrogate_pair_end(charCode) {
return charCode >= 0xDC00 && charCode <= 0xDFFF;
}
function starts_with_pair_end(str) {
return is_surrogate_pair_end(str.charCodeAt(0));
}
function ends_with_pair_start(str) {
return is_surrogate_pair_start(str.charCodeAt(str.length - 1));
}
function remove_empty_tuples(tuples) {
var ret = [];
for (var i = 0; i < tuples.length; i++) {
if (tuples[i][1].length > 0) {
ret.push(tuples[i]);
}
}
return ret;
}
function make_edit_splice(before, oldMiddle, newMiddle, after) {
if (ends_with_pair_start(before) || starts_with_pair_end(after)) {
return null;
}
return remove_empty_tuples([
[DIFF_EQUAL, before],
[DIFF_DELETE, oldMiddle],
[DIFF_INSERT, newMiddle],
[DIFF_EQUAL, after]
]);
}
function find_cursor_edit_diff(oldText, newText, cursor_pos) {
// note: this runs after equality check has ruled out exact equality
var oldRange = typeof cursor_pos === 'number' ?
{ index: cursor_pos, length: 0 } : cursor_pos.oldRange;
var newRange = typeof cursor_pos === 'number' ?
null : cursor_pos.newRange;
// take into account the old and new selection to generate the best diff
// possible for a text edit. for example, a text change from "xxx" to "xx"
// could be a delete or forwards-delete of any one of the x's, or the
// result of selecting two of the x's and typing "x".
var oldLength = oldText.length;
var newLength = newText.length;
if (oldRange.length === 0 && (newRange === null || newRange.length === 0)) {
// see if we have an insert or delete before or after cursor
var oldCursor = oldRange.index;
var oldBefore = oldText.slice(0, oldCursor);
var oldAfter = oldText.slice(oldCursor);
var maybeNewCursor = newRange ? newRange.index : null;
editBefore: {
// is this an insert or delete right before oldCursor?
var newCursor = oldCursor + newLength - oldLength;
if (maybeNewCursor !== null && maybeNewCursor !== newCursor) {
break editBefore;
}
if (newCursor < 0 || newCursor > newLength) {
break editBefore;
}
var newBefore = newText.slice(0, newCursor);
var newAfter = newText.slice(newCursor);
if (newAfter !== oldAfter) {
break editBefore;
}
var prefixLength = Math.min(oldCursor, newCursor);
var oldPrefix = oldBefore.slice(0, prefixLength);
var newPrefix = newBefore.slice(0, prefixLength);
if (oldPrefix !== newPrefix) {
break editBefore;
}
var oldMiddle = oldBefore.slice(prefixLength);
var newMiddle = newBefore.slice(prefixLength);
return make_edit_splice(oldPrefix, oldMiddle, newMiddle, oldAfter);
}
editAfter: {
// is this an insert or delete right after oldCursor?
if (maybeNewCursor !== null && maybeNewCursor !== oldCursor) {
break editAfter;
}
var cursor = oldCursor;
var newBefore = newText.slice(0, cursor);
var newAfter = newText.slice(cursor);
if (newBefore !== oldBefore) {
break editAfter;
}
var suffixLength = Math.min(oldLength - cursor, newLength - cursor);
var oldSuffix = oldAfter.slice(oldAfter.length - suffixLength);
var newSuffix = newAfter.slice(newAfter.length - suffixLength);
if (oldSuffix !== newSuffix) {
break editAfter;
}
var oldMiddle = oldAfter.slice(0, oldAfter.length - suffixLength);
var newMiddle = newAfter.slice(0, newAfter.length - suffixLength);
return make_edit_splice(oldBefore, oldMiddle, newMiddle, oldSuffix);
}
}
if (oldRange.length > 0 && newRange && newRange.length === 0) {
replaceRange: {
// see if diff could be a splice of the old selection range
var oldPrefix = oldText.slice(0, oldRange.index);
var oldSuffix = oldText.slice(oldRange.index + oldRange.length);
var prefixLength = oldPrefix.length;
var suffixLength = oldSuffix.length;
if (newLength < prefixLength + suffixLength) {
break replaceRange;
}
var newPrefix = newText.slice(0, prefixLength);
var newSuffix = newText.slice(newLength - suffixLength);
if (oldPrefix !== newPrefix || oldSuffix !== newSuffix) {
break replaceRange;
}
var oldMiddle = oldText.slice(prefixLength, oldLength - suffixLength);
var newMiddle = newText.slice(prefixLength, newLength - suffixLength);
return make_edit_splice(oldPrefix, oldMiddle, newMiddle, oldSuffix);
}
}
return null;
}
function diff$1(text1, text2, cursor_pos) {
// only pass fix_unicode=true at the top level, not when diff_main is
// recursively invoked
return diff_main(text1, text2, cursor_pos, true);
}
diff$1.INSERT = DIFF_INSERT;
diff$1.DELETE = DIFF_DELETE;
diff$1.EQUAL = DIFF_EQUAL;
var diff_1$2 = diff$1;
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* 更新内容时保持光标不变
* @param {Number} pos 光标相对文档开头的偏移量
* @param {String} oldContent 变更前的内容
* @param {String} newContent 变更后的内容
* @returns {Number} newPos 新的光标偏移量
*/
function getPosBydiffs(pos, oldContent, newContent) {
var diffs = diff_1$2(oldContent, newContent);
var newPos = pos;
var tmpPos = pos;
for (var i = 0; i < diffs.length; i++) {
var val = diffs[i];
if (tmpPos <= 0) {
return newPos;
}
var opType = val[0];
var opLength = val[1].length;
switch (opType) {
// 没有改变的内容
case diff_1$2.EQUAL:
if (tmpPos <= opLength) {
return newPos;
}
tmpPos -= opLength;
break;
// 删除的内容
case diff_1$2.DELETE:
if (tmpPos <= opLength) {
return newPos - opLength + tmpPos;
}
tmpPos -= opLength;
newPos -= opLength;
break;
// 新增的内容
case diff_1$2.INSERT:
newPos += opLength;
break;
}
}
return newPos;
}
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
var _arrayEach = arrayEach;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = _overArg(Object.keys, Object);
var _nativeKeys = nativeKeys;
/** Used for built-in method references. */
var objectProto$b = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$a = objectProto$b.hasOwnProperty;
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!_isPrototype(object)) {
return _nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty$a.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
var _baseKeys = baseKeys;
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys$8(object) {
return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
}
var keys_1 = keys$8;
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && _copyObject(source, keys_1(source), object);
}
var _baseAssign = baseAssign;
/**
* The base implementation of `_.assignIn` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssignIn(object, source) {
return object && _copyObject(source, keysIn_1(source), object);
}
var _baseAssignIn = baseAssignIn;
/**
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
var _arrayFilter = arrayFilter;
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
var stubArray_1 = stubArray;
/** Used for built-in method references. */
var objectProto$c = Object.prototype;
/** Built-in value references. */
var propertyIsEnumerable$2 = objectProto$c.propertyIsEnumerable;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = !nativeGetSymbols ? stubArray_1 : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return _arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable$2.call(object, symbol);
});
};
var _getSymbols = getSymbols;
/**
* Copies own symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbols(source, object) {
return _copyObject(source, _getSymbols(source), object);
}
var _copySymbols = copySymbols;
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
var _arrayPush = arrayPush;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols$1 = Object.getOwnPropertySymbols;
/**
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbolsIn = !nativeGetSymbols$1 ? stubArray_1 : function(object) {
var result = [];
while (object) {
_arrayPush(result, _getSymbols(object));
object = _getPrototype(object);
}
return result;
};
var _getSymbolsIn = getSymbolsIn;
/**
* Copies own and inherited symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbolsIn(source, object) {
return _copyObject(source, _getSymbolsIn(source), object);
}
var _copySymbolsIn = copySymbolsIn;
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
}
var _baseGetAllKeys = baseGetAllKeys;
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return _baseGetAllKeys(object, keys_1, _getSymbols);
}
var _getAllKeys = getAllKeys;
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeysIn(object) {
return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn);
}
var _getAllKeysIn = getAllKeysIn;
/* Built-in method references that are verified to be native. */
var DataView$1 = _getNative(_root, 'DataView');
var _DataView = DataView$1;
/* Built-in method references that are verified to be native. */
var Promise$2 = _getNative(_root, 'Promise');
var _Promise = Promise$2;
/* Built-in method references that are verified to be native. */
var Set$1 = _getNative(_root, 'Set');
var _Set = Set$1;
/* Built-in method references that are verified to be native. */
var WeakMap$2 = _getNative(_root, 'WeakMap');
var _WeakMap = WeakMap$2;
/** `Object#toString` result references. */
var mapTag$1 = '[object Map]',
objectTag$2 = '[object Object]',
promiseTag = '[object Promise]',
setTag$1 = '[object Set]',
weakMapTag$1 = '[object WeakMap]';
var dataViewTag$1 = '[object DataView]';
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = _toSource(_DataView),
mapCtorString = _toSource(_Map),
promiseCtorString = _toSource(_Promise),
setCtorString = _toSource(_Set),
weakMapCtorString = _toSource(_WeakMap);
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = _baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$1) ||
(_Map && getTag(new _Map) != mapTag$1) ||
(_Promise && getTag(_Promise.resolve()) != promiseTag) ||
(_Set && getTag(new _Set) != setTag$1) ||
(_WeakMap && getTag(new _WeakMap) != weakMapTag$1)) {
getTag = function(value) {
var result = _baseGetTag(value),
Ctor = result == objectTag$2 ? value.constructor : undefined,
ctorString = Ctor ? _toSource(Ctor) : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag$1;
case mapCtorString: return mapTag$1;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag$1;
case weakMapCtorString: return weakMapTag$1;
}
}
return result;
};
}
var _getTag = getTag;
/** Used for built-in method references. */
var objectProto$d = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$b = objectProto$d.hasOwnProperty;
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = new array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty$b.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
var _initCloneArray = initCloneArray;
/**
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
*/
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
var _cloneDataView = cloneDataView;
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
var _cloneRegExp = cloneRegExp;
/** Used to convert symbols to primitives and strings. */
var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined,
symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined;
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
var _cloneSymbol = cloneSymbol;
/** `Object#toString` result references. */
var boolTag$1 = '[object Boolean]',
dateTag$1 = '[object Date]',
mapTag$2 = '[object Map]',
numberTag$1 = '[object Number]',
regexpTag$1 = '[object RegExp]',
setTag$2 = '[object Set]',
stringTag$1 = '[object String]',
symbolTag$1 = '[object Symbol]';
var arrayBufferTag$1 = '[object ArrayBuffer]',
dataViewTag$2 = '[object DataView]',
float32Tag$1 = '[object Float32Array]',
float64Tag$1 = '[object Float64Array]',
int8Tag$1 = '[object Int8Array]',
int16Tag$1 = '[object Int16Array]',
int32Tag$1 = '[object Int32Array]',
uint8Tag$1 = '[object Uint8Array]',
uint8ClampedTag$1 = '[object Uint8ClampedArray]',
uint16Tag$1 = '[object Uint16Array]',
uint32Tag$1 = '[object Uint32Array]';
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag$1:
return _cloneArrayBuffer(object);
case boolTag$1:
case dateTag$1:
return new Ctor(+object);
case dataViewTag$2:
return _cloneDataView(object, isDeep);
case float32Tag$1: case float64Tag$1:
case int8Tag$1: case int16Tag$1: case int32Tag$1:
case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1:
return _cloneTypedArray(object, isDeep);
case mapTag$2:
return new Ctor;
case numberTag$1:
case stringTag$1:
return new Ctor(object);
case regexpTag$1:
return _cloneRegExp(object);
case setTag$2:
return new Ctor;
case symbolTag$1:
return _cloneSymbol(object);
}
}
var _initCloneByTag = initCloneByTag;
/** `Object#toString` result references. */
var mapTag$3 = '[object Map]';
/**
* The base implementation of `_.isMap` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
*/
function baseIsMap(value) {
return isObjectLike_1(value) && _getTag(value) == mapTag$3;
}
var _baseIsMap = baseIsMap;
/* Node.js helper references. */
var nodeIsMap = _nodeUtil && _nodeUtil.isMap;
/**
* Checks if `value` is classified as a `Map` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
* @example
*
* _.isMap(new Map);
* // => true
*
* _.isMap(new WeakMap);
* // => false
*/
var isMap = nodeIsMap ? _baseUnary(nodeIsMap) : _baseIsMap;
var isMap_1 = isMap;
/** `Object#toString` result references. */
var setTag$3 = '[object Set]';
/**
* The base implementation of `_.isSet` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
*/
function baseIsSet(value) {
return isObjectLike_1(value) && _getTag(value) == setTag$3;
}
var _baseIsSet = baseIsSet;
/* Node.js helper references. */
var nodeIsSet = _nodeUtil && _nodeUtil.isSet;
/**
* Checks if `value` is classified as a `Set` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
* @example
*
* _.isSet(new Set);
* // => true
*
* _.isSet(new WeakSet);
* // => false
*/
var isSet = nodeIsSet ? _baseUnary(nodeIsSet) : _baseIsSet;
var isSet_1 = isSet;
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/** `Object#toString` result references. */
var argsTag$2 = '[object Arguments]',
arrayTag$1 = '[object Array]',
boolTag$2 = '[object Boolean]',
dateTag$2 = '[object Date]',
errorTag$1 = '[object Error]',
funcTag$2 = '[object Function]',
genTag$1 = '[object GeneratorFunction]',
mapTag$4 = '[object Map]',
numberTag$2 = '[object Number]',
objectTag$3 = '[object Object]',
regexpTag$2 = '[object RegExp]',
setTag$4 = '[object Set]',
stringTag$2 = '[object String]',
symbolTag$2 = '[object Symbol]',
weakMapTag$2 = '[object WeakMap]';
var arrayBufferTag$2 = '[object ArrayBuffer]',
dataViewTag$3 = '[object DataView]',
float32Tag$2 = '[object Float32Array]',
float64Tag$2 = '[object Float64Array]',
int8Tag$2 = '[object Int8Array]',
int16Tag$2 = '[object Int16Array]',
int32Tag$2 = '[object Int32Array]',
uint8Tag$2 = '[object Uint8Array]',
uint8ClampedTag$2 = '[object Uint8ClampedArray]',
uint16Tag$2 = '[object Uint16Array]',
uint32Tag$2 = '[object Uint32Array]';
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag$2] = cloneableTags[arrayTag$1] =
cloneableTags[arrayBufferTag$2] = cloneableTags[dataViewTag$3] =
cloneableTags[boolTag$2] = cloneableTags[dateTag$2] =
cloneableTags[float32Tag$2] = cloneableTags[float64Tag$2] =
cloneableTags[int8Tag$2] = cloneableTags[int16Tag$2] =
cloneableTags[int32Tag$2] = cloneableTags[mapTag$4] =
cloneableTags[numberTag$2] = cloneableTags[objectTag$3] =
cloneableTags[regexpTag$2] = cloneableTags[setTag$4] =
cloneableTags[stringTag$2] = cloneableTags[symbolTag$2] =
cloneableTags[uint8Tag$2] = cloneableTags[uint8ClampedTag$2] =
cloneableTags[uint16Tag$2] = cloneableTags[uint32Tag$2] = true;
cloneableTags[errorTag$1] = cloneableTags[funcTag$2] =
cloneableTags[weakMapTag$2] = false;
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, bitmask, customizer, key, object, stack) {
var result,
isDeep = bitmask & CLONE_DEEP_FLAG,
isFlat = bitmask & CLONE_FLAT_FLAG,
isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject_1(value)) {
return value;
}
var isArr = isArray_1(value);
if (isArr) {
result = _initCloneArray(value);
if (!isDeep) {
return _copyArray(value, result);
}
} else {
var tag = _getTag(value),
isFunc = tag == funcTag$2 || tag == genTag$1;
if (isBuffer_1(value)) {
return _cloneBuffer(value, isDeep);
}
if (tag == objectTag$3 || tag == argsTag$2 || (isFunc && !object)) {
result = (isFlat || isFunc) ? {} : _initCloneObject(value);
if (!isDeep) {
return isFlat
? _copySymbolsIn(value, _baseAssignIn(result, value))
: _copySymbols(value, _baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = _initCloneByTag(value, tag, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new _Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
if (isSet_1(value)) {
value.forEach(function(subValue) {
result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
});
} else if (isMap_1(value)) {
value.forEach(function(subValue, key) {
result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
}
var keysFunc = isFull
? (isFlat ? _getAllKeysIn : _getAllKeys)
: (isFlat ? keysIn_1 : keys_1);
var props = isArr ? undefined : keysFunc(value);
_arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
_assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
return result;
}
var _baseClone = baseClone;
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG$1 = 1,
CLONE_SYMBOLS_FLAG$1 = 4;
/**
* This method is like `_.clone` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @returns {*} Returns the deep cloned value.
* @see _.clone
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var deep = _.cloneDeep(objects);
* console.log(deep[0] === objects[0]);
* // => false
*/
function cloneDeep(value) {
return _baseClone(value, CLONE_DEEP_FLAG$1 | CLONE_SYMBOLS_FLAG$1);
}
var cloneDeep_1 = cloneDeep;
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var callbacks = {
/**
* 全局的URL处理器
* @param {string} url 来源url
* @param {'image'|'audio'|'video'|'autolink'|'link'} srcType 来源类型
* @returns
*/
urlProcessor: function urlProcessor(url, srcType) {
return url;
},
fileUpload: function fileUpload(file, callback) {
if (/video/i.test(file.type)) {
callback('images/demo-dog.png', {
name: "".concat(file.name.replace(/\.[^.]+$/, '')),
poster: 'images/demo-dog.png?poster=true',
isBorder: true,
isShadow: true,
isRadius: true
});
} else {
callback('images/demo-dog.png', {
name: "".concat(file.name.replace(/\.[^.]+$/, '')),
isShadow: true
});
}
},
afterChange: function afterChange(text, html) {},
afterInit: function afterInit(text, html) {},
beforeImageMounted: function beforeImageMounted(srcProp, src) {
return {
srcProp: srcProp,
src: src
};
},
onClickPreview: function onClickPreview(event) {},
onCopyCode: function onCopyCode(event, code) {
// 阻止默认的粘贴事件
// return false;
// 对复制内容进行额外处理
return code;
},
// 获取中文的拼音
changeString2Pinyin: function changeString2Pinyin(string) {
/**
* 推荐使用这个组件https://github.com/liu11hao11/pinyin_js
*
* 可以在 ../scripts/pinyin/pinyin_dist.js 里直接引用
*/
return string;
}
};
/** @type {Partial<import('~types/cherry').CherryOptions>} */
var defaultConfig = {
// 第三方包
externals: {// externals
},
// chatGpt的openai配置
openai: {
apiKey: '',
// apiKey
// proxy: {
// host: '127.0.0.1',
// port: '7890',
// }, // http & https代理配置
ignoreError: false // 是否忽略请求失败,默认忽略
},
// 解析引擎配置
engine: {
// 全局配置
global: {
// 是否启用经典换行逻辑
// true一个换行会被忽略两个以上连续换行会分割成段落
// false 一个换行会转成<br>,两个连续换行会分割成段落,三个以上连续换行会转成<br>并分割段落
classicBr: false,
/**
* 全局的URL处理器
* @param {string} url 来源url
* @param {'image'|'audio'|'video'|'autolink'|'link'} srcType 来源类型
* @returns
*/
urlProcessor: callbacks.urlProcessor,
/**
* 额外允许渲染的html标签
* 标签以英文竖线分隔htmlWhiteList: 'iframe|script|style'
* 默认为空默认允许渲染的html见src/utils/sanitize.js whiteList 属性
* 需要注意:
* - 启用iframe、script等标签后会产生xss注入请根据实际场景判断是否需要启用
* - 一般编辑权限可控的场景如api文档系统可以允许iframe、script等标签
*/
htmlWhiteList: ''
},
// 内置语法配置
syntax: {
// 语法开关
// 'hookName': false,
// 语法配置
// 'hookName': {
//
// }
link: {
/** 生成的<a>标签追加target属性的默认值 空:在<a>标签里不会追加target属性 _blank在<a>标签里追加target="_blank"属性 */
target: '',
/** 生成的<a>标签追加rel属性的默认值 空:在<a>标签里不会追加rel属性 nofollow在<a>标签里追加rel="nofollow在"属性*/
rel: ''
},
autoLink: {
/** 生成的<a>标签追加target属性的默认值 空:在<a>标签里不会追加target属性 _blank在<a>标签里追加target="_blank"属性 */
target: '',
/** 生成的<a>标签追加rel属性的默认值 空:在<a>标签里不会追加rel属性 nofollow在<a>标签里追加rel="nofollow在"属性*/
rel: '',
/** 是否开启短链接 */
enableShortLink: true,
/** 短链接长度 */
shortLinkLength: 20
},
list: {
listNested: false,
// 同级列表类型转换后变为子级
indentSpace: 2 // 默认2个空格缩进
},
table: {
enableChart: false // chartRenderEngine: EChartsTableEngine,
// externals: ['echarts'],
},
inlineCode: {
theme: 'red'
},
codeBlock: {
theme: 'dark',
// 默认为深色主题
wrap: true,
// 超出长度是否换行false则显示滚动条
lineNumber: true,
// 默认显示行号
copyCode: true,
// 是否显示“复制”按钮
customRenderer: {// 自定义语法渲染器
},
mermaid: {
svg2img: false // 是否将mermaid生成的画图变成img格式
},
/**
* indentedCodeBlock是缩进代码块是否启用的开关
*
* 在6.X之前的版本中默认不支持该语法。
* 因为cherry的开发团队认为该语法太丑了容易误触
* 开发团队希望用```代码块语法来彻底取代该语法
* 但在后续的沟通中,开发团队发现在某些场景下该语法有更好的显示效果
* 因此开发团队在6.X版本中才引入了该语法
* 已经引用6.x以下版本的业务如果想做到用户无感知升级可以去掉该语法
* indentedCodeBlockfalse
*/
indentedCodeBlock: true
},
emoji: {
useUnicode: true // 是否使用unicode进行渲染
},
fontEmphasis: {
/**
* 是否允许首尾空格
* 首尾、前后的定义: 语法前**语法首+内容+语法尾**语法后
* 例:
* true:
* __ hello __ ====> <strong> hello </strong>
* __hello__ ====> <strong>hello</strong>
* false:
* __ hello __ ====> <em>_ hello _</em>
* __hello__ ====> <strong>hello</strong>
*/
allowWhitespace: false
},
strikethrough: {
/**
* 是否必须有前后空格
* 首尾、前后的定义: 语法前**语法首+内容+语法尾**语法后
* 例:
* true:
* hello wor~~l~~d ====> hello wor~~l~~d
* hello wor ~~l~~ d ====> hello wor <del>l</del> d
* false:
* hello wor~~l~~d ====> hello wor<del>l</del>d
* hello wor ~~l~~ d ====> hello wor <del>l</del> d
*/
needWhitespace: false
},
mathBlock: {
engine: 'MathJax',
// katex或MathJax
src: '',
plugins: true // 默认加载插件
},
inlineMath: {
engine: 'MathJax',
// katex或MathJax
src: ''
},
toc: {
/** 默认只渲染一个目录 */
allowMultiToc: false
},
header: {
/**
* 标题的样式:
* - default 默认样式,标题前面有锚点
* - autonumber 标题前面有自增序号锚点
* - none 标题没有锚点
*/
anchorStyle: 'default'
}
}
},
editor: {
id: 'code',
// textarea 的id属性值
name: 'code',
// textarea 的name属性值
autoSave2Textarea: false,
// 是否自动将编辑区的内容回写到textarea里
theme: 'default',
// depend on codemirror theme name: https://codemirror.net/demo/theme.htm
// 编辑器的高度默认100%如果挂载点存在内联设置的height则以内联样式为主
height: '100%',
// defaultModel 编辑器初始化后的默认模式一共有三种模式1、双栏编辑预览模式2、纯编辑模式3、预览模式
// edit&preview: 双栏编辑预览模式
// editOnly: 纯编辑模式没有预览可通过toolbar切换成双栏或预览模式
// previewOnly: 预览模式没有编辑框toolbar只显示“返回编辑”按钮可通过toolbar切换成编辑模式
defaultModel: 'edit&preview',
// 粘贴时是否自动将html转成markdown
convertWhenPaste: true,
codemirror: {
// 是否自动focus 默认为true
autofocus: true
},
writingStyle: 'normal' // 书写风格normal 普通 | typewriter 打字机 | focus 专注默认normal
},
toolbars: {
theme: 'dark',
// light or dark
showToolbar: true,
// false不展示顶部工具栏 true展示工具栏; toolbars.showToolbar=false 与 toolbars.toolbar=false 等效
toolbar: ['bold', 'italic', 'strikethrough', '|', 'color', 'header', 'ruby', '|', 'list', 'panel', // 'justify', // 对齐方式,默认不推荐这么“复杂”的样式要求
'detail', {
insert: ['image', 'audio', 'video', 'link', 'hr', 'br', 'code', 'formula', 'toc', 'table', 'line-table', 'bar-table', 'pdf', 'word']
}, 'graph', 'settings'],
toolbarRight: [],
sidebar: [],
bubble: ['bold', 'italic', 'underline', 'strikethrough', 'sub', 'sup', 'quote', '|', 'size', 'color'],
// array or false
"float": ['h1', 'h2', 'h3', '|', 'checklist', 'quote', 'table', 'code'] // array or false
},
// 打开draw.io编辑页的url如果为空则drawio按钮失效
drawioIframeUrl: '',
// 上传文件的回调
fileUpload: callbacks.fileUpload,
/**
* 上传文件的时候用来指定文件类型
*/
fileTypeLimitMap: {
video: 'video/*',
audio: 'audio/*',
image: 'image/*',
word: '.doc,.docx',
pdf: '.pdf',
file: '*'
},
callback: {
afterChange: callbacks.afterChange,
afterInit: callbacks.afterInit,
beforeImageMounted: callbacks.beforeImageMounted,
// 预览区域点击事件previewer.enablePreviewerBubble = true 时生效
onClickPreview: callbacks.onClickPreview,
// 复制代码块代码时的回调
onCopyCode: callbacks.onCopyCode,
// 把中文变成拼音的回调,当然也可以把中文变成英文、英文变成中文
changeString2Pinyin: callbacks.changeString2Pinyin
},
previewer: {
dom: false,
className: 'cherry-markdown',
// 是否启用预览区域编辑能力(目前支持编辑图片尺寸、编辑表格内容)
enablePreviewerBubble: true,
/**
* 配置图片懒加载的逻辑
* - 如果不希望图片懒加载,可配置成 lazyLoadImg = {noLoadImgNum: -1}
* - 如果希望所有图片都无脑懒加载,可配置成 lazyLoadImg = {noLoadImgNum: 0, autoLoadImgNum: -1}
* - 如果一共有15张图片希望
* 1、前5张图片1~5直接加载
* 2、后5张图片6~10不论在不在视区内都无脑懒加载
* 3、其他图片11~15在视区内时进行懒加载
* 则配置应该为lazyLoadImg = {noLoadImgNum: 5, autoLoadImgNum: 5}
*/
lazyLoadImg: {
// 加载图片时如果需要展示loading图则配置loading图的地址
loadingImgPath: '',
// 同一时间最多有几个图片请求最大同时加载6张图片
maxNumPerTime: 2,
// 不进行懒加载处理的图片数量如果为0即所有图片都进行懒加载处理 如果设置为-1则所有图片都不进行懒加载处理
noLoadImgNum: 5,
// 首次自动加载几张图片不论图片是否滚动到视野内autoLoadImgNum = -1 表示会自动加载完所有图片
autoLoadImgNum: 5,
// 针对加载失败的图片 或 beforeLoadOneImgCallback 返回false 的图片最多尝试加载几次为了防止死循环最多5次。以图片的src为纬度统计重试次数
maxTryTimesPerSrc: 2,
// 加载一张图片之前的回调函数函数return false 会终止加载操作
beforeLoadOneImgCallback: function beforeLoadOneImgCallback(img) {
return true;
},
// 加载一张图片失败之后的回调函数
failLoadOneImgCallback: function failLoadOneImgCallback(img) {},
// 加载一张图片之后的回调函数,如果图片加载失败,则不会回调该函数
afterLoadOneImgCallback: function afterLoadOneImgCallback(img) {},
// 加载完所有图片后调用的回调函数
afterLoadAllImgCallback: function afterLoadAllImgCallback() {}
}
},
/**
* 配置主题,第三方可以自行扩展主题
*/
theme: [{
className: 'default',
label: '默认'
}, {
className: 'dark',
label: '暗黑'
}, {
className: 'light',
label: '明亮'
}, {
className: 'green',
label: '清新'
}, {
className: 'red',
label: '热情'
}, {
className: 'violet',
label: '淡雅'
}, {
className: 'blue',
label: '清幽'
}],
// 预览页面不需要绑定事件
isPreviewOnly: false,
// 预览区域跟随编辑器光标自动滚动
autoScrollByCursor: true,
// 外层容器不存在时是否强制输出到body上
forceAppend: true,
// The locale Cherry is going to use. Locales live in /src/locales/
locale: 'zh_CN'
};
var defaultConfig$1 = cloneDeep_1(defaultConfig);
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var zhCn = {
bold: '加粗',
// 加粗
code: '代码',
// 代码
graph: '画图',
// 画图
h1: '一级标题',
// 一级标题
h2: '二级标题',
// 二级标题
h3: '三级标题',
// 三级标题
h4: '四级标题',
// 四级标题
h5: '五级标题',
// 五级标题
header: '标题',
// 标题
insert: '插入',
// 插入
italic: '斜体',
// 斜体
list: '列表',
// 列表
quickTable: '表格',
// 表格
quote: '引用',
// 引用
size: '大小',
// 大小
color: '文字颜色&背景',
// 文字颜色&背景
strikethrough: '删除线',
// 删除线
sub: '下标',
// 下标
sup: '上标',
// 上标
togglePreview: '预览',
// 预览
fullScreen: '全屏',
// 全屏
image: '图片',
// 图片
audio: '音频',
// 音频
video: '视频',
// 视频
link: '超链接',
// 超链接
hr: '分隔线',
// 分隔线
br: '换行',
// 换行
toc: '目录',
// 目录
pdf: 'pdf',
// pdf
word: 'word',
// word
table: '表格',
// 表格
'line-table': '折线表格',
// 折线表格
'bar-table': '柱状表格',
// 柱状表格
formula: '公式',
// 公式
insertFormula: '公式',
// 公式
insertFlow: '流程图',
// 流程图
insertSeq: '时序图',
// 时序图
insertState: '状态图',
// 状态图
insertClass: '类图',
// 类图
insertPie: '饼图',
// 饼图
insertGantt: '甘特图',
// 甘特图
checklist: '清单',
// 清单
ol: '有序列表',
// 有序列表
ul: '无序列表',
// 无序列表
undo: '撤销',
// 撤销
redo: '恢复',
// 恢复
previewClose: '关闭预览',
// 关闭预览
codeTheme: '代码主题',
// 代码主题
switchModel: '模式切换',
// 模式切换
switchPreview: '预览',
// 预览
switchEdit: '返回编辑',
// 返回编辑
classicBr: '经典换行',
// 经典换行
normalBr: '常规换行',
// 常规换行
settings: '设置',
// 设置
mobilePreview: '移动端预览',
// 移动端预览
copy: '复制内容',
// 复制内容
"export": '导出',
// 导出PDF、长图
underline: '下划线',
// 下划线
pinyin: '拼音',
// 拼音
file: '文件',
pastePlain: '粘贴为纯文本格式',
// 粘贴为纯文本格式
pasteMarkdown: '粘贴为markdown格式',
// 粘贴为markdown格式
hide: '隐藏(ctrl+0)',
// 隐藏(ctrl+0)
exportToPdf: '导出PDF',
// 导出PDF
exportScreenshot: '导出长图',
// 导出长图
exportMarkdownFile: '导出markdown',
// 导出markdown文件
exportHTMLFile: '导出html',
// 导出预览区html文件
theme: '主题',
// 导出长图
panel: '面板',
// 导出长图
detail: '手风琴',
// 手风琴
'H1 Heading': 'H1 一级标题',
'H2 Heading': 'H2 二级标题',
'H3 Heading': 'H3 三级标题',
complement: '续写',
summary: '总结',
save: '保存',
release: '发布',
back: '返回',
};
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var enUs = {
bold: 'Bold',
code: 'Code',
graph: 'Graph',
h1: 'Heading 1',
h2: 'Heading 2',
h3: 'Heading 3',
h4: 'Heading 4',
h5: 'Heading 5',
header: 'Header',
insert: 'Insert',
italic: 'Italic',
list: 'List',
quickTable: 'Quick Table',
quote: 'Quote',
size: 'Size',
color: 'Text Color & Background',
strikethrough: 'Strikethrough',
sub: 'Sub',
sup: 'Sup',
togglePreview: 'Toggle Preview',
fullScreen: 'Full Screen',
image: 'Image',
audio: 'Audio',
video: 'Video',
link: 'Link',
hr: 'Horizontal Rule',
br: 'New Line',
toc: 'Table Of Content',
pdf: 'PDF',
word: 'Word',
table: 'Table',
'line-table': 'Line Table',
'bar-table': 'Bar Table',
formula: 'Formula',
insertFormula: 'Insert Formula',
insertFlow: 'Insert Flow',
insertSeq: 'Insert Seq',
insertState: 'Insert State',
insertClass: 'Insert Class',
insertPie: 'Insert Pie',
insertGantt: 'Insert Gantt',
checklist: 'Checklist',
ol: 'Ordered List',
ul: 'Unordered List',
undo: 'Undo',
redo: 'Redo',
previewClose: 'Preview Close',
codeTheme: 'Code Theme',
switchModel: 'Switch Model',
switchPreview: 'Switch Preview',
switchEdit: 'Switch Edit',
classicBr: 'Classic New Line',
normalBr: 'Normal New Line',
settings: 'Settings',
mobilePreview: 'Mobile Preview',
copy: 'Copy',
"export": 'Export',
underline: 'Underline',
pinyin: 'Pinyin',
pastePlain: 'Paste as Plain Text',
pasteMarkdown: 'Paste as Markdown',
hide: 'Hide (ctrl+0)',
exportToPdf: 'Export to PDF',
exportScreenshot: 'Screenshot',
exportMarkdownFile: 'Export Markdown File',
exportHTMLFile: 'Export preview HTML File',
'H1 Heading': 'H1 Heading',
'H2 Heading': 'H1 Heading',
'H3 Heading': 'H1 Heading',
complement: 'Complement',
summary: 'Summary',
save: 'Save',
release: 'Release',
back: 'Back',
};
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var locales = {
zh_CN: zhCn,
en_US: enUs
};
function _createSuper$1r(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1r(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1r() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function filterOptions(options, whiteList, propTypes) {
var _context;
var filteredOptions = {};
forEach$3(_context = keys$3(options)).call(_context, function (key) {
if (indexOf$8(whiteList).call(whiteList, key) === -1) {
return;
}
if (_typeof(propTypes) === 'object') {
if (typeof propTypes[key] === 'string') {
if (_typeof(options[key]) === propTypes[key]) {
filteredOptions[key] = options[key];
}
} else {
if (options[key] instanceof propTypes[key]) {
filteredOptions[key] = options[key];
}
}
} else if (typeof propTypes === 'string') {
if (_typeof(options[key]) === propTypes) {
filteredOptions[key] = options[key];
}
}
});
return filteredOptions;
}
function createSyntaxHook(name, type, options) {
var _class;
var BaseClass = type === HOOKS_TYPE_LIST.PAR ? ParagraphBase : SyntaxBase;
var optionsWhiteList = ['beforeMakeHtml', 'makeHtml', 'afterMakeHtml', 'rule', 'test'];
var filteredOptions = filterOptions(options, optionsWhiteList, 'function');
var paragraphConfig = {
needCache: options.needCache,
defaultCache: options.defaultCache
};
return _class = /*#__PURE__*/function (_BaseClass) {
_inherits(CustomSyntax, _BaseClass);
var _super = _createSuper$1r(CustomSyntax);
function CustomSyntax() {
var _this;
var editorConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, CustomSyntax);
if (type === HOOKS_TYPE_LIST.PAR) {
_this = _super.call(this, {
needCache: !!paragraphConfig.needCache,
defaultCache: paragraphConfig.defaultCache
});
} else {
_this = _super.call(this);
}
_this.config = editorConfig.config;
return _possibleConstructorReturn(_this);
}
_createClass(CustomSyntax, [{
key: "beforeMakeHtml",
value: function beforeMakeHtml() {
var _get2, _context2;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (filteredOptions.beforeMakeHtml) {
return filteredOptions.beforeMakeHtml.apply(this, args);
}
return (_get2 = _get(_getPrototypeOf(CustomSyntax.prototype), "beforeMakeHtml", this)).call.apply(_get2, concat$5(_context2 = [this]).call(_context2, args));
}
}, {
key: "makeHtml",
value: function makeHtml() {
var _get3, _context3;
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
if (filteredOptions.makeHtml) {
return filteredOptions.makeHtml.apply(this, args);
}
return (_get3 = _get(_getPrototypeOf(CustomSyntax.prototype), "makeHtml", this)).call.apply(_get3, concat$5(_context3 = [this]).call(_context3, args));
}
}, {
key: "afterMakeHtml",
value: function afterMakeHtml() {
var _get4, _context4;
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
if (filteredOptions.afterMakeHtml) {
return filteredOptions.afterMakeHtml.apply(this, args);
}
return (_get4 = _get(_getPrototypeOf(CustomSyntax.prototype), "afterMakeHtml", this)).call.apply(_get4, concat$5(_context4 = [this]).call(_context4, args));
}
}, {
key: "test",
value: function test() {
var _get5, _context5;
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
if (filteredOptions.test) {
return filteredOptions.test.apply(this, args);
}
return (_get5 = _get(_getPrototypeOf(CustomSyntax.prototype), "test", this)).call.apply(_get5, concat$5(_context5 = [this]).call(_context5, args));
}
}, {
key: "rule",
value: function rule() {
var _get6, _context6;
for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
args[_key5] = arguments[_key5];
}
if (filteredOptions.rule) {
return filteredOptions.rule.apply(this, args);
}
return (_get6 = _get(_getPrototypeOf(CustomSyntax.prototype), "rule", this)).call.apply(_get6, concat$5(_context6 = [this]).call(_context6, args));
}
}]);
return CustomSyntax;
}(BaseClass), _defineProperty(_class, "HOOK_NAME", name), _class;
}
function createMenuHook(name, options) {
var optionsWhiteList = ['subMenuConfig', 'id', 'onClick', 'shortcutKeys', 'iconName'];
var propTypes = {
subMenuConfig: Array,
onClick: 'function',
shortcutKeys: Array,
id: 'string',
iconName: 'string'
};
var filteredOptions = filterOptions(options, optionsWhiteList, propTypes);
return /*#__PURE__*/function (_MenuBase) {
_inherits(CustomMenu, _MenuBase);
var _super2 = _createSuper$1r(CustomMenu);
function CustomMenu(editorInstance) {
var _this2;
_classCallCheck(this, CustomMenu);
_this2 = _super2.call(this, editorInstance);
if (!filteredOptions.iconName) {
_this2.noIcon = true;
}
_this2.setName(name, filteredOptions.iconName);
_this2.setId(filteredOptions.id);
_this2.subMenuConfig = filteredOptions.subMenuConfig || [];
return _this2;
}
_createClass(CustomMenu, [{
key: "onClick",
value: function onClick() {
var _get7, _context7;
for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
args[_key6] = arguments[_key6];
}
if (filteredOptions.onClick) {
return filteredOptions.onClick.apply(this, args);
}
return (_get7 = _get(_getPrototypeOf(CustomMenu.prototype), "onClick", this)).call.apply(_get7, concat$5(_context7 = [this]).call(_context7, args));
}
}, {
key: "shortcutKeys",
get: function get() {
if (filteredOptions.shortcutKeys) {
return filteredOptions.shortcutKeys;
}
return [];
}
}]);
return CustomMenu;
}(MenuBase);
}
var constants = {
HOOKS_TYPE_LIST: HOOKS_TYPE_LIST
};
var nodeIgnorePlugin = [];
if (!isBrowser()) {
forEach$3(nodeIgnorePlugin).call(nodeIgnorePlugin, function (key) {
});
}
var VERSION$1 = "0.8.21-4b60dd76";
var CherryStatic = /*#__PURE__*/function () {
function CherryStatic() {
_classCallCheck(this, CherryStatic);
}
_createClass(CherryStatic, null, [{
key: "usePlugin",
value:
/**
* @this {typeof import('./Cherry').default | typeof CherryStatic}
* @param {{ install: (defaultConfig: any, ...args: any[]) => void }} PluginClass 插件Class
* @param {...any} args 初始化插件的参数
* @returns
*/
function usePlugin(PluginClass) {
var _context;
if (this === CherryStatic) {
throw new Error('`usePlugin` is not allowed to called through CherryStatic class.');
} // @ts-ignore
if (this.initialized) {
throw new Error('The function `usePlugin` should be called before Cherry is instantiated.');
} // @ts-ignore
if (PluginClass.$cherry$mounted === true) {
return;
} // @ts-ignore
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
PluginClass.install.apply(PluginClass, concat$5(_context = [this.config.defaults]).call(_context, args)); // @ts-ignore
PluginClass.$cherry$mounted = true;
}
}]);
return CherryStatic;
}();
_defineProperty(CherryStatic, "createSyntaxHook", createSyntaxHook);
_defineProperty(CherryStatic, "createMenuHook", createMenuHook);
_defineProperty(CherryStatic, "constants", constants);
_defineProperty(CherryStatic, "VERSION", VERSION$1);
function ownKeys$9(object, enumerableOnly) { var keys = keys$3(object); if (getOwnPropertySymbols$2) { var symbols = getOwnPropertySymbols$2(object); enumerableOnly && (symbols = filter$3(symbols).call(symbols, function (sym) { return getOwnPropertyDescriptor$3(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$8(target) { for (var i = 1; i < arguments.length; i++) { var _context5, _context6; var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? forEach$3(_context5 = ownKeys$9(Object(source), !0)).call(_context5, function (key) { _defineProperty(target, key, source[key]); }) : getOwnPropertyDescriptors$2 ? defineProperties$2(target, getOwnPropertyDescriptors$2(source)) : forEach$3(_context6 = ownKeys$9(Object(source))).call(_context6, function (key) { defineProperty$5(target, key, getOwnPropertyDescriptor$3(source, key)); }); } return target; }
function _createSuper$1s(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1s(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = construct$4(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1s() { if (typeof Reflect === "undefined" || !construct$4) return false; if (construct$4.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(construct$4(Boolean, [], function () {})); return true; } catch (e) { return false; } }
/** @typedef {import('~types/cherry').CherryOptions} CherryOptions */
var Cherry = /*#__PURE__*/function (_CherryStatic) {
_inherits(Cherry, _CherryStatic);
var _super = _createSuper$1s(Cherry);
/**
* @protected
*/
/**
* @readonly
*/
/**
* @param {Partial<CherryOptions>} options
*/
function Cherry(options) {
var _context;
var _this;
_classCallCheck(this, Cherry);
_this = _super.call(this);
Cherry.initialized = true;
var defaultConfigCopy = cloneDeep_1(Cherry.config.defaults);
_this.defaultToolbar = defaultConfigCopy.toolbars.toolbar;
$expectTarget(options, Object);
/**
* @property
* @type {Partial<CherryOptions>}
*/
_this.options = mergeWith_1({}, defaultConfigCopy, options, customizer); // loading the locale
_this.locale = locales[_this.options.locale];
if (typeof _this.options.engine.global.urlProcessor === 'function') {
_this.options.engine.global.urlProcessor = urlProcessorProxy(_this.options.engine.global.urlProcessor);
}
_this.status = {
toolbar: 'show',
previewer: 'show',
editor: 'show'
};
if (_this.options.isPreviewOnly || _this.options.editor.defaultModel === 'previewOnly') {
_this.options.toolbars.showToolbar = false;
_this.options.editor.defaultModel = 'previewOnly';
_this.status.editor = 'hide';
_this.status.toolbar = 'hide';
}
/**
* @property
* @type {string} 实例ID
*/
_this.instanceId = concat$5(_context = "cherry-".concat(new Date().getTime())).call(_context, Math.random());
_this.options.instanceId = _this.instanceId;
/**
* @private
* @type {Engine}
*/
_this.engine = new Engine(_this.options, _assertThisInitialized(_this));
_this.init();
return _this;
}
/**
* 初始化工具栏、编辑区、预览区等
* @private
*/
_createClass(Cherry, [{
key: "init",
value: function init() {
var _context2,
_this2 = this;
var mountEl = this.options.id ? document.getElementById(this.options.id) : this.options.el;
if (!mountEl) {
if (!this.options.forceAppend) {
return false;
}
mountEl = document.createElement('div');
mountEl.id = this.options.id || 'cherry-markdown';
document.body.appendChild(mountEl);
}
if (!mountEl.style.height) {
mountEl.style.height = this.options.editor.height;
}
this.cherryDom = mountEl; // 蒙层dom用来拖拽编辑区&预览区宽度时展示蒙层
var wrapperDom = this.createWrapper(); // 创建编辑区
var editor = this.createEditor(); // 创建预览区
var previewer = this.createPreviewer();
if (this.options.toolbars.showToolbar === false || this.options.toolbars.toolbar === false) {
// 即便配置了不展示工具栏也要让工具栏加载对应的语法hook
wrapperDom.classList.add('cherry--no-toolbar');
this.options.toolbars.toolbar = this.defaultToolbar;
}
$expectTarget(this.options.toolbars.toolbar, Array); // 创建顶部工具栏
this.toolbar = this.createToolbar();
var wrapperFragment = document.createDocumentFragment();
wrapperFragment.appendChild(this.toolbar.options.dom);
wrapperFragment.appendChild(editor.options.editorDom); // 创建预览区域的侧边工具栏
this.createSidebar(wrapperFragment);
if (!this.options.previewer.dom) {
wrapperFragment.appendChild(previewer.options.previewerDom);
}
wrapperFragment.appendChild(previewer.options.virtualDragLineDom);
wrapperFragment.appendChild(previewer.options.editorMaskDom);
wrapperFragment.appendChild(previewer.options.previewerMaskDom);
wrapperDom.appendChild(wrapperFragment);
mountEl.appendChild(wrapperDom);
editor.init(previewer); // 创建bubble工具栏所谓bubble工具栏是指在编辑区选中文本时悬浮出现的工具栏
this.createBubble(); // 创建float工具栏所谓float工具栏是指当编辑区光标处于新行时在行内联想出的工具栏
this.createFloatMenu();
previewer.init(editor);
previewer.registerAfterUpdate(bind$5(_context2 = this.engine.mounted).call(_context2, this.engine)); // default value init
this.initText(editor.editor); // 切换模式,有纯预览模式、纯编辑模式、双栏编辑模式
this.switchModel(this.options.editor.defaultModel);
Event$1.on(this.instanceId, Event$1.Events.toolbarHide, function () {
_this2.status.toolbar = 'hide';
});
Event$1.on(this.instanceId, Event$1.Events.toolbarShow, function () {
_this2.status.toolbar = 'show';
});
Event$1.on(this.instanceId, Event$1.Events.previewerClose, function () {
_this2.status.previewer = 'hide';
});
Event$1.on(this.instanceId, Event$1.Events.previewerOpen, function () {
_this2.status.previewer = 'show';
});
Event$1.on(this.instanceId, Event$1.Events.editorClose, function () {
_this2.status.editor = 'hide'; // 关闭编辑区时,需要清除所有高亮
_this2.previewer.highlightLine(0);
});
Event$1.on(this.instanceId, Event$1.Events.editorOpen, function () {
_this2.status.editor = 'show';
});
}
/**
* 切换编辑模式
* @param {'edit&preview'|'editOnly'|'previewOnly'} model 模式类型
* 一般纯预览模式和纯编辑模式适合在屏幕较小的终端使用,比如手机移动端
*
* @returns
*/
}, {
key: "switchModel",
value: function switchModel() {
var model = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'edit&preview';
switch (model) {
case 'edit&preview':
if (this.previewer) {
this.previewer.editOnly(true);
this.previewer.recoverPreviewer();
}
if (this.toolbar) {
this.toolbar.showToolbar();
}
break;
case 'editOnly':
if (!this.previewer.isPreviewerHidden()) {
this.previewer.editOnly(true);
}
if (this.toolbar) {
this.toolbar.showToolbar();
}
break;
case 'previewOnly':
this.previewer.previewOnly();
this.toolbar && this.toolbar.previewOnly();
break;
}
}
/**
* 获取实例id
* @returns {string}
* @public
*/
}, {
key: "getInstanceId",
value: function getInstanceId() {
return this.instanceId;
}
/**
* 获取编辑器状态
* @returns {Object}
*/
}, {
key: "getStatus",
value: function getStatus() {
return this.status;
}
/**
* 获取编辑区内的markdown源码内容
* @returns markdown源码内容
*/
}, {
key: "getValue",
value: function getValue() {
return this.editor.editor.getValue();
}
/**
* 获取编辑区内的markdown源码内容
* @returns markdown源码内容
*/
}, {
key: "getMarkdown",
value: function getMarkdown() {
return this.getValue();
}
/**
* 获取CodeMirror实例
* @returns CodeMirror实例
*/
}, {
key: "getCodeMirror",
value: function getCodeMirror() {
return this.editor.editor;
}
/**
* 获取预览区内的html内容
* @param {boolean} wrapTheme 是否在外层包裹主题class
* @returns html内容
*/
}, {
key: "getHtml",
value: function getHtml() {
var wrapTheme = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
return this.previewer.getValue(wrapTheme);
}
}, {
key: "getPreviewer",
value: function getPreviewer() {
return this.previewer;
}
/**
* 获取目录目录由head1~6组成
* @returns 标题head数组
*/
}, {
key: "getTheme",
value: function getTheme() {
return getThemeFromLocal(true)
}
}, {
key: "setTheme",
value: function setTheme(theme) {
changeTheme(this, theme)
}
}, {
key: "getToc",
value: function getToc() {
var str = this.getHtml();
/** @type {({level: number;id: string;text: string})[]} */
var headerList = [];
var headerRegex = /<h([1-6]).*?id="([^"]+?)".*?>(.+?)<\/h[0-6]>/g;
str.replace(headerRegex, function (match, level, id, text) {
headerList.push({
level: +level,
id: id,
text: text
});
return match;
});
return headerList;
}
/**
* 覆盖编辑区的内容
* @param {string} content markdown内容
* @param {boolean} keepCursor 是否保持光标位置
* @returns
*/
}, {
key: "setValue",
value: function setValue(content) {
var keepCursor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (keepCursor === false) {
return this.editor.editor.setValue(content);
}
var codemirror = this.editor.editor;
var old = this.getValue();
var pos = codemirror.getDoc().indexFromPos(codemirror.getCursor());
var newPos = getPosBydiffs(pos, old, content);
var ret = codemirror.setValue(content);
var cursor = codemirror.getDoc().posFromIndex(newPos);
codemirror.setCursor(cursor);
return ret;
}
/**
* 在光标处或者指定行+偏移量插入内容
* @param {string} content 被插入的文本
* @param {boolean} [isSelect=false] 是否选中刚插入的内容
* @param {[number, number]|false} [anchor=false] [x,y] 代表x+1行y+1字符偏移量默认false 会从光标处插入
* @param {boolean} [focus=true] 保持编辑器处于focus状态
* @returns
*/
}, {
key: "insert",
value: function insert(content) {
var isSelect = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var anchor = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var focus = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
if (anchor) {
this.editor.editor.setSelection({
line: anchor[0],
ch: anchor[1]
}, {
line: anchor[0],
ch: anchor[1]
});
}
var ret = this.editor.editor.replaceSelection(content, isSelect ? 'around' : 'end');
focus && this.editor.editor.focus();
return ret;
}
/**
* 在光标处或者指定行+偏移量插入内容
* @param {string} content 被插入的文本
* @param {boolean} [isSelect=false] 是否选中刚插入的内容
* @param {[number, number]|false} [anchor=false] [x,y] 代表x+1行y+1字符偏移量默认false 会从光标处插入
* @param {boolean} [focus=true] 保持编辑器处于focus状态
* @returns
*/
}, {
key: "insertValue",
value: function insertValue(content) {
var isSelect = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var anchor = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var focus = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
return this.insert(content, isSelect, anchor, focus);
}
/**
* 强制重新渲染预览区域
*/
}, {
key: "refreshPreviewer",
value: function refreshPreviewer() {
try {
var markdownText = this.getValue();
var html = this.engine.makeHtml(markdownText);
this.previewer.refresh(html);
} catch (e) {
throw new NestedError(e);
}
}
/**
* 覆盖编辑区的内容
* @param {string} content markdown内容
* @param {boolean} keepCursor 是否保持光标位置
* @returns
*/
}, {
key: "setMarkdown",
value: function setMarkdown(content) {
var keepCursor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
return this.setValue(content, keepCursor);
}
/**
* @private
* @returns
*/
}, {
key: "createWrapper",
value: function createWrapper() {
var toolbarTheme = this.options.toolbars.theme === 'dark' ? 'dark' : ''; // TODO: 完善类型
var inlineCodeTheme =
/** @type {{theme?: string;}} */
this.options.engine.syntax.inlineCode.theme;
var codeBlockTheme =
/** @type {{theme?: string;}} */
this.options.engine.syntax.codeBlock.theme;
if (codeBlockTheme === 'dark') codeBlockTheme = 'tomorrow-night';else if (codeBlockTheme === 'light') codeBlockTheme = 'solarized-light';
var wrapperDom = createElement('div', ['cherry', 'clearfix', getThemeFromLocal(true)].join(' '), {
'data-toolbarTheme': toolbarTheme,
'data-inlineCodeTheme': inlineCodeTheme,
'data-codeBlockTheme': codeBlockTheme
});
this.wrapperDom = wrapperDom;
return wrapperDom;
}
/**
* @private
* @returns {Toolbar}
*/
}, {
key: "createToolbar",
value: function createToolbar() {
var dom = createElement('div', 'cherry-toolbar');
this.toolbar = new Toolbar({
dom: dom,
$cherry: this,
buttonRightConfig: this.options.toolbars.toolbarRight,
buttonConfig: this.options.toolbars.toolbar,
customMenu: this.options.toolbars.customMenu
});
return this.toolbar;
}
/**
* @private
* @returns
*/
}, {
key: "createSidebar",
value: function createSidebar(wrapperFragment) {
if (this.options.toolbars.sidebar) {
$expectTarget(this.options.toolbars.sidebar, Array);
var externalClass = this.options.toolbars.theme === 'dark' ? 'dark' : '';
var dom = createElement('div', "cherry-sidebar ".concat(externalClass));
this.sidebar = new Sidebar({
dom: dom,
$cherry: this,
buttonConfig: this.options.toolbars.sidebar,
customMenu: this.options.toolbars.customMenu
});
wrapperFragment.appendChild(this.sidebar.options.dom);
}
}
/**
* @private
* @returns
*/
}, {
key: "createFloatMenu",
value: function createFloatMenu() {
if (this.options.toolbars["float"]) {
var dom = createElement('div', 'cherry-floatmenu');
$expectTarget(this.options.toolbars["float"], Array);
this.floatMenu = new FloatMenu({
dom: dom,
$cherry: this,
buttonConfig: this.options.toolbars["float"],
customMenu: this.options.toolbars.customMenu
});
}
}
/**
* @private
* @returns
*/
}, {
key: "createBubble",
value: function createBubble() {
if (this.options.toolbars.bubble) {
var dom = createElement('div', 'cherry-bubble');
$expectTarget(this.options.toolbars.bubble, Array);
this.bubble = new Bubble({
dom: dom,
$cherry: this,
buttonConfig: this.options.toolbars.bubble,
customMenu: this.options.toolbars.customMenu,
engine: this.engine
});
}
}
/**
* @private
* @returns {import('@/Editor').default}
*/
}, {
key: "createEditor",
value: function createEditor() {
var _this$options$editor$, _this$options$editor$2, _context3, _context4;
var textArea = createElement('textarea', '', {
id: (_this$options$editor$ = this.options.editor.id) !== null && _this$options$editor$ !== void 0 ? _this$options$editor$ : 'code',
name: (_this$options$editor$2 = this.options.editor.name) !== null && _this$options$editor$2 !== void 0 ? _this$options$editor$2 : 'code'
});
textArea.textContent = this.options.value;
var editor = createElement('div', 'cherry-editor');
editor.appendChild(textArea);
this.editor = new Editor(_objectSpread$8({
$cherry: this,
editorDom: editor,
wrapperDom: this.wrapperDom,
value: this.options.value,
onKeydown: bind$5(_context3 = this.fireShortcutKey).call(_context3, this),
onChange: bind$5(_context4 = this.editText).call(_context4, this),
toolbars: this.options.toolbars,
fileUpload: this.options.fileUpload,
autoScrollByCursor: this.options.autoScrollByCursor
}, this.options.editor));
return this.editor;
}
/**
* @private
* @returns {import('@/Previewer').default}
*/
}, {
key: "createPreviewer",
value: function createPreviewer() {
/** @type {HTMLDivElement} */
var previewer;
var anchorStyle = this.options.engine.syntax.header && this.options.engine.syntax.header.anchorStyle || 'default';
var autonumberClass = anchorStyle === 'autonumber' ? ' head-num' : '';
var _this$options$preview = this.options.previewer,
className = _this$options$preview.className,
dom = _this$options$preview.dom,
enablePreviewerBubble = _this$options$preview.enablePreviewerBubble;
var previewerClassName = ['cherry-previewer cherry-markdown', className || '', autonumberClass, getThemeFromLocal(true)].join(' ');
if (dom) {
previewer = dom;
previewer.className += " ".concat(previewerClassName);
} else {
previewer = createElement('div', previewerClassName);
}
var virtualDragLine = createElement('div', 'cherry-drag');
var editorMask = createElement('div', 'cherry-editor-mask');
var previewerMask = createElement('div', 'cherry-previewer-mask');
this.previewer = new Previewer({
$cherry: this,
virtualDragLineDom: virtualDragLine,
editorMaskDom: editorMask,
previewerMaskDom: previewerMask,
previewerDom: previewer,
value: this.options.value,
isPreviewOnly: this.options.isPreviewOnly,
enablePreviewerBubble: enablePreviewerBubble,
lazyLoadImg: this.options.previewer.lazyLoadImg
});
return this.previewer;
}
/**
* @private
* @param {import('codemirror').Editor} codemirror
*/
}, {
key: "initText",
value: function initText(codemirror) {
try {
var markdownText = codemirror.getValue();
var html = this.engine.makeHtml(markdownText);
this.previewer.update(html);
if (this.options.callback.afterInit) {
this.options.callback.afterInit(markdownText, html);
}
} catch (e) {
throw new NestedError(e);
}
}
/**
* @private
* @param {Event} _evt
* @param {import('codemirror').Editor} codemirror
*/
}, {
key: "editText",
value: function editText(_evt, codemirror) {
var _this3 = this;
try {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this.timer = setTimeout$3(function () {
var markdownText = codemirror.getValue();
var html = _this3.engine.makeHtml(markdownText);
_this3.previewer.update(html);
if (_this3.options.callback.afterChange) {
_this3.options.callback.afterChange(markdownText, html);
} // 强制每次编辑包括undo、redo编辑器都会自动滚动到光标位置
codemirror.scrollIntoView(null);
}, 50);
} catch (e) {
throw new NestedError(e);
}
}
/**
* @private
* @param {any} cb
*/
}, {
key: "onChange",
value: function onChange(cb) {
this.editor.editor.on('change', function (codeMirror) {
cb({
markdown: codeMirror.getValue() // 后续可以按需增加html或其他状态
});
});
}
/**
* @private
* @param {*} evt
*/
}, {
key: "fireShortcutKey",
value: function fireShortcutKey(evt) {
if (this.toolbar.matchShortcutKey(evt)) {
// 快捷键
evt.preventDefault();
this.toolbar.fireShortcutKey(evt);
}
}
/**
* 导出预览区域内容
* @public
* @param {String} type 'pdf'导出成pdf文件; 'img':导出成图片
* @param {String} fileName 导出文件名
*/
}, {
key: "export",
value: function _export() {
var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'pdf';
var fileName = arguments.length > 1 ? arguments[1] : undefined;
this.previewer["export"](type, fileName);
}
/**
* 修改主题
* @param {string} theme option.theme里的className
*/
}, {
key: "setTheme",
value: function setTheme() {
var theme = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'default';
changeTheme(this, theme);
}
/**
* 修改书写风格
* @param {string} writingStyle normal 普通 | typewriter 打字机 | focus 专注
*/
}, {
key: "setWritingStyle",
value: function setWritingStyle(writingStyle) {
this.editor.setWritingStyle(writingStyle);
}
}]);
return Cherry;
}(CherryStatic);
_defineProperty(Cherry, "initialized", false);
_defineProperty(Cherry, "config", {
/** @type {Partial<CherryOptions>} */
defaults: defaultConfig$1
});
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if (window) {
// @ts-ignore
window.Cherry = Cherry;
}
function ownKeys$a(object, enumerableOnly) { var keys = keys$3(object); if (getOwnPropertySymbols$2) { var symbols = getOwnPropertySymbols$2(object); enumerableOnly && (symbols = filter$3(symbols).call(symbols, function (sym) { return getOwnPropertyDescriptor$3(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$9(target) { for (var i = 1; i < arguments.length; i++) { var _context4, _context5; var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? forEach$3(_context4 = ownKeys$a(Object(source), !0)).call(_context4, function (key) { _defineProperty(target, key, source[key]); }) : getOwnPropertyDescriptors$2 ? defineProperties$2(target, getOwnPropertyDescriptors$2(source)) : forEach$3(_context5 = ownKeys$a(Object(source))).call(_context5, function (key) { defineProperty$5(target, key, getOwnPropertyDescriptor$3(source, key)); }); } return target; }
var DEFAULT_OPTIONS = {
// TODO: themes
theme: 'default',
altFontFamily: 'sans-serif',
fontFamily: 'sans-serif',
themeCSS: '.label foreignObject { font-size: 90%; overflow: visible; } .label { font-family: sans-serif; }',
flowchart: {
useMaxWidth: false
},
sequence: {
useMaxWidth: false
},
startOnLoad: false,
logLevel: 5 // fontFamily: 'Arial, monospace'
};
var MermaidCodeEngine = /*#__PURE__*/function () {
function MermaidCodeEngine() {
var mermaidOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, MermaidCodeEngine);
_defineProperty(this, "mermaidAPIRefs", null);
_defineProperty(this, "options", DEFAULT_OPTIONS);
_defineProperty(this, "dom", null);
_defineProperty(this, "mermaidCanvas", null);
var mermaid = mermaidOptions.mermaid,
mermaidAPI = mermaidOptions.mermaidAPI;
if (!mermaidAPI && !window.mermaidAPI && (!mermaid || !mermaid.mermaidAPI) && (!window.mermaid || !window.mermaid.mermaidAPI)) {
throw new Error('code-block-mermaid-plugin[init]: Package mermaid or mermaidAPI not found.');
}
this.options = _objectSpread$9(_objectSpread$9({}, DEFAULT_OPTIONS), mermaidOptions || {});
this.mermaidAPIRefs = mermaidAPI || window.mermaidAPI || mermaid.mermaidAPI || window.mermaid.mermaidAPI;
delete this.options.mermaid;
delete this.options.mermaidAPI;
this.mermaidAPIRefs.initialize(this.options);
}
_createClass(MermaidCodeEngine, [{
key: "mountMermaidCanvas",
value: function mountMermaidCanvas($engine) {
if (this.mermaidCanvas && document.body.contains(this.mermaidCanvas)) {
return;
}
this.mermaidCanvas = document.createElement('div');
this.mermaidCanvas.style = 'width:1024px;opacity:0;position:fixed;top:100%;';
var container = $engine.$cherry.wrapperDom || document.body;
container.appendChild(this.mermaidCanvas);
}
/**
* 转换svg为img如果出错则直出svg
* @param {string} svgCode
* @param {string} graphId
* @returns {string}
*/
}, {
key: "convertMermaidSvgToImg",
value: function convertMermaidSvgToImg(svgCode, graphId) {
var domParser = new DOMParser();
var svgHtml;
var injectSvgFallback = function injectSvgFallback(svg) {
return svg.replace('<svg ', '<svg style="max-width:100%;height:auto;font-family:sans-serif;" ');
};
try {
var svgDoc =
/** @type {XMLDocument} */
domParser.parseFromString(svgCode, 'image/svg+xml');
var svgDom =
/** @type {SVGSVGElement} */
/** @type {any} */
svgDoc.documentElement; // tagName不是svg时说明存在parse error
if (svgDom.tagName.toLowerCase() === 'svg') {
svgDom.style.maxWidth = '100%';
svgDom.style.height = 'auto';
svgDom.style.fontFamily = 'sans-serif';
var shadowSvg =
/** @type {SVGSVGElement} */
/** @type {any} */
document.getElementById(graphId);
var svgBox = shadowSvg.getBBox();
if (!svgDom.hasAttribute('viewBox')) {
var _context;
svgDom.setAttribute('viewBox', concat$5(_context = "0 0 ".concat(svgBox.width, " ")).call(_context, svgBox.height));
} else {
svgBox = svgDom.viewBox.baseVal;
}
svgDom.getAttribute('width') === '100%' && svgDom.setAttribute('width', "".concat(svgBox.width));
svgDom.getAttribute('height') === '100%' && svgDom.setAttribute('height', "".concat(svgBox.height)); // fix end
svgHtml = svgDoc.documentElement.outerHTML; // 屏蔽转img标签功能如需要转换为img解除屏蔽即可
if (this.svg2img) {
var _context2;
var dataUrl = "data:image/svg+xml,".concat(encodeURIComponent(svgDoc.documentElement.outerHTML));
svgHtml = concat$5(_context2 = "<img class=\"svg-img\" src=\"".concat(dataUrl, "\" alt=\"")).call(_context2, graphId, "\" />");
}
} else {
svgHtml = injectSvgFallback(svgCode);
}
} catch (e) {
svgHtml = injectSvgFallback(svgCode);
}
return svgHtml;
}
}, {
key: "render",
value: function render(src, sign, $engine) {
var _context3,
_config$svg2img,
_this = this;
var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var $sign = sign;
if (!$sign) {
$sign = Math.round(Math.random() * 100000000);
}
this.mountMermaidCanvas($engine);
var html; // 多实例的情况下相同的内容ID相同会导致mermaid渲染异常
// 需要通过添加时间戳使得多次渲染相同内容的图像ID唯一
// 图像渲染节流在CodeBlock Hook内部控制
var graphId = concat$5(_context3 = "mermaid-".concat($sign, "-")).call(_context3, new Date().getTime());
this.svg2img = (_config$svg2img = config === null || config === void 0 ? void 0 : config.svg2img) !== null && _config$svg2img !== void 0 ? _config$svg2img : false;
try {
this.mermaidAPIRefs.render(graphId, src, function (svgCode) {
var fixedSvg = svgCode.replace(/\s*markerUnits="0"/g, '').replace(/\s*x="NaN"/g, '').replace(/<br>/g, '<br/>');
html = _this.convertMermaidSvgToImg(fixedSvg, graphId);
}, this.mermaidCanvas);
} catch (e) {
return e === null || e === void 0 ? void 0 : e.str;
}
return html;
}
}], [{
key: "install",
value: function install(cherryOptions) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
mergeWith_1(cherryOptions, {
engine: {
syntax: {
codeBlock: {
customRenderer: {
mermaid: _construct(MermaidCodeEngine, args)
}
}
}
}
});
}
}]);
return MermaidCodeEngine;
}();
_defineProperty(MermaidCodeEngine, "TYPE", 'figure');
// @ts-nocheck
/*
* $Id: rawdeflate.js,v 0.3 2009/03/01 19:05:05 dankogai Exp dankogai $
*
* Original:
* http://www.onicos.com/staff/iz/amuse/javascript/expert/deflate.txt
*/
// if run as a web worker, respond to messages by deflating them
var deflate = function () {
/* Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
* Version: 1.0.1
* LastModified: Dec 25 1999
*/
/* Interface:
* data = deflate(src);
*/
/* constant parameters */
var zip_WSIZE = 32768; // Sliding Window size
var zip_STORED_BLOCK = 0;
var zip_STATIC_TREES = 1;
var zip_DYN_TREES = 2;
/* for deflate */
var zip_DEFAULT_LEVEL = 6;
var zip_INBUFSIZ = 32768; // Input buffer size
var zip_INBUF_EXTRA = 64; // Extra buffer
var zip_OUTBUFSIZ = 1024 * 8;
var zip_window_size = 2 * zip_WSIZE;
var zip_MIN_MATCH = 3;
var zip_MAX_MATCH = 258;
var zip_BITS = 16; // for SMALL_MEM
var zip_LIT_BUFSIZE = 0x2000;
var zip_HASH_BITS = 13; // for MEDIUM_MEM
// var zip_LIT_BUFSIZE = 0x4000;
// var zip_HASH_BITS = 14;
// for BIG_MEM
// var zip_LIT_BUFSIZE = 0x8000;
// var zip_HASH_BITS = 15;
// if(zip_LIT_BUFSIZE > zip_INBUFSIZ)
// alert("error: zip_INBUFSIZ is too small");
// if((zip_WSIZE<<1) > (1<<zip_BITS))
// alert("error: zip_WSIZE is too large");
// if(zip_HASH_BITS > zip_BITS-1)
// alert("error: zip_HASH_BITS is too large");
// if(zip_HASH_BITS < 8 || zip_MAX_MATCH != 258)
// alert("error: Code too clever");
var zip_DIST_BUFSIZE = zip_LIT_BUFSIZE;
var zip_HASH_SIZE = 1 << zip_HASH_BITS;
var zip_HASH_MASK = zip_HASH_SIZE - 1;
var zip_WMASK = zip_WSIZE - 1;
var zip_NIL = 0; // Tail of hash chains
var zip_TOO_FAR = 4096;
var zip_MIN_LOOKAHEAD = zip_MAX_MATCH + zip_MIN_MATCH + 1;
var zip_MAX_DIST = zip_WSIZE - zip_MIN_LOOKAHEAD;
var zip_SMALLEST = 1;
var zip_MAX_BITS = 15;
var zip_MAX_BL_BITS = 7;
var zip_LENGTH_CODES = 29;
var zip_LITERALS = 256;
var zip_END_BLOCK = 256;
var zip_L_CODES = zip_LITERALS + 1 + zip_LENGTH_CODES;
var zip_D_CODES = 30;
var zip_BL_CODES = 19;
var zip_REP_3_6 = 16;
var zip_REPZ_3_10 = 17;
var zip_REPZ_11_138 = 18;
var zip_HEAP_SIZE = 2 * zip_L_CODES + 1;
var zip_H_SHIFT = _parseInt$2((zip_HASH_BITS + zip_MIN_MATCH - 1) / zip_MIN_MATCH);
/* variables */
var zip_free_queue;
var zip_qhead;
var zip_qtail;
var zip_initflag;
var zip_outbuf = null;
var zip_outcnt;
var zip_outoff;
var zip_complete;
var zip_window;
var zip_d_buf;
var zip_l_buf;
var zip_prev;
var zip_bi_buf;
var zip_bi_valid;
var zip_block_start;
var zip_ins_h;
var zip_hash_head;
var zip_prev_match;
var zip_match_available;
var zip_match_length;
var zip_prev_length;
var zip_strstart;
var zip_match_start;
var zip_eofile;
var zip_lookahead;
var zip_max_chain_length;
var zip_max_lazy_match;
var zip_compr_level;
var zip_good_match;
var zip_dyn_ltree;
var zip_dyn_dtree;
var zip_static_ltree;
var zip_static_dtree;
var zip_bl_tree;
var zip_l_desc;
var zip_d_desc;
var zip_bl_desc;
var zip_bl_count;
var zip_heap;
var zip_heap_len;
var zip_heap_max;
var zip_depth;
var zip_length_code;
var zip_dist_code;
var zip_base_length;
var zip_base_dist;
var zip_flag_buf;
var zip_last_lit;
var zip_last_dist;
var zip_last_flags;
var zip_flags;
var zip_flag_bit;
var zip_opt_len;
var zip_static_len;
var zip_deflate_data;
var zip_deflate_pos;
/* objects (deflate) */
function zip_DeflateCT() {
this.fc = 0; // frequency count or bit string
this.dl = 0; // father node in Huffman tree or length of bit string
}
function zip_DeflateTreeDesc() {
this.dyn_tree = null; // the dynamic tree
this.static_tree = null; // corresponding static tree or NULL
this.extra_bits = null; // extra bits for each code or NULL
this.extra_base = 0; // base index for extra_bits
this.elems = 0; // max number of elements in the tree
this.max_length = 0; // max bit length for the codes
this.max_code = 0; // largest code with non zero frequency
}
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
function zip_DeflateConfiguration(a, b, c, d) {
this.good_length = a; // reduce lazy search above this match length
this.max_lazy = b; // do not perform lazy search above this match length
this.nice_length = c; // quit search above this match length
this.max_chain = d;
}
function zip_DeflateBuffer() {
this.next = null;
this.len = 0;
this.ptr = new Array(zip_OUTBUFSIZ);
this.off = 0;
}
/* constant tables */
var zip_extra_lbits = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0];
var zip_extra_dbits = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13];
var zip_extra_blbits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7];
var zip_bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
var zip_configuration_table = [new zip_DeflateConfiguration(0, 0, 0, 0), new zip_DeflateConfiguration(4, 4, 8, 4), new zip_DeflateConfiguration(4, 5, 16, 8), new zip_DeflateConfiguration(4, 6, 32, 32), new zip_DeflateConfiguration(4, 4, 16, 16), new zip_DeflateConfiguration(8, 16, 32, 32), new zip_DeflateConfiguration(8, 16, 128, 128), new zip_DeflateConfiguration(8, 32, 128, 256), new zip_DeflateConfiguration(32, 128, 258, 1024), new zip_DeflateConfiguration(32, 258, 258, 4096)];
/* routines (deflate) */
function zip_deflate_start(level) {
var i;
if (!level) level = zip_DEFAULT_LEVEL;else if (level < 1) level = 1;else if (level > 9) level = 9;
zip_compr_level = level;
zip_initflag = false;
zip_eofile = false;
if (zip_outbuf != null) return;
zip_free_queue = zip_qhead = zip_qtail = null;
zip_outbuf = new Array(zip_OUTBUFSIZ);
zip_window = new Array(zip_window_size);
zip_d_buf = new Array(zip_DIST_BUFSIZE);
zip_l_buf = new Array(zip_INBUFSIZ + zip_INBUF_EXTRA);
zip_prev = new Array(1 << zip_BITS);
zip_dyn_ltree = new Array(zip_HEAP_SIZE);
for (i = 0; i < zip_HEAP_SIZE; i++) {
zip_dyn_ltree[i] = new zip_DeflateCT();
}
zip_dyn_dtree = new Array(2 * zip_D_CODES + 1);
for (i = 0; i < 2 * zip_D_CODES + 1; i++) {
zip_dyn_dtree[i] = new zip_DeflateCT();
}
zip_static_ltree = new Array(zip_L_CODES + 2);
for (i = 0; i < zip_L_CODES + 2; i++) {
zip_static_ltree[i] = new zip_DeflateCT();
}
zip_static_dtree = new Array(zip_D_CODES);
for (i = 0; i < zip_D_CODES; i++) {
zip_static_dtree[i] = new zip_DeflateCT();
}
zip_bl_tree = new Array(2 * zip_BL_CODES + 1);
for (i = 0; i < 2 * zip_BL_CODES + 1; i++) {
zip_bl_tree[i] = new zip_DeflateCT();
}
zip_l_desc = new zip_DeflateTreeDesc();
zip_d_desc = new zip_DeflateTreeDesc();
zip_bl_desc = new zip_DeflateTreeDesc();
zip_bl_count = new Array(zip_MAX_BITS + 1);
zip_heap = new Array(2 * zip_L_CODES + 1);
zip_depth = new Array(2 * zip_L_CODES + 1);
zip_length_code = new Array(zip_MAX_MATCH - zip_MIN_MATCH + 1);
zip_dist_code = new Array(512);
zip_base_length = new Array(zip_LENGTH_CODES);
zip_base_dist = new Array(zip_D_CODES);
zip_flag_buf = new Array(_parseInt$2(zip_LIT_BUFSIZE / 8));
}
function zip_reuse_queue(p) {
p.next = zip_free_queue;
zip_free_queue = p;
}
function zip_new_queue() {
var p;
if (zip_free_queue != null) {
p = zip_free_queue;
zip_free_queue = zip_free_queue.next;
} else p = new zip_DeflateBuffer();
p.next = null;
p.len = p.off = 0;
return p;
}
function zip_head1(i) {
return zip_prev[zip_WSIZE + i];
}
function zip_head2(i, val) {
return zip_prev[zip_WSIZE + i] = val;
}
/* put_byte is used for the compressed output, put_ubyte for the
* uncompressed output. However unlzw() uses window for its
* suffix table instead of its output buffer, so it does not use put_ubyte
* (to be cleaned up).
*/
function zip_put_byte(c) {
zip_outbuf[zip_outoff + zip_outcnt++] = c;
if (zip_outoff + zip_outcnt == zip_OUTBUFSIZ) zip_qoutbuf();
}
/* Output a 16 bit value, lsb first */
function zip_put_short(w) {
w &= 0xffff;
if (zip_outoff + zip_outcnt < zip_OUTBUFSIZ - 2) {
zip_outbuf[zip_outoff + zip_outcnt++] = w & 0xff;
zip_outbuf[zip_outoff + zip_outcnt++] = w >>> 8;
} else {
zip_put_byte(w & 0xff);
zip_put_byte(w >>> 8);
}
}
/* ==========================================================================
* Insert string s in the dictionary and set match_head to the previous head
* of the hash chain (the most recent string with same hash key). Return
* the previous length of the hash chain.
* IN assertion: all calls to to INSERT_STRING are made with consecutive
* input characters and the first MIN_MATCH bytes of s are valid
* (except for the last MIN_MATCH-1 bytes of the input file).
*/
function zip_INSERT_STRING() {
zip_ins_h = (zip_ins_h << zip_H_SHIFT ^ zip_window[zip_strstart + zip_MIN_MATCH - 1] & 0xff) & zip_HASH_MASK;
zip_hash_head = zip_head1(zip_ins_h);
zip_prev[zip_strstart & zip_WMASK] = zip_hash_head;
zip_head2(zip_ins_h, zip_strstart);
}
/* Send a code of the given tree. c and tree must not have side effects */
function zip_SEND_CODE(c, tree) {
zip_send_bits(tree[c].fc, tree[c].dl);
}
/* Mapping from a distance to a distance code. dist is the distance - 1 and
* must not have side effects. dist_code[256] and dist_code[257] are never
* used.
*/
function zip_D_CODE(dist) {
return (dist < 256 ? zip_dist_code[dist] : zip_dist_code[256 + (dist >> 7)]) & 0xff;
}
/* ==========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
function zip_SMALLER(tree, n, m) {
return tree[n].fc < tree[m].fc || tree[n].fc == tree[m].fc && zip_depth[n] <= zip_depth[m];
}
/* ==========================================================================
* read string data
*/
function zip_read_buff(buff, offset, n) {
var i;
for (i = 0; i < n && zip_deflate_pos < zip_deflate_data.length; i++) {
buff[offset + i] = zip_deflate_data.charCodeAt(zip_deflate_pos++) & 0xff;
}
return i;
}
/* ==========================================================================
* Initialize the "longest match" routines for a new file
*/
function zip_lm_init() {
var j;
/* Initialize the hash table. */
for (j = 0; j < zip_HASH_SIZE; j++) {
// zip_head2(j, zip_NIL);
zip_prev[zip_WSIZE + j] = 0;
}
/* prev will be initialized on the fly */
/* Set the default configuration parameters:
*/
zip_max_lazy_match = zip_configuration_table[zip_compr_level].max_lazy;
zip_good_match = zip_configuration_table[zip_compr_level].good_length;
zip_max_chain_length = zip_configuration_table[zip_compr_level].max_chain;
zip_strstart = 0;
zip_block_start = 0;
zip_lookahead = zip_read_buff(zip_window, 0, 2 * zip_WSIZE);
if (zip_lookahead <= 0) {
zip_eofile = true;
zip_lookahead = 0;
return;
}
zip_eofile = false;
/* Make sure that we always have enough lookahead. This is important
* if input comes from a device such as a tty.
*/
while (zip_lookahead < zip_MIN_LOOKAHEAD && !zip_eofile) {
zip_fill_window();
}
/* If lookahead < MIN_MATCH, ins_h is garbage, but this is
* not important since only literal bytes will be emitted.
*/
zip_ins_h = 0;
for (j = 0; j < zip_MIN_MATCH - 1; j++) {
// UPDATE_HASH(ins_h, window[j]);
zip_ins_h = (zip_ins_h << zip_H_SHIFT ^ zip_window[j] & 0xff) & zip_HASH_MASK;
}
}
/* ==========================================================================
* Set match_start to the longest match starting at the given string and
* return its length. Matches shorter or equal to prev_length are discarded,
* in which case the result is equal to prev_length and match_start is
* garbage.
* IN assertions: cur_match is the head of the hash chain for the current
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
*/
function zip_longest_match(cur_match) {
var chain_length = zip_max_chain_length; // max hash chain length
var scanp = zip_strstart; // current string
var matchp; // matched string
var len; // length of current match
var best_len = zip_prev_length; // best match length so far
/* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of window index 0.
*/
var limit = zip_strstart > zip_MAX_DIST ? zip_strstart - zip_MAX_DIST : zip_NIL;
var strendp = zip_strstart + zip_MAX_MATCH;
var scan_end1 = zip_window[scanp + best_len - 1];
var scan_end = zip_window[scanp + best_len];
/* Do not waste too much time if we already have a good match: */
if (zip_prev_length >= zip_good_match) chain_length >>= 2; // Assert(encoder->strstart <= window_size-MIN_LOOKAHEAD, "insufficient lookahead");
do {
// Assert(cur_match < encoder->strstart, "no future");
matchp = cur_match;
/* Skip to next match if the match length cannot increase
* or if the match length is less than 2:
*/
if (zip_window[matchp + best_len] != scan_end || zip_window[matchp + best_len - 1] != scan_end1 || zip_window[matchp] != zip_window[scanp] || zip_window[++matchp] != zip_window[scanp + 1]) {
continue;
}
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scanp += 2;
matchp++;
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {} while (zip_window[++scanp] == zip_window[++matchp] && zip_window[++scanp] == zip_window[++matchp] && zip_window[++scanp] == zip_window[++matchp] && zip_window[++scanp] == zip_window[++matchp] && zip_window[++scanp] == zip_window[++matchp] && zip_window[++scanp] == zip_window[++matchp] && zip_window[++scanp] == zip_window[++matchp] && zip_window[++scanp] == zip_window[++matchp] && scanp < strendp);
len = zip_MAX_MATCH - (strendp - scanp);
scanp = strendp - zip_MAX_MATCH;
if (len > best_len) {
zip_match_start = cur_match;
best_len = len;
{
if (len >= zip_MAX_MATCH) break;
}
scan_end1 = zip_window[scanp + best_len - 1];
scan_end = zip_window[scanp + best_len];
}
} while ((cur_match = zip_prev[cur_match & zip_WMASK]) > limit && --chain_length != 0);
return best_len;
}
/* ==========================================================================
* Fill the window when the lookahead becomes insufficient.
* Updates strstart and lookahead, and sets eofile if end of input file.
* IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0
* OUT assertions: at least one byte has been read, or eofile is set;
* file reads are performed for at least two bytes (required for the
* translate_eol option).
*/
function zip_fill_window() {
var n;
var m; // Amount of free space at the end of the window.
var more = zip_window_size - zip_lookahead - zip_strstart;
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (more == -1) {
/* Very unlikely, but possible on 16 bit machine if strstart == 0
* and lookahead == 1 (input done one byte at time)
*/
more--;
} else if (zip_strstart >= zip_WSIZE + zip_MAX_DIST) {
/* By the IN assertion, the window is not empty so we can't confuse
* more == 0 with more == 64K on a 16 bit machine.
*/
// Assert(window_size == (ulg)2*WSIZE, "no sliding with BIG_MEM");
// System.arraycopy(window, WSIZE, window, 0, WSIZE);
for (n = 0; n < zip_WSIZE; n++) {
zip_window[n] = zip_window[n + zip_WSIZE];
}
zip_match_start -= zip_WSIZE;
zip_strstart -= zip_WSIZE;
/* we now have strstart >= MAX_DIST: */
zip_block_start -= zip_WSIZE;
for (n = 0; n < zip_HASH_SIZE; n++) {
m = zip_head1(n);
zip_head2(n, m >= zip_WSIZE ? m - zip_WSIZE : zip_NIL);
}
for (n = 0; n < zip_WSIZE; n++) {
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
m = zip_prev[n];
zip_prev[n] = m >= zip_WSIZE ? m - zip_WSIZE : zip_NIL;
}
more += zip_WSIZE;
} // At this point, more >= 2
if (!zip_eofile) {
n = zip_read_buff(zip_window, zip_strstart + zip_lookahead, more);
if (n <= 0) zip_eofile = true;else zip_lookahead += n;
}
}
/* ==========================================================================
* Processes a new input file and return its compressed length. This
* function does not perform lazy evaluationof matches and inserts
* new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options.
*/
function zip_deflate_fast() {
while (zip_lookahead != 0 && zip_qhead == null) {
var flush; // set if current block must be flushed
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
zip_INSERT_STRING();
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < MIN_MATCH
*/
if (zip_hash_head != zip_NIL && zip_strstart - zip_hash_head <= zip_MAX_DIST) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
zip_match_length = zip_longest_match(zip_hash_head);
/* longest_match() sets match_start */
if (zip_match_length > zip_lookahead) zip_match_length = zip_lookahead;
}
if (zip_match_length >= zip_MIN_MATCH) {
// check_match(strstart, match_start, match_length);
flush = zip_ct_tally(zip_strstart - zip_match_start, zip_match_length - zip_MIN_MATCH);
zip_lookahead -= zip_match_length;
/* Insert new strings in the hash table only if the match length
* is not too large. This saves time but degrades compression.
*/
if (zip_match_length <= zip_max_lazy_match) {
zip_match_length--; // string at strstart already in hash table
do {
zip_strstart++;
zip_INSERT_STRING();
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
* these bytes are garbage, but it does not matter since
* the next lookahead bytes will be emitted as literals.
*/
} while (--zip_match_length != 0);
zip_strstart++;
} else {
zip_strstart += zip_match_length;
zip_match_length = 0;
zip_ins_h = zip_window[zip_strstart] & 0xff; // UPDATE_HASH(ins_h, window[strstart + 1]);
zip_ins_h = (zip_ins_h << zip_H_SHIFT ^ zip_window[zip_strstart + 1] & 0xff) & zip_HASH_MASK; // #if MIN_MATCH != 3
// Call UPDATE_HASH() MIN_MATCH-3 more times
// #endif
}
} else {
/* No match, output a literal byte */
flush = zip_ct_tally(0, zip_window[zip_strstart] & 0xff);
zip_lookahead--;
zip_strstart++;
}
if (flush) {
zip_flush_block(0);
zip_block_start = zip_strstart;
}
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
while (zip_lookahead < zip_MIN_LOOKAHEAD && !zip_eofile) {
zip_fill_window();
}
}
}
function zip_deflate_better() {
/* Process the input block. */
while (zip_lookahead != 0 && zip_qhead == null) {
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
zip_INSERT_STRING();
/* Find the longest match, discarding those <= prev_length.
*/
zip_prev_length = zip_match_length;
zip_prev_match = zip_match_start;
zip_match_length = zip_MIN_MATCH - 1;
if (zip_hash_head != zip_NIL && zip_prev_length < zip_max_lazy_match && zip_strstart - zip_hash_head <= zip_MAX_DIST) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
zip_match_length = zip_longest_match(zip_hash_head);
/* longest_match() sets match_start */
if (zip_match_length > zip_lookahead) zip_match_length = zip_lookahead;
/* Ignore a length 3 match if it is too distant: */
if (zip_match_length == zip_MIN_MATCH && zip_strstart - zip_match_start > zip_TOO_FAR) {
/* If prev_match is also MIN_MATCH, match_start is garbage
* but we will ignore the current match anyway.
*/
zip_match_length--;
}
}
/* If there was a match at the previous step and the current
* match is not better, output the previous match:
*/
if (zip_prev_length >= zip_MIN_MATCH && zip_match_length <= zip_prev_length) {
var flush; // set if current block must be flushed
// check_match(strstart - 1, prev_match, prev_length);
flush = zip_ct_tally(zip_strstart - 1 - zip_prev_match, zip_prev_length - zip_MIN_MATCH);
/* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted.
*/
zip_lookahead -= zip_prev_length - 1;
zip_prev_length -= 2;
do {
zip_strstart++;
zip_INSERT_STRING();
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
* these bytes are garbage, but it does not matter since the
* next lookahead bytes will always be emitted as literals.
*/
} while (--zip_prev_length != 0);
zip_match_available = 0;
zip_match_length = zip_MIN_MATCH - 1;
zip_strstart++;
if (flush) {
zip_flush_block(0);
zip_block_start = zip_strstart;
}
} else if (zip_match_available != 0) {
/* If there was no match at the previous position, output a
* single literal. If there was a match but the current match
* is longer, truncate the previous match to a single literal.
*/
if (zip_ct_tally(0, zip_window[zip_strstart - 1] & 0xff)) {
zip_flush_block(0);
zip_block_start = zip_strstart;
}
zip_strstart++;
zip_lookahead--;
} else {
/* There is no previous match to compare with, wait for
* the next step to decide.
*/
zip_match_available = 1;
zip_strstart++;
zip_lookahead--;
}
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
while (zip_lookahead < zip_MIN_LOOKAHEAD && !zip_eofile) {
zip_fill_window();
}
}
}
function zip_init_deflate() {
if (zip_eofile) return;
zip_bi_buf = 0;
zip_bi_valid = 0;
zip_ct_init();
zip_lm_init();
zip_qhead = null;
zip_outcnt = 0;
zip_outoff = 0;
if (zip_compr_level <= 3) {
zip_prev_length = zip_MIN_MATCH - 1;
zip_match_length = 0;
} else {
zip_match_length = zip_MIN_MATCH - 1;
zip_match_available = 0;
}
zip_complete = false;
}
/* ==========================================================================
* Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is
* no better match at the next window position.
*/
function zip_deflate_internal(buff, off, buff_size) {
var n;
if (!zip_initflag) {
zip_init_deflate();
zip_initflag = true;
if (zip_lookahead == 0) {
// empty
zip_complete = true;
return 0;
}
}
if ((n = zip_qcopy(buff, off, buff_size)) == buff_size) return buff_size;
if (zip_complete) return n;
if (zip_compr_level <= 3) // optimized for speed
zip_deflate_fast();else zip_deflate_better();
if (zip_lookahead == 0) {
if (zip_match_available != 0) zip_ct_tally(0, zip_window[zip_strstart - 1] & 0xff);
zip_flush_block(1);
zip_complete = true;
}
return n + zip_qcopy(buff, n + off, buff_size - n);
}
function zip_qcopy(buff, off, buff_size) {
var n;
var i;
var j;
n = 0;
while (zip_qhead != null && n < buff_size) {
i = buff_size - n;
if (i > zip_qhead.len) i = zip_qhead.len; // System.arraycopy(qhead.ptr, qhead.off, buff, off + n, i);
for (j = 0; j < i; j++) {
buff[off + n + j] = zip_qhead.ptr[zip_qhead.off + j];
}
zip_qhead.off += i;
zip_qhead.len -= i;
n += i;
if (zip_qhead.len == 0) {
var p;
p = zip_qhead;
zip_qhead = zip_qhead.next;
zip_reuse_queue(p);
}
}
if (n == buff_size) return n;
if (zip_outoff < zip_outcnt) {
i = buff_size - n;
if (i > zip_outcnt - zip_outoff) i = zip_outcnt - zip_outoff; // System.arraycopy(outbuf, outoff, buff, off + n, i);
for (j = 0; j < i; j++) {
buff[off + n + j] = zip_outbuf[zip_outoff + j];
}
zip_outoff += i;
n += i;
if (zip_outcnt == zip_outoff) zip_outcnt = zip_outoff = 0;
}
return n;
}
/* ==========================================================================
* Allocate the match buffer, initialize the various tables and save the
* location of the internal file attribute (ascii/binary) and method
* (DEFLATE/STORE).
*/
function zip_ct_init() {
var n; // iterates over tree elements
var bits; // bit counter
var length; // length value
var code; // code value
var dist; // distance index
if (zip_static_dtree[0].dl != 0) return; // ct_init already called
zip_l_desc.dyn_tree = zip_dyn_ltree;
zip_l_desc.static_tree = zip_static_ltree;
zip_l_desc.extra_bits = zip_extra_lbits;
zip_l_desc.extra_base = zip_LITERALS + 1;
zip_l_desc.elems = zip_L_CODES;
zip_l_desc.max_length = zip_MAX_BITS;
zip_l_desc.max_code = 0;
zip_d_desc.dyn_tree = zip_dyn_dtree;
zip_d_desc.static_tree = zip_static_dtree;
zip_d_desc.extra_bits = zip_extra_dbits;
zip_d_desc.extra_base = 0;
zip_d_desc.elems = zip_D_CODES;
zip_d_desc.max_length = zip_MAX_BITS;
zip_d_desc.max_code = 0;
zip_bl_desc.dyn_tree = zip_bl_tree;
zip_bl_desc.static_tree = null;
zip_bl_desc.extra_bits = zip_extra_blbits;
zip_bl_desc.extra_base = 0;
zip_bl_desc.elems = zip_BL_CODES;
zip_bl_desc.max_length = zip_MAX_BL_BITS;
zip_bl_desc.max_code = 0; // Initialize the mapping length (0..255) -> length code (0..28)
length = 0;
for (code = 0; code < zip_LENGTH_CODES - 1; code++) {
zip_base_length[code] = length;
for (n = 0; n < 1 << zip_extra_lbits[code]; n++) {
zip_length_code[length++] = code;
}
} // Assert (length == 256, "ct_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
zip_length_code[length - 1] = code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0; code < 16; code++) {
zip_base_dist[code] = dist;
for (n = 0; n < 1 << zip_extra_dbits[code]; n++) {
zip_dist_code[dist++] = code;
}
} // Assert (dist == 256, "ct_init: dist != 256");
dist >>= 7; // from now on, all distances are divided by 128
for (; code < zip_D_CODES; code++) {
zip_base_dist[code] = dist << 7;
for (n = 0; n < 1 << zip_extra_dbits[code] - 7; n++) {
zip_dist_code[256 + dist++] = code;
}
} // Assert (dist == 256, "ct_init: 256+dist != 512");
// Construct the codes of the static literal tree
for (bits = 0; bits <= zip_MAX_BITS; bits++) {
zip_bl_count[bits] = 0;
}
n = 0;
while (n <= 143) {
zip_static_ltree[n++].dl = 8;
zip_bl_count[8]++;
}
while (n <= 255) {
zip_static_ltree[n++].dl = 9;
zip_bl_count[9]++;
}
while (n <= 279) {
zip_static_ltree[n++].dl = 7;
zip_bl_count[7]++;
}
while (n <= 287) {
zip_static_ltree[n++].dl = 8;
zip_bl_count[8]++;
}
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
zip_gen_codes(zip_static_ltree, zip_L_CODES + 1);
/* The static distance tree is trivial: */
for (n = 0; n < zip_D_CODES; n++) {
zip_static_dtree[n].dl = 5;
zip_static_dtree[n].fc = zip_bi_reverse(n, 5);
} // Initialize the first block of the first file:
zip_init_block();
}
/* ==========================================================================
* Initialize a new block.
*/
function zip_init_block() {
var n; // iterates over tree elements
// Initialize the trees.
for (n = 0; n < zip_L_CODES; n++) {
zip_dyn_ltree[n].fc = 0;
}
for (n = 0; n < zip_D_CODES; n++) {
zip_dyn_dtree[n].fc = 0;
}
for (n = 0; n < zip_BL_CODES; n++) {
zip_bl_tree[n].fc = 0;
}
zip_dyn_ltree[zip_END_BLOCK].fc = 1;
zip_opt_len = zip_static_len = 0;
zip_last_lit = zip_last_dist = zip_last_flags = 0;
zip_flags = 0;
zip_flag_bit = 1;
}
/* ==========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
function zip_pqdownheap(tree, // the tree to restore
k) {
// node to move down
var v = zip_heap[k];
var j = k << 1; // left son of k
while (j <= zip_heap_len) {
// Set j to the smallest of the two sons:
if (j < zip_heap_len && zip_SMALLER(tree, zip_heap[j + 1], zip_heap[j])) j++; // Exit if v is smaller than both sons
if (zip_SMALLER(tree, v, zip_heap[j])) break; // Exchange v with the smallest son
zip_heap[k] = zip_heap[j];
k = j; // And continue down the tree, setting j to the left son of k
j <<= 1;
}
zip_heap[k] = v;
}
/* ==========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
function zip_gen_bitlen(desc) {
// the tree descriptor
var tree = desc.dyn_tree;
var extra = desc.extra_bits;
var base = desc.extra_base;
var max_code = desc.max_code;
var max_length = desc.max_length;
var stree = desc.static_tree;
var h; // heap index
var n;
var m; // iterate over the tree elements
var bits; // bit length
var xbits; // extra bits
var f; // frequency
var overflow = 0; // number of elements with bit length too large
for (bits = 0; bits <= zip_MAX_BITS; bits++) {
zip_bl_count[bits] = 0;
}
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[zip_heap[zip_heap_max]].dl = 0; // root of the heap
for (h = zip_heap_max + 1; h < zip_HEAP_SIZE; h++) {
n = zip_heap[h];
bits = tree[tree[n].dl].dl + 1;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n].dl = bits; // We overwrite tree[n].dl which is no longer needed
if (n > max_code) continue; // not a leaf node
zip_bl_count[bits]++;
xbits = 0;
if (n >= base) xbits = extra[n - base];
f = tree[n].fc;
zip_opt_len += f * (bits + xbits);
if (stree != null) zip_static_len += f * (stree[n].dl + xbits);
}
if (overflow == 0) return; // This happens for example on obj2 and pic of the Calgary corpus
// Find the first bit length which could increase:
do {
bits = max_length - 1;
while (zip_bl_count[bits] == 0) {
bits--;
}
zip_bl_count[bits]--; // move one leaf down the tree
zip_bl_count[bits + 1] += 2; // move one overflow item as its brother
zip_bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits != 0; bits--) {
n = zip_bl_count[bits];
while (n != 0) {
m = zip_heap[--h];
if (m > max_code) continue;
if (tree[m].dl != bits) {
zip_opt_len += (bits - tree[m].dl) * tree[m].fc;
tree[m].fc = bits;
}
n--;
}
}
}
/* ==========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
function zip_gen_codes(tree, // the tree to decorate
max_code) {
// largest code with non zero frequency
var next_code = new Array(zip_MAX_BITS + 1); // next code value for each bit length
var code = 0; // running code value
var bits; // bit index
var n; // code index
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= zip_MAX_BITS; bits++) {
code = code + zip_bl_count[bits - 1] << 1;
next_code[bits] = code;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
// Assert (code + encoder->bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
// Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
var len = tree[n].dl;
if (len == 0) continue; // Now reverse the bits
tree[n].fc = zip_bi_reverse(next_code[len]++, len); // Tracec(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
// n, (isgraph(n) ? n : ' '), len, tree[n].fc, next_code[len]-1));
}
}
/* ==========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
function zip_build_tree(desc) {
// the tree descriptor
var tree = desc.dyn_tree;
var stree = desc.static_tree;
var elems = desc.elems;
var n;
var m; // iterate over heap elements
var max_code = -1; // largest code with non zero frequency
var node = elems; // next internal node of the tree
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
zip_heap_len = 0;
zip_heap_max = zip_HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n].fc != 0) {
zip_heap[++zip_heap_len] = max_code = n;
zip_depth[n] = 0;
} else tree[n].dl = 0;
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (zip_heap_len < 2) {
var xnew = zip_heap[++zip_heap_len] = max_code < 2 ? ++max_code : 0;
tree[xnew].fc = 1;
zip_depth[xnew] = 0;
zip_opt_len--;
if (stree != null) zip_static_len -= stree[xnew].dl; // new is 0 or 1 so it does not have extra bits
}
desc.max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = zip_heap_len >> 1; n >= 1; n--) {
zip_pqdownheap(tree, n);
}
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
do {
n = zip_heap[zip_SMALLEST];
zip_heap[zip_SMALLEST] = zip_heap[zip_heap_len--];
zip_pqdownheap(tree, zip_SMALLEST);
m = zip_heap[zip_SMALLEST]; // m = node of next least frequency
// keep the nodes sorted by frequency
zip_heap[--zip_heap_max] = n;
zip_heap[--zip_heap_max] = m; // Create a new node father of n and m
tree[node].fc = tree[n].fc + tree[m].fc; // depth[node] = (char)(MAX(depth[n], depth[m]) + 1);
if (zip_depth[n] > zip_depth[m] + 1) zip_depth[node] = zip_depth[n];else zip_depth[node] = zip_depth[m] + 1;
tree[n].dl = tree[m].dl = node; // and insert the new node in the heap
zip_heap[zip_SMALLEST] = node++;
zip_pqdownheap(tree, zip_SMALLEST);
} while (zip_heap_len >= 2);
zip_heap[--zip_heap_max] = zip_heap[zip_SMALLEST];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
zip_gen_bitlen(desc); // The field len is now set, we can generate the bit codes
zip_gen_codes(tree, max_code);
}
/* ==========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree. Updates opt_len to take into account the repeat
* counts. (The contribution of the bit length codes will be added later
* during the construction of bl_tree.)
*/
function zip_scan_tree(tree, // the tree to be scanned
max_code) {
// and its largest code of non zero frequency
var n; // iterates over all tree elements
var prevlen = -1; // last emitted length
var curlen; // length of current code
var nextlen = tree[0].dl; // length of next code
var count = 0; // repeat count of the current code
var max_count = 7; // max repeat count
var min_count = 4; // min repeat count
if (nextlen == 0) {
max_count = 138;
min_count = 3;
}
tree[max_code + 1].dl = 0xffff; // guard
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[n + 1].dl;
if (++count < max_count && curlen == nextlen) continue;else if (count < min_count) zip_bl_tree[curlen].fc += count;else if (curlen != 0) {
if (curlen != prevlen) zip_bl_tree[curlen].fc++;
zip_bl_tree[zip_REP_3_6].fc++;
} else if (count <= 10) zip_bl_tree[zip_REPZ_3_10].fc++;else zip_bl_tree[zip_REPZ_11_138].fc++;
count = 0;
prevlen = curlen;
if (nextlen == 0) {
max_count = 138;
min_count = 3;
} else if (curlen == nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ==========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
function zip_send_tree(tree, // the tree to be scanned
max_code) {
// and its largest code of non zero frequency
var n; // iterates over all tree elements
var prevlen = -1; // last emitted length
var curlen; // length of current code
var nextlen = tree[0].dl; // length of next code
var count = 0; // repeat count of the current code
var max_count = 7; // max repeat count
var min_count = 4;
/* guard already set */
// min repeat count
/* tree[max_code+1].dl = -1; */
if (nextlen == 0) {
max_count = 138;
min_count = 3;
}
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[n + 1].dl;
if (++count < max_count && curlen == nextlen) {
continue;
} else if (count < min_count) {
do {
zip_SEND_CODE(curlen, zip_bl_tree);
} while (--count != 0);
} else if (curlen != 0) {
if (curlen != prevlen) {
zip_SEND_CODE(curlen, zip_bl_tree);
count--;
} // Assert(count >= 3 && count <= 6, " 3_6?");
zip_SEND_CODE(zip_REP_3_6, zip_bl_tree);
zip_send_bits(count - 3, 2);
} else if (count <= 10) {
zip_SEND_CODE(zip_REPZ_3_10, zip_bl_tree);
zip_send_bits(count - 3, 3);
} else {
zip_SEND_CODE(zip_REPZ_11_138, zip_bl_tree);
zip_send_bits(count - 11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen == 0) {
max_count = 138;
min_count = 3;
} else if (curlen == nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ==========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
function zip_build_bl_tree() {
var max_blindex; // index of last bit length code of non zero freq
// Determine the bit length frequencies for literal and distance trees
zip_scan_tree(zip_dyn_ltree, zip_l_desc.max_code);
zip_scan_tree(zip_dyn_dtree, zip_d_desc.max_code); // Build the bit length tree:
zip_build_tree(zip_bl_desc);
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = zip_BL_CODES - 1; max_blindex >= 3; max_blindex--) {
if (zip_bl_tree[zip_bl_order[max_blindex]].dl != 0) break;
}
/* Update opt_len to include the bit length tree and counts */
zip_opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; // Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
// encoder->opt_len, encoder->static_len));
return max_blindex;
}
/* ==========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
function zip_send_all_trees(lcodes, dcodes, blcodes) {
// number of codes for each tree
var rank; // index in bl_order
// Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
// Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
// "too many codes");
// Tracev((stderr, "\nbl counts: "));
zip_send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
zip_send_bits(dcodes - 1, 5);
zip_send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
for (rank = 0; rank < blcodes; rank++) {
// Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
zip_send_bits(zip_bl_tree[zip_bl_order[rank]].dl, 3);
} // send the literal tree
zip_send_tree(zip_dyn_ltree, lcodes - 1); // send the distance tree
zip_send_tree(zip_dyn_dtree, dcodes - 1);
}
/* ==========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
function zip_flush_block(eof) {
// true if this is the last block for a file
var opt_lenb;
var static_lenb; // opt_len and static_len in bytes
var max_blindex; // index of last bit length code of non zero freq
var stored_len; // length of input block
stored_len = zip_strstart - zip_block_start;
zip_flag_buf[zip_last_flags] = zip_flags; // Save the flags for the last 8 items
// Construct the literal and distance trees
zip_build_tree(zip_l_desc); // Tracev((stderr, "\nlit data: dyn %ld, stat %ld",
// encoder->opt_len, encoder->static_len));
zip_build_tree(zip_d_desc); // Tracev((stderr, "\ndist data: dyn %ld, stat %ld",
// encoder->opt_len, encoder->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = zip_build_bl_tree(); // Determine the best encoding. Compute first the block length in bytes
opt_lenb = zip_opt_len + 3 + 7 >> 3;
static_lenb = zip_static_len + 3 + 7 >> 3; // Trace((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ",
// opt_lenb, encoder->opt_len,
// static_lenb, encoder->static_len, stored_len,
// encoder->last_lit, encoder->last_dist));
if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
if (stored_len + 4 <= opt_lenb && // 4: two words for the lengths
zip_block_start >= 0) {
var i;
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
zip_send_bits((zip_STORED_BLOCK << 1) + eof, 3);
/* send block type */
zip_bi_windup();
/* align on byte boundary */
zip_put_short(stored_len);
zip_put_short(~stored_len); // copy block
/*
p = &window[block_start];
for(i = 0; i < stored_len; i++)
put_byte(p[i]);
*/
for (i = 0; i < stored_len; i++) {
zip_put_byte(zip_window[zip_block_start + i]);
}
} else if (static_lenb == opt_lenb) {
zip_send_bits((zip_STATIC_TREES << 1) + eof, 3);
zip_compress_block(zip_static_ltree, zip_static_dtree);
} else {
zip_send_bits((zip_DYN_TREES << 1) + eof, 3);
zip_send_all_trees(zip_l_desc.max_code + 1, zip_d_desc.max_code + 1, max_blindex + 1);
zip_compress_block(zip_dyn_ltree, zip_dyn_dtree);
}
zip_init_block();
if (eof != 0) zip_bi_windup();
}
/* ==========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
function zip_ct_tally(dist, // distance of matched string
lc) {
// match length-MIN_MATCH or unmatched char (if dist==0)
zip_l_buf[zip_last_lit++] = lc;
if (dist == 0) {
// lc is the unmatched char
zip_dyn_ltree[lc].fc++;
} else {
// Here, lc is the match length - MIN_MATCH
dist--; // dist = match distance - 1
// Assert((ush)dist < (ush)MAX_DIST &&
// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
// (ush)D_CODE(dist) < (ush)D_CODES, "ct_tally: bad match");
zip_dyn_ltree[zip_length_code[lc] + zip_LITERALS + 1].fc++;
zip_dyn_dtree[zip_D_CODE(dist)].fc++;
zip_d_buf[zip_last_dist++] = dist;
zip_flags |= zip_flag_bit;
}
zip_flag_bit <<= 1; // Output the flags if they fill a byte
if ((zip_last_lit & 7) == 0) {
zip_flag_buf[zip_last_flags++] = zip_flags;
zip_flags = 0;
zip_flag_bit = 1;
} // Try to guess if it is profitable to stop the current block here
if (zip_compr_level > 2 && (zip_last_lit & 0xfff) == 0) {
// Compute an upper bound for the compressed length
var out_length = zip_last_lit * 8;
var in_length = zip_strstart - zip_block_start;
var dcode;
for (dcode = 0; dcode < zip_D_CODES; dcode++) {
out_length += zip_dyn_dtree[dcode].fc * (5 + zip_extra_dbits[dcode]);
}
out_length >>= 3; // Trace((stderr,"\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ",
// encoder->last_lit, encoder->last_dist, in_length, out_length,
// 100L - out_length*100L/in_length));
if (zip_last_dist < _parseInt$2(zip_last_lit / 2) && out_length < _parseInt$2(in_length / 2)) return true;
}
return zip_last_lit == zip_LIT_BUFSIZE - 1 || zip_last_dist == zip_DIST_BUFSIZE;
/* We avoid equality with LIT_BUFSIZE because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
/* ==========================================================================
* Send the block data compressed using the given Huffman trees
*/
function zip_compress_block(ltree, // literal tree
dtree) {
// distance tree
var dist; // distance of matched string
var lc; // match length or unmatched char (if dist == 0)
var lx = 0; // running index in l_buf
var dx = 0; // running index in d_buf
var fx = 0; // running index in flag_buf
var flag = 0; // current flags
var code; // the code to send
var extra; // number of extra bits to send
if (zip_last_lit != 0) do {
if ((lx & 7) == 0) flag = zip_flag_buf[fx++];
lc = zip_l_buf[lx++] & 0xff;
if ((flag & 1) == 0) {
zip_SEND_CODE(lc, ltree);
/* send a literal byte */
// Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
// Here, lc is the match length - MIN_MATCH
code = zip_length_code[lc];
zip_SEND_CODE(code + zip_LITERALS + 1, ltree); // send the length code
extra = zip_extra_lbits[code];
if (extra != 0) {
lc -= zip_base_length[code];
zip_send_bits(lc, extra); // send the extra length bits
}
dist = zip_d_buf[dx++]; // Here, dist is the match distance - 1
code = zip_D_CODE(dist); // Assert (code < D_CODES, "bad d_code");
zip_SEND_CODE(code, dtree); // send the distance code
extra = zip_extra_dbits[code];
if (extra != 0) {
dist -= zip_base_dist[code];
zip_send_bits(dist, extra); // send the extra distance bits
}
} // literal or match pair ?
flag >>= 1;
} while (lx < zip_last_lit);
zip_SEND_CODE(zip_END_BLOCK, ltree);
}
/* ==========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
var zip_Buf_size = 16; // bit size of bi_buf
function zip_send_bits(value, // value to send
length) {
// number of bits
/* If not enough room in bi_buf, use (valid) bits from bi_buf and
* (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
* unused bits in value.
*/
if (zip_bi_valid > zip_Buf_size - length) {
zip_bi_buf |= value << zip_bi_valid;
zip_put_short(zip_bi_buf);
zip_bi_buf = value >> zip_Buf_size - zip_bi_valid;
zip_bi_valid += length - zip_Buf_size;
} else {
zip_bi_buf |= value << zip_bi_valid;
zip_bi_valid += length;
}
}
/* ==========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
function zip_bi_reverse(code, // the value to invert
len) {
// its bit length
var res = 0;
do {
res |= code & 1;
code >>= 1;
res <<= 1;
} while (--len > 0);
return res >> 1;
}
/* ==========================================================================
* Write out any remaining bits in an incomplete byte.
*/
function zip_bi_windup() {
if (zip_bi_valid > 8) {
zip_put_short(zip_bi_buf);
} else if (zip_bi_valid > 0) {
zip_put_byte(zip_bi_buf);
}
zip_bi_buf = 0;
zip_bi_valid = 0;
}
function zip_qoutbuf() {
if (zip_outcnt != 0) {
var q;
var i;
q = zip_new_queue();
if (zip_qhead == null) zip_qhead = zip_qtail = q;else zip_qtail = zip_qtail.next = q;
q.len = zip_outcnt - zip_outoff; // System.arraycopy(zip_outbuf, zip_outoff, q.ptr, 0, q.len);
for (i = 0; i < q.len; i++) {
q.ptr[i] = zip_outbuf[zip_outoff + i];
}
zip_outcnt = zip_outoff = 0;
}
}
return function deflate(str, level) {
var i;
var j;
zip_deflate_data = str;
zip_deflate_pos = 0;
if (typeof level === 'undefined') level = zip_DEFAULT_LEVEL;
zip_deflate_start(level);
var buff = new Array(1024);
var aout = [];
while ((i = zip_deflate_internal(buff, 0, buff.length)) > 0) {
var cbuf = new Array(i);
for (j = 0; j < i; j++) {
cbuf[j] = String.fromCharCode(buff[j]);
}
aout[aout.length] = cbuf.join('');
}
zip_deflate_data = null; // G.C.
return aout.join('');
};
}();
function ownKeys$b(object, enumerableOnly) { var keys = keys$3(object); if (getOwnPropertySymbols$2) { var symbols = getOwnPropertySymbols$2(object); enumerableOnly && (symbols = filter$3(symbols).call(symbols, function (sym) { return getOwnPropertyDescriptor$3(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$a(target) { for (var i = 1; i < arguments.length; i++) { var _context4, _context5; var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? forEach$3(_context4 = ownKeys$b(Object(source), !0)).call(_context4, function (key) { _defineProperty(target, key, source[key]); }) : getOwnPropertyDescriptors$2 ? defineProperties$2(target, getOwnPropertyDescriptors$2(source)) : forEach$3(_context5 = ownKeys$b(Object(source))).call(_context5, function (key) { defineProperty$5(target, key, getOwnPropertyDescriptor$3(source, key)); }); } return target; }
function encode64(data) {
var r = '';
for (var i = 0; i < data.length; i += 3) {
if (i + 2 === data.length) {
r += append3bytes(data.charCodeAt(i), data.charCodeAt(i + 1), 0);
} else if (i + 1 === data.length) {
r += append3bytes(data.charCodeAt(i), 0, 0);
} else {
r += append3bytes(data.charCodeAt(i), data.charCodeAt(i + 1), data.charCodeAt(i + 2));
}
}
return r;
}
function append3bytes(b1, b2, b3) {
var c1 = b1 >> 2;
var c2 = (b1 & 0x3) << 4 | b2 >> 4;
var c3 = (b2 & 0xf) << 2 | b3 >> 6;
var c4 = b3 & 0x3f;
var r = '';
r += encode6bit(c1 & 0x3f);
r += encode6bit(c2 & 0x3f);
r += encode6bit(c3 & 0x3f);
r += encode6bit(c4 & 0x3f);
return r;
}
function encode6bit(b1) {
var b = b1;
if (b < 10) {
return String.fromCharCode(48 + b);
}
b -= 10;
if (b < 26) {
return String.fromCharCode(65 + b);
}
b -= 26;
if (b < 26) {
return String.fromCharCode(97 + b);
}
b -= 26;
if (b === 0) {
return '-';
}
if (b === 1) {
return '_';
}
return '?';
}
function compress(s1, url) {
var _context;
var s = unescape(encodeURIComponent(s1));
return concat$5(_context = "".concat(url, "/svg/")).call(_context, encode64(deflate(s, 9)));
}
var PlantUMLCodeEngine = /*#__PURE__*/function () {
function PlantUMLCodeEngine() {
var _plantUMLOptions$base;
var plantUMLOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, PlantUMLCodeEngine);
var defaultUrl = 'http://www.plantuml.com/plantuml';
this.baseUrl = (_plantUMLOptions$base = plantUMLOptions.baseUrl) !== null && _plantUMLOptions$base !== void 0 ? _plantUMLOptions$base : defaultUrl;
}
_createClass(PlantUMLCodeEngine, [{
key: "render",
value: function render(src, sign) {
var _context2, _context3;
var $sign = sign;
if (!$sign) {
$sign = Math.round(Math.random() * 100000000);
}
var graphId = concat$5(_context2 = "plantuml-".concat($sign, "-")).call(_context2, new Date().getTime());
return concat$5(_context3 = "<img id=\"".concat(graphId, "\" src=\"")).call(_context3, compress(src, this.baseUrl), "\" />");
}
}], [{
key: "install",
value: function install(cherryOptions, args) {
var _cherryOptions$engine;
mergeWith_1(cherryOptions, {
engine: {
syntax: {
codeBlock: {
customRenderer: {
plantuml: new PlantUMLCodeEngine(_objectSpread$a(_objectSpread$a({}, args), (_cherryOptions$engine = cherryOptions.engine.syntax.plantuml) !== null && _cherryOptions$engine !== void 0 ? _cherryOptions$engine : {}))
}
}
}
}
});
}
}]);
return PlantUMLCodeEngine;
}();
/*! For license information please see mermaid.esm.min.mjs.LICENSE.txt */
var t={2536:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,6],n=[1,7],r=[1,8],i=[1,9],a=[1,16],o=[1,11],s=[1,12],l=[1,13],u=[1,14],h=[1,15],f=[1,27],d=[1,33],p=[1,34],g=[1,35],y=[1,36],m=[1,37],b=[1,72],v=[1,73],_=[1,74],x=[1,75],k=[1,76],w=[1,77],T=[1,78],E=[1,38],C=[1,39],S=[1,40],A=[1,41],M=[1,42],N=[1,43],O=[1,44],D=[1,45],B=[1,46],L=[1,47],I=[1,48],F=[1,49],R=[1,50],P=[1,51],j=[1,52],z=[1,53],Y=[1,54],U=[1,55],$=[1,56],W=[1,57],q=[1,59],H=[1,60],V=[1,61],G=[1,62],X=[1,63],Z=[1,64],Q=[1,65],K=[1,66],J=[1,67],tt=[1,68],et=[1,69],nt=[24,52],rt=[24,44,46,47,48,49,50,51,52,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84],it=[15,24,44,46,47,48,49,50,51,52,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84],at=[1,94],ot=[1,95],st=[1,96],ct=[1,97],lt=[15,24,52],ut=[7,8,9,10,18,22,25,26,27,28],ht=[15,24,43,52],ft=[15,24,43,52,86,87,89,90],dt=[15,43],pt=[44,46,47,48,49,50,51,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84],gt={trace:function(){},yy:{},symbols_:{error:2,start:3,mermaidDoc:4,direction:5,directive:6,direction_tb:7,direction_bt:8,direction_rl:9,direction_lr:10,graphConfig:11,openDirective:12,typeDirective:13,closeDirective:14,NEWLINE:15,":":16,argDirective:17,open_directive:18,type_directive:19,arg_directive:20,close_directive:21,C4_CONTEXT:22,statements:23,EOF:24,C4_CONTAINER:25,C4_COMPONENT:26,C4_DYNAMIC:27,C4_DEPLOYMENT:28,otherStatements:29,diagramStatements:30,otherStatement:31,title:32,accDescription:33,acc_title:34,acc_title_value:35,acc_descr:36,acc_descr_value:37,acc_descr_multiline_value:38,boundaryStatement:39,boundaryStartStatement:40,boundaryStopStatement:41,boundaryStart:42,LBRACE:43,ENTERPRISE_BOUNDARY:44,attributes:45,SYSTEM_BOUNDARY:46,BOUNDARY:47,CONTAINER_BOUNDARY:48,NODE:49,NODE_L:50,NODE_R:51,RBRACE:52,diagramStatement:53,PERSON:54,PERSON_EXT:55,SYSTEM:56,SYSTEM_DB:57,SYSTEM_QUEUE:58,SYSTEM_EXT:59,SYSTEM_EXT_DB:60,SYSTEM_EXT_QUEUE:61,CONTAINER:62,CONTAINER_DB:63,CONTAINER_QUEUE:64,CONTAINER_EXT:65,CONTAINER_EXT_DB:66,CONTAINER_EXT_QUEUE:67,COMPONENT:68,COMPONENT_DB:69,COMPONENT_QUEUE:70,COMPONENT_EXT:71,COMPONENT_EXT_DB:72,COMPONENT_EXT_QUEUE:73,REL:74,BIREL:75,REL_U:76,REL_D:77,REL_L:78,REL_R:79,REL_B:80,REL_INDEX:81,UPDATE_EL_STYLE:82,UPDATE_REL_STYLE:83,UPDATE_LAYOUT_CONFIG:84,attribute:85,STR:86,STR_KEY:87,STR_VALUE:88,ATTRIBUTE:89,ATTRIBUTE_EMPTY:90,$accept:0,$end:1},terminals_:{2:"error",7:"direction_tb",8:"direction_bt",9:"direction_rl",10:"direction_lr",15:"NEWLINE",16:":",18:"open_directive",19:"type_directive",20:"arg_directive",21:"close_directive",22:"C4_CONTEXT",24:"EOF",25:"C4_CONTAINER",26:"C4_COMPONENT",27:"C4_DYNAMIC",28:"C4_DEPLOYMENT",32:"title",33:"accDescription",34:"acc_title",35:"acc_title_value",36:"acc_descr",37:"acc_descr_value",38:"acc_descr_multiline_value",43:"LBRACE",44:"ENTERPRISE_BOUNDARY",46:"SYSTEM_BOUNDARY",47:"BOUNDARY",48:"CONTAINER_BOUNDARY",49:"NODE",50:"NODE_L",51:"NODE_R",52:"RBRACE",54:"PERSON",55:"PERSON_EXT",56:"SYSTEM",57:"SYSTEM_DB",58:"SYSTEM_QUEUE",59:"SYSTEM_EXT",60:"SYSTEM_EXT_DB",61:"SYSTEM_EXT_QUEUE",62:"CONTAINER",63:"CONTAINER_DB",64:"CONTAINER_QUEUE",65:"CONTAINER_EXT",66:"CONTAINER_EXT_DB",67:"CONTAINER_EXT_QUEUE",68:"COMPONENT",69:"COMPONENT_DB",70:"COMPONENT_QUEUE",71:"COMPONENT_EXT",72:"COMPONENT_EXT_DB",73:"COMPONENT_EXT_QUEUE",74:"REL",75:"BIREL",76:"REL_U",77:"REL_D",78:"REL_L",79:"REL_R",80:"REL_B",81:"REL_INDEX",82:"UPDATE_EL_STYLE",83:"UPDATE_REL_STYLE",84:"UPDATE_LAYOUT_CONFIG",86:"STR",87:"STR_KEY",88:"STR_VALUE",89:"ATTRIBUTE",90:"ATTRIBUTE_EMPTY"},productions_:[0,[3,1],[3,1],[3,2],[5,1],[5,1],[5,1],[5,1],[4,1],[6,4],[6,6],[12,1],[13,1],[17,1],[14,1],[11,4],[11,4],[11,4],[11,4],[11,4],[23,1],[23,1],[23,2],[29,1],[29,2],[29,3],[31,1],[31,1],[31,2],[31,2],[31,1],[39,3],[40,3],[40,3],[40,4],[42,2],[42,2],[42,2],[42,2],[42,2],[42,2],[42,2],[41,1],[30,1],[30,2],[30,3],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[53,1],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[53,2],[45,1],[45,2],[85,1],[85,2],[85,1],[85,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 4:r.setDirection("TB");break;case 5:r.setDirection("BT");break;case 6:r.setDirection("RL");break;case 7:r.setDirection("LR");break;case 11:console.log("open_directive: ",a[s]),r.parseDirective("%%{","open_directive");break;case 12:break;case 13:a[s]=a[s].trim().replace(/'/g,'"'),console.log("arg_directive: ",a[s]),r.parseDirective(a[s],"arg_directive");break;case 14:console.log("close_directive: ",a[s]),r.parseDirective("}%%","close_directive","c4Context");break;case 15:case 16:case 17:case 18:case 19:r.setC4Type(a[s-3]);break;case 26:r.setTitle(a[s].substring(6)),this.$=a[s].substring(6);break;case 27:r.setAccDescription(a[s].substring(15)),this.$=a[s].substring(15);break;case 28:this.$=a[s].trim(),r.setTitle(this.$);break;case 29:case 30:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 35:case 36:console.log(a[s-1],JSON.stringify(a[s])),a[s].splice(2,0,"ENTERPRISE"),r.addPersonOrSystemBoundary(...a[s]),this.$=a[s];break;case 37:console.log(a[s-1],JSON.stringify(a[s])),r.addPersonOrSystemBoundary(...a[s]),this.$=a[s];break;case 38:console.log(a[s-1],JSON.stringify(a[s])),a[s].splice(2,0,"CONTAINER"),r.addContainerBoundary(...a[s]),this.$=a[s];break;case 39:console.log(a[s-1],JSON.stringify(a[s])),r.addDeploymentNode("node",...a[s]),this.$=a[s];break;case 40:console.log(a[s-1],JSON.stringify(a[s])),r.addDeploymentNode("nodeL",...a[s]),this.$=a[s];break;case 41:console.log(a[s-1],JSON.stringify(a[s])),r.addDeploymentNode("nodeR",...a[s]),this.$=a[s];break;case 42:r.popBoundaryParseStack();break;case 46:console.log(a[s-1],JSON.stringify(a[s])),r.addPersonOrSystem("person",...a[s]),this.$=a[s];break;case 47:console.log(a[s-1],JSON.stringify(a[s])),r.addPersonOrSystem("external_person",...a[s]),this.$=a[s];break;case 48:console.log(a[s-1],JSON.stringify(a[s])),r.addPersonOrSystem("system",...a[s]),this.$=a[s];break;case 49:console.log(a[s-1],JSON.stringify(a[s])),r.addPersonOrSystem("system_db",...a[s]),this.$=a[s];break;case 50:console.log(a[s-1],JSON.stringify(a[s])),r.addPersonOrSystem("system_queue",...a[s]),this.$=a[s];break;case 51:console.log(a[s-1],JSON.stringify(a[s])),r.addPersonOrSystem("external_system",...a[s]),this.$=a[s];break;case 52:console.log(a[s-1],JSON.stringify(a[s])),r.addPersonOrSystem("external_system_db",...a[s]),this.$=a[s];break;case 53:console.log(a[s-1],JSON.stringify(a[s])),r.addPersonOrSystem("external_system_queue",...a[s]),this.$=a[s];break;case 54:console.log(a[s-1],JSON.stringify(a[s])),r.addContainer("container",...a[s]),this.$=a[s];break;case 55:console.log(a[s-1],JSON.stringify(a[s])),r.addContainer("container_db",...a[s]),this.$=a[s];break;case 56:console.log(a[s-1],JSON.stringify(a[s])),r.addContainer("container_queue",...a[s]),this.$=a[s];break;case 57:console.log(a[s-1],JSON.stringify(a[s])),r.addContainer("external_container",...a[s]),this.$=a[s];break;case 58:console.log(a[s-1],JSON.stringify(a[s])),r.addContainer("external_container_db",...a[s]),this.$=a[s];break;case 59:console.log(a[s-1],JSON.stringify(a[s])),r.addContainer("external_container_queue",...a[s]),this.$=a[s];break;case 60:console.log(a[s-1],JSON.stringify(a[s])),r.addComponent("component",...a[s]),this.$=a[s];break;case 61:console.log(a[s-1],JSON.stringify(a[s])),r.addComponent("component_db",...a[s]),this.$=a[s];break;case 62:console.log(a[s-1],JSON.stringify(a[s])),r.addComponent("component_queue",...a[s]),this.$=a[s];break;case 63:console.log(a[s-1],JSON.stringify(a[s])),r.addComponent("external_component",...a[s]),this.$=a[s];break;case 64:console.log(a[s-1],JSON.stringify(a[s])),r.addComponent("external_component_db",...a[s]),this.$=a[s];break;case 65:console.log(a[s-1],JSON.stringify(a[s])),r.addComponent("external_component_queue",...a[s]),this.$=a[s];break;case 67:console.log(a[s-1],JSON.stringify(a[s])),r.addRel("rel",...a[s]),this.$=a[s];break;case 68:console.log(a[s-1],JSON.stringify(a[s])),r.addRel("birel",...a[s]),this.$=a[s];break;case 69:console.log(a[s-1],JSON.stringify(a[s])),r.addRel("rel_u",...a[s]),this.$=a[s];break;case 70:console.log(a[s-1],JSON.stringify(a[s])),r.addRel("rel_d",...a[s]),this.$=a[s];break;case 71:console.log(a[s-1],JSON.stringify(a[s])),r.addRel("rel_l",...a[s]),this.$=a[s];break;case 72:console.log(a[s-1],JSON.stringify(a[s])),r.addRel("rel_r",...a[s]),this.$=a[s];break;case 73:console.log(a[s-1],JSON.stringify(a[s])),r.addRel("rel_b",...a[s]),this.$=a[s];break;case 74:console.log(a[s-1],JSON.stringify(a[s])),a[s].splice(0,1),r.addRel("rel",...a[s]),this.$=a[s];break;case 75:console.log(a[s-1],JSON.stringify(a[s])),r.updateElStyle("update_el_style",...a[s]),this.$=a[s];break;case 76:console.log(a[s-1],JSON.stringify(a[s])),r.updateRelStyle("update_rel_style",...a[s]),this.$=a[s];break;case 77:console.log(a[s-1],JSON.stringify(a[s])),r.updateLayoutConfig("update_layout_config",...a[s]),this.$=a[s];break;case 78:console.log("PUSH ATTRIBUTE: ",a[s]),this.$=[a[s]];break;case 79:console.log("PUSH ATTRIBUTE: ",a[s-1]),a[s].unshift(a[s-1]),this.$=a[s];break;case 80:case 82:this.$=a[s].trim();break;case 81:console.log("kv: ",a[s-1],a[s]);let t={};t[a[s-1].trim()]=a[s].trim(),this.$=t;break;case 83:this.$="";}},table:[{3:1,4:2,5:3,6:4,7:e,8:n,9:r,10:i,11:5,12:10,18:a,22:o,25:s,26:l,27:u,28:h},{1:[3]},{1:[2,1]},{1:[2,2]},{3:17,4:2,5:3,6:4,7:e,8:n,9:r,10:i,11:5,12:10,18:a,22:o,25:s,26:l,27:u,28:h},{1:[2,8]},{1:[2,4]},{1:[2,5]},{1:[2,6]},{1:[2,7]},{13:18,19:[1,19]},{15:[1,20]},{15:[1,21]},{15:[1,22]},{15:[1,23]},{15:[1,24]},{19:[2,11]},{1:[2,3]},{14:25,16:[1,26],21:f},t([16,21],[2,12]),{23:28,29:29,30:30,31:31,32:d,33:p,34:g,36:y,38:m,39:58,40:70,42:71,44:b,46:v,47:_,48:x,49:k,50:w,51:T,53:32,54:E,55:C,56:S,57:A,58:M,59:N,60:O,61:D,62:B,63:L,64:I,65:F,66:R,67:P,68:j,69:z,70:Y,71:U,72:$,73:W,74:q,75:H,76:V,77:G,78:X,79:Z,80:Q,81:K,82:J,83:tt,84:et},{23:79,29:29,30:30,31:31,32:d,33:p,34:g,36:y,38:m,39:58,40:70,42:71,44:b,46:v,47:_,48:x,49:k,50:w,51:T,53:32,54:E,55:C,56:S,57:A,58:M,59:N,60:O,61:D,62:B,63:L,64:I,65:F,66:R,67:P,68:j,69:z,70:Y,71:U,72:$,73:W,74:q,75:H,76:V,77:G,78:X,79:Z,80:Q,81:K,82:J,83:tt,84:et},{23:80,29:29,30:30,31:31,32:d,33:p,34:g,36:y,38:m,39:58,40:70,42:71,44:b,46:v,47:_,48:x,49:k,50:w,51:T,53:32,54:E,55:C,56:S,57:A,58:M,59:N,60:O,61:D,62:B,63:L,64:I,65:F,66:R,67:P,68:j,69:z,70:Y,71:U,72:$,73:W,74:q,75:H,76:V,77:G,78:X,79:Z,80:Q,81:K,82:J,83:tt,84:et},{23:81,29:29,30:30,31:31,32:d,33:p,34:g,36:y,38:m,39:58,40:70,42:71,44:b,46:v,47:_,48:x,49:k,50:w,51:T,53:32,54:E,55:C,56:S,57:A,58:M,59:N,60:O,61:D,62:B,63:L,64:I,65:F,66:R,67:P,68:j,69:z,70:Y,71:U,72:$,73:W,74:q,75:H,76:V,77:G,78:X,79:Z,80:Q,81:K,82:J,83:tt,84:et},{23:82,29:29,30:30,31:31,32:d,33:p,34:g,36:y,38:m,39:58,40:70,42:71,44:b,46:v,47:_,48:x,49:k,50:w,51:T,53:32,54:E,55:C,56:S,57:A,58:M,59:N,60:O,61:D,62:B,63:L,64:I,65:F,66:R,67:P,68:j,69:z,70:Y,71:U,72:$,73:W,74:q,75:H,76:V,77:G,78:X,79:Z,80:Q,81:K,82:J,83:tt,84:et},{15:[1,83]},{17:84,20:[1,85]},{15:[2,14]},{24:[1,86]},t(nt,[2,20],{53:32,39:58,40:70,42:71,30:87,44:b,46:v,47:_,48:x,49:k,50:w,51:T,54:E,55:C,56:S,57:A,58:M,59:N,60:O,61:D,62:B,63:L,64:I,65:F,66:R,67:P,68:j,69:z,70:Y,71:U,72:$,73:W,74:q,75:H,76:V,77:G,78:X,79:Z,80:Q,81:K,82:J,83:tt,84:et}),t(nt,[2,21]),t(rt,[2,23],{15:[1,88]}),t(nt,[2,43],{15:[1,89]}),t(it,[2,26]),t(it,[2,27]),{35:[1,90]},{37:[1,91]},t(it,[2,30]),{45:92,85:93,86:at,87:ot,89:st,90:ct},{45:98,85:93,86:at,87:ot,89:st,90:ct},{45:99,85:93,86:at,87:ot,89:st,90:ct},{45:100,85:93,86:at,87:ot,89:st,90:ct},{45:101,85:93,86:at,87:ot,89:st,90:ct},{45:102,85:93,86:at,87:ot,89:st,90:ct},{45:103,85:93,86:at,87:ot,89:st,90:ct},{45:104,85:93,86:at,87:ot,89:st,90:ct},{45:105,85:93,86:at,87:ot,89:st,90:ct},{45:106,85:93,86:at,87:ot,89:st,90:ct},{45:107,85:93,86:at,87:ot,89:st,90:ct},{45:108,85:93,86:at,87:ot,89:st,90:ct},{45:109,85:93,86:at,87:ot,89:st,90:ct},{45:110,85:93,86:at,87:ot,89:st,90:ct},{45:111,85:93,86:at,87:ot,89:st,90:ct},{45:112,85:93,86:at,87:ot,89:st,90:ct},{45:113,85:93,86:at,87:ot,89:st,90:ct},{45:114,85:93,86:at,87:ot,89:st,90:ct},{45:115,85:93,86:at,87:ot,89:st,90:ct},{45:116,85:93,86:at,87:ot,89:st,90:ct},t(lt,[2,66]),{45:117,85:93,86:at,87:ot,89:st,90:ct},{45:118,85:93,86:at,87:ot,89:st,90:ct},{45:119,85:93,86:at,87:ot,89:st,90:ct},{45:120,85:93,86:at,87:ot,89:st,90:ct},{45:121,85:93,86:at,87:ot,89:st,90:ct},{45:122,85:93,86:at,87:ot,89:st,90:ct},{45:123,85:93,86:at,87:ot,89:st,90:ct},{45:124,85:93,86:at,87:ot,89:st,90:ct},{45:125,85:93,86:at,87:ot,89:st,90:ct},{45:126,85:93,86:at,87:ot,89:st,90:ct},{45:127,85:93,86:at,87:ot,89:st,90:ct},{30:128,39:58,40:70,42:71,44:b,46:v,47:_,48:x,49:k,50:w,51:T,53:32,54:E,55:C,56:S,57:A,58:M,59:N,60:O,61:D,62:B,63:L,64:I,65:F,66:R,67:P,68:j,69:z,70:Y,71:U,72:$,73:W,74:q,75:H,76:V,77:G,78:X,79:Z,80:Q,81:K,82:J,83:tt,84:et},{15:[1,130],43:[1,129]},{45:131,85:93,86:at,87:ot,89:st,90:ct},{45:132,85:93,86:at,87:ot,89:st,90:ct},{45:133,85:93,86:at,87:ot,89:st,90:ct},{45:134,85:93,86:at,87:ot,89:st,90:ct},{45:135,85:93,86:at,87:ot,89:st,90:ct},{45:136,85:93,86:at,87:ot,89:st,90:ct},{45:137,85:93,86:at,87:ot,89:st,90:ct},{24:[1,138]},{24:[1,139]},{24:[1,140]},{24:[1,141]},t(ut,[2,9]),{14:142,21:f},{21:[2,13]},{1:[2,15]},t(nt,[2,22]),t(rt,[2,24],{31:31,29:143,32:d,33:p,34:g,36:y,38:m}),t(nt,[2,44],{29:29,30:30,31:31,53:32,39:58,40:70,42:71,23:144,32:d,33:p,34:g,36:y,38:m,44:b,46:v,47:_,48:x,49:k,50:w,51:T,54:E,55:C,56:S,57:A,58:M,59:N,60:O,61:D,62:B,63:L,64:I,65:F,66:R,67:P,68:j,69:z,70:Y,71:U,72:$,73:W,74:q,75:H,76:V,77:G,78:X,79:Z,80:Q,81:K,82:J,83:tt,84:et}),t(it,[2,28]),t(it,[2,29]),t(lt,[2,46]),t(ht,[2,78],{85:93,45:145,86:at,87:ot,89:st,90:ct}),t(ft,[2,80]),{88:[1,146]},t(ft,[2,82]),t(ft,[2,83]),t(lt,[2,47]),t(lt,[2,48]),t(lt,[2,49]),t(lt,[2,50]),t(lt,[2,51]),t(lt,[2,52]),t(lt,[2,53]),t(lt,[2,54]),t(lt,[2,55]),t(lt,[2,56]),t(lt,[2,57]),t(lt,[2,58]),t(lt,[2,59]),t(lt,[2,60]),t(lt,[2,61]),t(lt,[2,62]),t(lt,[2,63]),t(lt,[2,64]),t(lt,[2,65]),t(lt,[2,67]),t(lt,[2,68]),t(lt,[2,69]),t(lt,[2,70]),t(lt,[2,71]),t(lt,[2,72]),t(lt,[2,73]),t(lt,[2,74]),t(lt,[2,75]),t(lt,[2,76]),t(lt,[2,77]),{41:147,52:[1,148]},{15:[1,149]},{43:[1,150]},t(dt,[2,35]),t(dt,[2,36]),t(dt,[2,37]),t(dt,[2,38]),t(dt,[2,39]),t(dt,[2,40]),t(dt,[2,41]),{1:[2,16]},{1:[2,17]},{1:[2,18]},{1:[2,19]},{15:[1,151]},t(rt,[2,25]),t(nt,[2,45]),t(ht,[2,79]),t(ft,[2,81]),t(lt,[2,31]),t(lt,[2,42]),t(pt,[2,32]),t(pt,[2,33],{15:[1,152]}),t(ut,[2,10]),t(pt,[2,34])],defaultActions:{2:[2,1],3:[2,2],5:[2,8],6:[2,4],7:[2,5],8:[2,6],9:[2,7],16:[2,11],17:[2,3],27:[2,14],85:[2,13],86:[2,15],138:[2,16],139:[2,17],140:[2,18],141:[2,19]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t);},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,l=0,u=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var b=p.options&&p.options.ranges;function v(){var t;return "number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,k,w,T,E,C,S,A,M={};;){if(k=n[n.length-1],this.defaultActions[k]?w=this.defaultActions[k]:(null==_&&(_=v()),w=o[k]&&o[k][_]),void 0===w||!w.length||!w[0]){var N="";for(E in A=[],o[k])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A});}if(w[0]instanceof Array&&w.length>1)throw new Error("Parse Error: multiple actions possible at state: "+k+", token: "+_);switch(w[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(w[1]),_=null,x?(_=x,x=null):(l=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,u>0&&u--);break;case 2:if(C=this.productions_[w[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},b&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,l,c,g.yy,w[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[w[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return !0}}return !0}},yt={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e);},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t));},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return (t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return !1}return !1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;a<i.length;a++)if((n=this._input.match(this.rules[i[a]]))&&(!e||n[0].length>e[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return !1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t);},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return (t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t);},stateStackSize:function(){return this.conditionStack.length},options:{},performAction:function(t,e,n,r){switch(n){case 0:return this.begin("open_directive"),18;case 1:return 7;case 2:return 8;case 3:return 9;case 4:return 10;case 5:return this.begin("type_directive"),19;case 6:return this.popState(),this.begin("arg_directive"),16;case 7:return this.popState(),this.popState(),21;case 8:return 20;case 9:return 32;case 10:return 33;case 11:return this.begin("acc_title"),34;case 12:return this.popState(),"acc_title_value";case 13:return this.begin("acc_descr"),36;case 14:return this.popState(),"acc_descr_value";case 15:this.begin("acc_descr_multiline");break;case 16:this.popState();break;case 17:return "acc_descr_multiline_value";case 18:case 21:break;case 19:c;break;case 20:return 15;case 22:return 22;case 23:return 25;case 24:return 26;case 25:return 27;case 26:return 28;case 27:return this.begin("person_ext"),console.log("begin person_ext"),55;case 28:return this.begin("person"),console.log("begin person"),54;case 29:return this.begin("system_ext_queue"),console.log("begin system_ext_queue"),61;case 30:return this.begin("system_ext_db"),console.log("begin system_ext_db"),60;case 31:return this.begin("system_ext"),console.log("begin system_ext"),59;case 32:return this.begin("system_queue"),console.log("begin system_queue"),58;case 33:return this.begin("system_db"),console.log("begin system_db"),57;case 34:return this.begin("system"),console.log("begin system"),56;case 35:return this.begin("boundary"),console.log("begin boundary"),47;case 36:return this.begin("enterprise_boundary"),console.log("begin enterprise_boundary"),44;case 37:return this.begin("system_boundary"),console.log("begin system_boundary"),46;case 38:return this.begin("container_ext_queue"),console.log("begin container_ext_queue"),67;case 39:return this.begin("container_ext_db"),console.log("begin container_ext_db"),66;case 40:return this.begin("container_ext"),console.log("begin container_ext"),65;case 41:return this.begin("container_queue"),console.log("begin container_queue"),64;case 42:return this.begin("container_db"),console.log("begin container_db"),63;case 43:return this.begin("container"),console.log("begin container"),62;case 44:return this.begin("container_boundary"),console.log("begin container_boundary"),48;case 45:return this.begin("component_ext_queue"),console.log("begin component_ext_queue"),73;case 46:return this.begin("component_ext_db"),console.log("begin component_ext_db"),72;case 47:return this.begin("component_ext"),console.log("begin component_ext"),71;case 48:return this.begin("component_queue"),console.log("begin component_queue"),70;case 49:return this.begin("component_db"),console.log("begin component_db"),69;case 50:return this.begin("component"),console.log("begin component"),68;case 51:case 52:return this.begin("node"),console.log("begin node"),49;case 53:return this.begin("node_l"),console.log("begin node_l"),50;case 54:return this.begin("node_r"),console.log("begin node_r"),51;case 55:return this.begin("rel"),console.log("begin rel"),74;case 56:return this.begin("birel"),console.log("begin birel"),75;case 57:case 58:return this.begin("rel_u"),console.log("begin rel_u"),76;case 59:case 60:return this.begin("rel_d"),console.log("begin rel_d"),77;case 61:case 62:return this.begin("rel_l"),console.log("begin rel_l"),78;case 63:case 64:return this.begin("rel_r"),console.log("begin rel_r"),79;case 65:return this.begin("rel_b"),console.log("begin rel_b"),80;case 66:return this.begin("rel_index"),console.log("begin rel_index"),81;case 67:return this.begin("update_el_style"),console.log("begin update_el_style"),82;case 68:return this.begin("update_rel_style"),console.log("begin update_rel_style"),83;case 69:return this.begin("update_layout_config"),console.log("begin update_layout_config"),84;case 70:return "EOF_IN_STRUCT";case 71:return console.log("begin attribute with ATTRIBUTE_EMPTY"),this.begin("attribute"),"ATTRIBUTE_EMPTY";case 72:console.log("begin attribute"),this.begin("attribute");break;case 73:console.log("STOP attribute"),this.popState(),console.log("STOP diagram"),this.popState();break;case 74:return console.log(",,"),90;case 75:console.log(",");break;case 76:return console.log("ATTRIBUTE_EMPTY"),90;case 77:console.log("begin string"),this.begin("string");break;case 78:console.log("STOP string"),this.popState();break;case 79:return console.log("STR"),"STR";case 80:console.log("begin string_kv"),this.begin("string_kv");break;case 81:return console.log("STR_KEY"),this.begin("string_kv_key"),"STR_KEY";case 82:console.log("begin string_kv_value"),this.popState(),this.begin("string_kv_value");break;case 83:return console.log("STR_VALUE"),"STR_VALUE";case 84:console.log("STOP string_kv_value"),this.popState(),this.popState();break;case 85:return console.log("not STR"),"STR";case 86:return console.log("begin boundary block"),"LBRACE";case 87:return console.log("STOP boundary block"),"RBRACE";case 88:return "SPACE";case 89:return "EOL";case 90:return 24}},rules:[/^(?:%%\{)/,/^(?:.*direction\s+TB[^\n]*)/,/^(?:.*direction\s+BT[^\n]*)/,/^(?:.*direction\s+RL[^\n]*)/,/^(?:.*direction\s+LR[^\n]*)/,/^(?:((?:(?!\}%%)[^:.])*))/,/^(?::)/,/^(?:\}%%)/,/^(?:((?:(?!\}%%).|\n)*))/,/^(?:title\s[^#\n;]+)/,/^(?:accDescription\s[^#\n;]+)/,/^(?:accTitle\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*\{\s*)/,/^(?:[\}])/,/^(?:[^\}]*)/,/^(?:%%(?!\{)*[^\n]*(\r?\n?)+)/,/^(?:%%[^\n]*(\r?\n)*)/,/^(?:\s*(\r?\n)+)/,/^(?:\s+)/,/^(?:C4Context\b)/,/^(?:C4Container\b)/,/^(?:C4Component\b)/,/^(?:C4Dynamic\b)/,/^(?:C4Deployment\b)/,/^(?:Person_Ext\b)/,/^(?:Person\b)/,/^(?:SystemQueue_Ext\b)/,/^(?:SystemDb_Ext\b)/,/^(?:System_Ext\b)/,/^(?:SystemQueue\b)/,/^(?:SystemDb\b)/,/^(?:System\b)/,/^(?:Boundary\b)/,/^(?:Enterprise_Boundary\b)/,/^(?:System_Boundary\b)/,/^(?:ContainerQueue_Ext\b)/,/^(?:ContainerDb_Ext\b)/,/^(?:Container_Ext\b)/,/^(?:ContainerQueue\b)/,/^(?:ContainerDb\b)/,/^(?:Container\b)/,/^(?:Container_Boundary\b)/,/^(?:ComponentQueue_Ext\b)/,/^(?:ComponentDb_Ext\b)/,/^(?:Component_Ext\b)/,/^(?:ComponentQueue\b)/,/^(?:ComponentDb\b)/,/^(?:Component\b)/,/^(?:Deployment_Node\b)/,/^(?:Node\b)/,/^(?:Node_L\b)/,/^(?:Node_R\b)/,/^(?:Rel\b)/,/^(?:BiRel\b)/,/^(?:Rel_Up\b)/,/^(?:Rel_U\b)/,/^(?:Rel_Down\b)/,/^(?:Rel_D\b)/,/^(?:Rel_Left\b)/,/^(?:Rel_L\b)/,/^(?:Rel_Right\b)/,/^(?:Rel_R\b)/,/^(?:Rel_Back\b)/,/^(?:RelIndex\b)/,/^(?:UpdateElementStyle\b)/,/^(?:UpdateRelStyle\b)/,/^(?:UpdateLayoutConfig\b)/,/^(?:$)/,/^(?:[(][ ]*[,])/,/^(?:[(])/,/^(?:[)])/,/^(?:,,)/,/^(?:,)/,/^(?:[ ]*["]["])/,/^(?:[ ]*["])/,/^(?:["])/,/^(?:[^"]*)/,/^(?:[ ]*[\$])/,/^(?:[^=]*)/,/^(?:[=][ ]*["])/,/^(?:[^"]+)/,/^(?:["])/,/^(?:[^,]+)/,/^(?:\{)/,/^(?:\})/,/^(?:[\s]+)/,/^(?:[\n\r]+)/,/^(?:$)/],conditions:{acc_descr_multiline:{rules:[16,17],inclusive:!1},acc_descr:{rules:[14],inclusive:!1},acc_title:{rules:[12],inclusive:!1},close_directive:{rules:[],inclusive:!1},arg_directive:{rules:[7,8],inclusive:!1},type_directive:{rules:[6,7],inclusive:!1},open_directive:{rules:[5],inclusive:!1},string_kv_value:{rules:[83,84],inclusive:!1},string_kv_key:{rules:[82],inclusive:!1},string_kv:{rules:[81],inclusive:!1},string:{rules:[78,79],inclusive:!1},attribute:{rules:[73,74,75,76,77,80,85],inclusive:!1},update_layout_config:{rules:[70,71,72,73],inclusive:!1},update_rel_style:{rules:[70,71,72,73],inclusive:!1},update_el_style:{rules:[70,71,72,73],inclusive:!1},rel_b:{rules:[70,71,72,73],inclusive:!1},rel_r:{rules:[70,71,72,73],inclusive:!1},rel_l:{rules:[70,71,72,73],inclusive:!1},rel_d:{rules:[70,71,72,73],inclusive:!1},rel_u:{rules:[70,71,72,73],inclusive:!1},rel_bi:{rules:[],inclusive:!1},rel:{rules:[70,71,72,73],inclusive:!1},node_r:{rules:[70,71,72,73],inclusive:!1},node_l:{rules:[70,71,72,73],inclusive:!1},node:{rules:[70,71,72,73],inclusive:!1},index:{rules:[],inclusive:!1},rel_index:{rules:[70,71,72,73],inclusive:!1},component_ext_queue:{rules:[],inclusive:!1},component_ext_db:{rules:[70,71,72,73],inclusive:!1},component_ext:{rules:[70,71,72,73],inclusive:!1},component_queue:{rules:[70,71,72,73],inclusive:!1},component_db:{rules:[70,71,72,73],inclusive:!1},component:{rules:[70,71,72,73],inclusive:!1},container_boundary:{rules:[70,71,72,73],inclusive:!1},container_ext_queue:{rules:[],inclusive:!1},container_ext_db:{rules:[70,71,72,73],inclusive:!1},container_ext:{rules:[70,71,72,73],inclusive:!1},container_queue:{rules:[70,71,72,73],inclusive:!1},container_db:{rules:[70,71,72,73],inclusive:!1},container:{rules:[70,71,72,73],inclusive:!1},birel:{rules:[70,71,72,73],inclusive:!1},system_boundary:{rules:[70,71,72,73],inclusive:!1},enterprise_boundary:{rules:[70,71,72,73],inclusive:!1},boundary:{rules:[70,71,72,73],inclusive:!1},system_ext_queue:{rules:[70,71,72,73],inclusive:!1},system_ext_db:{rules:[70,71,72,73],inclusive:!1},system_ext:{rules:[70,71,72,73],inclusive:!1},system_queue:{rules:[70,71,72,73],inclusive:!1},system_db:{rules:[70,71,72,73],inclusive:!1},system:{rules:[70,71,72,73],inclusive:!1},person_ext:{rules:[70,71,72,73],inclusive:!1},person:{rules:[70,71,72,73],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,9,10,11,13,15,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,86,87,88,89,90],inclusive:!0}}};function mt(){this.yy={};}return gt.lexer=yt,mt.prototype=gt,gt.Parser=mt,new mt}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(555).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1));},1362:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,3],n=[1,7],r=[1,8],i=[1,9],a=[1,10],o=[1,13],s=[1,12],c=[1,16,25],l=[1,20],u=[1,31],h=[1,32],f=[1,33],d=[1,35],p=[1,38],g=[1,36],y=[1,37],m=[1,39],b=[1,40],v=[1,41],_=[1,42],x=[1,45],k=[1,46],w=[1,47],T=[1,48],E=[16,25],C=[1,62],S=[1,63],A=[1,64],M=[1,65],N=[1,66],O=[1,67],D=[1,68],B=[16,25,32,44,45,53,56,57,58,59,60,61,62,67,69],L=[16,25,30,32,44,45,49,53,56,57,58,59,60,61,62,67,69,84,85,86,87],I=[5,8,9,10,11,16,19,23,25],F=[53,84,85,86,87],R=[53,61,62,84,85,86,87],P=[53,56,57,58,59,60,84,85,86,87],j=[16,25,32],z=[1,100],Y={trace:function(){},yy:{},symbols_:{error:2,start:3,mermaidDoc:4,statments:5,direction:6,directive:7,direction_tb:8,direction_bt:9,direction_rl:10,direction_lr:11,graphConfig:12,openDirective:13,typeDirective:14,closeDirective:15,NEWLINE:16,":":17,argDirective:18,open_directive:19,type_directive:20,arg_directive:21,close_directive:22,CLASS_DIAGRAM:23,statements:24,EOF:25,statement:26,className:27,alphaNumToken:28,classLiteralName:29,GENERICTYPE:30,relationStatement:31,LABEL:32,classStatement:33,methodStatement:34,annotationStatement:35,clickStatement:36,cssClassStatement:37,acc_title:38,acc_title_value:39,acc_descr:40,acc_descr_value:41,acc_descr_multiline_value:42,CLASS:43,STYLE_SEPARATOR:44,STRUCT_START:45,members:46,STRUCT_STOP:47,ANNOTATION_START:48,ANNOTATION_END:49,MEMBER:50,SEPARATOR:51,relation:52,STR:53,relationType:54,lineType:55,AGGREGATION:56,EXTENSION:57,COMPOSITION:58,DEPENDENCY:59,LOLLIPOP:60,LINE:61,DOTTED_LINE:62,CALLBACK:63,LINK:64,LINK_TARGET:65,CLICK:66,CALLBACK_NAME:67,CALLBACK_ARGS:68,HREF:69,CSSCLASS:70,commentToken:71,textToken:72,graphCodeTokens:73,textNoTagsToken:74,TAGSTART:75,TAGEND:76,"==":77,"--":78,PCT:79,DEFAULT:80,SPACE:81,MINUS:82,keywords:83,UNICODE_TEXT:84,NUM:85,ALPHA:86,BQUOTE_STR:87,$accept:0,$end:1},terminals_:{2:"error",5:"statments",8:"direction_tb",9:"direction_bt",10:"direction_rl",11:"direction_lr",16:"NEWLINE",17:":",19:"open_directive",20:"type_directive",21:"arg_directive",22:"close_directive",23:"CLASS_DIAGRAM",25:"EOF",30:"GENERICTYPE",32:"LABEL",38:"acc_title",39:"acc_title_value",40:"acc_descr",41:"acc_descr_value",42:"acc_descr_multiline_value",43:"CLASS",44:"STYLE_SEPARATOR",45:"STRUCT_START",47:"STRUCT_STOP",48:"ANNOTATION_START",49:"ANNOTATION_END",50:"MEMBER",51:"SEPARATOR",53:"STR",56:"AGGREGATION",57:"EXTENSION",58:"COMPOSITION",59:"DEPENDENCY",60:"LOLLIPOP",61:"LINE",62:"DOTTED_LINE",63:"CALLBACK",64:"LINK",65:"LINK_TARGET",66:"CLICK",67:"CALLBACK_NAME",68:"CALLBACK_ARGS",69:"HREF",70:"CSSCLASS",73:"graphCodeTokens",75:"TAGSTART",76:"TAGEND",77:"==",78:"--",79:"PCT",80:"DEFAULT",81:"SPACE",82:"MINUS",83:"keywords",84:"UNICODE_TEXT",85:"NUM",86:"ALPHA",87:"BQUOTE_STR"},productions_:[0,[3,1],[3,1],[3,1],[3,2],[6,1],[6,1],[6,1],[6,1],[4,1],[7,4],[7,6],[13,1],[14,1],[18,1],[15,1],[12,4],[24,1],[24,2],[24,3],[27,1],[27,1],[27,2],[27,2],[27,2],[26,1],[26,2],[26,1],[26,1],[26,1],[26,1],[26,1],[26,1],[26,1],[26,2],[26,2],[26,1],[33,2],[33,4],[33,5],[33,7],[35,4],[46,1],[46,2],[34,1],[34,2],[34,1],[34,1],[31,3],[31,4],[31,4],[31,5],[52,3],[52,2],[52,2],[52,1],[54,1],[54,1],[54,1],[54,1],[54,1],[55,1],[55,1],[36,3],[36,4],[36,3],[36,4],[36,4],[36,5],[36,3],[36,4],[36,4],[36,5],[36,3],[36,4],[36,4],[36,5],[37,3],[71,1],[71,1],[72,1],[72,1],[72,1],[72,1],[72,1],[72,1],[72,1],[74,1],[74,1],[74,1],[74,1],[28,1],[28,1],[28,1],[29,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 5:r.setDirection("TB");break;case 6:r.setDirection("BT");break;case 7:r.setDirection("RL");break;case 8:r.setDirection("LR");break;case 12:r.parseDirective("%%{","open_directive");break;case 13:r.parseDirective(a[s],"type_directive");break;case 14:a[s]=a[s].trim().replace(/'/g,'"'),r.parseDirective(a[s],"arg_directive");break;case 15:r.parseDirective("}%%","close_directive","class");break;case 20:case 21:this.$=a[s];break;case 22:this.$=a[s-1]+a[s];break;case 23:case 24:this.$=a[s-1]+"~"+a[s];break;case 25:r.addRelation(a[s]);break;case 26:a[s-1].title=r.cleanupLabel(a[s]),r.addRelation(a[s-1]);break;case 34:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 35:case 36:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 37:r.addClass(a[s]);break;case 38:r.addClass(a[s-2]),r.setCssClass(a[s-2],a[s]);break;case 39:r.addClass(a[s-3]),r.addMembers(a[s-3],a[s-1]);break;case 40:r.addClass(a[s-5]),r.setCssClass(a[s-5],a[s-3]),r.addMembers(a[s-5],a[s-1]);break;case 41:r.addAnnotation(a[s],a[s-2]);break;case 42:this.$=[a[s]];break;case 43:a[s].push(a[s-1]),this.$=a[s];break;case 44:case 46:case 47:break;case 45:r.addMember(a[s-1],r.cleanupLabel(a[s]));break;case 48:this.$={id1:a[s-2],id2:a[s],relation:a[s-1],relationTitle1:"none",relationTitle2:"none"};break;case 49:this.$={id1:a[s-3],id2:a[s],relation:a[s-1],relationTitle1:a[s-2],relationTitle2:"none"};break;case 50:this.$={id1:a[s-3],id2:a[s],relation:a[s-2],relationTitle1:"none",relationTitle2:a[s-1]};break;case 51:this.$={id1:a[s-4],id2:a[s],relation:a[s-2],relationTitle1:a[s-3],relationTitle2:a[s-1]};break;case 52:this.$={type1:a[s-2],type2:a[s],lineType:a[s-1]};break;case 53:this.$={type1:"none",type2:a[s],lineType:a[s-1]};break;case 54:this.$={type1:a[s-1],type2:"none",lineType:a[s]};break;case 55:this.$={type1:"none",type2:"none",lineType:a[s]};break;case 56:this.$=r.relationType.AGGREGATION;break;case 57:this.$=r.relationType.EXTENSION;break;case 58:this.$=r.relationType.COMPOSITION;break;case 59:this.$=r.relationType.DEPENDENCY;break;case 60:this.$=r.relationType.LOLLIPOP;break;case 61:this.$=r.lineType.LINE;break;case 62:this.$=r.lineType.DOTTED_LINE;break;case 63:case 69:this.$=a[s-2],r.setClickEvent(a[s-1],a[s]);break;case 64:case 70:this.$=a[s-3],r.setClickEvent(a[s-2],a[s-1]),r.setTooltip(a[s-2],a[s]);break;case 65:case 73:this.$=a[s-2],r.setLink(a[s-1],a[s]);break;case 66:case 74:this.$=a[s-3],r.setLink(a[s-2],a[s-1],a[s]);break;case 67:case 75:this.$=a[s-3],r.setLink(a[s-2],a[s-1]),r.setTooltip(a[s-2],a[s]);break;case 68:case 76:this.$=a[s-4],r.setLink(a[s-3],a[s-2],a[s]),r.setTooltip(a[s-3],a[s-1]);break;case 71:this.$=a[s-3],r.setClickEvent(a[s-2],a[s-1],a[s]);break;case 72:this.$=a[s-4],r.setClickEvent(a[s-3],a[s-2],a[s-1]),r.setTooltip(a[s-3],a[s]);break;case 77:r.setCssClass(a[s-1],a[s]);}},table:[{3:1,4:2,5:e,6:4,7:5,8:n,9:r,10:i,11:a,12:6,13:11,19:o,23:s},{1:[3]},{1:[2,1]},{1:[2,2]},{1:[2,3]},{3:14,4:2,5:e,6:4,7:5,8:n,9:r,10:i,11:a,12:6,13:11,19:o,23:s},{1:[2,9]},t(c,[2,5]),t(c,[2,6]),t(c,[2,7]),t(c,[2,8]),{14:15,20:[1,16]},{16:[1,17]},{20:[2,12]},{1:[2,4]},{15:18,17:[1,19],22:l},t([17,22],[2,13]),{6:30,7:29,8:n,9:r,10:i,11:a,13:11,19:o,24:21,26:22,27:34,28:43,29:44,31:23,33:24,34:25,35:26,36:27,37:28,38:u,40:h,42:f,43:d,48:p,50:g,51:y,63:m,64:b,66:v,70:_,84:x,85:k,86:w,87:T},{16:[1,49]},{18:50,21:[1,51]},{16:[2,15]},{25:[1,52]},{16:[1,53],25:[2,17]},t(E,[2,25],{32:[1,54]}),t(E,[2,27]),t(E,[2,28]),t(E,[2,29]),t(E,[2,30]),t(E,[2,31]),t(E,[2,32]),t(E,[2,33]),{39:[1,55]},{41:[1,56]},t(E,[2,36]),t(E,[2,44],{52:57,54:60,55:61,32:[1,59],53:[1,58],56:C,57:S,58:A,59:M,60:N,61:O,62:D}),{27:69,28:43,29:44,84:x,85:k,86:w,87:T},t(E,[2,46]),t(E,[2,47]),{28:70,84:x,85:k,86:w},{27:71,28:43,29:44,84:x,85:k,86:w,87:T},{27:72,28:43,29:44,84:x,85:k,86:w,87:T},{27:73,28:43,29:44,84:x,85:k,86:w,87:T},{53:[1,74]},t(B,[2,20],{28:43,29:44,27:75,30:[1,76],84:x,85:k,86:w,87:T}),t(B,[2,21],{30:[1,77]}),t(L,[2,91]),t(L,[2,92]),t(L,[2,93]),t([16,25,30,32,44,45,53,56,57,58,59,60,61,62,67,69],[2,94]),t(I,[2,10]),{15:78,22:l},{22:[2,14]},{1:[2,16]},{6:30,7:29,8:n,9:r,10:i,11:a,13:11,19:o,24:79,25:[2,18],26:22,27:34,28:43,29:44,31:23,33:24,34:25,35:26,36:27,37:28,38:u,40:h,42:f,43:d,48:p,50:g,51:y,63:m,64:b,66:v,70:_,84:x,85:k,86:w,87:T},t(E,[2,26]),t(E,[2,34]),t(E,[2,35]),{27:80,28:43,29:44,53:[1,81],84:x,85:k,86:w,87:T},{52:82,54:60,55:61,56:C,57:S,58:A,59:M,60:N,61:O,62:D},t(E,[2,45]),{55:83,61:O,62:D},t(F,[2,55],{54:84,56:C,57:S,58:A,59:M,60:N}),t(R,[2,56]),t(R,[2,57]),t(R,[2,58]),t(R,[2,59]),t(R,[2,60]),t(P,[2,61]),t(P,[2,62]),t(E,[2,37],{44:[1,85],45:[1,86]}),{49:[1,87]},{53:[1,88]},{53:[1,89]},{67:[1,90],69:[1,91]},{28:92,84:x,85:k,86:w},t(B,[2,22]),t(B,[2,23]),t(B,[2,24]),{16:[1,93]},{25:[2,19]},t(j,[2,48]),{27:94,28:43,29:44,84:x,85:k,86:w,87:T},{27:95,28:43,29:44,53:[1,96],84:x,85:k,86:w,87:T},t(F,[2,54],{54:97,56:C,57:S,58:A,59:M,60:N}),t(F,[2,53]),{28:98,84:x,85:k,86:w},{46:99,50:z},{27:101,28:43,29:44,84:x,85:k,86:w,87:T},t(E,[2,63],{53:[1,102]}),t(E,[2,65],{53:[1,104],65:[1,103]}),t(E,[2,69],{53:[1,105],68:[1,106]}),t(E,[2,73],{53:[1,108],65:[1,107]}),t(E,[2,77]),t(I,[2,11]),t(j,[2,50]),t(j,[2,49]),{27:109,28:43,29:44,84:x,85:k,86:w,87:T},t(F,[2,52]),t(E,[2,38],{45:[1,110]}),{47:[1,111]},{46:112,47:[2,42],50:z},t(E,[2,41]),t(E,[2,64]),t(E,[2,66]),t(E,[2,67],{65:[1,113]}),t(E,[2,70]),t(E,[2,71],{53:[1,114]}),t(E,[2,74]),t(E,[2,75],{65:[1,115]}),t(j,[2,51]),{46:116,50:z},t(E,[2,39]),{47:[2,43]},t(E,[2,68]),t(E,[2,72]),t(E,[2,76]),{47:[1,117]},t(E,[2,40])],defaultActions:{2:[2,1],3:[2,2],4:[2,3],6:[2,9],13:[2,12],14:[2,4],20:[2,15],51:[2,14],52:[2,16],79:[2,19],112:[2,43]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t);},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,l=0,u=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var b=p.options&&p.options.ranges;function v(){var t;return "number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,k,w,T,E,C,S,A,M={};;){if(k=n[n.length-1],this.defaultActions[k]?w=this.defaultActions[k]:(null==_&&(_=v()),w=o[k]&&o[k][_]),void 0===w||!w.length||!w[0]){var N="";for(E in A=[],o[k])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A});}if(w[0]instanceof Array&&w.length>1)throw new Error("Parse Error: multiple actions possible at state: "+k+", token: "+_);switch(w[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(w[1]),_=null,x?(_=x,x=null):(l=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,u>0&&u--);break;case 2:if(C=this.productions_[w[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},b&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,l,c,g.yy,w[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[w[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return !0}}return !0}},U={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e);},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t));},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return (t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return !1}return !1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;a<i.length;a++)if((n=this._input.match(this.rules[i[a]]))&&(!e||n[0].length>e[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return !1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t);},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return (t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t);},stateStackSize:function(){return this.conditionStack.length},options:{},performAction:function(t,e,n,r){switch(n){case 0:return this.begin("open_directive"),19;case 1:return 8;case 2:return 9;case 3:return 10;case 4:return 11;case 5:return this.begin("type_directive"),20;case 6:return this.popState(),this.begin("arg_directive"),17;case 7:return this.popState(),this.popState(),22;case 8:return 21;case 9:case 10:case 19:case 27:break;case 11:return this.begin("acc_title"),38;case 12:return this.popState(),"acc_title_value";case 13:return this.begin("acc_descr"),40;case 14:return this.popState(),"acc_descr_value";case 15:this.begin("acc_descr_multiline");break;case 16:case 37:case 40:case 43:case 46:case 49:case 52:this.popState();break;case 17:return "acc_descr_multiline_value";case 18:return 16;case 20:case 21:return 23;case 22:return this.begin("struct"),45;case 23:return "EDGE_STATE";case 24:return "EOF_IN_STRUCT";case 25:return "OPEN_IN_STRUCT";case 26:return this.popState(),47;case 28:return "MEMBER";case 29:return 43;case 30:return 70;case 31:return 63;case 32:return 64;case 33:return 66;case 34:return 48;case 35:return 49;case 36:this.begin("generic");break;case 38:return "GENERICTYPE";case 39:this.begin("string");break;case 41:return "STR";case 42:this.begin("bqstring");break;case 44:return "BQUOTE_STR";case 45:this.begin("href");break;case 47:return 69;case 48:this.begin("callback_name");break;case 50:this.popState(),this.begin("callback_args");break;case 51:return 67;case 53:return 68;case 54:case 55:case 56:case 57:return 65;case 58:case 59:return 57;case 60:case 61:return 59;case 62:return 58;case 63:return 56;case 64:return 60;case 65:return 61;case 66:return 62;case 67:return 32;case 68:return 44;case 69:return 82;case 70:return "DOT";case 71:return "PLUS";case 72:return 79;case 73:case 74:return "EQUALS";case 75:return 86;case 76:return "PUNCTUATION";case 77:return 85;case 78:return 84;case 79:return 81;case 80:return 25}},rules:[/^(?:%%\{)/,/^(?:.*direction\s+TB[^\n]*)/,/^(?:.*direction\s+BT[^\n]*)/,/^(?:.*direction\s+RL[^\n]*)/,/^(?:.*direction\s+LR[^\n]*)/,/^(?:((?:(?!\}%%)[^:.])*))/,/^(?::)/,/^(?:\}%%)/,/^(?:((?:(?!\}%%).|\n)*))/,/^(?:%%(?!\{)*[^\n]*(\r?\n?)+)/,/^(?:%%[^\n]*(\r?\n)*)/,/^(?:accTitle\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*\{\s*)/,/^(?:[\}])/,/^(?:[^\}]*)/,/^(?:\s*(\r?\n)+)/,/^(?:\s+)/,/^(?:classDiagram-v2\b)/,/^(?:classDiagram\b)/,/^(?:[{])/,/^(?:\[\*\])/,/^(?:$)/,/^(?:[{])/,/^(?:[}])/,/^(?:[\n])/,/^(?:[^{}\n]*)/,/^(?:class\b)/,/^(?:cssClass\b)/,/^(?:callback\b)/,/^(?:link\b)/,/^(?:click\b)/,/^(?:<<)/,/^(?:>>)/,/^(?:[~])/,/^(?:[~])/,/^(?:[^~]*)/,/^(?:["])/,/^(?:["])/,/^(?:[^"]*)/,/^(?:[`])/,/^(?:[`])/,/^(?:[^`]+)/,/^(?:href[\s]+["])/,/^(?:["])/,/^(?:[^"]*)/,/^(?:call[\s]+)/,/^(?:\([\s]*\))/,/^(?:\()/,/^(?:[^(]*)/,/^(?:\))/,/^(?:[^)]*)/,/^(?:_self\b)/,/^(?:_blank\b)/,/^(?:_parent\b)/,/^(?:_top\b)/,/^(?:\s*<\|)/,/^(?:\s*\|>)/,/^(?:\s*>)/,/^(?:\s*<)/,/^(?:\s*\*)/,/^(?:\s*o\b)/,/^(?:\s*\(\))/,/^(?:--)/,/^(?:\.\.)/,/^(?::{1}[^:\n;]+)/,/^(?::{3})/,/^(?:-)/,/^(?:\.)/,/^(?:\+)/,/^(?:%)/,/^(?:=)/,/^(?:=)/,/^(?:\w+)/,/^(?:[!"#$%&'*+,-.`?\\/])/,/^(?:[0-9]+)/,/^(?:[\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6]|[\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377]|[\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5]|[\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA]|[\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE]|[\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA]|[\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0]|[\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977]|[\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2]|[\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A]|[\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39]|[\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8]|[\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C]|[\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C]|[\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99]|[\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0]|[\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D]|[\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3]|[\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10]|[\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1]|[\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81]|[\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3]|[\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6]|[\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A]|[\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081]|[\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D]|[\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0]|[\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310]|[\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C]|[\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711]|[\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7]|[\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C]|[\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16]|[\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF]|[\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC]|[\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D]|[\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D]|[\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3]|[\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F]|[\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128]|[\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184]|[\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3]|[\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6]|[\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE]|[\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C]|[\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D]|[\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC]|[\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B]|[\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788]|[\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805]|[\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB]|[\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28]|[\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5]|[\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4]|[\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E]|[\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D]|[\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36]|[\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D]|[\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC]|[\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF]|[\uFFD2-\uFFD7\uFFDA-\uFFDC])/,/^(?:\s)/,/^(?:$)/],conditions:{acc_descr_multiline:{rules:[16,17],inclusive:!1},acc_descr:{rules:[14],inclusive:!1},acc_title:{rules:[12],inclusive:!1},arg_directive:{rules:[7,8],inclusive:!1},type_directive:{rules:[6,7],inclusive:!1},open_directive:{rules:[5],inclusive:!1},callback_args:{rules:[52,53],inclusive:!1},callback_name:{rules:[49,50,51],inclusive:!1},href:{rules:[46,47],inclusive:!1},struct:{rules:[23,24,25,26,27,28],inclusive:!1},generic:{rules:[37,38],inclusive:!1},bqstring:{rules:[43,44],inclusive:!1},string:{rules:[40,41],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,9,10,11,13,15,18,19,20,21,22,23,29,30,31,32,33,34,35,36,39,42,45,48,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80],inclusive:!0}}};function $(){this.yy={};}return Y.lexer=U,$.prototype=Y,Y.Parser=$,new $}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(8218).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1));},5890:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,2],n=[1,5],r=[6,9,11,23,25,27,29,30,49],i=[1,17],a=[1,18],o=[1,19],s=[1,20],c=[1,21],l=[1,24],u=[1,29],h=[1,30],f=[1,31],d=[1,32],p=[6,9,11,15,20,23,25,27,29,30,42,43,44,45,49],g=[1,45],y=[30,46,47],m=[4,6,9,11,23,25,27,29,30,49],b=[42,43,44,45],v=[22,37],_=[1,64],x={trace:function(){},yy:{},symbols_:{error:2,start:3,ER_DIAGRAM:4,document:5,EOF:6,directive:7,line:8,SPACE:9,statement:10,NEWLINE:11,openDirective:12,typeDirective:13,closeDirective:14,":":15,argDirective:16,entityName:17,relSpec:18,role:19,BLOCK_START:20,attributes:21,BLOCK_STOP:22,title:23,title_value:24,acc_title:25,acc_title_value:26,acc_descr:27,acc_descr_value:28,acc_descr_multiline_value:29,ALPHANUM:30,".":31,attribute:32,attributeType:33,attributeName:34,attributeKeyType:35,attributeComment:36,ATTRIBUTE_WORD:37,ATTRIBUTE_KEY:38,COMMENT:39,cardinality:40,relType:41,ZERO_OR_ONE:42,ZERO_OR_MORE:43,ONE_OR_MORE:44,ONLY_ONE:45,NON_IDENTIFYING:46,IDENTIFYING:47,WORD:48,open_directive:49,type_directive:50,arg_directive:51,close_directive:52,$accept:0,$end:1},terminals_:{2:"error",4:"ER_DIAGRAM",6:"EOF",9:"SPACE",11:"NEWLINE",15:":",20:"BLOCK_START",22:"BLOCK_STOP",23:"title",24:"title_value",25:"acc_title",26:"acc_title_value",27:"acc_descr",28:"acc_descr_value",29:"acc_descr_multiline_value",30:"ALPHANUM",31:".",37:"ATTRIBUTE_WORD",38:"ATTRIBUTE_KEY",39:"COMMENT",42:"ZERO_OR_ONE",43:"ZERO_OR_MORE",44:"ONE_OR_MORE",45:"ONLY_ONE",46:"NON_IDENTIFYING",47:"IDENTIFYING",48:"WORD",49:"open_directive",50:"type_directive",51:"arg_directive",52:"close_directive"},productions_:[0,[3,3],[3,2],[5,0],[5,2],[8,2],[8,1],[8,1],[8,1],[7,4],[7,6],[10,1],[10,5],[10,4],[10,3],[10,1],[10,2],[10,2],[10,2],[10,1],[17,1],[17,3],[21,1],[21,2],[32,2],[32,3],[32,3],[32,4],[33,1],[34,1],[35,1],[36,1],[18,3],[40,1],[40,1],[40,1],[40,1],[41,1],[41,1],[19,1],[19,1],[12,1],[13,1],[16,1],[14,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 1:break;case 3:case 7:case 8:this.$=[];break;case 4:a[s-1].push(a[s]),this.$=a[s-1];break;case 5:case 6:case 20:case 28:case 29:case 30:case 40:this.$=a[s];break;case 12:r.addEntity(a[s-4]),r.addEntity(a[s-2]),r.addRelationship(a[s-4],a[s],a[s-2],a[s-3]);break;case 13:r.addEntity(a[s-3]),r.addAttributes(a[s-3],a[s-1]);break;case 14:r.addEntity(a[s-2]);break;case 15:r.addEntity(a[s]);break;case 16:case 17:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 18:case 19:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 21:this.$=a[s-2]+a[s-1]+a[s];break;case 22:this.$=[a[s]];break;case 23:a[s].push(a[s-1]),this.$=a[s];break;case 24:this.$={attributeType:a[s-1],attributeName:a[s]};break;case 25:this.$={attributeType:a[s-2],attributeName:a[s-1],attributeKeyType:a[s]};break;case 26:this.$={attributeType:a[s-2],attributeName:a[s-1],attributeComment:a[s]};break;case 27:this.$={attributeType:a[s-3],attributeName:a[s-2],attributeKeyType:a[s-1],attributeComment:a[s]};break;case 31:case 39:this.$=a[s].replace(/"/g,"");break;case 32:this.$={cardA:a[s],relType:a[s-1],cardB:a[s-2]};break;case 33:this.$=r.Cardinality.ZERO_OR_ONE;break;case 34:this.$=r.Cardinality.ZERO_OR_MORE;break;case 35:this.$=r.Cardinality.ONE_OR_MORE;break;case 36:this.$=r.Cardinality.ONLY_ONE;break;case 37:this.$=r.Identification.NON_IDENTIFYING;break;case 38:this.$=r.Identification.IDENTIFYING;break;case 41:r.parseDirective("%%{","open_directive");break;case 42:r.parseDirective(a[s],"type_directive");break;case 43:a[s]=a[s].trim().replace(/'/g,'"'),r.parseDirective(a[s],"arg_directive");break;case 44:r.parseDirective("}%%","close_directive","er");}},table:[{3:1,4:e,7:3,12:4,49:n},{1:[3]},t(r,[2,3],{5:6}),{3:7,4:e,7:3,12:4,49:n},{13:8,50:[1,9]},{50:[2,41]},{6:[1,10],7:15,8:11,9:[1,12],10:13,11:[1,14],12:4,17:16,23:i,25:a,27:o,29:s,30:c,49:n},{1:[2,2]},{14:22,15:[1,23],52:l},t([15,52],[2,42]),t(r,[2,8],{1:[2,1]}),t(r,[2,4]),{7:15,10:25,12:4,17:16,23:i,25:a,27:o,29:s,30:c,49:n},t(r,[2,6]),t(r,[2,7]),t(r,[2,11]),t(r,[2,15],{18:26,40:28,20:[1,27],42:u,43:h,44:f,45:d}),{24:[1,33]},{26:[1,34]},{28:[1,35]},t(r,[2,19]),t(p,[2,20],{31:[1,36]}),{11:[1,37]},{16:38,51:[1,39]},{11:[2,44]},t(r,[2,5]),{17:40,30:c},{21:41,22:[1,42],32:43,33:44,37:g},{41:46,46:[1,47],47:[1,48]},t(y,[2,33]),t(y,[2,34]),t(y,[2,35]),t(y,[2,36]),t(r,[2,16]),t(r,[2,17]),t(r,[2,18]),{17:49,30:c},t(m,[2,9]),{14:50,52:l},{52:[2,43]},{15:[1,51]},{22:[1,52]},t(r,[2,14]),{21:53,22:[2,22],32:43,33:44,37:g},{34:54,37:[1,55]},{37:[2,28]},{40:56,42:u,43:h,44:f,45:d},t(b,[2,37]),t(b,[2,38]),t(p,[2,21]),{11:[1,57]},{19:58,30:[1,60],48:[1,59]},t(r,[2,13]),{22:[2,23]},t(v,[2,24],{35:61,36:62,38:[1,63],39:_}),t([22,37,38,39],[2,29]),{30:[2,32]},t(m,[2,10]),t(r,[2,12]),t(r,[2,39]),t(r,[2,40]),t(v,[2,25],{36:65,39:_}),t(v,[2,26]),t([22,37,39],[2,30]),t(v,[2,31]),t(v,[2,27])],defaultActions:{5:[2,41],7:[2,2],24:[2,44],39:[2,43],45:[2,28],53:[2,23],56:[2,32]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t);},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,l=0,u=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var b=p.options&&p.options.ranges;function v(){var t;return "number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,k,w,T,E,C,S,A,M={};;){if(k=n[n.length-1],this.defaultActions[k]?w=this.defaultActions[k]:(null==_&&(_=v()),w=o[k]&&o[k][_]),void 0===w||!w.length||!w[0]){var N="";for(E in A=[],o[k])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A});}if(w[0]instanceof Array&&w.length>1)throw new Error("Parse Error: multiple actions possible at state: "+k+", token: "+_);switch(w[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(w[1]),_=null,x?(_=x,x=null):(l=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,u>0&&u--);break;case 2:if(C=this.productions_[w[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},b&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,l,c,g.yy,w[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[w[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return !0}}return !0}},k={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e);},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t));},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return (t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return !1}return !1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;a<i.length;a++)if((n=this._input.match(this.rules[i[a]]))&&(!e||n[0].length>e[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return !1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t);},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return (t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t);},stateStackSize:function(){return this.conditionStack.length},options:{"case-insensitive":!0},performAction:function(t,e,n,r){switch(n){case 0:return this.begin("acc_title"),25;case 1:return this.popState(),"acc_title_value";case 2:return this.begin("acc_descr"),27;case 3:return this.popState(),"acc_descr_value";case 4:this.begin("acc_descr_multiline");break;case 5:this.popState();break;case 6:return "acc_descr_multiline_value";case 7:return this.begin("open_directive"),49;case 8:return this.begin("type_directive"),50;case 9:return this.popState(),this.begin("arg_directive"),15;case 10:return this.popState(),this.popState(),52;case 11:return 51;case 12:case 13:case 15:case 20:case 25:break;case 14:return 11;case 16:return 9;case 17:return 48;case 18:return 4;case 19:return this.begin("block"),20;case 21:return 38;case 22:case 23:return 37;case 24:return 39;case 26:return this.popState(),22;case 27:case 40:return e.yytext[0];case 28:case 32:return 42;case 29:case 33:return 43;case 30:case 34:return 44;case 31:return 45;case 35:case 37:case 38:return 46;case 36:return 47;case 39:return 30;case 41:return 6}},rules:[/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:%%\{)/i,/^(?:((?:(?!\}%%)[^:.])*))/i,/^(?::)/i,/^(?:\}%%)/i,/^(?:((?:(?!\}%%).|\n)*))/i,/^(?:%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[\n]+)/i,/^(?:\s+)/i,/^(?:[\s]+)/i,/^(?:"[^"]*")/i,/^(?:erDiagram\b)/i,/^(?:\{)/i,/^(?:\s+)/i,/^(?:\b((?:PK)|(?:FK))\b)/i,/^(?:(.*?)[~](.*?)*[~])/i,/^(?:[A-Za-z][A-Za-z0-9\-_\[\]]*)/i,/^(?:"[^"]*")/i,/^(?:[\n]+)/i,/^(?:\})/i,/^(?:.)/i,/^(?:\|o\b)/i,/^(?:\}o\b)/i,/^(?:\}\|)/i,/^(?:\|\|)/i,/^(?:o\|)/i,/^(?:o\{)/i,/^(?:\|\{)/i,/^(?:\.\.)/i,/^(?:--)/i,/^(?:\.-)/i,/^(?:-\.)/i,/^(?:[A-Za-z][A-Za-z0-9\-_]*)/i,/^(?:.)/i,/^(?:$)/i],conditions:{acc_descr_multiline:{rules:[5,6],inclusive:!1},acc_descr:{rules:[3],inclusive:!1},acc_title:{rules:[1],inclusive:!1},open_directive:{rules:[8],inclusive:!1},type_directive:{rules:[9,10],inclusive:!1},arg_directive:{rules:[10,11],inclusive:!1},block:{rules:[20,21,22,23,24,25,26,27],inclusive:!1},INITIAL:{rules:[0,2,4,7,12,13,14,15,16,17,18,19,28,29,30,31,32,33,34,35,36,37,38,39,40,41],inclusive:!0}}};function w(){this.yy={};}return x.lexer=k,w.prototype=x,x.Parser=w,new w}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(8009).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1));},3602:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,9],n=[1,7],r=[1,6],i=[1,8],a=[1,20,21,22,23,38,44,46,48,52,66,67,86,87,88,89,90,91,95,105,106,109,111,112,118,119,120,121,122,123,124,125,126,127],o=[2,10],s=[1,20],c=[1,21],l=[1,22],u=[1,23],h=[1,30],f=[1,32],d=[1,33],p=[1,34],g=[1,62],y=[1,48],m=[1,52],b=[1,36],v=[1,37],_=[1,38],x=[1,39],k=[1,40],w=[1,56],T=[1,63],E=[1,51],C=[1,53],S=[1,55],A=[1,59],M=[1,60],N=[1,41],O=[1,42],D=[1,43],B=[1,44],L=[1,61],I=[1,50],F=[1,54],R=[1,57],P=[1,58],j=[1,49],z=[1,66],Y=[1,71],U=[1,20,21,22,23,38,42,44,46,48,52,66,67,86,87,88,89,90,91,95,105,106,109,111,112,118,119,120,121,122,123,124,125,126,127],$=[1,75],W=[1,74],q=[1,76],H=[20,21,23,81,82],V=[1,99],G=[1,104],X=[1,107],Z=[1,108],Q=[1,101],K=[1,106],J=[1,109],tt=[1,102],et=[1,114],nt=[1,113],rt=[1,103],it=[1,105],at=[1,110],ot=[1,111],st=[1,112],ct=[1,115],lt=[20,21,22,23,81,82],ut=[20,21,22,23,53,81,82],ht=[20,21,22,23,40,52,53,55,57,59,61,63,65,66,67,69,71,73,74,76,81,82,91,95,105,106,109,111,112,122,123,124,125,126,127],ft=[20,21,23],dt=[20,21,23,52,66,67,81,82,91,95,105,106,109,111,112,122,123,124,125,126,127],pt=[1,12,20,21,22,23,24,38,42,44,46,48,52,66,67,86,87,88,89,90,91,95,105,106,109,111,112,118,119,120,121,122,123,124,125,126,127],gt=[52,66,67,91,95,105,106,109,111,112,122,123,124,125,126,127],yt=[1,149],mt=[1,157],bt=[1,158],vt=[1,159],_t=[1,160],xt=[1,144],kt=[1,145],wt=[1,141],Tt=[1,152],Et=[1,153],Ct=[1,154],St=[1,155],At=[1,156],Mt=[1,161],Nt=[1,162],Ot=[1,147],Dt=[1,150],Bt=[1,146],Lt=[1,143],It=[20,21,22,23,38,42,44,46,48,52,66,67,86,87,88,89,90,91,95,105,106,109,111,112,118,119,120,121,122,123,124,125,126,127],Ft=[1,165],Rt=[20,21,22,23,26,52,66,67,91,105,106,109,111,112,122,123,124,125,126,127],Pt=[20,21,22,23,24,26,38,40,41,42,52,56,58,60,62,64,66,67,68,70,72,73,75,77,81,82,86,87,88,89,90,91,92,95,105,106,109,111,112,113,114,122,123,124,125,126,127],jt=[12,21,22,24],zt=[22,106],Yt=[1,250],Ut=[1,245],$t=[1,246],Wt=[1,254],qt=[1,251],Ht=[1,248],Vt=[1,247],Gt=[1,249],Xt=[1,252],Zt=[1,253],Qt=[1,255],Kt=[1,273],Jt=[20,21,23,106],te=[20,21,22,23,66,67,86,102,105,106,109,110,111,112,113],ee={trace:function(){},yy:{},symbols_:{error:2,start:3,mermaidDoc:4,directive:5,openDirective:6,typeDirective:7,closeDirective:8,separator:9,":":10,argDirective:11,open_directive:12,type_directive:13,arg_directive:14,close_directive:15,graphConfig:16,document:17,line:18,statement:19,SEMI:20,NEWLINE:21,SPACE:22,EOF:23,GRAPH:24,NODIR:25,DIR:26,FirstStmtSeperator:27,ending:28,endToken:29,spaceList:30,spaceListNewline:31,verticeStatement:32,styleStatement:33,linkStyleStatement:34,classDefStatement:35,classStatement:36,clickStatement:37,subgraph:38,text:39,SQS:40,SQE:41,end:42,direction:43,acc_title:44,acc_title_value:45,acc_descr:46,acc_descr_value:47,acc_descr_multiline_value:48,link:49,node:50,vertex:51,AMP:52,STYLE_SEPARATOR:53,idString:54,DOUBLECIRCLESTART:55,DOUBLECIRCLEEND:56,PS:57,PE:58,"(-":59,"-)":60,STADIUMSTART:61,STADIUMEND:62,SUBROUTINESTART:63,SUBROUTINEEND:64,VERTEX_WITH_PROPS_START:65,ALPHA:66,COLON:67,PIPE:68,CYLINDERSTART:69,CYLINDEREND:70,DIAMOND_START:71,DIAMOND_STOP:72,TAGEND:73,TRAPSTART:74,TRAPEND:75,INVTRAPSTART:76,INVTRAPEND:77,linkStatement:78,arrowText:79,TESTSTR:80,START_LINK:81,LINK:82,textToken:83,STR:84,keywords:85,STYLE:86,LINKSTYLE:87,CLASSDEF:88,CLASS:89,CLICK:90,DOWN:91,UP:92,textNoTags:93,textNoTagsToken:94,DEFAULT:95,stylesOpt:96,alphaNum:97,CALLBACKNAME:98,CALLBACKARGS:99,HREF:100,LINK_TARGET:101,HEX:102,numList:103,INTERPOLATE:104,NUM:105,COMMA:106,style:107,styleComponent:108,MINUS:109,UNIT:110,BRKT:111,DOT:112,PCT:113,TAGSTART:114,alphaNumToken:115,idStringToken:116,alphaNumStatement:117,direction_tb:118,direction_bt:119,direction_rl:120,direction_lr:121,PUNCTUATION:122,UNICODE_TEXT:123,PLUS:124,EQUALS:125,MULT:126,UNDERSCORE:127,graphCodeTokens:128,ARROW_CROSS:129,ARROW_POINT:130,ARROW_CIRCLE:131,ARROW_OPEN:132,QUOTE:133,$accept:0,$end:1},terminals_:{2:"error",10:":",12:"open_directive",13:"type_directive",14:"arg_directive",15:"close_directive",20:"SEMI",21:"NEWLINE",22:"SPACE",23:"EOF",24:"GRAPH",25:"NODIR",26:"DIR",38:"subgraph",40:"SQS",41:"SQE",42:"end",44:"acc_title",45:"acc_title_value",46:"acc_descr",47:"acc_descr_value",48:"acc_descr_multiline_value",52:"AMP",53:"STYLE_SEPARATOR",55:"DOUBLECIRCLESTART",56:"DOUBLECIRCLEEND",57:"PS",58:"PE",59:"(-",60:"-)",61:"STADIUMSTART",62:"STADIUMEND",63:"SUBROUTINESTART",64:"SUBROUTINEEND",65:"VERTEX_WITH_PROPS_START",66:"ALPHA",67:"COLON",68:"PIPE",69:"CYLINDERSTART",70:"CYLINDEREND",71:"DIAMOND_START",72:"DIAMOND_STOP",73:"TAGEND",74:"TRAPSTART",75:"TRAPEND",76:"INVTRAPSTART",77:"INVTRAPEND",80:"TESTSTR",81:"START_LINK",82:"LINK",84:"STR",86:"STYLE",87:"LINKSTYLE",88:"CLASSDEF",89:"CLASS",90:"CLICK",91:"DOWN",92:"UP",95:"DEFAULT",98:"CALLBACKNAME",99:"CALLBACKARGS",100:"HREF",101:"LINK_TARGET",102:"HEX",104:"INTERPOLATE",105:"NUM",106:"COMMA",109:"MINUS",110:"UNIT",111:"BRKT",112:"DOT",113:"PCT",114:"TAGSTART",118:"direction_tb",119:"direction_bt",120:"direction_rl",121:"direction_lr",122:"PUNCTUATION",123:"UNICODE_TEXT",124:"PLUS",125:"EQUALS",126:"MULT",127:"UNDERSCORE",129:"ARROW_CROSS",130:"ARROW_POINT",131:"ARROW_CIRCLE",132:"ARROW_OPEN",133:"QUOTE"},productions_:[0,[3,1],[3,2],[5,4],[5,6],[6,1],[7,1],[11,1],[8,1],[4,2],[17,0],[17,2],[18,1],[18,1],[18,1],[18,1],[18,1],[16,2],[16,2],[16,2],[16,3],[28,2],[28,1],[29,1],[29,1],[29,1],[27,1],[27,1],[27,2],[31,2],[31,2],[31,1],[31,1],[30,2],[30,1],[19,2],[19,2],[19,2],[19,2],[19,2],[19,2],[19,9],[19,6],[19,4],[19,1],[19,2],[19,2],[19,1],[9,1],[9,1],[9,1],[32,3],[32,4],[32,2],[32,1],[50,1],[50,5],[50,3],[51,4],[51,4],[51,6],[51,4],[51,4],[51,4],[51,8],[51,4],[51,4],[51,4],[51,6],[51,4],[51,4],[51,4],[51,4],[51,4],[51,1],[49,2],[49,3],[49,3],[49,1],[49,3],[78,1],[79,3],[39,1],[39,2],[39,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[93,1],[93,2],[35,5],[35,5],[36,5],[37,2],[37,4],[37,3],[37,5],[37,2],[37,4],[37,4],[37,6],[37,2],[37,4],[37,2],[37,4],[37,4],[37,6],[33,5],[33,5],[34,5],[34,5],[34,9],[34,9],[34,7],[34,7],[103,1],[103,3],[96,1],[96,3],[107,1],[107,2],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[83,1],[83,1],[83,1],[83,1],[83,1],[83,1],[94,1],[94,1],[94,1],[94,1],[54,1],[54,2],[97,1],[97,2],[117,1],[117,1],[117,1],[117,1],[43,1],[43,1],[43,1],[43,1],[115,1],[115,1],[115,1],[115,1],[115,1],[115,1],[115,1],[115,1],[115,1],[115,1],[115,1],[115,1],[115,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[116,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1],[128,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 5:r.parseDirective("%%{","open_directive");break;case 6:r.parseDirective(a[s],"type_directive");break;case 7:a[s]=a[s].trim().replace(/'/g,'"'),r.parseDirective(a[s],"arg_directive");break;case 8:r.parseDirective("}%%","close_directive","flowchart");break;case 10:case 36:case 37:case 38:case 39:case 40:this.$=[];break;case 11:a[s]!==[]&&a[s-1].push(a[s]),this.$=a[s-1];break;case 12:case 82:case 84:case 96:case 152:case 154:case 155:case 78:case 150:this.$=a[s];break;case 19:r.setDirection("TB"),this.$="TB";break;case 20:r.setDirection(a[s-1]),this.$=a[s-1];break;case 35:this.$=a[s-1].nodes;break;case 41:this.$=r.addSubGraph(a[s-6],a[s-1],a[s-4]);break;case 42:this.$=r.addSubGraph(a[s-3],a[s-1],a[s-3]);break;case 43:this.$=r.addSubGraph(void 0,a[s-1],void 0);break;case 45:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 46:case 47:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 51:r.addLink(a[s-2].stmt,a[s],a[s-1]),this.$={stmt:a[s],nodes:a[s].concat(a[s-2].nodes)};break;case 52:r.addLink(a[s-3].stmt,a[s-1],a[s-2]),this.$={stmt:a[s-1],nodes:a[s-1].concat(a[s-3].nodes)};break;case 53:this.$={stmt:a[s-1],nodes:a[s-1]};break;case 54:this.$={stmt:a[s],nodes:a[s]};break;case 55:case 123:case 125:this.$=[a[s]];break;case 56:this.$=a[s-4].concat(a[s]);break;case 57:this.$=[a[s-2]],r.setClass(a[s-2],a[s]);break;case 58:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"square");break;case 59:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"doublecircle");break;case 60:this.$=a[s-5],r.addVertex(a[s-5],a[s-2],"circle");break;case 61:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"ellipse");break;case 62:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"stadium");break;case 63:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"subroutine");break;case 64:this.$=a[s-7],r.addVertex(a[s-7],a[s-1],"rect",void 0,void 0,void 0,Object.fromEntries([[a[s-5],a[s-3]]]));break;case 65:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"cylinder");break;case 66:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"round");break;case 67:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"diamond");break;case 68:this.$=a[s-5],r.addVertex(a[s-5],a[s-2],"hexagon");break;case 69:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"odd");break;case 70:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"trapezoid");break;case 71:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"inv_trapezoid");break;case 72:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"lean_right");break;case 73:this.$=a[s-3],r.addVertex(a[s-3],a[s-1],"lean_left");break;case 74:this.$=a[s],r.addVertex(a[s]);break;case 75:a[s-1].text=a[s],this.$=a[s-1];break;case 76:case 77:a[s-2].text=a[s-1],this.$=a[s-2];break;case 79:var c=r.destructLink(a[s],a[s-2]);this.$={type:c.type,stroke:c.stroke,length:c.length,text:a[s-1]};break;case 80:c=r.destructLink(a[s]),this.$={type:c.type,stroke:c.stroke,length:c.length};break;case 81:this.$=a[s-1];break;case 83:case 97:case 153:case 151:this.$=a[s-1]+""+a[s];break;case 98:case 99:this.$=a[s-4],r.addClass(a[s-2],a[s]);break;case 100:this.$=a[s-4],r.setClass(a[s-2],a[s]);break;case 101:case 109:this.$=a[s-1],r.setClickEvent(a[s-1],a[s]);break;case 102:case 110:this.$=a[s-3],r.setClickEvent(a[s-3],a[s-2]),r.setTooltip(a[s-3],a[s]);break;case 103:this.$=a[s-2],r.setClickEvent(a[s-2],a[s-1],a[s]);break;case 104:this.$=a[s-4],r.setClickEvent(a[s-4],a[s-3],a[s-2]),r.setTooltip(a[s-4],a[s]);break;case 105:case 111:this.$=a[s-1],r.setLink(a[s-1],a[s]);break;case 106:case 112:this.$=a[s-3],r.setLink(a[s-3],a[s-2]),r.setTooltip(a[s-3],a[s]);break;case 107:case 113:this.$=a[s-3],r.setLink(a[s-3],a[s-2],a[s]);break;case 108:case 114:this.$=a[s-5],r.setLink(a[s-5],a[s-4],a[s]),r.setTooltip(a[s-5],a[s-2]);break;case 115:this.$=a[s-4],r.addVertex(a[s-2],void 0,void 0,a[s]);break;case 116:case 118:this.$=a[s-4],r.updateLink(a[s-2],a[s]);break;case 117:this.$=a[s-4],r.updateLink([a[s-2]],a[s]);break;case 119:this.$=a[s-8],r.updateLinkInterpolate([a[s-6]],a[s-2]),r.updateLink([a[s-6]],a[s]);break;case 120:this.$=a[s-8],r.updateLinkInterpolate(a[s-6],a[s-2]),r.updateLink(a[s-6],a[s]);break;case 121:this.$=a[s-6],r.updateLinkInterpolate([a[s-4]],a[s]);break;case 122:this.$=a[s-6],r.updateLinkInterpolate(a[s-4],a[s]);break;case 124:case 126:a[s-2].push(a[s]),this.$=a[s-2];break;case 128:this.$=a[s-1]+a[s];break;case 156:this.$="v";break;case 157:this.$="-";break;case 158:this.$={stmt:"dir",value:"TB"};break;case 159:this.$={stmt:"dir",value:"BT"};break;case 160:this.$={stmt:"dir",value:"RL"};break;case 161:this.$={stmt:"dir",value:"LR"};}},table:[{3:1,4:2,5:3,6:5,12:e,16:4,21:n,22:r,24:i},{1:[3]},{1:[2,1]},{3:10,4:2,5:3,6:5,12:e,16:4,21:n,22:r,24:i},t(a,o,{17:11}),{7:12,13:[1,13]},{16:14,21:n,22:r,24:i},{16:15,21:n,22:r,24:i},{25:[1,16],26:[1,17]},{13:[2,5]},{1:[2,2]},{1:[2,9],18:18,19:19,20:s,21:c,22:l,23:u,32:24,33:25,34:26,35:27,36:28,37:29,38:h,43:31,44:f,46:d,48:p,50:35,51:45,52:g,54:46,66:y,67:m,86:b,87:v,88:_,89:x,90:k,91:w,95:T,105:E,106:C,109:S,111:A,112:M,116:47,118:N,119:O,120:D,121:B,122:L,123:I,124:F,125:R,126:P,127:j},{8:64,10:[1,65],15:z},t([10,15],[2,6]),t(a,[2,17]),t(a,[2,18]),t(a,[2,19]),{20:[1,68],21:[1,69],22:Y,27:67,30:70},t(U,[2,11]),t(U,[2,12]),t(U,[2,13]),t(U,[2,14]),t(U,[2,15]),t(U,[2,16]),{9:72,20:$,21:W,23:q,49:73,78:77,81:[1,78],82:[1,79]},{9:80,20:$,21:W,23:q},{9:81,20:$,21:W,23:q},{9:82,20:$,21:W,23:q},{9:83,20:$,21:W,23:q},{9:84,20:$,21:W,23:q},{9:86,20:$,21:W,22:[1,85],23:q},t(U,[2,44]),{45:[1,87]},{47:[1,88]},t(U,[2,47]),t(H,[2,54],{30:89,22:Y}),{22:[1,90]},{22:[1,91]},{22:[1,92]},{22:[1,93]},{26:V,52:G,66:X,67:Z,84:[1,97],91:Q,97:96,98:[1,94],100:[1,95],105:K,106:J,109:tt,111:et,112:nt,115:100,117:98,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(U,[2,158]),t(U,[2,159]),t(U,[2,160]),t(U,[2,161]),t(lt,[2,55],{53:[1,116]}),t(ut,[2,74],{116:129,40:[1,117],52:g,55:[1,118],57:[1,119],59:[1,120],61:[1,121],63:[1,122],65:[1,123],66:y,67:m,69:[1,124],71:[1,125],73:[1,126],74:[1,127],76:[1,128],91:w,95:T,105:E,106:C,109:S,111:A,112:M,122:L,123:I,124:F,125:R,126:P,127:j}),t(ht,[2,150]),t(ht,[2,175]),t(ht,[2,176]),t(ht,[2,177]),t(ht,[2,178]),t(ht,[2,179]),t(ht,[2,180]),t(ht,[2,181]),t(ht,[2,182]),t(ht,[2,183]),t(ht,[2,184]),t(ht,[2,185]),t(ht,[2,186]),t(ht,[2,187]),t(ht,[2,188]),t(ht,[2,189]),t(ht,[2,190]),{9:130,20:$,21:W,23:q},{11:131,14:[1,132]},t(ft,[2,8]),t(a,[2,20]),t(a,[2,26]),t(a,[2,27]),{21:[1,133]},t(dt,[2,34],{30:134,22:Y}),t(U,[2,35]),{50:135,51:45,52:g,54:46,66:y,67:m,91:w,95:T,105:E,106:C,109:S,111:A,112:M,116:47,122:L,123:I,124:F,125:R,126:P,127:j},t(pt,[2,48]),t(pt,[2,49]),t(pt,[2,50]),t(gt,[2,78],{79:136,68:[1,138],80:[1,137]}),{22:yt,24:mt,26:bt,38:vt,39:139,42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:140,84:wt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},t([52,66,67,68,80,91,95,105,106,109,111,112,122,123,124,125,126,127],[2,80]),t(U,[2,36]),t(U,[2,37]),t(U,[2,38]),t(U,[2,39]),t(U,[2,40]),{22:yt,24:mt,26:bt,38:vt,39:163,42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:140,84:wt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(It,o,{17:164}),t(U,[2,45]),t(U,[2,46]),t(H,[2,53],{52:Ft}),{26:V,52:G,66:X,67:Z,91:Q,97:166,102:[1,167],105:K,106:J,109:tt,111:et,112:nt,115:100,117:98,122:rt,123:it,124:at,125:ot,126:st,127:ct},{95:[1,168],103:169,105:[1,170]},{26:V,52:G,66:X,67:Z,91:Q,95:[1,171],97:172,105:K,106:J,109:tt,111:et,112:nt,115:100,117:98,122:rt,123:it,124:at,125:ot,126:st,127:ct},{26:V,52:G,66:X,67:Z,91:Q,97:173,105:K,106:J,109:tt,111:et,112:nt,115:100,117:98,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(ft,[2,101],{22:[1,174],99:[1,175]}),t(ft,[2,105],{22:[1,176]}),t(ft,[2,109],{115:100,117:178,22:[1,177],26:V,52:G,66:X,67:Z,91:Q,105:K,106:J,109:tt,111:et,112:nt,122:rt,123:it,124:at,125:ot,126:st,127:ct}),t(ft,[2,111],{22:[1,179]}),t(Rt,[2,152]),t(Rt,[2,154]),t(Rt,[2,155]),t(Rt,[2,156]),t(Rt,[2,157]),t(Pt,[2,162]),t(Pt,[2,163]),t(Pt,[2,164]),t(Pt,[2,165]),t(Pt,[2,166]),t(Pt,[2,167]),t(Pt,[2,168]),t(Pt,[2,169]),t(Pt,[2,170]),t(Pt,[2,171]),t(Pt,[2,172]),t(Pt,[2,173]),t(Pt,[2,174]),{52:g,54:180,66:y,67:m,91:w,95:T,105:E,106:C,109:S,111:A,112:M,116:47,122:L,123:I,124:F,125:R,126:P,127:j},{22:yt,24:mt,26:bt,38:vt,39:181,42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:140,84:wt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,39:182,42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:140,84:wt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,39:184,42:_t,52:G,57:[1,183],66:X,67:Z,73:xt,81:kt,83:140,84:wt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,39:185,42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:140,84:wt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,39:186,42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:140,84:wt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,39:187,42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:140,84:wt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{66:[1,188]},{22:yt,24:mt,26:bt,38:vt,39:189,42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:140,84:wt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,39:190,42:_t,52:G,66:X,67:Z,71:[1,191],73:xt,81:kt,83:140,84:wt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,39:192,42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:140,84:wt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,39:193,42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:140,84:wt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,39:194,42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:140,84:wt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(ht,[2,151]),t(jt,[2,3]),{8:195,15:z},{15:[2,7]},t(a,[2,28]),t(dt,[2,33]),t(H,[2,51],{30:196,22:Y}),t(gt,[2,75],{22:[1,197]}),{22:[1,198]},{22:yt,24:mt,26:bt,38:vt,39:199,42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:140,84:wt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,42:_t,52:G,66:X,67:Z,73:xt,81:kt,82:[1,200],83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(Pt,[2,82]),t(Pt,[2,84]),t(Pt,[2,140]),t(Pt,[2,141]),t(Pt,[2,142]),t(Pt,[2,143]),t(Pt,[2,144]),t(Pt,[2,145]),t(Pt,[2,146]),t(Pt,[2,147]),t(Pt,[2,148]),t(Pt,[2,149]),t(Pt,[2,85]),t(Pt,[2,86]),t(Pt,[2,87]),t(Pt,[2,88]),t(Pt,[2,89]),t(Pt,[2,90]),t(Pt,[2,91]),t(Pt,[2,92]),t(Pt,[2,93]),t(Pt,[2,94]),t(Pt,[2,95]),{9:203,20:$,21:W,22:yt,23:q,24:mt,26:bt,38:vt,40:[1,202],42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{18:18,19:19,20:s,21:c,22:l,23:u,32:24,33:25,34:26,35:27,36:28,37:29,38:h,42:[1,204],43:31,44:f,46:d,48:p,50:35,51:45,52:g,54:46,66:y,67:m,86:b,87:v,88:_,89:x,90:k,91:w,95:T,105:E,106:C,109:S,111:A,112:M,116:47,118:N,119:O,120:D,121:B,122:L,123:I,124:F,125:R,126:P,127:j},{22:Y,30:205},{22:[1,206],26:V,52:G,66:X,67:Z,91:Q,105:K,106:J,109:tt,111:et,112:nt,115:100,117:178,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:[1,207]},{22:[1,208]},{22:[1,209],106:[1,210]},t(zt,[2,123]),{22:[1,211]},{22:[1,212],26:V,52:G,66:X,67:Z,91:Q,105:K,106:J,109:tt,111:et,112:nt,115:100,117:178,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:[1,213],26:V,52:G,66:X,67:Z,91:Q,105:K,106:J,109:tt,111:et,112:nt,115:100,117:178,122:rt,123:it,124:at,125:ot,126:st,127:ct},{84:[1,214]},t(ft,[2,103],{22:[1,215]}),{84:[1,216],101:[1,217]},{84:[1,218]},t(Rt,[2,153]),{84:[1,219],101:[1,220]},t(lt,[2,57],{116:129,52:g,66:y,67:m,91:w,95:T,105:E,106:C,109:S,111:A,112:M,122:L,123:I,124:F,125:R,126:P,127:j}),{22:yt,24:mt,26:bt,38:vt,41:[1,221],42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,42:_t,52:G,56:[1,222],66:X,67:Z,73:xt,81:kt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,39:223,42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:140,84:wt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,42:_t,52:G,58:[1,224],66:X,67:Z,73:xt,81:kt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,42:_t,52:G,60:[1,225],66:X,67:Z,73:xt,81:kt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,42:_t,52:G,62:[1,226],66:X,67:Z,73:xt,81:kt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,42:_t,52:G,64:[1,227],66:X,67:Z,73:xt,81:kt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{67:[1,228]},{22:yt,24:mt,26:bt,38:vt,42:_t,52:G,66:X,67:Z,70:[1,229],73:xt,81:kt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,42:_t,52:G,66:X,67:Z,72:[1,230],73:xt,81:kt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,39:231,42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:140,84:wt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,41:[1,232],42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,42:_t,52:G,66:X,67:Z,73:xt,75:[1,233],77:[1,234],81:kt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{22:yt,24:mt,26:bt,38:vt,42:_t,52:G,66:X,67:Z,73:xt,75:[1,236],77:[1,235],81:kt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{9:237,20:$,21:W,23:q},t(H,[2,52],{52:Ft}),t(gt,[2,77]),t(gt,[2,76]),{22:yt,24:mt,26:bt,38:vt,42:_t,52:G,66:X,67:Z,68:[1,238],73:xt,81:kt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(gt,[2,79]),t(Pt,[2,83]),{22:yt,24:mt,26:bt,38:vt,39:239,42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:140,84:wt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(It,o,{17:240}),t(U,[2,43]),{51:241,52:g,54:46,66:y,67:m,91:w,95:T,105:E,106:C,109:S,111:A,112:M,116:47,122:L,123:I,124:F,125:R,126:P,127:j},{22:Yt,66:Ut,67:$t,86:Wt,96:242,102:qt,105:Ht,107:243,108:244,109:Vt,110:Gt,111:Xt,112:Zt,113:Qt},{22:Yt,66:Ut,67:$t,86:Wt,96:256,102:qt,105:Ht,107:243,108:244,109:Vt,110:Gt,111:Xt,112:Zt,113:Qt},{22:Yt,66:Ut,67:$t,86:Wt,96:257,102:qt,104:[1,258],105:Ht,107:243,108:244,109:Vt,110:Gt,111:Xt,112:Zt,113:Qt},{22:Yt,66:Ut,67:$t,86:Wt,96:259,102:qt,104:[1,260],105:Ht,107:243,108:244,109:Vt,110:Gt,111:Xt,112:Zt,113:Qt},{105:[1,261]},{22:Yt,66:Ut,67:$t,86:Wt,96:262,102:qt,105:Ht,107:243,108:244,109:Vt,110:Gt,111:Xt,112:Zt,113:Qt},{22:Yt,66:Ut,67:$t,86:Wt,96:263,102:qt,105:Ht,107:243,108:244,109:Vt,110:Gt,111:Xt,112:Zt,113:Qt},{26:V,52:G,66:X,67:Z,91:Q,97:264,105:K,106:J,109:tt,111:et,112:nt,115:100,117:98,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(ft,[2,102]),{84:[1,265]},t(ft,[2,106],{22:[1,266]}),t(ft,[2,107]),t(ft,[2,110]),t(ft,[2,112],{22:[1,267]}),t(ft,[2,113]),t(ut,[2,58]),t(ut,[2,59]),{22:yt,24:mt,26:bt,38:vt,42:_t,52:G,58:[1,268],66:X,67:Z,73:xt,81:kt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(ut,[2,66]),t(ut,[2,61]),t(ut,[2,62]),t(ut,[2,63]),{66:[1,269]},t(ut,[2,65]),t(ut,[2,67]),{22:yt,24:mt,26:bt,38:vt,42:_t,52:G,66:X,67:Z,72:[1,270],73:xt,81:kt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(ut,[2,69]),t(ut,[2,70]),t(ut,[2,72]),t(ut,[2,71]),t(ut,[2,73]),t(jt,[2,4]),t([22,52,66,67,91,95,105,106,109,111,112,122,123,124,125,126,127],[2,81]),{22:yt,24:mt,26:bt,38:vt,41:[1,271],42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{18:18,19:19,20:s,21:c,22:l,23:u,32:24,33:25,34:26,35:27,36:28,37:29,38:h,42:[1,272],43:31,44:f,46:d,48:p,50:35,51:45,52:g,54:46,66:y,67:m,86:b,87:v,88:_,89:x,90:k,91:w,95:T,105:E,106:C,109:S,111:A,112:M,116:47,118:N,119:O,120:D,121:B,122:L,123:I,124:F,125:R,126:P,127:j},t(lt,[2,56]),t(ft,[2,115],{106:Kt}),t(Jt,[2,125],{108:274,22:Yt,66:Ut,67:$t,86:Wt,102:qt,105:Ht,109:Vt,110:Gt,111:Xt,112:Zt,113:Qt}),t(te,[2,127]),t(te,[2,129]),t(te,[2,130]),t(te,[2,131]),t(te,[2,132]),t(te,[2,133]),t(te,[2,134]),t(te,[2,135]),t(te,[2,136]),t(te,[2,137]),t(te,[2,138]),t(te,[2,139]),t(ft,[2,116],{106:Kt}),t(ft,[2,117],{106:Kt}),{22:[1,275]},t(ft,[2,118],{106:Kt}),{22:[1,276]},t(zt,[2,124]),t(ft,[2,98],{106:Kt}),t(ft,[2,99],{106:Kt}),t(ft,[2,100],{115:100,117:178,26:V,52:G,66:X,67:Z,91:Q,105:K,106:J,109:tt,111:et,112:nt,122:rt,123:it,124:at,125:ot,126:st,127:ct}),t(ft,[2,104]),{101:[1,277]},{101:[1,278]},{58:[1,279]},{68:[1,280]},{72:[1,281]},{9:282,20:$,21:W,23:q},t(U,[2,42]),{22:Yt,66:Ut,67:$t,86:Wt,102:qt,105:Ht,107:283,108:244,109:Vt,110:Gt,111:Xt,112:Zt,113:Qt},t(te,[2,128]),{26:V,52:G,66:X,67:Z,91:Q,97:284,105:K,106:J,109:tt,111:et,112:nt,115:100,117:98,122:rt,123:it,124:at,125:ot,126:st,127:ct},{26:V,52:G,66:X,67:Z,91:Q,97:285,105:K,106:J,109:tt,111:et,112:nt,115:100,117:98,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(ft,[2,108]),t(ft,[2,114]),t(ut,[2,60]),{22:yt,24:mt,26:bt,38:vt,39:286,42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:140,84:wt,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},t(ut,[2,68]),t(It,o,{17:287}),t(Jt,[2,126],{108:274,22:Yt,66:Ut,67:$t,86:Wt,102:qt,105:Ht,109:Vt,110:Gt,111:Xt,112:Zt,113:Qt}),t(ft,[2,121],{115:100,117:178,22:[1,288],26:V,52:G,66:X,67:Z,91:Q,105:K,106:J,109:tt,111:et,112:nt,122:rt,123:it,124:at,125:ot,126:st,127:ct}),t(ft,[2,122],{115:100,117:178,22:[1,289],26:V,52:G,66:X,67:Z,91:Q,105:K,106:J,109:tt,111:et,112:nt,122:rt,123:it,124:at,125:ot,126:st,127:ct}),{22:yt,24:mt,26:bt,38:vt,41:[1,290],42:_t,52:G,66:X,67:Z,73:xt,81:kt,83:201,85:151,86:Tt,87:Et,88:Ct,89:St,90:At,91:Mt,92:Nt,94:142,95:Ot,105:K,106:J,109:Dt,111:et,112:nt,113:Bt,114:Lt,115:148,122:rt,123:it,124:at,125:ot,126:st,127:ct},{18:18,19:19,20:s,21:c,22:l,23:u,32:24,33:25,34:26,35:27,36:28,37:29,38:h,42:[1,291],43:31,44:f,46:d,48:p,50:35,51:45,52:g,54:46,66:y,67:m,86:b,87:v,88:_,89:x,90:k,91:w,95:T,105:E,106:C,109:S,111:A,112:M,116:47,118:N,119:O,120:D,121:B,122:L,123:I,124:F,125:R,126:P,127:j},{22:Yt,66:Ut,67:$t,86:Wt,96:292,102:qt,105:Ht,107:243,108:244,109:Vt,110:Gt,111:Xt,112:Zt,113:Qt},{22:Yt,66:Ut,67:$t,86:Wt,96:293,102:qt,105:Ht,107:243,108:244,109:Vt,110:Gt,111:Xt,112:Zt,113:Qt},t(ut,[2,64]),t(U,[2,41]),t(ft,[2,119],{106:Kt}),t(ft,[2,120],{106:Kt})],defaultActions:{2:[2,1],9:[2,5],10:[2,2],132:[2,7]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t);},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,l=0,u=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var b=p.options&&p.options.ranges;function v(){var t;return "number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,k,w,T,E,C,S,A,M={};;){if(k=n[n.length-1],this.defaultActions[k]?w=this.defaultActions[k]:(null==_&&(_=v()),w=o[k]&&o[k][_]),void 0===w||!w.length||!w[0]){var N="";for(E in A=[],o[k])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A});}if(w[0]instanceof Array&&w.length>1)throw new Error("Parse Error: multiple actions possible at state: "+k+", token: "+_);switch(w[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(w[1]),_=null,x?(_=x,x=null):(l=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,u>0&&u--);break;case 2:if(C=this.productions_[w[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},b&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,l,c,g.yy,w[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[w[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return !0}}return !0}},ne={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e);},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t));},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return (t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return !1}return !1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;a<i.length;a++)if((n=this._input.match(this.rules[i[a]]))&&(!e||n[0].length>e[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return !1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t);},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return (t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t);},stateStackSize:function(){return this.conditionStack.length},options:{},performAction:function(t,e,n,r){switch(n){case 0:return this.begin("open_directive"),12;case 1:return this.begin("type_directive"),13;case 2:return this.popState(),this.begin("arg_directive"),10;case 3:return this.popState(),this.popState(),15;case 4:return 14;case 5:case 6:break;case 7:return this.begin("acc_title"),44;case 8:return this.popState(),"acc_title_value";case 9:return this.begin("acc_descr"),46;case 10:return this.popState(),"acc_descr_value";case 11:this.begin("acc_descr_multiline");break;case 12:case 15:case 24:case 27:case 30:case 33:this.popState();break;case 13:return "acc_descr_multiline_value";case 14:this.begin("string");break;case 16:return "STR";case 17:return 86;case 18:return 95;case 19:return 87;case 20:return 104;case 21:return 88;case 22:return 89;case 23:this.begin("href");break;case 25:return 100;case 26:this.begin("callbackname");break;case 28:this.popState(),this.begin("callbackargs");break;case 29:return 98;case 31:return 99;case 32:this.begin("click");break;case 34:return 90;case 35:case 36:return t.lex.firstGraph()&&this.begin("dir"),24;case 37:return 38;case 38:return 42;case 39:case 40:case 41:case 42:return 101;case 43:return this.popState(),25;case 44:case 45:case 46:case 47:case 48:case 49:case 50:case 51:case 52:case 53:return this.popState(),26;case 54:return 118;case 55:return 119;case 56:return 120;case 57:return 121;case 58:return 105;case 59:return 111;case 60:return 53;case 61:return 67;case 62:return 52;case 63:return 20;case 64:return 106;case 65:return 126;case 66:case 67:case 68:return 82;case 69:case 70:case 71:return 81;case 72:return 59;case 73:return 60;case 74:return 61;case 75:return 62;case 76:return 63;case 77:return 64;case 78:return 65;case 79:return 69;case 80:return 70;case 81:return 55;case 82:return 56;case 83:return 109;case 84:return 112;case 85:return 127;case 86:return 124;case 87:return 113;case 88:case 89:return 125;case 90:return 114;case 91:return 73;case 92:return 92;case 93:return "SEP";case 94:return 91;case 95:return 66;case 96:return 75;case 97:return 74;case 98:return 77;case 99:return 76;case 100:return 122;case 101:return 123;case 102:return 68;case 103:return 57;case 104:return 58;case 105:return 40;case 106:return 41;case 107:return 71;case 108:return 72;case 109:return 133;case 110:return 21;case 111:return 22;case 112:return 23}},rules:[/^(?:%%\{)/,/^(?:((?:(?!\}%%)[^:.])*))/,/^(?::)/,/^(?:\}%%)/,/^(?:((?:(?!\}%%).|\n)*))/,/^(?:%%(?!\{)[^\n]*)/,/^(?:[^\}]%%[^\n]*)/,/^(?:accTitle\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*\{\s*)/,/^(?:[\}])/,/^(?:[^\}]*)/,/^(?:["])/,/^(?:["])/,/^(?:[^"]*)/,/^(?:style\b)/,/^(?:default\b)/,/^(?:linkStyle\b)/,/^(?:interpolate\b)/,/^(?:classDef\b)/,/^(?:class\b)/,/^(?:href[\s]+["])/,/^(?:["])/,/^(?:[^"]*)/,/^(?:call[\s]+)/,/^(?:\([\s]*\))/,/^(?:\()/,/^(?:[^(]*)/,/^(?:\))/,/^(?:[^)]*)/,/^(?:click[\s]+)/,/^(?:[\s\n])/,/^(?:[^\s\n]*)/,/^(?:graph\b)/,/^(?:flowchart\b)/,/^(?:subgraph\b)/,/^(?:end\b\s*)/,/^(?:_self\b)/,/^(?:_blank\b)/,/^(?:_parent\b)/,/^(?:_top\b)/,/^(?:(\r?\n)*\s*\n)/,/^(?:\s*LR\b)/,/^(?:\s*RL\b)/,/^(?:\s*TB\b)/,/^(?:\s*BT\b)/,/^(?:\s*TD\b)/,/^(?:\s*BR\b)/,/^(?:\s*<)/,/^(?:\s*>)/,/^(?:\s*\^)/,/^(?:\s*v\b)/,/^(?:.*direction\s+TB[^\n]*)/,/^(?:.*direction\s+BT[^\n]*)/,/^(?:.*direction\s+RL[^\n]*)/,/^(?:.*direction\s+LR[^\n]*)/,/^(?:[0-9]+)/,/^(?:#)/,/^(?::::)/,/^(?::)/,/^(?:&)/,/^(?:;)/,/^(?:,)/,/^(?:\*)/,/^(?:\s*[xo<]?--+[-xo>]\s*)/,/^(?:\s*[xo<]?==+[=xo>]\s*)/,/^(?:\s*[xo<]?-?\.+-[xo>]?\s*)/,/^(?:\s*[xo<]?--\s*)/,/^(?:\s*[xo<]?==\s*)/,/^(?:\s*[xo<]?-\.\s*)/,/^(?:\(-)/,/^(?:-\))/,/^(?:\(\[)/,/^(?:\]\))/,/^(?:\[\[)/,/^(?:\]\])/,/^(?:\[\|)/,/^(?:\[\()/,/^(?:\)\])/,/^(?:\(\(\()/,/^(?:\)\)\))/,/^(?:-)/,/^(?:\.)/,/^(?:[\_])/,/^(?:\+)/,/^(?:%)/,/^(?:=)/,/^(?:=)/,/^(?:<)/,/^(?:>)/,/^(?:\^)/,/^(?:\\\|)/,/^(?:v\b)/,/^(?:[A-Za-z]+)/,/^(?:\\\])/,/^(?:\[\/)/,/^(?:\/\])/,/^(?:\[\\)/,/^(?:[!"#$%&'*+,-.`?\\_/])/,/^(?:[\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6]|[\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377]|[\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5]|[\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA]|[\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE]|[\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA]|[\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0]|[\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977]|[\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2]|[\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A]|[\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39]|[\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8]|[\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C]|[\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C]|[\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99]|[\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0]|[\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D]|[\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3]|[\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10]|[\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1]|[\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81]|[\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3]|[\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6]|[\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A]|[\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081]|[\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D]|[\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0]|[\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310]|[\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C]|[\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711]|[\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7]|[\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C]|[\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16]|[\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF]|[\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC]|[\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D]|[\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D]|[\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3]|[\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F]|[\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128]|[\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184]|[\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3]|[\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6]|[\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE]|[\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C]|[\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D]|[\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC]|[\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B]|[\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788]|[\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805]|[\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB]|[\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28]|[\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5]|[\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4]|[\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E]|[\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D]|[\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36]|[\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D]|[\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC]|[\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF]|[\uFFD2-\uFFD7\uFFDA-\uFFDC])/,/^(?:\|)/,/^(?:\()/,/^(?:\))/,/^(?:\[)/,/^(?:\])/,/^(?:\{)/,/^(?:\})/,/^(?:")/,/^(?:(\r?\n)+)/,/^(?:\s)/,/^(?:$)/],conditions:{close_directive:{rules:[],inclusive:!1},arg_directive:{rules:[3,4],inclusive:!1},type_directive:{rules:[2,3],inclusive:!1},open_directive:{rules:[1],inclusive:!1},callbackargs:{rules:[30,31],inclusive:!1},callbackname:{rules:[27,28,29],inclusive:!1},href:{rules:[24,25],inclusive:!1},click:{rules:[33,34],inclusive:!1},vertex:{rules:[],inclusive:!1},dir:{rules:[43,44,45,46,47,48,49,50,51,52,53],inclusive:!1},acc_descr_multiline:{rules:[12,13],inclusive:!1},acc_descr:{rules:[10],inclusive:!1},acc_title:{rules:[8],inclusive:!1},string:{rules:[15,16],inclusive:!1},INITIAL:{rules:[0,5,6,7,9,11,14,17,18,19,20,21,22,23,26,32,35,36,37,38,39,40,41,42,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112],inclusive:!0}}};function re(){this.yy={};}return ee.lexer=ne,re.prototype=ee,ee.Parser=re,new re}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(5354).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1));},9959:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,3],n=[1,5],r=[7,9,11,12,13,14,15,16,17,18,19,20,22,24,25,27,34,39],i=[1,15],a=[1,16],o=[1,17],s=[1,18],c=[1,19],l=[1,20],u=[1,21],h=[1,22],f=[1,23],d=[1,24],p=[1,25],g=[1,26],y=[1,28],m=[1,30],b=[1,33],v=[5,7,9,11,12,13,14,15,16,17,18,19,20,22,24,25,27,34,39],_={trace:function(){},yy:{},symbols_:{error:2,start:3,directive:4,gantt:5,document:6,EOF:7,line:8,SPACE:9,statement:10,NL:11,dateFormat:12,inclusiveEndDates:13,topAxis:14,axisFormat:15,excludes:16,includes:17,todayMarker:18,title:19,acc_title:20,acc_title_value:21,acc_descr:22,acc_descr_value:23,acc_descr_multiline_value:24,section:25,clickStatement:26,taskTxt:27,taskData:28,openDirective:29,typeDirective:30,closeDirective:31,":":32,argDirective:33,click:34,callbackname:35,callbackargs:36,href:37,clickStatementDebug:38,open_directive:39,type_directive:40,arg_directive:41,close_directive:42,$accept:0,$end:1},terminals_:{2:"error",5:"gantt",7:"EOF",9:"SPACE",11:"NL",12:"dateFormat",13:"inclusiveEndDates",14:"topAxis",15:"axisFormat",16:"excludes",17:"includes",18:"todayMarker",19:"title",20:"acc_title",21:"acc_title_value",22:"acc_descr",23:"acc_descr_value",24:"acc_descr_multiline_value",25:"section",27:"taskTxt",28:"taskData",32:":",34:"click",35:"callbackname",36:"callbackargs",37:"href",39:"open_directive",40:"type_directive",41:"arg_directive",42:"close_directive"},productions_:[0,[3,2],[3,3],[6,0],[6,2],[8,2],[8,1],[8,1],[8,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,2],[10,2],[10,1],[10,1],[10,1],[10,2],[10,1],[4,4],[4,6],[26,2],[26,3],[26,3],[26,4],[26,3],[26,4],[26,2],[38,2],[38,3],[38,3],[38,4],[38,3],[38,4],[38,2],[29,1],[30,1],[33,1],[31,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 2:return a[s-1];case 3:case 7:case 8:this.$=[];break;case 4:a[s-1].push(a[s]),this.$=a[s-1];break;case 5:case 6:this.$=a[s];break;case 9:r.setDateFormat(a[s].substr(11)),this.$=a[s].substr(11);break;case 10:r.enableInclusiveEndDates(),this.$=a[s].substr(18);break;case 11:r.TopAxis(),this.$=a[s].substr(8);break;case 12:r.setAxisFormat(a[s].substr(11)),this.$=a[s].substr(11);break;case 13:r.setExcludes(a[s].substr(9)),this.$=a[s].substr(9);break;case 14:r.setIncludes(a[s].substr(9)),this.$=a[s].substr(9);break;case 15:r.setTodayMarker(a[s].substr(12)),this.$=a[s].substr(12);break;case 16:r.setDiagramTitle(a[s].substr(6)),this.$=a[s].substr(6);break;case 17:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 18:case 19:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 20:r.addSection(a[s].substr(8)),this.$=a[s].substr(8);break;case 22:r.addTask(a[s-1],a[s]),this.$="task";break;case 26:this.$=a[s-1],r.setClickEvent(a[s-1],a[s],null);break;case 27:this.$=a[s-2],r.setClickEvent(a[s-2],a[s-1],a[s]);break;case 28:this.$=a[s-2],r.setClickEvent(a[s-2],a[s-1],null),r.setLink(a[s-2],a[s]);break;case 29:this.$=a[s-3],r.setClickEvent(a[s-3],a[s-2],a[s-1]),r.setLink(a[s-3],a[s]);break;case 30:this.$=a[s-2],r.setClickEvent(a[s-2],a[s],null),r.setLink(a[s-2],a[s-1]);break;case 31:this.$=a[s-3],r.setClickEvent(a[s-3],a[s-1],a[s]),r.setLink(a[s-3],a[s-2]);break;case 32:this.$=a[s-1],r.setLink(a[s-1],a[s]);break;case 33:case 39:this.$=a[s-1]+" "+a[s];break;case 34:case 35:case 37:this.$=a[s-2]+" "+a[s-1]+" "+a[s];break;case 36:case 38:this.$=a[s-3]+" "+a[s-2]+" "+a[s-1]+" "+a[s];break;case 40:r.parseDirective("%%{","open_directive");break;case 41:r.parseDirective(a[s],"type_directive");break;case 42:a[s]=a[s].trim().replace(/'/g,'"'),r.parseDirective(a[s],"arg_directive");break;case 43:r.parseDirective("}%%","close_directive","gantt");}},table:[{3:1,4:2,5:e,29:4,39:n},{1:[3]},{3:6,4:2,5:e,29:4,39:n},t(r,[2,3],{6:7}),{30:8,40:[1,9]},{40:[2,40]},{1:[2,1]},{4:29,7:[1,10],8:11,9:[1,12],10:13,11:[1,14],12:i,13:a,14:o,15:s,16:c,17:l,18:u,19:h,20:f,22:d,24:p,25:g,26:27,27:y,29:4,34:m,39:n},{31:31,32:[1,32],42:b},t([32,42],[2,41]),t(r,[2,8],{1:[2,2]}),t(r,[2,4]),{4:29,10:34,12:i,13:a,14:o,15:s,16:c,17:l,18:u,19:h,20:f,22:d,24:p,25:g,26:27,27:y,29:4,34:m,39:n},t(r,[2,6]),t(r,[2,7]),t(r,[2,9]),t(r,[2,10]),t(r,[2,11]),t(r,[2,12]),t(r,[2,13]),t(r,[2,14]),t(r,[2,15]),t(r,[2,16]),{21:[1,35]},{23:[1,36]},t(r,[2,19]),t(r,[2,20]),t(r,[2,21]),{28:[1,37]},t(r,[2,23]),{35:[1,38],37:[1,39]},{11:[1,40]},{33:41,41:[1,42]},{11:[2,43]},t(r,[2,5]),t(r,[2,17]),t(r,[2,18]),t(r,[2,22]),t(r,[2,26],{36:[1,43],37:[1,44]}),t(r,[2,32],{35:[1,45]}),t(v,[2,24]),{31:46,42:b},{42:[2,42]},t(r,[2,27],{37:[1,47]}),t(r,[2,28]),t(r,[2,30],{36:[1,48]}),{11:[1,49]},t(r,[2,29]),t(r,[2,31]),t(v,[2,25])],defaultActions:{5:[2,40],6:[2,1],33:[2,43],42:[2,42]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t);},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,l=0,u=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var b=p.options&&p.options.ranges;function v(){var t;return "number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,k,w,T,E,C,S,A,M={};;){if(k=n[n.length-1],this.defaultActions[k]?w=this.defaultActions[k]:(null==_&&(_=v()),w=o[k]&&o[k][_]),void 0===w||!w.length||!w[0]){var N="";for(E in A=[],o[k])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A});}if(w[0]instanceof Array&&w.length>1)throw new Error("Parse Error: multiple actions possible at state: "+k+", token: "+_);switch(w[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(w[1]),_=null,x?(_=x,x=null):(l=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,u>0&&u--);break;case 2:if(C=this.productions_[w[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},b&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,l,c,g.yy,w[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[w[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return !0}}return !0}},x={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e);},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t));},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return (t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return !1}return !1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;a<i.length;a++)if((n=this._input.match(this.rules[i[a]]))&&(!e||n[0].length>e[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return !1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t);},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return (t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t);},stateStackSize:function(){return this.conditionStack.length},options:{"case-insensitive":!0},performAction:function(t,e,n,r){switch(n){case 0:return this.begin("open_directive"),39;case 1:return this.begin("type_directive"),40;case 2:return this.popState(),this.begin("arg_directive"),32;case 3:return this.popState(),this.popState(),42;case 4:return 41;case 5:return this.begin("acc_title"),20;case 6:return this.popState(),"acc_title_value";case 7:return this.begin("acc_descr"),22;case 8:return this.popState(),"acc_descr_value";case 9:this.begin("acc_descr_multiline");break;case 10:case 20:case 23:case 26:case 29:this.popState();break;case 11:return "acc_descr_multiline_value";case 12:case 13:case 14:case 16:case 17:case 18:break;case 15:return 11;case 19:this.begin("href");break;case 21:return 37;case 22:this.begin("callbackname");break;case 24:this.popState(),this.begin("callbackargs");break;case 25:return 35;case 27:return 36;case 28:this.begin("click");break;case 30:return 34;case 31:return 5;case 32:return 12;case 33:return 13;case 34:return 14;case 35:return 15;case 36:return 17;case 37:return 16;case 38:return 18;case 39:return "date";case 40:return 19;case 41:return "accDescription";case 42:return 25;case 43:return 27;case 44:return 28;case 45:return 32;case 46:return 7;case 47:return "INVALID"}},rules:[/^(?:%%\{)/i,/^(?:((?:(?!\}%%)[^:.])*))/i,/^(?::)/i,/^(?:\}%%)/i,/^(?:((?:(?!\}%%).|\n)*))/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:%%(?!\{)*[^\n]*)/i,/^(?:[^\}]%%*[^\n]*)/i,/^(?:%%*[^\n]*[\n]*)/i,/^(?:[\n]+)/i,/^(?:\s+)/i,/^(?:#[^\n]*)/i,/^(?:%[^\n]*)/i,/^(?:href[\s]+["])/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:call[\s]+)/i,/^(?:\([\s]*\))/i,/^(?:\()/i,/^(?:[^(]*)/i,/^(?:\))/i,/^(?:[^)]*)/i,/^(?:click[\s]+)/i,/^(?:[\s\n])/i,/^(?:[^\s\n]*)/i,/^(?:gantt\b)/i,/^(?:dateFormat\s[^#\n;]+)/i,/^(?:inclusiveEndDates\b)/i,/^(?:topAxis\b)/i,/^(?:axisFormat\s[^#\n;]+)/i,/^(?:includes\s[^#\n;]+)/i,/^(?:excludes\s[^#\n;]+)/i,/^(?:todayMarker\s[^\n;]+)/i,/^(?:\d\d\d\d-\d\d-\d\d\b)/i,/^(?:title\s[^#\n;]+)/i,/^(?:accDescription\s[^#\n;]+)/i,/^(?:section\s[^#:\n;]+)/i,/^(?:[^#:\n;]+)/i,/^(?::[^#\n;]+)/i,/^(?::)/i,/^(?:$)/i,/^(?:.)/i],conditions:{acc_descr_multiline:{rules:[10,11],inclusive:!1},acc_descr:{rules:[8],inclusive:!1},acc_title:{rules:[6],inclusive:!1},close_directive:{rules:[],inclusive:!1},arg_directive:{rules:[3,4],inclusive:!1},type_directive:{rules:[2,3],inclusive:!1},open_directive:{rules:[1],inclusive:!1},callbackargs:{rules:[26,27],inclusive:!1},callbackname:{rules:[23,24,25],inclusive:!1},href:{rules:[20,21],inclusive:!1},click:{rules:[29,30],inclusive:!1},INITIAL:{rules:[0,5,7,9,12,13,14,15,16,17,18,19,22,28,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47],inclusive:!0}}};function k(){this.yy={};}return _.lexer=x,k.prototype=_,_.Parser=k,new k}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(6878).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1));},2553:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,4],n=[1,7],r=[1,5],i=[1,9],a=[1,6],o=[2,6],s=[1,16],c=[6,8,14,20,22,24,25,27,29,32,35,39,49,53],l=[8,14,20,22,24,25,27,29,32,35,39],u=[8,13,14,20,22,24,25,27,29,32,35,39],h=[1,26],f=[6,8,14,49,53],d=[8,14,53],p=[1,64],g=[1,65],y=[1,66],m=[8,14,33,38,41,53],b={trace:function(){},yy:{},symbols_:{error:2,start:3,eol:4,directive:5,GG:6,document:7,EOF:8,":":9,DIR:10,options:11,body:12,OPT:13,NL:14,line:15,statement:16,commitStatement:17,mergeStatement:18,cherryPickStatement:19,acc_title:20,acc_title_value:21,acc_descr:22,acc_descr_value:23,acc_descr_multiline_value:24,section:25,branchStatement:26,CHECKOUT:27,ID:28,BRANCH:29,ORDER:30,NUM:31,CHERRY_PICK:32,COMMIT_ID:33,STR:34,MERGE:35,COMMIT_TYPE:36,commitType:37,COMMIT_TAG:38,COMMIT:39,commit_arg:40,COMMIT_MSG:41,NORMAL:42,REVERSE:43,HIGHLIGHT:44,openDirective:45,typeDirective:46,closeDirective:47,argDirective:48,open_directive:49,type_directive:50,arg_directive:51,close_directive:52,";":53,$accept:0,$end:1},terminals_:{2:"error",6:"GG",8:"EOF",9:":",10:"DIR",13:"OPT",14:"NL",20:"acc_title",21:"acc_title_value",22:"acc_descr",23:"acc_descr_value",24:"acc_descr_multiline_value",25:"section",27:"CHECKOUT",28:"ID",29:"BRANCH",30:"ORDER",31:"NUM",32:"CHERRY_PICK",33:"COMMIT_ID",34:"STR",35:"MERGE",36:"COMMIT_TYPE",38:"COMMIT_TAG",39:"COMMIT",41:"COMMIT_MSG",42:"NORMAL",43:"REVERSE",44:"HIGHLIGHT",49:"open_directive",50:"type_directive",51:"arg_directive",52:"close_directive",53:";"},productions_:[0,[3,2],[3,2],[3,3],[3,4],[3,5],[7,0],[7,2],[11,2],[11,1],[12,0],[12,2],[15,2],[15,1],[16,1],[16,1],[16,1],[16,2],[16,2],[16,1],[16,1],[16,1],[16,2],[26,2],[26,4],[19,3],[18,2],[18,4],[18,4],[18,4],[18,6],[18,6],[18,6],[18,6],[18,6],[18,6],[18,8],[18,8],[18,8],[18,8],[18,8],[18,8],[17,2],[17,3],[17,3],[17,5],[17,5],[17,3],[17,5],[17,5],[17,5],[17,5],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,3],[17,5],[17,5],[17,5],[17,5],[17,5],[17,5],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,7],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[17,9],[40,0],[40,1],[37,1],[37,1],[37,1],[5,3],[5,5],[45,1],[46,1],[48,1],[47,1],[4,1],[4,1],[4,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 3:return a[s];case 4:return a[s-1];case 5:return r.setDirection(a[s-3]),a[s-1];case 7:r.setOptions(a[s-1]),this.$=a[s];break;case 8:a[s-1]+=a[s],this.$=a[s-1];break;case 10:this.$=[];break;case 11:a[s-1].push(a[s]),this.$=a[s-1];break;case 12:this.$=a[s-1];break;case 17:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 18:case 19:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 20:r.addSection(a[s].substr(8)),this.$=a[s].substr(8);break;case 22:r.checkout(a[s]);break;case 23:r.branch(a[s]);break;case 24:r.branch(a[s-2],a[s]);break;case 25:r.cherryPick(a[s]);break;case 26:r.merge(a[s],"","","");break;case 27:r.merge(a[s-2],a[s],"","");break;case 28:r.merge(a[s-2],"",a[s],"");break;case 29:r.merge(a[s-2],"","",a[s]);break;case 30:r.merge(a[s-4],a[s],"",a[s-2]);break;case 31:r.merge(a[s-4],"",a[s],a[s-2]);break;case 32:r.merge(a[s-4],"",a[s-2],a[s]);break;case 33:r.merge(a[s-4],a[s-2],a[s],"");break;case 34:r.merge(a[s-4],a[s-2],"",a[s]);break;case 35:r.merge(a[s-4],a[s],a[s-2],"");break;case 36:r.merge(a[s-6],a[s-4],a[s-2],a[s]);break;case 37:r.merge(a[s-6],a[s],a[s-4],a[s-2]);break;case 38:r.merge(a[s-6],a[s-4],a[s],a[s-2]);break;case 39:r.merge(a[s-6],a[s-2],a[s-4],a[s]);break;case 40:r.merge(a[s-6],a[s],a[s-2],a[s-4]);break;case 41:r.merge(a[s-6],a[s-2],a[s],a[s-4]);break;case 42:r.commit(a[s]);break;case 43:r.commit("","",r.commitType.NORMAL,a[s]);break;case 44:r.commit("","",a[s],"");break;case 45:r.commit("","",a[s],a[s-2]);break;case 46:r.commit("","",a[s-2],a[s]);break;case 47:r.commit("",a[s],r.commitType.NORMAL,"");break;case 48:r.commit("",a[s-2],r.commitType.NORMAL,a[s]);break;case 49:r.commit("",a[s],r.commitType.NORMAL,a[s-2]);break;case 50:r.commit("",a[s-2],a[s],"");break;case 51:r.commit("",a[s],a[s-2],"");break;case 52:r.commit("",a[s-4],a[s-2],a[s]);break;case 53:r.commit("",a[s-4],a[s],a[s-2]);break;case 54:r.commit("",a[s-2],a[s-4],a[s]);break;case 55:r.commit("",a[s],a[s-4],a[s-2]);break;case 56:r.commit("",a[s],a[s-2],a[s-4]);break;case 57:r.commit("",a[s-2],a[s],a[s-4]);break;case 58:r.commit(a[s],"",r.commitType.NORMAL,"");break;case 59:r.commit(a[s],"",r.commitType.NORMAL,a[s-2]);break;case 60:r.commit(a[s-2],"",r.commitType.NORMAL,a[s]);break;case 61:r.commit(a[s-2],"",a[s],"");break;case 62:r.commit(a[s],"",a[s-2],"");break;case 63:r.commit(a[s],a[s-2],r.commitType.NORMAL,"");break;case 64:r.commit(a[s-2],a[s],r.commitType.NORMAL,"");break;case 65:r.commit(a[s-4],"",a[s-2],a[s]);break;case 66:r.commit(a[s-4],"",a[s],a[s-2]);break;case 67:r.commit(a[s-2],"",a[s-4],a[s]);break;case 68:r.commit(a[s],"",a[s-4],a[s-2]);break;case 69:r.commit(a[s],"",a[s-2],a[s-4]);break;case 70:r.commit(a[s-2],"",a[s],a[s-4]);break;case 71:r.commit(a[s-4],a[s],a[s-2],"");break;case 72:r.commit(a[s-4],a[s-2],a[s],"");break;case 73:r.commit(a[s-2],a[s],a[s-4],"");break;case 74:r.commit(a[s],a[s-2],a[s-4],"");break;case 75:r.commit(a[s],a[s-4],a[s-2],"");break;case 76:r.commit(a[s-2],a[s-4],a[s],"");break;case 77:r.commit(a[s-4],a[s],r.commitType.NORMAL,a[s-2]);break;case 78:r.commit(a[s-4],a[s-2],r.commitType.NORMAL,a[s]);break;case 79:r.commit(a[s-2],a[s],r.commitType.NORMAL,a[s-4]);break;case 80:r.commit(a[s],a[s-2],r.commitType.NORMAL,a[s-4]);break;case 81:r.commit(a[s],a[s-4],r.commitType.NORMAL,a[s-2]);break;case 82:r.commit(a[s-2],a[s-4],r.commitType.NORMAL,a[s]);break;case 83:r.commit(a[s-6],a[s-4],a[s-2],a[s]);break;case 84:r.commit(a[s-6],a[s-4],a[s],a[s-2]);break;case 85:r.commit(a[s-6],a[s-2],a[s-4],a[s]);break;case 86:r.commit(a[s-6],a[s],a[s-4],a[s-2]);break;case 87:r.commit(a[s-6],a[s-2],a[s],a[s-4]);break;case 88:r.commit(a[s-6],a[s],a[s-2],a[s-4]);break;case 89:r.commit(a[s-4],a[s-6],a[s-2],a[s]);break;case 90:r.commit(a[s-4],a[s-6],a[s],a[s-2]);break;case 91:r.commit(a[s-2],a[s-6],a[s-4],a[s]);break;case 92:r.commit(a[s],a[s-6],a[s-4],a[s-2]);break;case 93:r.commit(a[s-2],a[s-6],a[s],a[s-4]);break;case 94:r.commit(a[s],a[s-6],a[s-2],a[s-4]);break;case 95:r.commit(a[s],a[s-4],a[s-2],a[s-6]);break;case 96:r.commit(a[s-2],a[s-4],a[s],a[s-6]);break;case 97:r.commit(a[s],a[s-2],a[s-4],a[s-6]);break;case 98:r.commit(a[s-2],a[s],a[s-4],a[s-6]);break;case 99:r.commit(a[s-4],a[s-2],a[s],a[s-6]);break;case 100:r.commit(a[s-4],a[s],a[s-2],a[s-6]);break;case 101:r.commit(a[s-2],a[s-4],a[s-6],a[s]);break;case 102:r.commit(a[s],a[s-4],a[s-6],a[s-2]);break;case 103:r.commit(a[s-2],a[s],a[s-6],a[s-4]);break;case 104:r.commit(a[s],a[s-2],a[s-6],a[s-4]);break;case 105:r.commit(a[s-4],a[s-2],a[s-6],a[s]);break;case 106:r.commit(a[s-4],a[s],a[s-6],a[s-2]);break;case 107:this.$="";break;case 108:this.$=a[s];break;case 109:this.$=r.commitType.NORMAL;break;case 110:this.$=r.commitType.REVERSE;break;case 111:this.$=r.commitType.HIGHLIGHT;break;case 114:r.parseDirective("%%{","open_directive");break;case 115:r.parseDirective(a[s],"type_directive");break;case 116:a[s]=a[s].trim().replace(/'/g,'"'),r.parseDirective(a[s],"arg_directive");break;case 117:r.parseDirective("}%%","close_directive","gitGraph");}},table:[{3:1,4:2,5:3,6:e,8:n,14:r,45:8,49:i,53:a},{1:[3]},{3:10,4:2,5:3,6:e,8:n,14:r,45:8,49:i,53:a},{3:11,4:2,5:3,6:e,8:n,14:r,45:8,49:i,53:a},{7:12,8:o,9:[1,13],10:[1,14],11:15,14:s},t(c,[2,118]),t(c,[2,119]),t(c,[2,120]),{46:17,50:[1,18]},{50:[2,114]},{1:[2,1]},{1:[2,2]},{8:[1,19]},{7:20,8:o,11:15,14:s},{9:[1,21]},t(l,[2,10],{12:22,13:[1,23]}),t(u,[2,9]),{9:[1,25],47:24,52:h},t([9,52],[2,115]),{1:[2,3]},{8:[1,27]},{7:28,8:o,11:15,14:s},{8:[2,7],14:[1,31],15:29,16:30,17:32,18:33,19:34,20:[1,35],22:[1,36],24:[1,37],25:[1,38],26:39,27:[1,40],29:[1,44],32:[1,43],35:[1,42],39:[1,41]},t(u,[2,8]),t(f,[2,112]),{48:45,51:[1,46]},t(f,[2,117]),{1:[2,4]},{8:[1,47]},t(l,[2,11]),{4:48,8:n,14:r,53:a},t(l,[2,13]),t(d,[2,14]),t(d,[2,15]),t(d,[2,16]),{21:[1,49]},{23:[1,50]},t(d,[2,19]),t(d,[2,20]),t(d,[2,21]),{28:[1,51]},t(d,[2,107],{40:52,33:[1,55],34:[1,57],36:[1,54],38:[1,53],41:[1,56]}),{28:[1,58]},{33:[1,59]},{28:[1,60]},{47:61,52:h},{52:[2,116]},{1:[2,5]},t(l,[2,12]),t(d,[2,17]),t(d,[2,18]),t(d,[2,22]),t(d,[2,42]),{34:[1,62]},{37:63,42:p,43:g,44:y},{34:[1,67]},{34:[1,68]},t(d,[2,108]),t(d,[2,26],{33:[1,69],36:[1,70],38:[1,71]}),{34:[1,72]},t(d,[2,23],{30:[1,73]}),t(f,[2,113]),t(d,[2,43],{33:[1,75],36:[1,74],41:[1,76]}),t(d,[2,44],{33:[1,78],38:[1,77],41:[1,79]}),t(m,[2,109]),t(m,[2,110]),t(m,[2,111]),t(d,[2,47],{36:[1,81],38:[1,80],41:[1,82]}),t(d,[2,58],{33:[1,85],36:[1,84],38:[1,83]}),{34:[1,86]},{37:87,42:p,43:g,44:y},{34:[1,88]},t(d,[2,25]),{31:[1,89]},{37:90,42:p,43:g,44:y},{34:[1,91]},{34:[1,92]},{34:[1,93]},{34:[1,94]},{34:[1,95]},{34:[1,96]},{37:97,42:p,43:g,44:y},{34:[1,98]},{34:[1,99]},{37:100,42:p,43:g,44:y},{34:[1,101]},t(d,[2,27],{36:[1,102],38:[1,103]}),t(d,[2,28],{33:[1,105],38:[1,104]}),t(d,[2,29],{33:[1,106],36:[1,107]}),t(d,[2,24]),t(d,[2,45],{33:[1,108],41:[1,109]}),t(d,[2,49],{36:[1,110],41:[1,111]}),t(d,[2,59],{33:[1,113],36:[1,112]}),t(d,[2,46],{33:[1,114],41:[1,115]}),t(d,[2,51],{38:[1,116],41:[1,117]}),t(d,[2,62],{33:[1,119],38:[1,118]}),t(d,[2,48],{36:[1,120],41:[1,121]}),t(d,[2,50],{38:[1,122],41:[1,123]}),t(d,[2,63],{36:[1,124],38:[1,125]}),t(d,[2,60],{33:[1,127],36:[1,126]}),t(d,[2,61],{33:[1,129],38:[1,128]}),t(d,[2,64],{36:[1,130],38:[1,131]}),{37:132,42:p,43:g,44:y},{34:[1,133]},{34:[1,134]},{34:[1,135]},{34:[1,136]},{37:137,42:p,43:g,44:y},{34:[1,138]},{34:[1,139]},{37:140,42:p,43:g,44:y},{34:[1,141]},{37:142,42:p,43:g,44:y},{34:[1,143]},{34:[1,144]},{34:[1,145]},{34:[1,146]},{34:[1,147]},{34:[1,148]},{34:[1,149]},{37:150,42:p,43:g,44:y},{34:[1,151]},{34:[1,152]},{34:[1,153]},{37:154,42:p,43:g,44:y},{34:[1,155]},{37:156,42:p,43:g,44:y},{34:[1,157]},{34:[1,158]},{34:[1,159]},{37:160,42:p,43:g,44:y},{34:[1,161]},t(d,[2,33],{38:[1,162]}),t(d,[2,34],{36:[1,163]}),t(d,[2,32],{33:[1,164]}),t(d,[2,35],{38:[1,165]}),t(d,[2,30],{36:[1,166]}),t(d,[2,31],{33:[1,167]}),t(d,[2,56],{41:[1,168]}),t(d,[2,69],{33:[1,169]}),t(d,[2,57],{41:[1,170]}),t(d,[2,80],{36:[1,171]}),t(d,[2,70],{33:[1,172]}),t(d,[2,79],{36:[1,173]}),t(d,[2,55],{41:[1,174]}),t(d,[2,68],{33:[1,175]}),t(d,[2,54],{41:[1,176]}),t(d,[2,74],{38:[1,177]}),t(d,[2,67],{33:[1,178]}),t(d,[2,73],{38:[1,179]}),t(d,[2,53],{41:[1,180]}),t(d,[2,81],{36:[1,181]}),t(d,[2,52],{41:[1,182]}),t(d,[2,75],{38:[1,183]}),t(d,[2,76],{38:[1,184]}),t(d,[2,82],{36:[1,185]}),t(d,[2,66],{33:[1,186]}),t(d,[2,77],{36:[1,187]}),t(d,[2,65],{33:[1,188]}),t(d,[2,71],{38:[1,189]}),t(d,[2,72],{38:[1,190]}),t(d,[2,78],{36:[1,191]}),{34:[1,192]},{37:193,42:p,43:g,44:y},{34:[1,194]},{34:[1,195]},{37:196,42:p,43:g,44:y},{34:[1,197]},{34:[1,198]},{34:[1,199]},{34:[1,200]},{37:201,42:p,43:g,44:y},{34:[1,202]},{37:203,42:p,43:g,44:y},{34:[1,204]},{34:[1,205]},{34:[1,206]},{34:[1,207]},{34:[1,208]},{34:[1,209]},{34:[1,210]},{37:211,42:p,43:g,44:y},{34:[1,212]},{34:[1,213]},{34:[1,214]},{37:215,42:p,43:g,44:y},{34:[1,216]},{37:217,42:p,43:g,44:y},{34:[1,218]},{34:[1,219]},{34:[1,220]},{37:221,42:p,43:g,44:y},t(d,[2,36]),t(d,[2,38]),t(d,[2,37]),t(d,[2,39]),t(d,[2,41]),t(d,[2,40]),t(d,[2,97]),t(d,[2,98]),t(d,[2,95]),t(d,[2,96]),t(d,[2,100]),t(d,[2,99]),t(d,[2,104]),t(d,[2,103]),t(d,[2,102]),t(d,[2,101]),t(d,[2,106]),t(d,[2,105]),t(d,[2,94]),t(d,[2,93]),t(d,[2,92]),t(d,[2,91]),t(d,[2,89]),t(d,[2,90]),t(d,[2,88]),t(d,[2,87]),t(d,[2,86]),t(d,[2,85]),t(d,[2,83]),t(d,[2,84])],defaultActions:{9:[2,114],10:[2,1],11:[2,2],19:[2,3],27:[2,4],46:[2,116],47:[2,5]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t);},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,l=0,u=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var b=p.options&&p.options.ranges;function v(){var t;return "number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,k,w,T,E,C,S,A,M={};;){if(k=n[n.length-1],this.defaultActions[k]?w=this.defaultActions[k]:(null==_&&(_=v()),w=o[k]&&o[k][_]),void 0===w||!w.length||!w[0]){var N="";for(E in A=[],o[k])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A});}if(w[0]instanceof Array&&w.length>1)throw new Error("Parse Error: multiple actions possible at state: "+k+", token: "+_);switch(w[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(w[1]),_=null,x?(_=x,x=null):(l=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,u>0&&u--);break;case 2:if(C=this.productions_[w[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},b&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,l,c,g.yy,w[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[w[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return !0}}return !0}},v={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e);},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t));},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return (t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return !1}return !1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;a<i.length;a++)if((n=this._input.match(this.rules[i[a]]))&&(!e||n[0].length>e[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return !1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t);},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return (t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t);},stateStackSize:function(){return this.conditionStack.length},options:{"case-insensitive":!0},performAction:function(t,e,n,r){switch(n){case 0:return this.begin("open_directive"),49;case 1:return this.begin("type_directive"),50;case 2:return this.popState(),this.begin("arg_directive"),9;case 3:return this.popState(),this.popState(),52;case 4:return 51;case 5:return this.begin("acc_title"),20;case 6:return this.popState(),"acc_title_value";case 7:return this.begin("acc_descr"),22;case 8:return this.popState(),"acc_descr_value";case 9:this.begin("acc_descr_multiline");break;case 10:case 35:case 38:this.popState();break;case 11:return "acc_descr_multiline_value";case 12:return 14;case 13:case 14:case 15:break;case 16:return 6;case 17:return 39;case 18:return 33;case 19:return 36;case 20:return 41;case 21:return 42;case 22:return 43;case 23:return 44;case 24:return 38;case 25:return 29;case 26:return 30;case 27:return 35;case 28:return 32;case 29:return 27;case 30:case 31:return 10;case 32:return 9;case 33:return "CARET";case 34:this.begin("options");break;case 36:return 13;case 37:this.begin("string");break;case 39:return 34;case 40:return 31;case 41:return 28;case 42:return 8}},rules:[/^(?:%%\{)/i,/^(?:((?:(?!\}%%)[^:.])*))/i,/^(?::)/i,/^(?:\}%%)/i,/^(?:((?:(?!\}%%).|\n)*))/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:(\r?\n)+)/i,/^(?:\s+)/i,/^(?:#[^\n]*)/i,/^(?:%[^\n]*)/i,/^(?:gitGraph\b)/i,/^(?:commit\b)/i,/^(?:id:)/i,/^(?:type:)/i,/^(?:msg:)/i,/^(?:NORMAL\b)/i,/^(?:REVERSE\b)/i,/^(?:HIGHLIGHT\b)/i,/^(?:tag:)/i,/^(?:branch\b)/i,/^(?:order:)/i,/^(?:merge\b)/i,/^(?:cherry-pick\b)/i,/^(?:checkout\b)/i,/^(?:LR\b)/i,/^(?:BT\b)/i,/^(?::)/i,/^(?:\^)/i,/^(?:options\r?\n)/i,/^(?:[ \r\n\t]+end\b)/i,/^(?:[\s\S]+(?=[ \r\n\t]+end))/i,/^(?:["])/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:[0-9]+)/i,/^(?:[a-zA-Z][-_\./a-zA-Z0-9]*[-_a-zA-Z0-9])/i,/^(?:$)/i],conditions:{acc_descr_multiline:{rules:[10,11],inclusive:!1},acc_descr:{rules:[8],inclusive:!1},acc_title:{rules:[6],inclusive:!1},close_directive:{rules:[],inclusive:!1},arg_directive:{rules:[3,4],inclusive:!1},type_directive:{rules:[2,3],inclusive:!1},open_directive:{rules:[1],inclusive:!1},options:{rules:[35,36],inclusive:!1},string:{rules:[38,39],inclusive:!1},INITIAL:{rules:[0,5,7,9,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,37,40,41,42],inclusive:!0}}};function _(){this.yy={};}return b.lexer=v,_.prototype=b,b.Parser=_,new _}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(8183).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1));},6765:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[6,9,10],n={trace:function(){},yy:{},symbols_:{error:2,start:3,info:4,document:5,EOF:6,line:7,statement:8,NL:9,showInfo:10,$accept:0,$end:1},terminals_:{2:"error",4:"info",6:"EOF",9:"NL",10:"showInfo"},productions_:[0,[3,3],[5,0],[5,2],[7,1],[7,1],[8,1]],performAction:function(t,e,n,r,i,a,o){switch(a.length,i){case 1:return r;case 4:break;case 6:r.setInfo(!0);}},table:[{3:1,4:[1,2]},{1:[3]},t(e,[2,2],{5:3}),{6:[1,4],7:5,8:6,9:[1,7],10:[1,8]},{1:[2,1]},t(e,[2,3]),t(e,[2,4]),t(e,[2,5]),t(e,[2,6])],defaultActions:{4:[2,1]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t);},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,l=0,u=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var b=p.options&&p.options.ranges;function v(){var t;return "number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,k,w,T,E,C,S,A,M={};;){if(k=n[n.length-1],this.defaultActions[k]?w=this.defaultActions[k]:(null==_&&(_=v()),w=o[k]&&o[k][_]),void 0===w||!w.length||!w[0]){var N="";for(E in A=[],o[k])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A});}if(w[0]instanceof Array&&w.length>1)throw new Error("Parse Error: multiple actions possible at state: "+k+", token: "+_);switch(w[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(w[1]),_=null,x?(_=x,x=null):(l=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,u>0&&u--);break;case 2:if(C=this.productions_[w[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},b&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,l,c,g.yy,w[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[w[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return !0}}return !0}},r={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e);},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t));},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return (t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return !1}return !1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;a<i.length;a++)if((n=this._input.match(this.rules[i[a]]))&&(!e||n[0].length>e[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return !1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t);},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return (t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t);},stateStackSize:function(){return this.conditionStack.length},options:{"case-insensitive":!0},performAction:function(t,e,n,r){switch(n){case 0:return 4;case 1:return 9;case 2:return "space";case 3:return 10;case 4:return 6;case 5:return "TXT"}},rules:[/^(?:info\b)/i,/^(?:[\s\n\r]+)/i,/^(?:[\s]+)/i,/^(?:showInfo\b)/i,/^(?:$)/i,/^(?:.)/i],conditions:{INITIAL:{rules:[0,1,2,3,4,5],inclusive:!0}}};function i(){this.yy={};}return n.lexer=r,i.prototype=n,n.Parser=i,new i}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(1428).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1));},7062:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,4],n=[1,5],r=[1,6],i=[1,7],a=[1,9],o=[1,11,13,15,17,19,20,26,27,28,29],s=[2,5],c=[1,6,11,13,15,17,19,20,26,27,28,29],l=[26,27,28],u=[2,8],h=[1,18],f=[1,19],d=[1,20],p=[1,21],g=[1,22],y=[1,23],m=[1,28],b=[6,26,27,28,29],v={trace:function(){},yy:{},symbols_:{error:2,start:3,eol:4,directive:5,PIE:6,document:7,showData:8,line:9,statement:10,txt:11,value:12,title:13,title_value:14,acc_title:15,acc_title_value:16,acc_descr:17,acc_descr_value:18,acc_descr_multiline_value:19,section:20,openDirective:21,typeDirective:22,closeDirective:23,":":24,argDirective:25,NEWLINE:26,";":27,EOF:28,open_directive:29,type_directive:30,arg_directive:31,close_directive:32,$accept:0,$end:1},terminals_:{2:"error",6:"PIE",8:"showData",11:"txt",12:"value",13:"title",14:"title_value",15:"acc_title",16:"acc_title_value",17:"acc_descr",18:"acc_descr_value",19:"acc_descr_multiline_value",20:"section",24:":",26:"NEWLINE",27:";",28:"EOF",29:"open_directive",30:"type_directive",31:"arg_directive",32:"close_directive"},productions_:[0,[3,2],[3,2],[3,2],[3,3],[7,0],[7,2],[9,2],[10,0],[10,2],[10,2],[10,2],[10,2],[10,1],[10,1],[10,1],[5,3],[5,5],[4,1],[4,1],[4,1],[21,1],[22,1],[25,1],[23,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 4:r.setShowData(!0);break;case 7:this.$=a[s-1];break;case 9:r.addSection(a[s-1],r.cleanupValue(a[s]));break;case 10:this.$=a[s].trim(),r.setDiagramTitle(this.$);break;case 11:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 12:case 13:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 14:r.addSection(a[s].substr(8)),this.$=a[s].substr(8);break;case 21:r.parseDirective("%%{","open_directive");break;case 22:r.parseDirective(a[s],"type_directive");break;case 23:a[s]=a[s].trim().replace(/'/g,'"'),r.parseDirective(a[s],"arg_directive");break;case 24:r.parseDirective("}%%","close_directive","pie");}},table:[{3:1,4:2,5:3,6:e,21:8,26:n,27:r,28:i,29:a},{1:[3]},{3:10,4:2,5:3,6:e,21:8,26:n,27:r,28:i,29:a},{3:11,4:2,5:3,6:e,21:8,26:n,27:r,28:i,29:a},t(o,s,{7:12,8:[1,13]}),t(c,[2,18]),t(c,[2,19]),t(c,[2,20]),{22:14,30:[1,15]},{30:[2,21]},{1:[2,1]},{1:[2,2]},t(l,u,{21:8,9:16,10:17,5:24,1:[2,3],11:h,13:f,15:d,17:p,19:g,20:y,29:a}),t(o,s,{7:25}),{23:26,24:[1,27],32:m},t([24,32],[2,22]),t(o,[2,6]),{4:29,26:n,27:r,28:i},{12:[1,30]},{14:[1,31]},{16:[1,32]},{18:[1,33]},t(l,[2,13]),t(l,[2,14]),t(l,[2,15]),t(l,u,{21:8,9:16,10:17,5:24,1:[2,4],11:h,13:f,15:d,17:p,19:g,20:y,29:a}),t(b,[2,16]),{25:34,31:[1,35]},t(b,[2,24]),t(o,[2,7]),t(l,[2,9]),t(l,[2,10]),t(l,[2,11]),t(l,[2,12]),{23:36,32:m},{32:[2,23]},t(b,[2,17])],defaultActions:{9:[2,21],10:[2,1],11:[2,2],35:[2,23]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t);},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,l=0,u=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var b=p.options&&p.options.ranges;function v(){var t;return "number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,k,w,T,E,C,S,A,M={};;){if(k=n[n.length-1],this.defaultActions[k]?w=this.defaultActions[k]:(null==_&&(_=v()),w=o[k]&&o[k][_]),void 0===w||!w.length||!w[0]){var N="";for(E in A=[],o[k])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A});}if(w[0]instanceof Array&&w.length>1)throw new Error("Parse Error: multiple actions possible at state: "+k+", token: "+_);switch(w[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(w[1]),_=null,x?(_=x,x=null):(l=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,u>0&&u--);break;case 2:if(C=this.productions_[w[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},b&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,l,c,g.yy,w[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[w[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return !0}}return !0}},_={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e);},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t));},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return (t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return !1}return !1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;a<i.length;a++)if((n=this._input.match(this.rules[i[a]]))&&(!e||n[0].length>e[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return !1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t);},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return (t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t);},stateStackSize:function(){return this.conditionStack.length},options:{"case-insensitive":!0},performAction:function(t,e,n,r){switch(n){case 0:return this.begin("open_directive"),29;case 1:return this.begin("type_directive"),30;case 2:return this.popState(),this.begin("arg_directive"),24;case 3:return this.popState(),this.popState(),32;case 4:return 31;case 5:case 6:case 8:case 9:break;case 7:return 26;case 10:return this.begin("title"),13;case 11:return this.popState(),"title_value";case 12:return this.begin("acc_title"),15;case 13:return this.popState(),"acc_title_value";case 14:return this.begin("acc_descr"),17;case 15:return this.popState(),"acc_descr_value";case 16:this.begin("acc_descr_multiline");break;case 17:case 20:this.popState();break;case 18:return "acc_descr_multiline_value";case 19:this.begin("string");break;case 21:return "txt";case 22:return 6;case 23:return 8;case 24:return "value";case 25:return 28}},rules:[/^(?:%%\{)/i,/^(?:((?:(?!\}%%)[^:.])*))/i,/^(?::)/i,/^(?:\}%%)/i,/^(?:((?:(?!\}%%).|\n)*))/i,/^(?:%%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[\n\r]+)/i,/^(?:%%[^\n]*)/i,/^(?:[\s]+)/i,/^(?:title\b)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:["])/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:pie\b)/i,/^(?:showData\b)/i,/^(?::[\s]*[\d]+(?:\.[\d]+)?)/i,/^(?:$)/i],conditions:{acc_descr_multiline:{rules:[17,18],inclusive:!1},acc_descr:{rules:[15],inclusive:!1},acc_title:{rules:[13],inclusive:!1},close_directive:{rules:[],inclusive:!1},arg_directive:{rules:[3,4],inclusive:!1},type_directive:{rules:[2,3],inclusive:!1},open_directive:{rules:[1],inclusive:!1},title:{rules:[11],inclusive:!1},string:{rules:[20,21],inclusive:!1},INITIAL:{rules:[0,5,6,7,8,9,10,12,14,16,19,22,23,24,25],inclusive:!0}}};function x(){this.yy={};}return v.lexer=_,x.prototype=v,v.Parser=x,new x}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(4551).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1));},3176:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,3],n=[1,5],r=[1,6],i=[1,7],a=[1,8],o=[5,6,8,14,16,18,19,40,41,42,43,44,45,53,71,72],s=[1,22],c=[2,13],l=[1,26],u=[1,27],h=[1,28],f=[1,29],d=[1,30],p=[1,31],g=[1,24],y=[1,32],m=[1,33],b=[1,36],v=[71,72],_=[5,8,14,16,18,19,40,41,42,43,44,45,53,60,62,71,72],x=[1,56],k=[1,57],w=[1,58],T=[1,59],E=[1,60],C=[1,61],S=[1,62],A=[62,63],M=[1,74],N=[1,70],O=[1,71],D=[1,72],B=[1,73],L=[1,75],I=[1,79],F=[1,80],R=[1,77],P=[1,78],j=[5,8,14,16,18,19,40,41,42,43,44,45,53,71,72],z={trace:function(){},yy:{},symbols_:{error:2,start:3,directive:4,NEWLINE:5,RD:6,diagram:7,EOF:8,openDirective:9,typeDirective:10,closeDirective:11,":":12,argDirective:13,acc_title:14,acc_title_value:15,acc_descr:16,acc_descr_value:17,acc_descr_multiline_value:18,open_directive:19,type_directive:20,arg_directive:21,close_directive:22,requirementDef:23,elementDef:24,relationshipDef:25,requirementType:26,requirementName:27,STRUCT_START:28,requirementBody:29,ID:30,COLONSEP:31,id:32,TEXT:33,text:34,RISK:35,riskLevel:36,VERIFYMTHD:37,verifyType:38,STRUCT_STOP:39,REQUIREMENT:40,FUNCTIONAL_REQUIREMENT:41,INTERFACE_REQUIREMENT:42,PERFORMANCE_REQUIREMENT:43,PHYSICAL_REQUIREMENT:44,DESIGN_CONSTRAINT:45,LOW_RISK:46,MED_RISK:47,HIGH_RISK:48,VERIFY_ANALYSIS:49,VERIFY_DEMONSTRATION:50,VERIFY_INSPECTION:51,VERIFY_TEST:52,ELEMENT:53,elementName:54,elementBody:55,TYPE:56,type:57,DOCREF:58,ref:59,END_ARROW_L:60,relationship:61,LINE:62,END_ARROW_R:63,CONTAINS:64,COPIES:65,DERIVES:66,SATISFIES:67,VERIFIES:68,REFINES:69,TRACES:70,unqString:71,qString:72,$accept:0,$end:1},terminals_:{2:"error",5:"NEWLINE",6:"RD",8:"EOF",12:":",14:"acc_title",15:"acc_title_value",16:"acc_descr",17:"acc_descr_value",18:"acc_descr_multiline_value",19:"open_directive",20:"type_directive",21:"arg_directive",22:"close_directive",28:"STRUCT_START",30:"ID",31:"COLONSEP",33:"TEXT",35:"RISK",37:"VERIFYMTHD",39:"STRUCT_STOP",40:"REQUIREMENT",41:"FUNCTIONAL_REQUIREMENT",42:"INTERFACE_REQUIREMENT",43:"PERFORMANCE_REQUIREMENT",44:"PHYSICAL_REQUIREMENT",45:"DESIGN_CONSTRAINT",46:"LOW_RISK",47:"MED_RISK",48:"HIGH_RISK",49:"VERIFY_ANALYSIS",50:"VERIFY_DEMONSTRATION",51:"VERIFY_INSPECTION",52:"VERIFY_TEST",53:"ELEMENT",56:"TYPE",58:"DOCREF",60:"END_ARROW_L",62:"LINE",63:"END_ARROW_R",64:"CONTAINS",65:"COPIES",66:"DERIVES",67:"SATISFIES",68:"VERIFIES",69:"REFINES",70:"TRACES",71:"unqString",72:"qString"},productions_:[0,[3,3],[3,2],[3,4],[4,3],[4,5],[4,2],[4,2],[4,1],[9,1],[10,1],[13,1],[11,1],[7,0],[7,2],[7,2],[7,2],[7,2],[7,2],[23,5],[29,5],[29,5],[29,5],[29,5],[29,2],[29,1],[26,1],[26,1],[26,1],[26,1],[26,1],[26,1],[36,1],[36,1],[36,1],[38,1],[38,1],[38,1],[38,1],[24,5],[55,5],[55,5],[55,2],[55,1],[25,5],[25,5],[61,1],[61,1],[61,1],[61,1],[61,1],[61,1],[61,1],[27,1],[27,1],[32,1],[32,1],[34,1],[34,1],[54,1],[54,1],[57,1],[57,1],[59,1],[59,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 6:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 7:case 8:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 9:r.parseDirective("%%{","open_directive");break;case 10:r.parseDirective(a[s],"type_directive");break;case 11:a[s]=a[s].trim().replace(/'/g,'"'),r.parseDirective(a[s],"arg_directive");break;case 12:r.parseDirective("}%%","close_directive","pie");break;case 13:this.$=[];break;case 19:r.addRequirement(a[s-3],a[s-4]);break;case 20:r.setNewReqId(a[s-2]);break;case 21:r.setNewReqText(a[s-2]);break;case 22:r.setNewReqRisk(a[s-2]);break;case 23:r.setNewReqVerifyMethod(a[s-2]);break;case 26:this.$=r.RequirementType.REQUIREMENT;break;case 27:this.$=r.RequirementType.FUNCTIONAL_REQUIREMENT;break;case 28:this.$=r.RequirementType.INTERFACE_REQUIREMENT;break;case 29:this.$=r.RequirementType.PERFORMANCE_REQUIREMENT;break;case 30:this.$=r.RequirementType.PHYSICAL_REQUIREMENT;break;case 31:this.$=r.RequirementType.DESIGN_CONSTRAINT;break;case 32:this.$=r.RiskLevel.LOW_RISK;break;case 33:this.$=r.RiskLevel.MED_RISK;break;case 34:this.$=r.RiskLevel.HIGH_RISK;break;case 35:this.$=r.VerifyType.VERIFY_ANALYSIS;break;case 36:this.$=r.VerifyType.VERIFY_DEMONSTRATION;break;case 37:this.$=r.VerifyType.VERIFY_INSPECTION;break;case 38:this.$=r.VerifyType.VERIFY_TEST;break;case 39:r.addElement(a[s-3]);break;case 40:r.setNewElementType(a[s-2]);break;case 41:r.setNewElementDocRef(a[s-2]);break;case 44:r.addRelationship(a[s-2],a[s],a[s-4]);break;case 45:r.addRelationship(a[s-2],a[s-4],a[s]);break;case 46:this.$=r.Relationships.CONTAINS;break;case 47:this.$=r.Relationships.COPIES;break;case 48:this.$=r.Relationships.DERIVES;break;case 49:this.$=r.Relationships.SATISFIES;break;case 50:this.$=r.Relationships.VERIFIES;break;case 51:this.$=r.Relationships.REFINES;break;case 52:this.$=r.Relationships.TRACES;}},table:[{3:1,4:2,6:e,9:4,14:n,16:r,18:i,19:a},{1:[3]},{3:10,4:2,5:[1,9],6:e,9:4,14:n,16:r,18:i,19:a},{5:[1,11]},{10:12,20:[1,13]},{15:[1,14]},{17:[1,15]},t(o,[2,8]),{20:[2,9]},{3:16,4:2,6:e,9:4,14:n,16:r,18:i,19:a},{1:[2,2]},{4:21,5:s,7:17,8:c,9:4,14:n,16:r,18:i,19:a,23:18,24:19,25:20,26:23,32:25,40:l,41:u,42:h,43:f,44:d,45:p,53:g,71:y,72:m},{11:34,12:[1,35],22:b},t([12,22],[2,10]),t(o,[2,6]),t(o,[2,7]),{1:[2,1]},{8:[1,37]},{4:21,5:s,7:38,8:c,9:4,14:n,16:r,18:i,19:a,23:18,24:19,25:20,26:23,32:25,40:l,41:u,42:h,43:f,44:d,45:p,53:g,71:y,72:m},{4:21,5:s,7:39,8:c,9:4,14:n,16:r,18:i,19:a,23:18,24:19,25:20,26:23,32:25,40:l,41:u,42:h,43:f,44:d,45:p,53:g,71:y,72:m},{4:21,5:s,7:40,8:c,9:4,14:n,16:r,18:i,19:a,23:18,24:19,25:20,26:23,32:25,40:l,41:u,42:h,43:f,44:d,45:p,53:g,71:y,72:m},{4:21,5:s,7:41,8:c,9:4,14:n,16:r,18:i,19:a,23:18,24:19,25:20,26:23,32:25,40:l,41:u,42:h,43:f,44:d,45:p,53:g,71:y,72:m},{4:21,5:s,7:42,8:c,9:4,14:n,16:r,18:i,19:a,23:18,24:19,25:20,26:23,32:25,40:l,41:u,42:h,43:f,44:d,45:p,53:g,71:y,72:m},{27:43,71:[1,44],72:[1,45]},{54:46,71:[1,47],72:[1,48]},{60:[1,49],62:[1,50]},t(v,[2,26]),t(v,[2,27]),t(v,[2,28]),t(v,[2,29]),t(v,[2,30]),t(v,[2,31]),t(_,[2,55]),t(_,[2,56]),t(o,[2,4]),{13:51,21:[1,52]},t(o,[2,12]),{1:[2,3]},{8:[2,14]},{8:[2,15]},{8:[2,16]},{8:[2,17]},{8:[2,18]},{28:[1,53]},{28:[2,53]},{28:[2,54]},{28:[1,54]},{28:[2,59]},{28:[2,60]},{61:55,64:x,65:k,66:w,67:T,68:E,69:C,70:S},{61:63,64:x,65:k,66:w,67:T,68:E,69:C,70:S},{11:64,22:b},{22:[2,11]},{5:[1,65]},{5:[1,66]},{62:[1,67]},t(A,[2,46]),t(A,[2,47]),t(A,[2,48]),t(A,[2,49]),t(A,[2,50]),t(A,[2,51]),t(A,[2,52]),{63:[1,68]},t(o,[2,5]),{5:M,29:69,30:N,33:O,35:D,37:B,39:L},{5:I,39:F,55:76,56:R,58:P},{32:81,71:y,72:m},{32:82,71:y,72:m},t(j,[2,19]),{31:[1,83]},{31:[1,84]},{31:[1,85]},{31:[1,86]},{5:M,29:87,30:N,33:O,35:D,37:B,39:L},t(j,[2,25]),t(j,[2,39]),{31:[1,88]},{31:[1,89]},{5:I,39:F,55:90,56:R,58:P},t(j,[2,43]),t(j,[2,44]),t(j,[2,45]),{32:91,71:y,72:m},{34:92,71:[1,93],72:[1,94]},{36:95,46:[1,96],47:[1,97],48:[1,98]},{38:99,49:[1,100],50:[1,101],51:[1,102],52:[1,103]},t(j,[2,24]),{57:104,71:[1,105],72:[1,106]},{59:107,71:[1,108],72:[1,109]},t(j,[2,42]),{5:[1,110]},{5:[1,111]},{5:[2,57]},{5:[2,58]},{5:[1,112]},{5:[2,32]},{5:[2,33]},{5:[2,34]},{5:[1,113]},{5:[2,35]},{5:[2,36]},{5:[2,37]},{5:[2,38]},{5:[1,114]},{5:[2,61]},{5:[2,62]},{5:[1,115]},{5:[2,63]},{5:[2,64]},{5:M,29:116,30:N,33:O,35:D,37:B,39:L},{5:M,29:117,30:N,33:O,35:D,37:B,39:L},{5:M,29:118,30:N,33:O,35:D,37:B,39:L},{5:M,29:119,30:N,33:O,35:D,37:B,39:L},{5:I,39:F,55:120,56:R,58:P},{5:I,39:F,55:121,56:R,58:P},t(j,[2,20]),t(j,[2,21]),t(j,[2,22]),t(j,[2,23]),t(j,[2,40]),t(j,[2,41])],defaultActions:{8:[2,9],10:[2,2],16:[2,1],37:[2,3],38:[2,14],39:[2,15],40:[2,16],41:[2,17],42:[2,18],44:[2,53],45:[2,54],47:[2,59],48:[2,60],52:[2,11],93:[2,57],94:[2,58],96:[2,32],97:[2,33],98:[2,34],100:[2,35],101:[2,36],102:[2,37],103:[2,38],105:[2,61],106:[2,62],108:[2,63],109:[2,64]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t);},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,l=0,u=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var b=p.options&&p.options.ranges;function v(){var t;return "number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,k,w,T,E,C,S,A,M={};;){if(k=n[n.length-1],this.defaultActions[k]?w=this.defaultActions[k]:(null==_&&(_=v()),w=o[k]&&o[k][_]),void 0===w||!w.length||!w[0]){var N="";for(E in A=[],o[k])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A});}if(w[0]instanceof Array&&w.length>1)throw new Error("Parse Error: multiple actions possible at state: "+k+", token: "+_);switch(w[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(w[1]),_=null,x?(_=x,x=null):(l=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,u>0&&u--);break;case 2:if(C=this.productions_[w[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},b&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,l,c,g.yy,w[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[w[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return !0}}return !0}},Y={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e);},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t));},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return (t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return !1}return !1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;a<i.length;a++)if((n=this._input.match(this.rules[i[a]]))&&(!e||n[0].length>e[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return !1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t);},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return (t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t);},stateStackSize:function(){return this.conditionStack.length},options:{"case-insensitive":!0},performAction:function(t,e,n,r){switch(n){case 0:return this.begin("open_directive"),19;case 1:return this.begin("type_directive"),20;case 2:return this.popState(),this.begin("arg_directive"),12;case 3:return this.popState(),this.popState(),22;case 4:return 21;case 5:return "title";case 6:return this.begin("acc_title"),14;case 7:return this.popState(),"acc_title_value";case 8:return this.begin("acc_descr"),16;case 9:return this.popState(),"acc_descr_value";case 10:this.begin("acc_descr_multiline");break;case 11:case 53:this.popState();break;case 12:return "acc_descr_multiline_value";case 13:return 5;case 14:case 15:case 16:break;case 17:return 8;case 18:return 6;case 19:return 28;case 20:return 39;case 21:return 31;case 22:return 30;case 23:return 33;case 24:return 35;case 25:return 37;case 26:return 40;case 27:return 41;case 28:return 42;case 29:return 43;case 30:return 44;case 31:return 45;case 32:return 46;case 33:return 47;case 34:return 48;case 35:return 49;case 36:return 50;case 37:return 51;case 38:return 52;case 39:return 53;case 40:return 64;case 41:return 65;case 42:return 66;case 43:return 67;case 44:return 68;case 45:return 69;case 46:return 70;case 47:return 56;case 48:return 58;case 49:return 60;case 50:return 63;case 51:return 62;case 52:this.begin("string");break;case 54:return "qString";case 55:return e.yytext=e.yytext.trim(),71}},rules:[/^(?:%%\{)/i,/^(?:((?:(?!\}%%)[^:.])*))/i,/^(?::)/i,/^(?:\}%%)/i,/^(?:((?:(?!\}%%).|\n)*))/i,/^(?:title\s[^#\n;]+)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:(\r?\n)+)/i,/^(?:\s+)/i,/^(?:#[^\n]*)/i,/^(?:%[^\n]*)/i,/^(?:$)/i,/^(?:requirementDiagram\b)/i,/^(?:\{)/i,/^(?:\})/i,/^(?::)/i,/^(?:id\b)/i,/^(?:text\b)/i,/^(?:risk\b)/i,/^(?:verifyMethod\b)/i,/^(?:requirement\b)/i,/^(?:functionalRequirement\b)/i,/^(?:interfaceRequirement\b)/i,/^(?:performanceRequirement\b)/i,/^(?:physicalRequirement\b)/i,/^(?:designConstraint\b)/i,/^(?:low\b)/i,/^(?:medium\b)/i,/^(?:high\b)/i,/^(?:analysis\b)/i,/^(?:demonstration\b)/i,/^(?:inspection\b)/i,/^(?:test\b)/i,/^(?:element\b)/i,/^(?:contains\b)/i,/^(?:copies\b)/i,/^(?:derives\b)/i,/^(?:satisfies\b)/i,/^(?:verifies\b)/i,/^(?:refines\b)/i,/^(?:traces\b)/i,/^(?:type\b)/i,/^(?:docref\b)/i,/^(?:<-)/i,/^(?:->)/i,/^(?:-)/i,/^(?:["])/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:[\w][^\r\n\{\<\>\-\=]*)/i],conditions:{acc_descr_multiline:{rules:[11,12],inclusive:!1},acc_descr:{rules:[9],inclusive:!1},acc_title:{rules:[7],inclusive:!1},close_directive:{rules:[],inclusive:!1},arg_directive:{rules:[3,4],inclusive:!1},type_directive:{rules:[2,3],inclusive:!1},open_directive:{rules:[1],inclusive:!1},unqString:{rules:[],inclusive:!1},token:{rules:[],inclusive:!1},string:{rules:[53,54],inclusive:!1},INITIAL:{rules:[0,5,6,8,10,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,55],inclusive:!0}}};function U(){this.yy={};}return z.lexer=Y,U.prototype=z,z.Parser=U,new U}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(8800).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1));},6876:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,2],n=[1,3],r=[1,5],i=[1,7],a=[2,5],o=[1,15],s=[1,17],c=[1,18],l=[1,19],u=[1,21],h=[1,22],f=[1,23],d=[1,29],p=[1,30],g=[1,31],y=[1,32],m=[1,33],b=[1,34],v=[1,35],_=[1,36],x=[1,37],k=[1,38],w=[1,39],T=[1,40],E=[1,43],C=[1,44],S=[1,45],A=[1,46],M=[1,47],N=[1,48],O=[1,51],D=[1,4,5,16,20,22,25,26,32,33,34,36,38,39,40,41,42,43,45,47,49,50,51,52,53,58,59,60,61,69,79],B=[4,5,16,20,22,25,26,32,33,34,36,38,39,40,41,42,43,45,47,49,53,58,59,60,61,69,79],L=[4,5,16,20,22,25,26,32,33,34,36,38,39,40,41,42,43,45,47,49,52,53,58,59,60,61,69,79],I=[4,5,16,20,22,25,26,32,33,34,36,38,39,40,41,42,43,45,47,49,51,53,58,59,60,61,69,79],F=[4,5,16,20,22,25,26,32,33,34,36,38,39,40,41,42,43,45,47,49,50,53,58,59,60,61,69,79],R=[67,68,69],P=[1,121],j=[1,4,5,7,16,20,22,25,26,32,33,34,36,38,39,40,41,42,43,45,47,49,50,51,52,53,58,59,60,61,69,79],z={trace:function(){},yy:{},symbols_:{error:2,start:3,SPACE:4,NEWLINE:5,directive:6,SD:7,document:8,line:9,statement:10,openDirective:11,typeDirective:12,closeDirective:13,":":14,argDirective:15,participant:16,actor:17,AS:18,restOfLine:19,participant_actor:20,signal:21,autonumber:22,NUM:23,off:24,activate:25,deactivate:26,note_statement:27,links_statement:28,link_statement:29,properties_statement:30,details_statement:31,title:32,legacy_title:33,acc_title:34,acc_title_value:35,acc_descr:36,acc_descr_value:37,acc_descr_multiline_value:38,loop:39,end:40,rect:41,opt:42,alt:43,else_sections:44,par:45,par_sections:46,critical:47,option_sections:48,break:49,option:50,and:51,else:52,note:53,placement:54,text2:55,over:56,actor_pair:57,links:58,link:59,properties:60,details:61,spaceList:62,",":63,left_of:64,right_of:65,signaltype:66,"+":67,"-":68,ACTOR:69,SOLID_OPEN_ARROW:70,DOTTED_OPEN_ARROW:71,SOLID_ARROW:72,DOTTED_ARROW:73,SOLID_CROSS:74,DOTTED_CROSS:75,SOLID_POINT:76,DOTTED_POINT:77,TXT:78,open_directive:79,type_directive:80,arg_directive:81,close_directive:82,$accept:0,$end:1},terminals_:{2:"error",4:"SPACE",5:"NEWLINE",7:"SD",14:":",16:"participant",18:"AS",19:"restOfLine",20:"participant_actor",22:"autonumber",23:"NUM",24:"off",25:"activate",26:"deactivate",32:"title",33:"legacy_title",34:"acc_title",35:"acc_title_value",36:"acc_descr",37:"acc_descr_value",38:"acc_descr_multiline_value",39:"loop",40:"end",41:"rect",42:"opt",43:"alt",45:"par",47:"critical",49:"break",50:"option",51:"and",52:"else",53:"note",56:"over",58:"links",59:"link",60:"properties",61:"details",63:",",64:"left_of",65:"right_of",67:"+",68:"-",69:"ACTOR",70:"SOLID_OPEN_ARROW",71:"DOTTED_OPEN_ARROW",72:"SOLID_ARROW",73:"DOTTED_ARROW",74:"SOLID_CROSS",75:"DOTTED_CROSS",76:"SOLID_POINT",77:"DOTTED_POINT",78:"TXT",79:"open_directive",80:"type_directive",81:"arg_directive",82:"close_directive"},productions_:[0,[3,2],[3,2],[3,2],[3,2],[8,0],[8,2],[9,2],[9,1],[9,1],[6,4],[6,6],[10,5],[10,3],[10,5],[10,3],[10,2],[10,4],[10,3],[10,3],[10,2],[10,3],[10,3],[10,2],[10,2],[10,2],[10,2],[10,2],[10,1],[10,1],[10,2],[10,2],[10,1],[10,4],[10,4],[10,4],[10,4],[10,4],[10,4],[10,4],[10,1],[48,1],[48,4],[46,1],[46,4],[44,1],[44,4],[27,4],[27,4],[28,3],[29,3],[30,3],[31,3],[62,2],[62,1],[57,3],[57,1],[54,1],[54,1],[21,5],[21,5],[21,4],[17,1],[66,1],[66,1],[66,1],[66,1],[66,1],[66,1],[66,1],[66,1],[55,1],[11,1],[12,1],[15,1],[13,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 4:return r.apply(a[s]),a[s];case 5:case 9:this.$=[];break;case 6:a[s-1].push(a[s]),this.$=a[s-1];break;case 7:case 8:case 56:this.$=a[s];break;case 12:a[s-3].type="addParticipant",a[s-3].description=r.parseMessage(a[s-1]),this.$=a[s-3];break;case 13:a[s-1].type="addParticipant",this.$=a[s-1];break;case 14:a[s-3].type="addActor",a[s-3].description=r.parseMessage(a[s-1]),this.$=a[s-3];break;case 15:a[s-1].type="addActor",this.$=a[s-1];break;case 17:this.$={type:"sequenceIndex",sequenceIndex:Number(a[s-2]),sequenceIndexStep:Number(a[s-1]),sequenceVisible:!0,signalType:r.LINETYPE.AUTONUMBER};break;case 18:this.$={type:"sequenceIndex",sequenceIndex:Number(a[s-1]),sequenceIndexStep:1,sequenceVisible:!0,signalType:r.LINETYPE.AUTONUMBER};break;case 19:this.$={type:"sequenceIndex",sequenceVisible:!1,signalType:r.LINETYPE.AUTONUMBER};break;case 20:this.$={type:"sequenceIndex",sequenceVisible:!0,signalType:r.LINETYPE.AUTONUMBER};break;case 21:this.$={type:"activeStart",signalType:r.LINETYPE.ACTIVE_START,actor:a[s-1]};break;case 22:this.$={type:"activeEnd",signalType:r.LINETYPE.ACTIVE_END,actor:a[s-1]};break;case 28:r.setDiagramTitle(a[s].substring(6)),this.$=a[s].substring(6);break;case 29:r.setDiagramTitle(a[s].substring(7)),this.$=a[s].substring(7);break;case 30:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 31:case 32:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 33:a[s-1].unshift({type:"loopStart",loopText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.LOOP_START}),a[s-1].push({type:"loopEnd",loopText:a[s-2],signalType:r.LINETYPE.LOOP_END}),this.$=a[s-1];break;case 34:a[s-1].unshift({type:"rectStart",color:r.parseMessage(a[s-2]),signalType:r.LINETYPE.RECT_START}),a[s-1].push({type:"rectEnd",color:r.parseMessage(a[s-2]),signalType:r.LINETYPE.RECT_END}),this.$=a[s-1];break;case 35:a[s-1].unshift({type:"optStart",optText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.OPT_START}),a[s-1].push({type:"optEnd",optText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.OPT_END}),this.$=a[s-1];break;case 36:a[s-1].unshift({type:"altStart",altText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.ALT_START}),a[s-1].push({type:"altEnd",signalType:r.LINETYPE.ALT_END}),this.$=a[s-1];break;case 37:a[s-1].unshift({type:"parStart",parText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.PAR_START}),a[s-1].push({type:"parEnd",signalType:r.LINETYPE.PAR_END}),this.$=a[s-1];break;case 38:a[s-1].unshift({type:"criticalStart",criticalText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.CRITICAL_START}),a[s-1].push({type:"criticalEnd",signalType:r.LINETYPE.CRITICAL_END}),this.$=a[s-1];break;case 39:a[s-1].unshift({type:"breakStart",breakText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.BREAK_START}),a[s-1].push({type:"breakEnd",optText:r.parseMessage(a[s-2]),signalType:r.LINETYPE.BREAK_END}),this.$=a[s-1];break;case 42:this.$=a[s-3].concat([{type:"option",optionText:r.parseMessage(a[s-1]),signalType:r.LINETYPE.CRITICAL_OPTION},a[s]]);break;case 44:this.$=a[s-3].concat([{type:"and",parText:r.parseMessage(a[s-1]),signalType:r.LINETYPE.PAR_AND},a[s]]);break;case 46:this.$=a[s-3].concat([{type:"else",altText:r.parseMessage(a[s-1]),signalType:r.LINETYPE.ALT_ELSE},a[s]]);break;case 47:this.$=[a[s-1],{type:"addNote",placement:a[s-2],actor:a[s-1].actor,text:a[s]}];break;case 48:a[s-2]=[].concat(a[s-1],a[s-1]).slice(0,2),a[s-2][0]=a[s-2][0].actor,a[s-2][1]=a[s-2][1].actor,this.$=[a[s-1],{type:"addNote",placement:r.PLACEMENT.OVER,actor:a[s-2].slice(0,2),text:a[s]}];break;case 49:this.$=[a[s-1],{type:"addLinks",actor:a[s-1].actor,text:a[s]}];break;case 50:this.$=[a[s-1],{type:"addALink",actor:a[s-1].actor,text:a[s]}];break;case 51:this.$=[a[s-1],{type:"addProperties",actor:a[s-1].actor,text:a[s]}];break;case 52:this.$=[a[s-1],{type:"addDetails",actor:a[s-1].actor,text:a[s]}];break;case 55:this.$=[a[s-2],a[s]];break;case 57:this.$=r.PLACEMENT.LEFTOF;break;case 58:this.$=r.PLACEMENT.RIGHTOF;break;case 59:this.$=[a[s-4],a[s-1],{type:"addMessage",from:a[s-4].actor,to:a[s-1].actor,signalType:a[s-3],msg:a[s]},{type:"activeStart",signalType:r.LINETYPE.ACTIVE_START,actor:a[s-1]}];break;case 60:this.$=[a[s-4],a[s-1],{type:"addMessage",from:a[s-4].actor,to:a[s-1].actor,signalType:a[s-3],msg:a[s]},{type:"activeEnd",signalType:r.LINETYPE.ACTIVE_END,actor:a[s-4]}];break;case 61:this.$=[a[s-3],a[s-1],{type:"addMessage",from:a[s-3].actor,to:a[s-1].actor,signalType:a[s-2],msg:a[s]}];break;case 62:this.$={type:"addParticipant",actor:a[s]};break;case 63:this.$=r.LINETYPE.SOLID_OPEN;break;case 64:this.$=r.LINETYPE.DOTTED_OPEN;break;case 65:this.$=r.LINETYPE.SOLID;break;case 66:this.$=r.LINETYPE.DOTTED;break;case 67:this.$=r.LINETYPE.SOLID_CROSS;break;case 68:this.$=r.LINETYPE.DOTTED_CROSS;break;case 69:this.$=r.LINETYPE.SOLID_POINT;break;case 70:this.$=r.LINETYPE.DOTTED_POINT;break;case 71:this.$=r.parseMessage(a[s].trim().substring(1));break;case 72:r.parseDirective("%%{","open_directive");break;case 73:r.parseDirective(a[s],"type_directive");break;case 74:a[s]=a[s].trim().replace(/'/g,'"'),r.parseDirective(a[s],"arg_directive");break;case 75:r.parseDirective("}%%","close_directive","sequence");}},table:[{3:1,4:e,5:n,6:4,7:r,11:6,79:i},{1:[3]},{3:8,4:e,5:n,6:4,7:r,11:6,79:i},{3:9,4:e,5:n,6:4,7:r,11:6,79:i},{3:10,4:e,5:n,6:4,7:r,11:6,79:i},t([1,4,5,16,20,22,25,26,32,33,34,36,38,39,41,42,43,45,47,49,53,58,59,60,61,69,79],a,{8:11}),{12:12,80:[1,13]},{80:[2,72]},{1:[2,1]},{1:[2,2]},{1:[2,3]},{1:[2,4],4:o,5:s,6:41,9:14,10:16,11:6,16:c,17:42,20:l,21:20,22:u,25:h,26:f,27:24,28:25,29:26,30:27,31:28,32:d,33:p,34:g,36:y,38:m,39:b,41:v,42:_,43:x,45:k,47:w,49:T,53:E,58:C,59:S,60:A,61:M,69:N,79:i},{13:49,14:[1,50],82:O},t([14,82],[2,73]),t(D,[2,6]),{6:41,10:52,11:6,16:c,17:42,20:l,21:20,22:u,25:h,26:f,27:24,28:25,29:26,30:27,31:28,32:d,33:p,34:g,36:y,38:m,39:b,41:v,42:_,43:x,45:k,47:w,49:T,53:E,58:C,59:S,60:A,61:M,69:N,79:i},t(D,[2,8]),t(D,[2,9]),{17:53,69:N},{17:54,69:N},{5:[1,55]},{5:[1,58],23:[1,56],24:[1,57]},{17:59,69:N},{17:60,69:N},{5:[1,61]},{5:[1,62]},{5:[1,63]},{5:[1,64]},{5:[1,65]},t(D,[2,28]),t(D,[2,29]),{35:[1,66]},{37:[1,67]},t(D,[2,32]),{19:[1,68]},{19:[1,69]},{19:[1,70]},{19:[1,71]},{19:[1,72]},{19:[1,73]},{19:[1,74]},t(D,[2,40]),{66:75,70:[1,76],71:[1,77],72:[1,78],73:[1,79],74:[1,80],75:[1,81],76:[1,82],77:[1,83]},{54:84,56:[1,85],64:[1,86],65:[1,87]},{17:88,69:N},{17:89,69:N},{17:90,69:N},{17:91,69:N},t([5,18,63,70,71,72,73,74,75,76,77,78],[2,62]),{5:[1,92]},{15:93,81:[1,94]},{5:[2,75]},t(D,[2,7]),{5:[1,96],18:[1,95]},{5:[1,98],18:[1,97]},t(D,[2,16]),{5:[1,100],23:[1,99]},{5:[1,101]},t(D,[2,20]),{5:[1,102]},{5:[1,103]},t(D,[2,23]),t(D,[2,24]),t(D,[2,25]),t(D,[2,26]),t(D,[2,27]),t(D,[2,30]),t(D,[2,31]),t(B,a,{8:104}),t(B,a,{8:105}),t(B,a,{8:106}),t(L,a,{44:107,8:108}),t(I,a,{46:109,8:110}),t(F,a,{48:111,8:112}),t(B,a,{8:113}),{17:116,67:[1,114],68:[1,115],69:N},t(R,[2,63]),t(R,[2,64]),t(R,[2,65]),t(R,[2,66]),t(R,[2,67]),t(R,[2,68]),t(R,[2,69]),t(R,[2,70]),{17:117,69:N},{17:119,57:118,69:N},{69:[2,57]},{69:[2,58]},{55:120,78:P},{55:122,78:P},{55:123,78:P},{55:124,78:P},t(j,[2,10]),{13:125,82:O},{82:[2,74]},{19:[1,126]},t(D,[2,13]),{19:[1,127]},t(D,[2,15]),{5:[1,128]},t(D,[2,18]),t(D,[2,19]),t(D,[2,21]),t(D,[2,22]),{4:o,5:s,6:41,9:14,10:16,11:6,16:c,17:42,20:l,21:20,22:u,25:h,26:f,27:24,28:25,29:26,30:27,31:28,32:d,33:p,34:g,36:y,38:m,39:b,40:[1,129],41:v,42:_,43:x,45:k,47:w,49:T,53:E,58:C,59:S,60:A,61:M,69:N,79:i},{4:o,5:s,6:41,9:14,10:16,11:6,16:c,17:42,20:l,21:20,22:u,25:h,26:f,27:24,28:25,29:26,30:27,31:28,32:d,33:p,34:g,36:y,38:m,39:b,40:[1,130],41:v,42:_,43:x,45:k,47:w,49:T,53:E,58:C,59:S,60:A,61:M,69:N,79:i},{4:o,5:s,6:41,9:14,10:16,11:6,16:c,17:42,20:l,21:20,22:u,25:h,26:f,27:24,28:25,29:26,30:27,31:28,32:d,33:p,34:g,36:y,38:m,39:b,40:[1,131],41:v,42:_,43:x,45:k,47:w,49:T,53:E,58:C,59:S,60:A,61:M,69:N,79:i},{40:[1,132]},{4:o,5:s,6:41,9:14,10:16,11:6,16:c,17:42,20:l,21:20,22:u,25:h,26:f,27:24,28:25,29:26,30:27,31:28,32:d,33:p,34:g,36:y,38:m,39:b,40:[2,45],41:v,42:_,43:x,45:k,47:w,49:T,52:[1,133],53:E,58:C,59:S,60:A,61:M,69:N,79:i},{40:[1,134]},{4:o,5:s,6:41,9:14,10:16,11:6,16:c,17:42,20:l,21:20,22:u,25:h,26:f,27:24,28:25,29:26,30:27,31:28,32:d,33:p,34:g,36:y,38:m,39:b,40:[2,43],41:v,42:_,43:x,45:k,47:w,49:T,51:[1,135],53:E,58:C,59:S,60:A,61:M,69:N,79:i},{40:[1,136]},{4:o,5:s,6:41,9:14,10:16,11:6,16:c,17:42,20:l,21:20,22:u,25:h,26:f,27:24,28:25,29:26,30:27,31:28,32:d,33:p,34:g,36:y,38:m,39:b,40:[2,41],41:v,42:_,43:x,45:k,47:w,49:T,50:[1,137],53:E,58:C,59:S,60:A,61:M,69:N,79:i},{4:o,5:s,6:41,9:14,10:16,11:6,16:c,17:42,20:l,21:20,22:u,25:h,26:f,27:24,28:25,29:26,30:27,31:28,32:d,33:p,34:g,36:y,38:m,39:b,40:[1,138],41:v,42:_,43:x,45:k,47:w,49:T,53:E,58:C,59:S,60:A,61:M,69:N,79:i},{17:139,69:N},{17:140,69:N},{55:141,78:P},{55:142,78:P},{55:143,78:P},{63:[1,144],78:[2,56]},{5:[2,49]},{5:[2,71]},{5:[2,50]},{5:[2,51]},{5:[2,52]},{5:[1,145]},{5:[1,146]},{5:[1,147]},t(D,[2,17]),t(D,[2,33]),t(D,[2,34]),t(D,[2,35]),t(D,[2,36]),{19:[1,148]},t(D,[2,37]),{19:[1,149]},t(D,[2,38]),{19:[1,150]},t(D,[2,39]),{55:151,78:P},{55:152,78:P},{5:[2,61]},{5:[2,47]},{5:[2,48]},{17:153,69:N},t(j,[2,11]),t(D,[2,12]),t(D,[2,14]),t(L,a,{8:108,44:154}),t(I,a,{8:110,46:155}),t(F,a,{8:112,48:156}),{5:[2,59]},{5:[2,60]},{78:[2,55]},{40:[2,46]},{40:[2,44]},{40:[2,42]}],defaultActions:{7:[2,72],8:[2,1],9:[2,2],10:[2,3],51:[2,75],86:[2,57],87:[2,58],94:[2,74],120:[2,49],121:[2,71],122:[2,50],123:[2,51],124:[2,52],141:[2,61],142:[2,47],143:[2,48],151:[2,59],152:[2,60],153:[2,55],154:[2,46],155:[2,44],156:[2,42]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t);},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,l=0,u=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var b=p.options&&p.options.ranges;function v(){var t;return "number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,k,w,T,E,C,S,A,M={};;){if(k=n[n.length-1],this.defaultActions[k]?w=this.defaultActions[k]:(null==_&&(_=v()),w=o[k]&&o[k][_]),void 0===w||!w.length||!w[0]){var N="";for(E in A=[],o[k])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A});}if(w[0]instanceof Array&&w.length>1)throw new Error("Parse Error: multiple actions possible at state: "+k+", token: "+_);switch(w[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(w[1]),_=null,x?(_=x,x=null):(l=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,u>0&&u--);break;case 2:if(C=this.productions_[w[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},b&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,l,c,g.yy,w[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[w[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return !0}}return !0}},Y={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e);},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t));},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return (t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return !1}return !1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;a<i.length;a++)if((n=this._input.match(this.rules[i[a]]))&&(!e||n[0].length>e[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return !1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t);},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return (t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t);},stateStackSize:function(){return this.conditionStack.length},options:{"case-insensitive":!0},performAction:function(t,e,n,r){switch(n){case 0:return this.begin("open_directive"),79;case 1:return this.begin("type_directive"),80;case 2:return this.popState(),this.begin("arg_directive"),14;case 3:return this.popState(),this.popState(),82;case 4:return 81;case 5:case 52:case 65:return 5;case 6:case 7:case 8:case 9:case 10:break;case 11:return 23;case 12:return this.begin("ID"),16;case 13:return this.begin("ID"),20;case 14:return e.yytext=e.yytext.trim(),this.begin("ALIAS"),69;case 15:return this.popState(),this.popState(),this.begin("LINE"),18;case 16:return this.popState(),this.popState(),5;case 17:return this.begin("LINE"),39;case 18:return this.begin("LINE"),41;case 19:return this.begin("LINE"),42;case 20:return this.begin("LINE"),43;case 21:return this.begin("LINE"),52;case 22:return this.begin("LINE"),45;case 23:return this.begin("LINE"),51;case 24:return this.begin("LINE"),47;case 25:return this.begin("LINE"),50;case 26:return this.begin("LINE"),49;case 27:return this.popState(),19;case 28:return 40;case 29:return 64;case 30:return 65;case 31:return 58;case 32:return 59;case 33:return 60;case 34:return 61;case 35:return 56;case 36:return 53;case 37:return this.begin("ID"),25;case 38:return this.begin("ID"),26;case 39:return 32;case 40:return 33;case 41:return this.begin("acc_title"),34;case 42:return this.popState(),"acc_title_value";case 43:return this.begin("acc_descr"),36;case 44:return this.popState(),"acc_descr_value";case 45:this.begin("acc_descr_multiline");break;case 46:this.popState();break;case 47:return "acc_descr_multiline_value";case 48:return 7;case 49:return 22;case 50:return 24;case 51:return 63;case 53:return e.yytext=e.yytext.trim(),69;case 54:return 72;case 55:return 73;case 56:return 70;case 57:return 71;case 58:return 74;case 59:return 75;case 60:return 76;case 61:return 77;case 62:return 78;case 63:return 67;case 64:return 68;case 66:return "INVALID"}},rules:[/^(?:%%\{)/i,/^(?:((?:(?!\}%%)[^:.])*))/i,/^(?::)/i,/^(?:\}%%)/i,/^(?:((?:(?!\}%%).|\n)*))/i,/^(?:[\n]+)/i,/^(?:\s+)/i,/^(?:((?!\n)\s)+)/i,/^(?:#[^\n]*)/i,/^(?:%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[0-9]+(?=[ \n]+))/i,/^(?:participant\b)/i,/^(?:actor\b)/i,/^(?:[^\->:\n,;]+?(?=((?!\n)\s)+as(?!\n)\s|[#\n;]|$))/i,/^(?:as\b)/i,/^(?:(?:))/i,/^(?:loop\b)/i,/^(?:rect\b)/i,/^(?:opt\b)/i,/^(?:alt\b)/i,/^(?:else\b)/i,/^(?:par\b)/i,/^(?:and\b)/i,/^(?:critical\b)/i,/^(?:option\b)/i,/^(?:break\b)/i,/^(?:(?:[:]?(?:no)?wrap)?[^#\n;]*)/i,/^(?:end\b)/i,/^(?:left of\b)/i,/^(?:right of\b)/i,/^(?:links\b)/i,/^(?:link\b)/i,/^(?:properties\b)/i,/^(?:details\b)/i,/^(?:over\b)/i,/^(?:note\b)/i,/^(?:activate\b)/i,/^(?:deactivate\b)/i,/^(?:title\s[^#\n;]+)/i,/^(?:title:\s[^#\n;]+)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:sequenceDiagram\b)/i,/^(?:autonumber\b)/i,/^(?:off\b)/i,/^(?:,)/i,/^(?:;)/i,/^(?:[^\+\->:\n,;]+((?!(-x|--x|-\)|--\)))[\-]*[^\+\->:\n,;]+)*)/i,/^(?:->>)/i,/^(?:-->>)/i,/^(?:->)/i,/^(?:-->)/i,/^(?:-[x])/i,/^(?:--[x])/i,/^(?:-[\)])/i,/^(?:--[\)])/i,/^(?::(?:(?:no)?wrap)?[^#\n;]+)/i,/^(?:\+)/i,/^(?:-)/i,/^(?:$)/i,/^(?:.)/i],conditions:{acc_descr_multiline:{rules:[46,47],inclusive:!1},acc_descr:{rules:[44],inclusive:!1},acc_title:{rules:[42],inclusive:!1},open_directive:{rules:[1,8],inclusive:!1},type_directive:{rules:[2,3,8],inclusive:!1},arg_directive:{rules:[3,4,8],inclusive:!1},ID:{rules:[7,8,14],inclusive:!1},ALIAS:{rules:[7,8,15,16],inclusive:!1},LINE:{rules:[7,8,27],inclusive:!1},INITIAL:{rules:[0,5,6,8,9,10,11,12,13,17,18,19,20,21,22,23,24,25,26,28,29,30,31,32,33,34,35,36,37,38,39,40,41,43,45,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66],inclusive:!0}}};function U(){this.yy={};}return z.lexer=Y,U.prototype=z,z.Parser=U,new U}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(1993).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1));},3584:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,2],n=[1,3],r=[1,5],i=[1,7],a=[2,5],o=[1,15],s=[1,17],c=[1,19],l=[1,20],u=[1,21],h=[1,22],f=[1,33],d=[1,23],p=[1,24],g=[1,25],y=[1,26],m=[1,27],b=[1,30],v=[1,31],_=[1,32],x=[1,35],k=[1,36],w=[1,37],T=[1,38],E=[1,34],C=[1,41],S=[1,4,5,14,15,17,19,20,22,23,24,25,26,27,31,33,35,41,42,43,44,47,50],A=[1,4,5,12,13,14,15,17,19,20,22,23,24,25,26,27,31,33,35,41,42,43,44,47,50],M=[1,4,5,7,14,15,17,19,20,22,23,24,25,26,27,31,33,35,41,42,43,44,47,50],N=[4,5,14,15,17,19,20,22,23,24,25,26,27,31,33,35,41,42,43,44,47,50],O={trace:function(){},yy:{},symbols_:{error:2,start:3,SPACE:4,NL:5,directive:6,SD:7,document:8,line:9,statement:10,idStatement:11,DESCR:12,"--\x3e":13,HIDE_EMPTY:14,scale:15,WIDTH:16,COMPOSIT_STATE:17,STRUCT_START:18,STRUCT_STOP:19,STATE_DESCR:20,AS:21,ID:22,FORK:23,JOIN:24,CHOICE:25,CONCURRENT:26,note:27,notePosition:28,NOTE_TEXT:29,direction:30,acc_title:31,acc_title_value:32,acc_descr:33,acc_descr_value:34,acc_descr_multiline_value:35,openDirective:36,typeDirective:37,closeDirective:38,":":39,argDirective:40,direction_tb:41,direction_bt:42,direction_rl:43,direction_lr:44,eol:45,";":46,EDGE_STATE:47,left_of:48,right_of:49,open_directive:50,type_directive:51,arg_directive:52,close_directive:53,$accept:0,$end:1},terminals_:{2:"error",4:"SPACE",5:"NL",7:"SD",12:"DESCR",13:"--\x3e",14:"HIDE_EMPTY",15:"scale",16:"WIDTH",17:"COMPOSIT_STATE",18:"STRUCT_START",19:"STRUCT_STOP",20:"STATE_DESCR",21:"AS",22:"ID",23:"FORK",24:"JOIN",25:"CHOICE",26:"CONCURRENT",27:"note",29:"NOTE_TEXT",31:"acc_title",32:"acc_title_value",33:"acc_descr",34:"acc_descr_value",35:"acc_descr_multiline_value",39:":",41:"direction_tb",42:"direction_bt",43:"direction_rl",44:"direction_lr",46:";",47:"EDGE_STATE",48:"left_of",49:"right_of",50:"open_directive",51:"type_directive",52:"arg_directive",53:"close_directive"},productions_:[0,[3,2],[3,2],[3,2],[3,2],[8,0],[8,2],[9,2],[9,1],[9,1],[10,1],[10,2],[10,3],[10,4],[10,1],[10,2],[10,1],[10,4],[10,3],[10,6],[10,1],[10,1],[10,1],[10,1],[10,4],[10,4],[10,1],[10,1],[10,2],[10,2],[10,1],[6,3],[6,5],[30,1],[30,1],[30,1],[30,1],[45,1],[45,1],[11,1],[11,1],[28,1],[28,1],[36,1],[37,1],[40,1],[38,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 4:return r.setRootDoc(a[s]),a[s];case 5:this.$=[];break;case 6:"nl"!=a[s]&&(a[s-1].push(a[s]),this.$=a[s-1]);break;case 7:case 8:case 39:case 40:this.$=a[s];break;case 9:this.$="nl";break;case 10:this.$={stmt:"state",id:a[s],type:"default",description:""};break;case 11:this.$={stmt:"state",id:a[s-1],type:"default",description:r.trimColon(a[s])};break;case 12:this.$={stmt:"relation",state1:{stmt:"state",id:a[s-2],type:"default",description:""},state2:{stmt:"state",id:a[s],type:"default",description:""}};break;case 13:this.$={stmt:"relation",state1:{stmt:"state",id:a[s-3],type:"default",description:""},state2:{stmt:"state",id:a[s-1],type:"default",description:""},description:a[s].substr(1).trim()};break;case 17:this.$={stmt:"state",id:a[s-3],type:"default",description:"",doc:a[s-1]};break;case 18:var c=a[s],l=a[s-2].trim();if(a[s].match(":")){var u=a[s].split(":");c=u[0],l=[l,u[1]];}this.$={stmt:"state",id:c,type:"default",description:l};break;case 19:this.$={stmt:"state",id:a[s-3],type:"default",description:a[s-5],doc:a[s-1]};break;case 20:this.$={stmt:"state",id:a[s],type:"fork"};break;case 21:this.$={stmt:"state",id:a[s],type:"join"};break;case 22:this.$={stmt:"state",id:a[s],type:"choice"};break;case 23:this.$={stmt:"state",id:r.getDividerId(),type:"divider"};break;case 24:this.$={stmt:"state",id:a[s-1].trim(),note:{position:a[s-2].trim(),text:a[s].trim()}};break;case 28:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 29:case 30:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 33:r.setDirection("TB"),this.$={stmt:"dir",value:"TB"};break;case 34:r.setDirection("BT"),this.$={stmt:"dir",value:"BT"};break;case 35:r.setDirection("RL"),this.$={stmt:"dir",value:"RL"};break;case 36:r.setDirection("LR"),this.$={stmt:"dir",value:"LR"};break;case 43:r.parseDirective("%%{","open_directive");break;case 44:r.parseDirective(a[s],"type_directive");break;case 45:a[s]=a[s].trim().replace(/'/g,'"'),r.parseDirective(a[s],"arg_directive");break;case 46:r.parseDirective("}%%","close_directive","state");}},table:[{3:1,4:e,5:n,6:4,7:r,36:6,50:i},{1:[3]},{3:8,4:e,5:n,6:4,7:r,36:6,50:i},{3:9,4:e,5:n,6:4,7:r,36:6,50:i},{3:10,4:e,5:n,6:4,7:r,36:6,50:i},t([1,4,5,14,15,17,20,22,23,24,25,26,27,31,33,35,41,42,43,44,47,50],a,{8:11}),{37:12,51:[1,13]},{51:[2,43]},{1:[2,1]},{1:[2,2]},{1:[2,3]},{1:[2,4],4:o,5:s,6:28,9:14,10:16,11:18,14:c,15:l,17:u,20:h,22:f,23:d,24:p,25:g,26:y,27:m,30:29,31:b,33:v,35:_,36:6,41:x,42:k,43:w,44:T,47:E,50:i},{38:39,39:[1,40],53:C},t([39,53],[2,44]),t(S,[2,6]),{6:28,10:42,11:18,14:c,15:l,17:u,20:h,22:f,23:d,24:p,25:g,26:y,27:m,30:29,31:b,33:v,35:_,36:6,41:x,42:k,43:w,44:T,47:E,50:i},t(S,[2,8]),t(S,[2,9]),t(S,[2,10],{12:[1,43],13:[1,44]}),t(S,[2,14]),{16:[1,45]},t(S,[2,16],{18:[1,46]}),{21:[1,47]},t(S,[2,20]),t(S,[2,21]),t(S,[2,22]),t(S,[2,23]),{28:48,29:[1,49],48:[1,50],49:[1,51]},t(S,[2,26]),t(S,[2,27]),{32:[1,52]},{34:[1,53]},t(S,[2,30]),t(A,[2,39]),t(A,[2,40]),t(S,[2,33]),t(S,[2,34]),t(S,[2,35]),t(S,[2,36]),t(M,[2,31]),{40:54,52:[1,55]},t(M,[2,46]),t(S,[2,7]),t(S,[2,11]),{11:56,22:f,47:E},t(S,[2,15]),t(N,a,{8:57}),{22:[1,58]},{22:[1,59]},{21:[1,60]},{22:[2,41]},{22:[2,42]},t(S,[2,28]),t(S,[2,29]),{38:61,53:C},{53:[2,45]},t(S,[2,12],{12:[1,62]}),{4:o,5:s,6:28,9:14,10:16,11:18,14:c,15:l,17:u,19:[1,63],20:h,22:f,23:d,24:p,25:g,26:y,27:m,30:29,31:b,33:v,35:_,36:6,41:x,42:k,43:w,44:T,47:E,50:i},t(S,[2,18],{18:[1,64]}),{29:[1,65]},{22:[1,66]},t(M,[2,32]),t(S,[2,13]),t(S,[2,17]),t(N,a,{8:67}),t(S,[2,24]),t(S,[2,25]),{4:o,5:s,6:28,9:14,10:16,11:18,14:c,15:l,17:u,19:[1,68],20:h,22:f,23:d,24:p,25:g,26:y,27:m,30:29,31:b,33:v,35:_,36:6,41:x,42:k,43:w,44:T,47:E,50:i},t(S,[2,19])],defaultActions:{7:[2,43],8:[2,1],9:[2,2],10:[2,3],50:[2,41],51:[2,42],55:[2,45]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t);},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,l=0,u=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var b=p.options&&p.options.ranges;function v(){var t;return "number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,k,w,T,E,C,S,A,M={};;){if(k=n[n.length-1],this.defaultActions[k]?w=this.defaultActions[k]:(null==_&&(_=v()),w=o[k]&&o[k][_]),void 0===w||!w.length||!w[0]){var N="";for(E in A=[],o[k])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A});}if(w[0]instanceof Array&&w.length>1)throw new Error("Parse Error: multiple actions possible at state: "+k+", token: "+_);switch(w[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(w[1]),_=null,x?(_=x,x=null):(l=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,u>0&&u--);break;case 2:if(C=this.productions_[w[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},b&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,l,c,g.yy,w[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[w[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return !0}}return !0}},D={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e);},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t));},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return (t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return !1}return !1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;a<i.length;a++)if((n=this._input.match(this.rules[i[a]]))&&(!e||n[0].length>e[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return !1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t);},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return (t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t);},stateStackSize:function(){return this.conditionStack.length},options:{"case-insensitive":!0},performAction:function(t,e,n,r){switch(n){case 0:case 33:return 41;case 1:case 34:return 42;case 2:case 35:return 43;case 3:case 36:return 44;case 4:return this.begin("open_directive"),50;case 5:return this.begin("type_directive"),51;case 6:return this.popState(),this.begin("arg_directive"),39;case 7:return this.popState(),this.popState(),53;case 8:return 52;case 9:case 10:case 12:case 13:case 14:case 15:case 46:case 52:break;case 11:case 66:return 5;case 16:return this.pushState("SCALE"),15;case 17:return 16;case 18:case 24:case 40:case 43:this.popState();break;case 19:return this.begin("acc_title"),31;case 20:return this.popState(),"acc_title_value";case 21:return this.begin("acc_descr"),33;case 22:return this.popState(),"acc_descr_value";case 23:this.begin("acc_descr_multiline");break;case 25:return "acc_descr_multiline_value";case 26:this.pushState("STATE");break;case 27:case 30:return this.popState(),e.yytext=e.yytext.slice(0,-8).trim(),23;case 28:case 31:return this.popState(),e.yytext=e.yytext.slice(0,-8).trim(),24;case 29:case 32:return this.popState(),e.yytext=e.yytext.slice(0,-10).trim(),25;case 37:this.begin("STATE_STRING");break;case 38:return this.popState(),this.pushState("STATE_ID"),"AS";case 39:case 54:return this.popState(),"ID";case 41:return "STATE_DESCR";case 42:return 17;case 44:return this.popState(),this.pushState("struct"),18;case 45:return this.popState(),19;case 47:return this.begin("NOTE"),27;case 48:return this.popState(),this.pushState("NOTE_ID"),48;case 49:return this.popState(),this.pushState("NOTE_ID"),49;case 50:this.popState(),this.pushState("FLOATING_NOTE");break;case 51:return this.popState(),this.pushState("FLOATING_NOTE_ID"),"AS";case 53:return "NOTE_TEXT";case 55:return this.popState(),this.pushState("NOTE_TEXT"),22;case 56:return this.popState(),e.yytext=e.yytext.substr(2).trim(),29;case 57:return this.popState(),e.yytext=e.yytext.slice(0,-8).trim(),29;case 58:case 59:return 7;case 60:return 14;case 61:return 47;case 62:return 22;case 63:return e.yytext=e.yytext.trim(),12;case 64:return 13;case 65:return 26;case 67:return "INVALID"}},rules:[/^(?:.*direction\s+TB[^\n]*)/i,/^(?:.*direction\s+BT[^\n]*)/i,/^(?:.*direction\s+RL[^\n]*)/i,/^(?:.*direction\s+LR[^\n]*)/i,/^(?:%%\{)/i,/^(?:((?:(?!\}%%)[^:.])*))/i,/^(?::)/i,/^(?:\}%%)/i,/^(?:((?:(?!\}%%).|\n)*))/i,/^(?:%%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[\n]+)/i,/^(?:[\s]+)/i,/^(?:((?!\n)\s)+)/i,/^(?:#[^\n]*)/i,/^(?:%[^\n]*)/i,/^(?:scale\s+)/i,/^(?:\d+)/i,/^(?:\s+width\b)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:state\s+)/i,/^(?:.*<<fork>>)/i,/^(?:.*<<join>>)/i,/^(?:.*<<choice>>)/i,/^(?:.*\[\[fork\]\])/i,/^(?:.*\[\[join\]\])/i,/^(?:.*\[\[choice\]\])/i,/^(?:.*direction\s+TB[^\n]*)/i,/^(?:.*direction\s+BT[^\n]*)/i,/^(?:.*direction\s+RL[^\n]*)/i,/^(?:.*direction\s+LR[^\n]*)/i,/^(?:["])/i,/^(?:\s*as\s+)/i,/^(?:[^\n\{]*)/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:[^\n\s\{]+)/i,/^(?:\n)/i,/^(?:\{)/i,/^(?:\})/i,/^(?:[\n])/i,/^(?:note\s+)/i,/^(?:left of\b)/i,/^(?:right of\b)/i,/^(?:")/i,/^(?:\s*as\s*)/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:[^\n]*)/i,/^(?:\s*[^:\n\s\-]+)/i,/^(?:\s*:[^:\n;]+)/i,/^(?:[\s\S]*?end note\b)/i,/^(?:stateDiagram\s+)/i,/^(?:stateDiagram-v2\s+)/i,/^(?:hide empty description\b)/i,/^(?:\[\*\])/i,/^(?:[^:\n\s\-\{]+)/i,/^(?:\s*:[^:\n;]+)/i,/^(?:-->)/i,/^(?:--)/i,/^(?:$)/i,/^(?:.)/i],conditions:{LINE:{rules:[13,14],inclusive:!1},close_directive:{rules:[13,14],inclusive:!1},arg_directive:{rules:[7,8,13,14],inclusive:!1},type_directive:{rules:[6,7,13,14],inclusive:!1},open_directive:{rules:[5,13,14],inclusive:!1},struct:{rules:[13,14,26,33,34,35,36,45,46,47,61,62,63,64,65],inclusive:!1},FLOATING_NOTE_ID:{rules:[54],inclusive:!1},FLOATING_NOTE:{rules:[51,52,53],inclusive:!1},NOTE_TEXT:{rules:[56,57],inclusive:!1},NOTE_ID:{rules:[55],inclusive:!1},NOTE:{rules:[48,49,50],inclusive:!1},acc_descr_multiline:{rules:[24,25],inclusive:!1},acc_descr:{rules:[22],inclusive:!1},acc_title:{rules:[20],inclusive:!1},SCALE:{rules:[17,18],inclusive:!1},ALIAS:{rules:[],inclusive:!1},STATE_ID:{rules:[39],inclusive:!1},STATE_STRING:{rules:[40,41],inclusive:!1},FORK_STATE:{rules:[],inclusive:!1},STATE:{rules:[13,14,27,28,29,30,31,32,37,38,42,43,44],inclusive:!1},ID:{rules:[13,14],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,9,10,11,12,14,15,16,19,21,23,26,44,47,58,59,60,61,62,63,64,66,67],inclusive:!0}}};function B(){this.yy={};}return O.lexer=D,B.prototype=O,O.Parser=B,new B}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(3069).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1));},9763:(t,e,n)=>{t=n.nmd(t);var r=function(){var t=function(t,e,n,r){for(n=n||{},r=t.length;r--;n[t[r]]=e);return n},e=[1,2],n=[1,5],r=[6,9,11,17,18,20,22,23,24,26],i=[1,15],a=[1,16],o=[1,17],s=[1,18],c=[1,19],l=[1,20],u=[1,24],h=[4,6,9,11,17,18,20,22,23,24,26],f={trace:function(){},yy:{},symbols_:{error:2,start:3,journey:4,document:5,EOF:6,directive:7,line:8,SPACE:9,statement:10,NEWLINE:11,openDirective:12,typeDirective:13,closeDirective:14,":":15,argDirective:16,title:17,acc_title:18,acc_title_value:19,acc_descr:20,acc_descr_value:21,acc_descr_multiline_value:22,section:23,taskName:24,taskData:25,open_directive:26,type_directive:27,arg_directive:28,close_directive:29,$accept:0,$end:1},terminals_:{2:"error",4:"journey",6:"EOF",9:"SPACE",11:"NEWLINE",15:":",17:"title",18:"acc_title",19:"acc_title_value",20:"acc_descr",21:"acc_descr_value",22:"acc_descr_multiline_value",23:"section",24:"taskName",25:"taskData",26:"open_directive",27:"type_directive",28:"arg_directive",29:"close_directive"},productions_:[0,[3,3],[3,2],[5,0],[5,2],[8,2],[8,1],[8,1],[8,1],[7,4],[7,6],[10,1],[10,2],[10,2],[10,1],[10,1],[10,2],[10,1],[12,1],[13,1],[16,1],[14,1]],performAction:function(t,e,n,r,i,a,o){var s=a.length-1;switch(i){case 1:return a[s-1];case 3:case 7:case 8:this.$=[];break;case 4:a[s-1].push(a[s]),this.$=a[s-1];break;case 5:case 6:this.$=a[s];break;case 11:r.setDiagramTitle(a[s].substr(6)),this.$=a[s].substr(6);break;case 12:this.$=a[s].trim(),r.setAccTitle(this.$);break;case 13:case 14:this.$=a[s].trim(),r.setAccDescription(this.$);break;case 15:r.addSection(a[s].substr(8)),this.$=a[s].substr(8);break;case 16:r.addTask(a[s-1],a[s]),this.$="task";break;case 18:r.parseDirective("%%{","open_directive");break;case 19:r.parseDirective(a[s],"type_directive");break;case 20:a[s]=a[s].trim().replace(/'/g,'"'),r.parseDirective(a[s],"arg_directive");break;case 21:r.parseDirective("}%%","close_directive","journey");}},table:[{3:1,4:e,7:3,12:4,26:n},{1:[3]},t(r,[2,3],{5:6}),{3:7,4:e,7:3,12:4,26:n},{13:8,27:[1,9]},{27:[2,18]},{6:[1,10],7:21,8:11,9:[1,12],10:13,11:[1,14],12:4,17:i,18:a,20:o,22:s,23:c,24:l,26:n},{1:[2,2]},{14:22,15:[1,23],29:u},t([15,29],[2,19]),t(r,[2,8],{1:[2,1]}),t(r,[2,4]),{7:21,10:25,12:4,17:i,18:a,20:o,22:s,23:c,24:l,26:n},t(r,[2,6]),t(r,[2,7]),t(r,[2,11]),{19:[1,26]},{21:[1,27]},t(r,[2,14]),t(r,[2,15]),{25:[1,28]},t(r,[2,17]),{11:[1,29]},{16:30,28:[1,31]},{11:[2,21]},t(r,[2,5]),t(r,[2,12]),t(r,[2,13]),t(r,[2,16]),t(h,[2,9]),{14:32,29:u},{29:[2,20]},{11:[1,33]},t(h,[2,10])],defaultActions:{5:[2,18],7:[2,2],24:[2,21],31:[2,20]},parseError:function(t,e){if(!e.recoverable){var n=new Error(t);throw n.hash=e,n}this.trace(t);},parse:function(t){var e=this,n=[0],r=[],i=[null],a=[],o=this.table,s="",c=0,l=0,u=0,h=2,f=1,d=a.slice.call(arguments,1),p=Object.create(this.lexer),g={yy:{}};for(var y in this.yy)Object.prototype.hasOwnProperty.call(this.yy,y)&&(g.yy[y]=this.yy[y]);p.setInput(t,g.yy),g.yy.lexer=p,g.yy.parser=this,void 0===p.yylloc&&(p.yylloc={});var m=p.yylloc;a.push(m);var b=p.options&&p.options.ranges;function v(){var t;return "number"!=typeof(t=r.pop()||p.lex()||f)&&(t instanceof Array&&(t=(r=t).pop()),t=e.symbols_[t]||t),t}"function"==typeof g.yy.parseError?this.parseError=g.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var _,x,k,w,T,E,C,S,A,M={};;){if(k=n[n.length-1],this.defaultActions[k]?w=this.defaultActions[k]:(null==_&&(_=v()),w=o[k]&&o[k][_]),void 0===w||!w.length||!w[0]){var N="";for(E in A=[],o[k])this.terminals_[E]&&E>h&&A.push("'"+this.terminals_[E]+"'");N=p.showPosition?"Parse error on line "+(c+1)+":\n"+p.showPosition()+"\nExpecting "+A.join(", ")+", got '"+(this.terminals_[_]||_)+"'":"Parse error on line "+(c+1)+": Unexpected "+(_==f?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(N,{text:p.match,token:this.terminals_[_]||_,line:p.yylineno,loc:m,expected:A});}if(w[0]instanceof Array&&w.length>1)throw new Error("Parse Error: multiple actions possible at state: "+k+", token: "+_);switch(w[0]){case 1:n.push(_),i.push(p.yytext),a.push(p.yylloc),n.push(w[1]),_=null,x?(_=x,x=null):(l=p.yyleng,s=p.yytext,c=p.yylineno,m=p.yylloc,u>0&&u--);break;case 2:if(C=this.productions_[w[1]][1],M.$=i[i.length-C],M._$={first_line:a[a.length-(C||1)].first_line,last_line:a[a.length-1].last_line,first_column:a[a.length-(C||1)].first_column,last_column:a[a.length-1].last_column},b&&(M._$.range=[a[a.length-(C||1)].range[0],a[a.length-1].range[1]]),void 0!==(T=this.performAction.apply(M,[s,l,c,g.yy,w[1],i,a].concat(d))))return T;C&&(n=n.slice(0,-1*C*2),i=i.slice(0,-1*C),a=a.slice(0,-1*C)),n.push(this.productions_[w[1]][0]),i.push(M.$),a.push(M._$),S=o[n[n.length-2]][n[n.length-1]],n.push(S);break;case 3:return !0}}return !0}},d={EOF:1,parseError:function(t,e){if(!this.yy.parser)throw new Error(t);this.yy.parser.parseError(t,e);},setInput:function(t,e){return this.yy=e||this.yy||{},this._input=t,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var t=this._input[0];return this.yytext+=t,this.yyleng++,this.offset++,this.match+=t,this.matched+=t,t.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),t},unput:function(t){var e=t.length,n=t.split(/(?:\r\n?|\n)/g);this._input=t+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-e),this.offset-=e;var r=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),n.length-1&&(this.yylineno-=n.length-1);var i=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:n?(n.length===r.length?this.yylloc.first_column:0)+r[r.length-n.length].length-n[0].length:this.yylloc.first_column-e},this.options.ranges&&(this.yylloc.range=[i[0],i[0]+this.yyleng-e]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(t){this.unput(this.match.slice(t));},pastInput:function(){var t=this.matched.substr(0,this.matched.length-this.match.length);return (t.length>20?"...":"")+t.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var t=this.match;return t.length<20&&(t+=this._input.substr(0,20-t.length)),(t.substr(0,20)+(t.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var t=this.pastInput(),e=new Array(t.length+1).join("-");return t+this.upcomingInput()+"\n"+e+"^"},test_match:function(t,e){var n,r,i;if(this.options.backtrack_lexer&&(i={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(i.yylloc.range=this.yylloc.range.slice(0))),(r=t[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=r.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:r?r[r.length-1].length-r[r.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+t[0].length},this.yytext+=t[0],this.match+=t[0],this.matches=t,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(t[0].length),this.matched+=t[0],n=this.performAction.call(this,this.yy,this,e,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),n)return n;if(this._backtrack){for(var a in i)this[a]=i[a];return !1}return !1},next:function(){if(this.done)return this.EOF;var t,e,n,r;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var i=this._currentRules(),a=0;a<i.length;a++)if((n=this._input.match(this.rules[i[a]]))&&(!e||n[0].length>e[0].length)){if(e=n,r=a,this.options.backtrack_lexer){if(!1!==(t=this.test_match(n,i[a])))return t;if(this._backtrack){e=!1;continue}return !1}if(!this.options.flex)break}return e?!1!==(t=this.test_match(e,i[r]))&&t:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(t){this.conditionStack.push(t);},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(t){return (t=this.conditionStack.length-1-Math.abs(t||0))>=0?this.conditionStack[t]:"INITIAL"},pushState:function(t){this.begin(t);},stateStackSize:function(){return this.conditionStack.length},options:{"case-insensitive":!0},performAction:function(t,e,n,r){switch(n){case 0:return this.begin("open_directive"),26;case 1:return this.begin("type_directive"),27;case 2:return this.popState(),this.begin("arg_directive"),15;case 3:return this.popState(),this.popState(),29;case 4:return 28;case 5:case 6:case 8:case 9:break;case 7:return 11;case 10:return 4;case 11:return 17;case 12:return this.begin("acc_title"),18;case 13:return this.popState(),"acc_title_value";case 14:return this.begin("acc_descr"),20;case 15:return this.popState(),"acc_descr_value";case 16:this.begin("acc_descr_multiline");break;case 17:this.popState();break;case 18:return "acc_descr_multiline_value";case 19:return 23;case 20:return 24;case 21:return 25;case 22:return 15;case 23:return 6;case 24:return "INVALID"}},rules:[/^(?:%%\{)/i,/^(?:((?:(?!\}%%)[^:.])*))/i,/^(?::)/i,/^(?:\}%%)/i,/^(?:((?:(?!\}%%).|\n)*))/i,/^(?:%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[\n]+)/i,/^(?:\s+)/i,/^(?:#[^\n]*)/i,/^(?:journey\b)/i,/^(?:title\s[^#\n;]+)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:section\s[^#:\n;]+)/i,/^(?:[^#:\n;]+)/i,/^(?::[^#\n;]+)/i,/^(?::)/i,/^(?:$)/i,/^(?:.)/i],conditions:{open_directive:{rules:[1],inclusive:!1},type_directive:{rules:[2,3],inclusive:!1},arg_directive:{rules:[3,4],inclusive:!1},acc_descr_multiline:{rules:[17,18],inclusive:!1},acc_descr:{rules:[15],inclusive:!1},acc_title:{rules:[13],inclusive:!1},INITIAL:{rules:[0,5,6,7,8,9,10,11,12,14,16,19,20,21,22,23,24],inclusive:!0}}};function p(){this.yy={};}return f.lexer=d,p.prototype=f,f.Parser=p,new p}();e.parser=r,e.Parser=r.Parser,e.parse=function(){return r.parse.apply(r,arguments)},e.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),process.exit(1));var r=n(9143).readFileSync(n(6470).normalize(t[1]),"utf8");return e.parser.parse(r)},n.c[n.s]===t&&e.main(process.argv.slice(1));},7967:(t,e)=>{e.N=void 0;var n=/^([^\w]*)(javascript|data|vbscript)/im,r=/&#(\w+)(^\w|;)?/g,i=/[\u0000-\u001F\u007F-\u009F\u2000-\u200D\uFEFF]/gim,a=/^([^:]+):/gm,o=[".","/"];e.N=function(t){var e,s=(e=t||"",e.replace(r,(function(t,e){return String.fromCharCode(e)}))).replace(i,"").trim();if(!s)return "about:blank";if(function(t){return o.indexOf(t[0])>-1}(s))return s;var c=s.match(a);if(!c)return s;var l=c[0];return n.test(l)?"about:blank":s};},3841:t=>{t.exports=function(t,e){return t.intersect(e)};},6187:(t,e,n)=>{n.d(e,{Z:()=>fu});var r=n(1941),i=n.n(r),a={debug:1,info:2,warn:3,error:4,fatal:5},o={debug:function(){},info:function(){},warn:function(){},error:function(){},fatal:function(){}},s=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"fatal";isNaN(t)&&(t=t.toLowerCase(),void 0!==a[t]&&(t=a[t])),o.trace=function(){},o.debug=function(){},o.info=function(){},o.warn=function(){},o.error=function(){},o.fatal=function(){},t<=a.fatal&&(o.fatal=console.error?console.error.bind(console,c("FATAL"),"color: orange"):console.log.bind(console,"",c("FATAL"))),t<=a.error&&(o.error=console.error?console.error.bind(console,c("ERROR"),"color: orange"):console.log.bind(console,"",c("ERROR"))),t<=a.warn&&(o.warn=console.warn?console.warn.bind(console,c("WARN"),"color: orange"):console.log.bind(console,"",c("WARN"))),t<=a.info&&(o.info=console.info?console.info.bind(console,c("INFO"),"color: lightblue"):console.log.bind(console,"",c("INFO"))),t<=a.debug&&(o.debug=console.debug?console.debug.bind(console,c("DEBUG"),"color: lightgreen"):console.log.bind(console,"",c("DEBUG")));},c=function(t){var e=i()().format("ss.SSS");return "%c".concat(e," : ").concat(t," : ")},l=n(7543),u="comm",h="rule",f="decl",d=Math.abs,p=String.fromCharCode;function g(t){return t.trim()}function y(t,e,n){return t.replace(e,n)}function m(t,e){return t.indexOf(e)}function b(t,e){return 0|t.charCodeAt(e)}function v(t,e,n){return t.slice(e,n)}function _(t){return t.length}function x(t){return t.length}function k(t,e){return e.push(t),t}function w(t,e){for(var n="",r=x(t),i=0;i<r;i++)n+=e(t[i],i,t,e)||"";return n}function T(t,e,n,r){switch(t.type){case"@import":case f:return t.return=t.return||t.value;case u:return "";case"@keyframes":return t.return=t.value+"{"+w(t.children,r)+"}";case h:t.value=t.props.join(",");}return _(n=w(t.children,r))?t.return=t.value+"{"+n+"}":""}var E=1,C=1,S=0,A=0,M=0,N="";function O(t,e,n,r,i,a,o){return {value:t,root:e,parent:n,type:r,props:i,children:a,line:E,column:C,length:o,return:""}}function D(){return M=A>0?b(N,--A):0,C--,10===M&&(C=1,E--),M}function B(){return M=A<S?b(N,A++):0,C++,10===M&&(C=1,E++),M}function L(){return b(N,A)}function I(){return A}function F(t,e){return v(N,t,e)}function R(t){switch(t){case 0:case 9:case 10:case 13:case 32:return 5;case 33:case 43:case 44:case 47:case 62:case 64:case 126:case 59:case 123:case 125:return 4;case 58:return 3;case 34:case 39:case 40:case 91:return 2;case 41:case 93:return 1}return 0}function P(t){return g(F(A-1,Y(91===t?t+2:40===t?t+1:t)))}function j(t){for(;(M=L())&&M<33;)B();return R(t)>2||R(M)>3?"":" "}function z(t,e){for(;--e&&B()&&!(M<48||M>102||M>57&&M<65||M>70&&M<97););return F(t,I()+(e<6&&32==L()&&32==B()))}function Y(t){for(;B();)switch(M){case t:return A;case 34:case 39:34!==t&&39!==t&&Y(M);break;case 40:41===t&&Y(t);break;case 92:B();}return A}function U(t,e){for(;B()&&t+M!==57&&(t+M!==84||47!==L()););return "/*"+F(e,A-1)+"*"+p(47===t?t:B())}function $(t){for(;!R(L());)B();return F(t,A)}function W(t){return function(t){return N="",t}(q("",null,null,null,[""],t=function(t){return E=C=1,S=_(N=t),A=0,[]}(t),0,[0],t))}function q(t,e,n,r,i,a,o,s,c){for(var l=0,u=0,h=o,f=0,d=0,g=0,b=1,v=1,x=1,w=0,T="",E=i,C=a,S=r,A=T;v;)switch(g=w,w=B()){case 40:if(108!=g&&58==A.charCodeAt(h-1)){-1!=m(A+=y(P(w),"&","&\f"),"&\f")&&(x=-1);break}case 34:case 39:case 91:A+=P(w);break;case 9:case 10:case 13:case 32:A+=j(g);break;case 92:A+=z(I()-1,7);continue;case 47:switch(L()){case 42:case 47:k(V(U(B(),I()),e,n),c);break;default:A+="/";}break;case 123*b:s[l++]=_(A)*x;case 125*b:case 59:case 0:switch(w){case 0:case 125:v=0;case 59+u:d>0&&_(A)-h&&k(d>32?G(A+";",r,n,h-1):G(y(A," ","")+";",r,n,h-2),c);break;case 59:A+=";";default:if(k(S=H(A,e,n,l,u,i,s,T,E=[],C=[],h),a),123===w)if(0===u)q(A,e,S,S,E,a,h,s,C);else switch(f){case 100:case 109:case 115:q(t,S,S,r&&k(H(t,S,S,0,0,i,s,T,i,E=[],h),C),i,C,h,s,r?E:C);break;default:q(A,S,S,S,[""],C,0,s,C);}}l=u=d=0,b=x=1,T=A="",h=o;break;case 58:h=1+_(A),d=g;default:if(b<1)if(123==w)--b;else if(125==w&&0==b++&&125==D())continue;switch(A+=p(w),w*b){case 38:x=u>0?1:(A+="\f",-1);break;case 44:s[l++]=(_(A)-1)*x,x=1;break;case 64:45===L()&&(A+=P(B())),f=L(),u=h=_(T=A+=$(I())),w++;break;case 45:45===g&&2==_(A)&&(b=0);}}return a}function H(t,e,n,r,i,a,o,s,c,l,u){for(var f=i-1,p=0===i?a:[""],m=x(p),b=0,_=0,k=0;b<r;++b)for(var w=0,T=v(t,f+1,f=d(_=o[b])),E=t;w<m;++w)(E=g(_>0?p[w]+" "+T:y(T,/&\f/g,p[w])))&&(c[k++]=E);return O(t,e,n,0===i?h:s,c,l,u)}function V(t,e,n){return O(t,e,n,u,p(M),v(t,2,-2),0)}function G(t,e,n,r){return O(t,e,n,f,v(t,0,r),v(t,r+1,-1),r)}const X="9.1.7";function Z(t){return Z="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Z(t)}const Q=function t(e,n,r){var i=Object.assign({depth:2,clobber:!1},r),a=i.depth,o=i.clobber;return Array.isArray(n)&&!Array.isArray(e)?(n.forEach((function(n){return t(e,n,r)})),e):Array.isArray(n)&&Array.isArray(e)?(n.forEach((function(t){-1===e.indexOf(t)&&e.push(t);})),e):void 0===e||a<=0?null!=e&&"object"===Z(e)&&"object"===Z(n)?Object.assign(e,n):n:(void 0!==n&&"object"===Z(e)&&"object"===Z(n)&&Object.keys(n).forEach((function(r){"object"!==Z(n[r])||void 0!==e[r]&&"object"!==Z(e[r])?(o||"object"!==Z(e[r])&&"object"!==Z(n[r]))&&(e[r]=n[r]):(void 0===e[r]&&(e[r]=Array.isArray(n[r])?[]:{}),e[r]=t(e[r],n[r],{depth:a-1,clobber:o}));})),e)},K={min:{r:0,g:0,b:0,s:0,l:0,a:0},max:{r:255,g:255,b:255,h:360,s:100,l:100,a:1},clamp:{r:t=>t>=255?255:t<0?0:t,g:t=>t>=255?255:t<0?0:t,b:t=>t>=255?255:t<0?0:t,h:t=>t%360,s:t=>t>=100?100:t<0?0:t,l:t=>t>=100?100:t<0?0:t,a:t=>t>=1?1:t<0?0:t},toLinear:t=>{const e=t/255;return t>.03928?Math.pow((e+.055)/1.055,2.4):e/12.92},hue2rgb:(t,e,n)=>(n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+6*(e-t)*n:n<.5?e:n<2/3?t+(e-t)*(2/3-n)*6:t),hsl2rgb:({h:t,s:e,l:n},r)=>{if(!e)return 2.55*n;t/=360,e/=100;const i=(n/=100)<.5?n*(1+e):n+e-n*e,a=2*n-i;switch(r){case"r":return 255*K.hue2rgb(a,i,t+1/3);case"g":return 255*K.hue2rgb(a,i,t);case"b":return 255*K.hue2rgb(a,i,t-1/3)}},rgb2hsl:({r:t,g:e,b:n},r)=>{t/=255,e/=255,n/=255;const i=Math.max(t,e,n),a=Math.min(t,e,n),o=(i+a)/2;if("l"===r)return 100*o;if(i===a)return 0;const s=i-a;if("s"===r)return 100*(o>.5?s/(2-i-a):s/(i+a));switch(i){case t:return 60*((e-n)/s+(e<n?6:0));case e:return 60*((n-t)/s+2);case n:return 60*((t-e)/s+4);default:return -1}}},J={channel:K,lang:{clamp:(t,e,n)=>e>n?Math.min(e,Math.max(n,t)):Math.min(n,Math.max(e,t)),round:t=>Math.round(1e10*t)/1e10},unit:{dec2hex:t=>{const e=Math.round(t).toString(16);return e.length>1?e:`0${e}`}}},tt={};for(let t=0;t<=255;t++)tt[t]=J.unit.dec2hex(t);const et=new class{constructor(t,e){this.color=e,this.changed=!1,this.data=t,this.type=new class{constructor(){this.type=0;}get(){return this.type}set(t){if(this.type&&this.type!==t)throw new Error("Cannot change both RGB and HSL channels at the same time");this.type=t;}reset(){this.type=0;}is(t){return this.type===t}};}set(t,e){return this.color=e,this.changed=!1,this.data=t,this.type.type=0,this}_ensureHSL(){const t=this.data,{h:e,s:n,l:r}=t;void 0===e&&(t.h=J.channel.rgb2hsl(t,"h")),void 0===n&&(t.s=J.channel.rgb2hsl(t,"s")),void 0===r&&(t.l=J.channel.rgb2hsl(t,"l"));}_ensureRGB(){const t=this.data,{r:e,g:n,b:r}=t;void 0===e&&(t.r=J.channel.hsl2rgb(t,"r")),void 0===n&&(t.g=J.channel.hsl2rgb(t,"g")),void 0===r&&(t.b=J.channel.hsl2rgb(t,"b"));}get r(){const t=this.data,e=t.r;return this.type.is(2)||void 0===e?(this._ensureHSL(),J.channel.hsl2rgb(t,"r")):e}get g(){const t=this.data,e=t.g;return this.type.is(2)||void 0===e?(this._ensureHSL(),J.channel.hsl2rgb(t,"g")):e}get b(){const t=this.data,e=t.b;return this.type.is(2)||void 0===e?(this._ensureHSL(),J.channel.hsl2rgb(t,"b")):e}get h(){const t=this.data,e=t.h;return this.type.is(1)||void 0===e?(this._ensureRGB(),J.channel.rgb2hsl(t,"h")):e}get s(){const t=this.data,e=t.s;return this.type.is(1)||void 0===e?(this._ensureRGB(),J.channel.rgb2hsl(t,"s")):e}get l(){const t=this.data,e=t.l;return this.type.is(1)||void 0===e?(this._ensureRGB(),J.channel.rgb2hsl(t,"l")):e}get a(){return this.data.a}set r(t){this.type.set(1),this.changed=!0,this.data.r=t;}set g(t){this.type.set(1),this.changed=!0,this.data.g=t;}set b(t){this.type.set(1),this.changed=!0,this.data.b=t;}set h(t){this.type.set(2),this.changed=!0,this.data.h=t;}set s(t){this.type.set(2),this.changed=!0,this.data.s=t;}set l(t){this.type.set(2),this.changed=!0,this.data.l=t;}set a(t){this.changed=!0,this.data.a=t;}}({r:0,g:0,b:0,a:0},"transparent"),nt={re:/^#((?:[a-f0-9]{2}){2,4}|[a-f0-9]{3})$/i,parse:t=>{if(35!==t.charCodeAt(0))return;const e=t.match(nt.re);if(!e)return;const n=e[1],r=parseInt(n,16),i=n.length,a=i%4==0,o=i>4,s=o?1:17,c=o?8:4,l=a?0:-1,u=o?255:15;return et.set({r:(r>>c*(l+3)&u)*s,g:(r>>c*(l+2)&u)*s,b:(r>>c*(l+1)&u)*s,a:a?(r&u)*s/255:1},t)},stringify:t=>{const{r:e,g:n,b:r,a:i}=t;return i<1?`#${tt[Math.round(e)]}${tt[Math.round(n)]}${tt[Math.round(r)]}${tt[Math.round(255*i)]}`:`#${tt[Math.round(e)]}${tt[Math.round(n)]}${tt[Math.round(r)]}`}},rt=nt,it={re:/^hsla?\(\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?(?:deg|grad|rad|turn)?)\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?%)\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?%)(?:\s*?(?:,|\/)\s*?\+?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?(%)?))?\s*?\)$/i,hueRe:/^(.+?)(deg|grad|rad|turn)$/i,_hue2deg:t=>{const e=t.match(it.hueRe);if(e){const[,t,n]=e;switch(n){case"grad":return J.channel.clamp.h(.9*parseFloat(t));case"rad":return J.channel.clamp.h(180*parseFloat(t)/Math.PI);case"turn":return J.channel.clamp.h(360*parseFloat(t))}}return J.channel.clamp.h(parseFloat(t))},parse:t=>{const e=t.charCodeAt(0);if(104!==e&&72!==e)return;const n=t.match(it.re);if(!n)return;const[,r,i,a,o,s]=n;return et.set({h:it._hue2deg(r),s:J.channel.clamp.s(parseFloat(i)),l:J.channel.clamp.l(parseFloat(a)),a:o?J.channel.clamp.a(s?parseFloat(o)/100:parseFloat(o)):1},t)},stringify:t=>{const{h:e,s:n,l:r,a:i}=t;return i<1?`hsla(${J.lang.round(e)}, ${J.lang.round(n)}%, ${J.lang.round(r)}%, ${i})`:`hsl(${J.lang.round(e)}, ${J.lang.round(n)}%, ${J.lang.round(r)}%)`}},at=it,ot={colors:{aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyanaqua:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",transparent:"#00000000",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},parse:t=>{t=t.toLowerCase();const e=ot.colors[t];if(e)return rt.parse(e)},stringify:t=>{const e=rt.stringify(t);for(const t in ot.colors)if(ot.colors[t]===e)return t}},st=ot,ct={re:/^rgba?\(\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?))\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?))\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?))(?:\s*?(?:,|\/)\s*?\+?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?)))?\s*?\)$/i,parse:t=>{const e=t.charCodeAt(0);if(114!==e&&82!==e)return;const n=t.match(ct.re);if(!n)return;const[,r,i,a,o,s,c,l,u]=n;return et.set({r:J.channel.clamp.r(i?2.55*parseFloat(r):parseFloat(r)),g:J.channel.clamp.g(o?2.55*parseFloat(a):parseFloat(a)),b:J.channel.clamp.b(c?2.55*parseFloat(s):parseFloat(s)),a:l?J.channel.clamp.a(u?parseFloat(l)/100:parseFloat(l)):1},t)},stringify:t=>{const{r:e,g:n,b:r,a:i}=t;return i<1?`rgba(${J.lang.round(e)}, ${J.lang.round(n)}, ${J.lang.round(r)}, ${J.lang.round(i)})`:`rgb(${J.lang.round(e)}, ${J.lang.round(n)}, ${J.lang.round(r)})`}},lt=ct,ut={format:{keyword:st,hex:rt,rgb:lt,rgba:lt,hsl:at,hsla:at},parse:t=>{if("string"!=typeof t)return t;const e=rt.parse(t)||lt.parse(t)||at.parse(t)||st.parse(t);if(e)return e;throw new Error(`Unsupported color format: "${t}"`)},stringify:t=>!t.changed&&t.color?t.color:t.type.is(2)||void 0===t.data.r?at.stringify(t):t.a<1||!Number.isInteger(t.r)||!Number.isInteger(t.g)||!Number.isInteger(t.b)?lt.stringify(t):rt.stringify(t)},ht=(t,e)=>{const n=ut.parse(t);for(const t in e)n[t]=J.channel.clamp[t](e[t]);return ut.stringify(n)},ft=(t,e)=>{const n=ut.parse(t),r={};for(const t in e)e[t]&&(r[t]=n[t]+e[t]);return ht(t,r)},dt=(t,e,n=0,r=1)=>{if("number"!=typeof t)return ht(t,{a:e});const i=et.set({r:J.channel.clamp.r(t),g:J.channel.clamp.g(e),b:J.channel.clamp.b(n),a:J.channel.clamp.a(r)});return ut.stringify(i)},pt=(t,e=100)=>{const n=ut.parse(t);return n.r=255-n.r,n.g=255-n.g,n.b=255-n.b,((t,e,n=50)=>{const{r,g:i,b:a,a:o}=ut.parse(t),{r:s,g:c,b:l,a:u}=ut.parse(e),h=n/100,f=2*h-1,d=o-u,p=((f*d==-1?f:(f+d)/(1+f*d))+1)/2,g=1-p;return dt(r*p+s*g,i*p+c*g,a*p+l*g,o*h+u*(1-h))})(n,t,e)},gt=(t,e,n)=>{const r=ut.parse(t),i=r[e],a=J.channel.clamp[e](i+n);return i!==a&&(r[e]=a),ut.stringify(r)},yt=(t,e)=>gt(t,"l",-e),mt=(t,e)=>gt(t,"l",e);var bt=function(t,e){return ft(t,e?{s:-40,l:10}:{s:-40,l:-10})};function vt(t){return vt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},vt(t)}function _t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r);}}var xt=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.background="#f4f4f4",this.darkMode=!1,this.primaryColor="#fff4dd",this.noteBkgColor="#fff5ad",this.noteTextColor="#333",this.fontFamily='"trebuchet ms", verdana, arial, sans-serif',this.fontSize="16px";}var e,n;return e=t,n=[{key:"updateColors",value:function(){this.primaryTextColor=this.primaryTextColor||(this.darkMode?"#eee":"#333"),this.secondaryColor=this.secondaryColor||ft(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||ft(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||bt(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||bt(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||bt(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||bt(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||"#fff5ad",this.noteTextColor=this.noteTextColor||"#333",this.secondaryTextColor=this.secondaryTextColor||pt(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||pt(this.tertiaryColor),this.lineColor=this.lineColor||pt(this.background),this.textColor=this.textColor||this.primaryTextColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.primaryBorderColor,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?yt(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||"grey",this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||yt(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||pt(this.lineColor),this.sectionBkgColor=this.sectionBkgColor||this.tertiaryColor,this.altSectionBkgColor=this.altSectionBkgColor||"white",this.sectionBkgColor=this.sectionBkgColor||this.secondaryColor,this.sectionBkgColor2=this.sectionBkgColor2||this.primaryColor,this.excludeBkgColor=this.excludeBkgColor||"#eeeeee",this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||this.primaryColor,this.activeTaskBorderColor=this.activeTaskBorderColor||this.primaryColor,this.activeTaskBkgColor=this.activeTaskBkgColor||mt(this.primaryColor,23),this.gridColor=this.gridColor||"lightgrey",this.doneTaskBkgColor=this.doneTaskBkgColor||"lightgrey",this.doneTaskBorderColor=this.doneTaskBorderColor||"grey",this.critBorderColor=this.critBorderColor||"#ff8888",this.critBkgColor=this.critBkgColor||"red",this.todayLineColor=this.todayLineColor||"red",this.taskTextColor=this.taskTextColor||this.textColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||"#003163",this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||this.tertiaryColor,this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor,this.classText=this.classText||this.textColor,this.fillType0=this.fillType0||this.primaryColor,this.fillType1=this.fillType1||this.secondaryColor,this.fillType2=this.fillType2||ft(this.primaryColor,{h:64}),this.fillType3=this.fillType3||ft(this.secondaryColor,{h:64}),this.fillType4=this.fillType4||ft(this.primaryColor,{h:-64}),this.fillType5=this.fillType5||ft(this.secondaryColor,{h:-64}),this.fillType6=this.fillType6||ft(this.primaryColor,{h:128}),this.fillType7=this.fillType7||ft(this.secondaryColor,{h:128}),this.pie1=this.pie1||this.primaryColor,this.pie2=this.pie2||this.secondaryColor,this.pie3=this.pie3||this.tertiaryColor,this.pie4=this.pie4||ft(this.primaryColor,{l:-10}),this.pie5=this.pie5||ft(this.secondaryColor,{l:-10}),this.pie6=this.pie6||ft(this.tertiaryColor,{l:-10}),this.pie7=this.pie7||ft(this.primaryColor,{h:60,l:-10}),this.pie8=this.pie8||ft(this.primaryColor,{h:-60,l:-10}),this.pie9=this.pie9||ft(this.primaryColor,{h:120,l:0}),this.pie10=this.pie10||ft(this.primaryColor,{h:60,l:-20}),this.pie11=this.pie11||ft(this.primaryColor,{h:-60,l:-20}),this.pie12=this.pie12||ft(this.primaryColor,{h:120,l:-10}),this.pieTitleTextSize=this.pieTitleTextSize||"25px",this.pieTitleTextColor=this.pieTitleTextColor||this.taskTextDarkColor,this.pieSectionTextSize=this.pieSectionTextSize||"17px",this.pieSectionTextColor=this.pieSectionTextColor||this.textColor,this.pieLegendTextSize=this.pieLegendTextSize||"17px",this.pieLegendTextColor=this.pieLegendTextColor||this.taskTextDarkColor,this.pieStrokeColor=this.pieStrokeColor||"black",this.pieStrokeWidth=this.pieStrokeWidth||"2px",this.pieOpacity=this.pieOpacity||"0.7",this.requirementBackground=this.requirementBackground||this.primaryColor,this.requirementBorderColor=this.requirementBorderColor||this.primaryBorderColor,this.requirementBorderSize=this.requirementBorderSize||this.primaryBorderColor,this.requirementTextColor=this.requirementTextColor||this.primaryTextColor,this.relationColor=this.relationColor||this.lineColor,this.relationLabelBackground=this.relationLabelBackground||(this.darkMode?yt(this.secondaryColor,30):this.secondaryColor),this.relationLabelColor=this.relationLabelColor||this.actorTextColor,this.git0=this.git0||this.primaryColor,this.git1=this.git1||this.secondaryColor,this.git2=this.git2||this.tertiaryColor,this.git3=this.git3||ft(this.primaryColor,{h:-30}),this.git4=this.git4||ft(this.primaryColor,{h:-60}),this.git5=this.git5||ft(this.primaryColor,{h:-90}),this.git6=this.git6||ft(this.primaryColor,{h:60}),this.git7=this.git7||ft(this.primaryColor,{h:120}),this.darkMode?(this.git0=mt(this.git0,25),this.git1=mt(this.git1,25),this.git2=mt(this.git2,25),this.git3=mt(this.git3,25),this.git4=mt(this.git4,25),this.git5=mt(this.git5,25),this.git6=mt(this.git6,25),this.git7=mt(this.git7,25)):(this.git0=yt(this.git0,25),this.git1=yt(this.git1,25),this.git2=yt(this.git2,25),this.git3=yt(this.git3,25),this.git4=yt(this.git4,25),this.git5=yt(this.git5,25),this.git6=yt(this.git6,25),this.git7=yt(this.git7,25)),this.gitInv0=this.gitInv0||pt(this.git0),this.gitInv1=this.gitInv1||pt(this.git1),this.gitInv2=this.gitInv2||pt(this.git2),this.gitInv3=this.gitInv3||pt(this.git3),this.gitInv4=this.gitInv4||pt(this.git4),this.gitInv5=this.gitInv5||pt(this.git5),this.gitInv6=this.gitInv6||pt(this.git6),this.gitInv7=this.gitInv7||pt(this.git7),this.branchLabelColor=this.branchLabelColor||(this.darkMode?"black":this.labelTextColor),this.gitBranchLabel0=this.gitBranchLabel0||this.branchLabelColor,this.gitBranchLabel1=this.gitBranchLabel1||this.branchLabelColor,this.gitBranchLabel2=this.gitBranchLabel2||this.branchLabelColor,this.gitBranchLabel3=this.gitBranchLabel3||this.branchLabelColor,this.gitBranchLabel4=this.gitBranchLabel4||this.branchLabelColor,this.gitBranchLabel5=this.gitBranchLabel5||this.branchLabelColor,this.gitBranchLabel6=this.gitBranchLabel6||this.branchLabelColor,this.gitBranchLabel7=this.gitBranchLabel7||this.branchLabelColor,this.tagLabelColor=this.tagLabelColor||this.primaryTextColor,this.tagLabelBackground=this.tagLabelBackground||this.primaryColor,this.tagLabelBorder=this.tagBorder||this.primaryBorderColor,this.tagLabelFontSize=this.tagLabelFontSize||"10px",this.commitLabelColor=this.commitLabelColor||this.secondaryTextColor,this.commitLabelBackground=this.commitLabelBackground||this.secondaryColor,this.commitLabelFontSize=this.commitLabelFontSize||"10px";}},{key:"calculate",value:function(t){var e=this;if("object"===vt(t)){var n=Object.keys(t);n.forEach((function(n){e[n]=t[n];})),this.updateColors(),n.forEach((function(n){e[n]=t[n];}));}else this.updateColors();}}],n&&_t(e.prototype,n),Object.defineProperty(e,"prototype",{writable:!1}),t}();function kt(t){return kt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},kt(t)}function wt(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r);}}var Tt=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.background="#333",this.primaryColor="#1f2020",this.secondaryColor=mt(this.primaryColor,16),this.tertiaryColor=ft(this.primaryColor,{h:-160}),this.primaryBorderColor=pt(this.background),this.secondaryBorderColor=bt(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=bt(this.tertiaryColor,this.darkMode),this.primaryTextColor=pt(this.primaryColor),this.secondaryTextColor=pt(this.secondaryColor),this.tertiaryTextColor=pt(this.tertiaryColor),this.lineColor=pt(this.background),this.textColor=pt(this.background),this.mainBkg="#1f2020",this.secondBkg="calculated",this.mainContrastColor="lightgrey",this.darkTextColor=mt(pt("#323D47"),10),this.lineColor="calculated",this.border1="#81B1DB",this.border2=dt(255,255,255,.25),this.arrowheadColor="calculated",this.fontFamily='"trebuchet ms", verdana, arial, sans-serif',this.fontSize="16px",this.labelBackground="#181818",this.textColor="#ccc",this.nodeBkg="calculated",this.nodeBorder="calculated",this.clusterBkg="calculated",this.clusterBorder="calculated",this.defaultLinkColor="calculated",this.titleColor="#F9FFFE",this.edgeLabelBackground="calculated",this.actorBorder="calculated",this.actorBkg="calculated",this.actorTextColor="calculated",this.actorLineColor="calculated",this.signalColor="calculated",this.signalTextColor="calculated",this.labelBoxBkgColor="calculated",this.labelBoxBorderColor="calculated",this.labelTextColor="calculated",this.loopTextColor="calculated",this.noteBorderColor="calculated",this.noteBkgColor="#fff5ad",this.noteTextColor="calculated",this.activationBorderColor="calculated",this.activationBkgColor="calculated",this.sequenceNumberColor="black",this.sectionBkgColor=yt("#EAE8D9",30),this.altSectionBkgColor="calculated",this.sectionBkgColor2="#EAE8D9",this.taskBorderColor=dt(255,255,255,70),this.taskBkgColor="calculated",this.taskTextColor="calculated",this.taskTextLightColor="calculated",this.taskTextOutsideColor="calculated",this.taskTextClickableColor="#003163",this.activeTaskBorderColor=dt(255,255,255,50),this.activeTaskBkgColor="#81B1DB",this.gridColor="calculated",this.doneTaskBkgColor="calculated",this.doneTaskBorderColor="grey",this.critBorderColor="#E83737",this.critBkgColor="#E83737",this.taskTextDarkColor="calculated",this.todayLineColor="#DB5757",this.personBorder="calculated",this.personBkg="calculated",this.labelColor="calculated",this.errorBkgColor="#a44141",this.errorTextColor="#ddd";}var e,n;return e=t,n=[{key:"updateColors",value:function(){this.secondBkg=mt(this.mainBkg,16),this.lineColor=this.mainContrastColor,this.arrowheadColor=this.mainContrastColor,this.nodeBkg=this.mainBkg,this.nodeBorder=this.border1,this.clusterBkg=this.secondBkg,this.clusterBorder=this.border2,this.defaultLinkColor=this.lineColor,this.edgeLabelBackground=mt(this.labelBackground,25),this.actorBorder=this.border1,this.actorBkg=this.mainBkg,this.actorTextColor=this.mainContrastColor,this.actorLineColor=this.mainContrastColor,this.signalColor=this.mainContrastColor,this.signalTextColor=this.mainContrastColor,this.labelBoxBkgColor=this.actorBkg,this.labelBoxBorderColor=this.actorBorder,this.labelTextColor=this.mainContrastColor,this.loopTextColor=this.mainContrastColor,this.noteBorderColor=this.secondaryBorderColor,this.noteBkgColor=this.secondBkg,this.noteTextColor=this.secondaryTextColor,this.activationBorderColor=this.border1,this.activationBkgColor=this.secondBkg,this.altSectionBkgColor=this.background,this.taskBkgColor=mt(this.mainBkg,23),this.taskTextColor=this.darkTextColor,this.taskTextLightColor=this.mainContrastColor,this.taskTextOutsideColor=this.taskTextLightColor,this.gridColor=this.mainContrastColor,this.doneTaskBkgColor=this.mainContrastColor,this.taskTextDarkColor=this.darkTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||"#555",this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.primaryBorderColor,this.specialStateColor="#f4f4f4",this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.fillType0=this.primaryColor,this.fillType1=this.secondaryColor,this.fillType2=ft(this.primaryColor,{h:64}),this.fillType3=ft(this.secondaryColor,{h:64}),this.fillType4=ft(this.primaryColor,{h:-64}),this.fillType5=ft(this.secondaryColor,{h:-64}),this.fillType6=ft(this.primaryColor,{h:128}),this.fillType7=ft(this.secondaryColor,{h:128}),this.pie1=this.pie1||"#0b0000",this.pie2=this.pie2||"#4d1037",this.pie3=this.pie3||"#3f5258",this.pie4=this.pie4||"#4f2f1b",this.pie5=this.pie5||"#6e0a0a",this.pie6=this.pie6||"#3b0048",this.pie7=this.pie7||"#995a01",this.pie8=this.pie8||"#154706",this.pie9=this.pie9||"#161722",this.pie10=this.pie10||"#00296f",this.pie11=this.pie11||"#01629c",this.pie12=this.pie12||"#010029",this.pieTitleTextSize=this.pieTitleTextSize||"25px",this.pieTitleTextColor=this.pieTitleTextColor||this.taskTextDarkColor,this.pieSectionTextSize=this.pieSectionTextSize||"17px",this.pieSectionTextColor=this.pieSectionTextColor||this.textColor,this.pieLegendTextSize=this.pieLegendTextSize||"17px",this.pieLegendTextColor=this.pieLegendTextColor||this.taskTextDarkColor,this.pieStrokeColor=this.pieStrokeColor||"black",this.pieStrokeWidth=this.pieStrokeWidth||"2px",this.pieOpacity=this.pieOpacity||"0.7",this.classText=this.primaryTextColor,this.requirementBackground=this.requirementBackground||this.primaryColor,this.requirementBorderColor=this.requirementBorderColor||this.primaryBorderColor,this.requirementBorderSize=this.requirementBorderSize||this.primaryBorderColor,this.requirementTextColor=this.requirementTextColor||this.primaryTextColor,this.relationColor=this.relationColor||this.lineColor,this.relationLabelBackground=this.relationLabelBackground||(this.darkMode?yt(this.secondaryColor,30):this.secondaryColor),this.relationLabelColor=this.relationLabelColor||this.actorTextColor,this.git0=mt(this.secondaryColor,20),this.git1=mt(this.pie2||this.secondaryColor,20),this.git2=mt(this.pie3||this.tertiaryColor,20),this.git3=mt(this.pie4||ft(this.primaryColor,{h:-30}),20),this.git4=mt(this.pie5||ft(this.primaryColor,{h:-60}),20),this.git5=mt(this.pie6||ft(this.primaryColor,{h:-90}),10),this.git6=mt(this.pie7||ft(this.primaryColor,{h:60}),10),this.git7=mt(this.pie8||ft(this.primaryColor,{h:120}),20),this.gitInv0=this.gitInv0||pt(this.git0),this.gitInv1=this.gitInv1||pt(this.git1),this.gitInv2=this.gitInv2||pt(this.git2),this.gitInv3=this.gitInv3||pt(this.git3),this.gitInv4=this.gitInv4||pt(this.git4),this.gitInv5=this.gitInv5||pt(this.git5),this.gitInv6=this.gitInv6||pt(this.git6),this.gitInv7=this.gitInv7||pt(this.git7),this.tagLabelColor=this.tagLabelColor||this.primaryTextColor,this.tagLabelBackground=this.tagLabelBackground||this.primaryColor,this.tagLabelBorder=this.tagBorder||this.primaryBorderColor,this.tagLabelFontSize=this.tagLabelFontSize||"10px",this.commitLabelColor=this.commitLabelColor||this.secondaryTextColor,this.commitLabelBackground=this.commitLabelBackground||this.secondaryColor,this.commitLabelFontSize=this.commitLabelFontSize||"10px";}},{key:"calculate",value:function(t){var e=this;if("object"===kt(t)){var n=Object.keys(t);n.forEach((function(n){e[n]=t[n];})),this.updateColors(),n.forEach((function(n){e[n]=t[n];}));}else this.updateColors();}}],n&&wt(e.prototype,n),Object.defineProperty(e,"prototype",{writable:!1}),t}();function Et(t){return Et="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Et(t)}function Ct(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r);}}var St=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.background="#f4f4f4",this.primaryColor="#ECECFF",this.secondaryColor=ft(this.primaryColor,{h:120}),this.secondaryColor="#ffffde",this.tertiaryColor=ft(this.primaryColor,{h:-160}),this.primaryBorderColor=bt(this.primaryColor,this.darkMode),this.secondaryBorderColor=bt(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=bt(this.tertiaryColor,this.darkMode),this.primaryTextColor=pt(this.primaryColor),this.secondaryTextColor=pt(this.secondaryColor),this.tertiaryTextColor=pt(this.tertiaryColor),this.lineColor=pt(this.background),this.textColor=pt(this.background),this.background="white",this.mainBkg="#ECECFF",this.secondBkg="#ffffde",this.lineColor="#333333",this.border1="#9370DB",this.border2="#aaaa33",this.arrowheadColor="#333333",this.fontFamily='"trebuchet ms", verdana, arial, sans-serif',this.fontSize="16px",this.labelBackground="#e8e8e8",this.textColor="#333",this.nodeBkg="calculated",this.nodeBorder="calculated",this.clusterBkg="calculated",this.clusterBorder="calculated",this.defaultLinkColor="calculated",this.titleColor="calculated",this.edgeLabelBackground="calculated",this.actorBorder="calculated",this.actorBkg="calculated",this.actorTextColor="black",this.actorLineColor="grey",this.signalColor="calculated",this.signalTextColor="calculated",this.labelBoxBkgColor="calculated",this.labelBoxBorderColor="calculated",this.labelTextColor="calculated",this.loopTextColor="calculated",this.noteBorderColor="calculated",this.noteBkgColor="#fff5ad",this.noteTextColor="calculated",this.activationBorderColor="#666",this.activationBkgColor="#f4f4f4",this.sequenceNumberColor="white",this.sectionBkgColor="calculated",this.altSectionBkgColor="calculated",this.sectionBkgColor2="calculated",this.excludeBkgColor="#eeeeee",this.taskBorderColor="calculated",this.taskBkgColor="calculated",this.taskTextLightColor="calculated",this.taskTextColor=this.taskTextLightColor,this.taskTextDarkColor="calculated",this.taskTextOutsideColor=this.taskTextDarkColor,this.taskTextClickableColor="calculated",this.activeTaskBorderColor="calculated",this.activeTaskBkgColor="calculated",this.gridColor="calculated",this.doneTaskBkgColor="calculated",this.doneTaskBorderColor="calculated",this.critBorderColor="calculated",this.critBkgColor="calculated",this.todayLineColor="calculated",this.sectionBkgColor=dt(102,102,255,.49),this.altSectionBkgColor="white",this.sectionBkgColor2="#fff400",this.taskBorderColor="#534fbc",this.taskBkgColor="#8a90dd",this.taskTextLightColor="white",this.taskTextColor="calculated",this.taskTextDarkColor="black",this.taskTextOutsideColor="calculated",this.taskTextClickableColor="#003163",this.activeTaskBorderColor="#534fbc",this.activeTaskBkgColor="#bfc7ff",this.gridColor="lightgrey",this.doneTaskBkgColor="lightgrey",this.doneTaskBorderColor="grey",this.critBorderColor="#ff8888",this.critBkgColor="red",this.todayLineColor="red",this.personBorder="calculated",this.personBkg="calculated",this.labelColor="black",this.errorBkgColor="#552222",this.errorTextColor="#552222",this.updateColors();}var e,n;return e=t,n=[{key:"updateColors",value:function(){this.nodeBkg=this.mainBkg,this.nodeBorder=this.border1,this.clusterBkg=this.secondBkg,this.clusterBorder=this.border2,this.defaultLinkColor=this.lineColor,this.titleColor=this.textColor,this.edgeLabelBackground=this.labelBackground,this.actorBorder=mt(this.border1,23),this.actorBkg=this.mainBkg,this.labelBoxBkgColor=this.actorBkg,this.signalColor=this.textColor,this.signalTextColor=this.textColor,this.labelBoxBorderColor=this.actorBorder,this.labelTextColor=this.actorTextColor,this.loopTextColor=this.actorTextColor,this.noteBorderColor=this.border2,this.noteTextColor=this.actorTextColor,this.taskTextColor=this.taskTextLightColor,this.taskTextOutsideColor=this.taskTextDarkColor,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||"#f0f0f0",this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.specialStateColor=this.lineColor,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.classText=this.primaryTextColor,this.fillType0=this.primaryColor,this.fillType1=this.secondaryColor,this.fillType2=ft(this.primaryColor,{h:64}),this.fillType3=ft(this.secondaryColor,{h:64}),this.fillType4=ft(this.primaryColor,{h:-64}),this.fillType5=ft(this.secondaryColor,{h:-64}),this.fillType6=ft(this.primaryColor,{h:128}),this.fillType7=ft(this.secondaryColor,{h:128}),this.pie1=this.pie1||this.primaryColor,this.pie2=this.pie2||this.secondaryColor,this.pie3=this.pie3||ft(this.tertiaryColor,{l:-40}),this.pie4=this.pie4||ft(this.primaryColor,{l:-10}),this.pie5=this.pie5||ft(this.secondaryColor,{l:-30}),this.pie6=this.pie6||ft(this.tertiaryColor,{l:-20}),this.pie7=this.pie7||ft(this.primaryColor,{h:60,l:-20}),this.pie8=this.pie8||ft(this.primaryColor,{h:-60,l:-40}),this.pie9=this.pie9||ft(this.primaryColor,{h:120,l:-40}),this.pie10=this.pie10||ft(this.primaryColor,{h:60,l:-40}),this.pie11=this.pie11||ft(this.primaryColor,{h:-90,l:-40}),this.pie12=this.pie12||ft(this.primaryColor,{h:120,l:-30}),this.pieTitleTextSize=this.pieTitleTextSize||"25px",this.pieTitleTextColor=this.pieTitleTextColor||this.taskTextDarkColor,this.pieSectionTextSize=this.pieSectionTextSize||"17px",this.pieSectionTextColor=this.pieSectionTextColor||this.textColor,this.pieLegendTextSize=this.pieLegendTextSize||"17px",this.pieLegendTextColor=this.pieLegendTextColor||this.taskTextDarkColor,this.pieStrokeColor=this.pieStrokeColor||"black",this.pieStrokeWidth=this.pieStrokeWidth||"2px",this.pieOpacity=this.pieOpacity||"0.7",this.requirementBackground=this.requirementBackground||this.primaryColor,this.requirementBorderColor=this.requirementBorderColor||this.primaryBorderColor,this.requirementBorderSize=this.requirementBorderSize||this.primaryBorderColor,this.requirementTextColor=this.requirementTextColor||this.primaryTextColor,this.relationColor=this.relationColor||this.lineColor,this.relationLabelBackground=this.relationLabelBackground||this.labelBackground,this.relationLabelColor=this.relationLabelColor||this.actorTextColor,this.git0=this.git0||this.primaryColor,this.git1=this.git1||this.secondaryColor,this.git2=this.git2||this.tertiaryColor,this.git3=this.git3||ft(this.primaryColor,{h:-30}),this.git4=this.git4||ft(this.primaryColor,{h:-60}),this.git5=this.git5||ft(this.primaryColor,{h:-90}),this.git6=this.git6||ft(this.primaryColor,{h:60}),this.git7=this.git7||ft(this.primaryColor,{h:120}),this.darkMode?(this.git0=mt(this.git0,25),this.git1=mt(this.git1,25),this.git2=mt(this.git2,25),this.git3=mt(this.git3,25),this.git4=mt(this.git4,25),this.git5=mt(this.git5,25),this.git6=mt(this.git6,25),this.git7=mt(this.git7,25)):(this.git0=yt(this.git0,25),this.git1=yt(this.git1,25),this.git2=yt(this.git2,25),this.git3=yt(this.git3,25),this.git4=yt(this.git4,25),this.git5=yt(this.git5,25),this.git6=yt(this.git6,25),this.git7=yt(this.git7,25)),this.gitInv0=this.gitInv0||yt(pt(this.git0),25),this.gitInv1=this.gitInv1||pt(this.git1),this.gitInv2=this.gitInv2||pt(this.git2),this.gitInv3=this.gitInv3||pt(this.git3),this.gitInv4=this.gitInv4||pt(this.git4),this.gitInv5=this.gitInv5||pt(this.git5),this.gitInv6=this.gitInv6||pt(this.git6),this.gitInv7=this.gitInv7||pt(this.git7),this.gitBranchLabel0=this.gitBranchLabel0||pt(this.labelTextColor),this.gitBranchLabel1=this.gitBranchLabel1||this.labelTextColor,this.gitBranchLabel2=this.gitBranchLabel2||this.labelTextColor,this.gitBranchLabel3=this.gitBranchLabel3||pt(this.labelTextColor),this.gitBranchLabel4=this.gitBranchLabel4||this.labelTextColor,this.gitBranchLabel5=this.gitBranchLabel5||this.labelTextColor,this.gitBranchLabel6=this.gitBranchLabel6||this.labelTextColor,this.gitBranchLabel7=this.gitBranchLabel7||this.labelTextColor,this.tagLabelColor=this.tagLabelColor||this.primaryTextColor,this.tagLabelBackground=this.tagLabelBackground||this.primaryColor,this.tagLabelBorder=this.tagBorder||this.primaryBorderColor,this.tagLabelFontSize=this.tagLabelFontSize||"10px",this.commitLabelColor=this.commitLabelColor||this.secondaryTextColor,this.commitLabelBackground=this.commitLabelBackground||this.secondaryColor,this.commitLabelFontSize=this.commitLabelFontSize||"10px";}},{key:"calculate",value:function(t){var e=this;if("object"===Et(t)){var n=Object.keys(t);n.forEach((function(n){e[n]=t[n];})),this.updateColors(),n.forEach((function(n){e[n]=t[n];}));}else this.updateColors();}}],n&&Ct(e.prototype,n),Object.defineProperty(e,"prototype",{writable:!1}),t}();function At(t){return At="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},At(t)}function Mt(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r);}}var Nt=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.background="#f4f4f4",this.primaryColor="#cde498",this.secondaryColor="#cdffb2",this.background="white",this.mainBkg="#cde498",this.secondBkg="#cdffb2",this.lineColor="green",this.border1="#13540c",this.border2="#6eaa49",this.arrowheadColor="green",this.fontFamily='"trebuchet ms", verdana, arial, sans-serif',this.fontSize="16px",this.tertiaryColor=mt("#cde498",10),this.primaryBorderColor=bt(this.primaryColor,this.darkMode),this.secondaryBorderColor=bt(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=bt(this.tertiaryColor,this.darkMode),this.primaryTextColor=pt(this.primaryColor),this.secondaryTextColor=pt(this.secondaryColor),this.tertiaryTextColor=pt(this.primaryColor),this.lineColor=pt(this.background),this.textColor=pt(this.background),this.nodeBkg="calculated",this.nodeBorder="calculated",this.clusterBkg="calculated",this.clusterBorder="calculated",this.defaultLinkColor="calculated",this.titleColor="#333",this.edgeLabelBackground="#e8e8e8",this.actorBorder="calculated",this.actorBkg="calculated",this.actorTextColor="black",this.actorLineColor="grey",this.signalColor="#333",this.signalTextColor="#333",this.labelBoxBkgColor="calculated",this.labelBoxBorderColor="#326932",this.labelTextColor="calculated",this.loopTextColor="calculated",this.noteBorderColor="calculated",this.noteBkgColor="#fff5ad",this.noteTextColor="calculated",this.activationBorderColor="#666",this.activationBkgColor="#f4f4f4",this.sequenceNumberColor="white",this.sectionBkgColor="#6eaa49",this.altSectionBkgColor="white",this.sectionBkgColor2="#6eaa49",this.excludeBkgColor="#eeeeee",this.taskBorderColor="calculated",this.taskBkgColor="#487e3a",this.taskTextLightColor="white",this.taskTextColor="calculated",this.taskTextDarkColor="black",this.taskTextOutsideColor="calculated",this.taskTextClickableColor="#003163",this.activeTaskBorderColor="calculated",this.activeTaskBkgColor="calculated",this.gridColor="lightgrey",this.doneTaskBkgColor="lightgrey",this.doneTaskBorderColor="grey",this.critBorderColor="#ff8888",this.critBkgColor="red",this.todayLineColor="red",this.personBorder="calculated",this.personBkg="calculated",this.labelColor="black",this.errorBkgColor="#552222",this.errorTextColor="#552222";}var e,n;return e=t,n=[{key:"updateColors",value:function(){this.nodeBkg=this.mainBkg,this.nodeBorder=this.border1,this.clusterBkg=this.secondBkg,this.clusterBorder=this.border2,this.defaultLinkColor=this.lineColor,this.actorBorder=yt(this.mainBkg,20),this.actorBkg=this.mainBkg,this.labelBoxBkgColor=this.actorBkg,this.labelTextColor=this.actorTextColor,this.loopTextColor=this.actorTextColor,this.noteBorderColor=this.border2,this.noteTextColor=this.actorTextColor,this.taskBorderColor=this.border1,this.taskTextColor=this.taskTextLightColor,this.taskTextOutsideColor=this.taskTextDarkColor,this.activeTaskBorderColor=this.taskBorderColor,this.activeTaskBkgColor=this.mainBkg,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||"#f0f0f0",this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.primaryBorderColor,this.specialStateColor=this.lineColor,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.classText=this.primaryTextColor,this.fillType0=this.primaryColor,this.fillType1=this.secondaryColor,this.fillType2=ft(this.primaryColor,{h:64}),this.fillType3=ft(this.secondaryColor,{h:64}),this.fillType4=ft(this.primaryColor,{h:-64}),this.fillType5=ft(this.secondaryColor,{h:-64}),this.fillType6=ft(this.primaryColor,{h:128}),this.fillType7=ft(this.secondaryColor,{h:128}),this.pie1=this.pie1||this.primaryColor,this.pie2=this.pie2||this.secondaryColor,this.pie3=this.pie3||this.tertiaryColor,this.pie4=this.pie4||ft(this.primaryColor,{l:-30}),this.pie5=this.pie5||ft(this.secondaryColor,{l:-30}),this.pie6=this.pie6||ft(this.tertiaryColor,{h:40,l:-40}),this.pie7=this.pie7||ft(this.primaryColor,{h:60,l:-10}),this.pie8=this.pie8||ft(this.primaryColor,{h:-60,l:-10}),this.pie9=this.pie9||ft(this.primaryColor,{h:120,l:0}),this.pie10=this.pie10||ft(this.primaryColor,{h:60,l:-50}),this.pie11=this.pie11||ft(this.primaryColor,{h:-60,l:-50}),this.pie12=this.pie12||ft(this.primaryColor,{h:120,l:-50}),this.pieTitleTextSize=this.pieTitleTextSize||"25px",this.pieTitleTextColor=this.pieTitleTextColor||this.taskTextDarkColor,this.pieSectionTextSize=this.pieSectionTextSize||"17px",this.pieSectionTextColor=this.pieSectionTextColor||this.textColor,this.pieLegendTextSize=this.pieLegendTextSize||"17px",this.pieLegendTextColor=this.pieLegendTextColor||this.taskTextDarkColor,this.pieStrokeColor=this.pieStrokeColor||"black",this.pieStrokeWidth=this.pieStrokeWidth||"2px",this.pieOpacity=this.pieOpacity||"0.7",this.requirementBackground=this.requirementBackground||this.primaryColor,this.requirementBorderColor=this.requirementBorderColor||this.primaryBorderColor,this.requirementBorderSize=this.requirementBorderSize||this.primaryBorderColor,this.requirementTextColor=this.requirementTextColor||this.primaryTextColor,this.relationColor=this.relationColor||this.lineColor,this.relationLabelBackground=this.relationLabelBackground||this.edgeLabelBackground,this.relationLabelColor=this.relationLabelColor||this.actorTextColor,this.git0=this.git0||this.primaryColor,this.git1=this.git1||this.secondaryColor,this.git2=this.git2||this.tertiaryColor,this.git3=this.git3||ft(this.primaryColor,{h:-30}),this.git4=this.git4||ft(this.primaryColor,{h:-60}),this.git5=this.git5||ft(this.primaryColor,{h:-90}),this.git6=this.git6||ft(this.primaryColor,{h:60}),this.git7=this.git7||ft(this.primaryColor,{h:120}),this.darkMode?(this.git0=mt(this.git0,25),this.git1=mt(this.git1,25),this.git2=mt(this.git2,25),this.git3=mt(this.git3,25),this.git4=mt(this.git4,25),this.git5=mt(this.git5,25),this.git6=mt(this.git6,25),this.git7=mt(this.git7,25)):(this.git0=yt(this.git0,25),this.git1=yt(this.git1,25),this.git2=yt(this.git2,25),this.git3=yt(this.git3,25),this.git4=yt(this.git4,25),this.git5=yt(this.git5,25),this.git6=yt(this.git6,25),this.git7=yt(this.git7,25)),this.gitInv0=this.gitInv0||pt(this.git0),this.gitInv1=this.gitInv1||pt(this.git1),this.gitInv2=this.gitInv2||pt(this.git2),this.gitInv3=this.gitInv3||pt(this.git3),this.gitInv4=this.gitInv4||pt(this.git4),this.gitInv5=this.gitInv5||pt(this.git5),this.gitInv6=this.gitInv6||pt(this.git6),this.gitInv7=this.gitInv7||pt(this.git7),this.tagLabelColor=this.tagLabelColor||this.primaryTextColor,this.tagLabelBackground=this.tagLabelBackground||this.primaryColor,this.tagLabelBorder=this.tagBorder||this.primaryBorderColor,this.tagLabelFontSize=this.tagLabelFontSize||"10px",this.commitLabelColor=this.commitLabelColor||this.secondaryTextColor,this.commitLabelBackground=this.commitLabelBackground||this.secondaryColor,this.commitLabelFontSize=this.commitLabelFontSize||"10px";}},{key:"calculate",value:function(t){var e=this;if("object"===At(t)){var n=Object.keys(t);n.forEach((function(n){e[n]=t[n];})),this.updateColors(),n.forEach((function(n){e[n]=t[n];}));}else this.updateColors();}}],n&&Mt(e.prototype,n),Object.defineProperty(e,"prototype",{writable:!1}),t}();function Ot(t){return Ot="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ot(t)}function Dt(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r);}}var Bt=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.primaryColor="#eee",this.contrast="#707070",this.secondaryColor=mt(this.contrast,55),this.background="#ffffff",this.tertiaryColor=ft(this.primaryColor,{h:-160}),this.primaryBorderColor=bt(this.primaryColor,this.darkMode),this.secondaryBorderColor=bt(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=bt(this.tertiaryColor,this.darkMode),this.primaryTextColor=pt(this.primaryColor),this.secondaryTextColor=pt(this.secondaryColor),this.tertiaryTextColor=pt(this.tertiaryColor),this.lineColor=pt(this.background),this.textColor=pt(this.background),this.mainBkg="#eee",this.secondBkg="calculated",this.lineColor="#666",this.border1="#999",this.border2="calculated",this.note="#ffa",this.text="#333",this.critical="#d42",this.done="#bbb",this.arrowheadColor="#333333",this.fontFamily='"trebuchet ms", verdana, arial, sans-serif',this.fontSize="16px",this.nodeBkg="calculated",this.nodeBorder="calculated",this.clusterBkg="calculated",this.clusterBorder="calculated",this.defaultLinkColor="calculated",this.titleColor="calculated",this.edgeLabelBackground="white",this.actorBorder="calculated",this.actorBkg="calculated",this.actorTextColor="calculated",this.actorLineColor="calculated",this.signalColor="calculated",this.signalTextColor="calculated",this.labelBoxBkgColor="calculated",this.labelBoxBorderColor="calculated",this.labelTextColor="calculated",this.loopTextColor="calculated",this.noteBorderColor="calculated",this.noteBkgColor="calculated",this.noteTextColor="calculated",this.activationBorderColor="#666",this.activationBkgColor="#f4f4f4",this.sequenceNumberColor="white",this.sectionBkgColor="calculated",this.altSectionBkgColor="white",this.sectionBkgColor2="calculated",this.excludeBkgColor="#eeeeee",this.taskBorderColor="calculated",this.taskBkgColor="calculated",this.taskTextLightColor="white",this.taskTextColor="calculated",this.taskTextDarkColor="calculated",this.taskTextOutsideColor="calculated",this.taskTextClickableColor="#003163",this.activeTaskBorderColor="calculated",this.activeTaskBkgColor="calculated",this.gridColor="calculated",this.doneTaskBkgColor="calculated",this.doneTaskBorderColor="calculated",this.critBkgColor="calculated",this.critBorderColor="calculated",this.todayLineColor="calculated",this.personBorder="calculated",this.personBkg="calculated",this.labelColor="black",this.errorBkgColor="#552222",this.errorTextColor="#552222";}var e,n;return e=t,n=[{key:"updateColors",value:function(){this.secondBkg=mt(this.contrast,55),this.border2=this.contrast,this.nodeBkg=this.mainBkg,this.nodeBorder=this.border1,this.clusterBkg=this.secondBkg,this.clusterBorder=this.border2,this.defaultLinkColor=this.lineColor,this.titleColor=this.text,this.actorBorder=mt(this.border1,23),this.actorBkg=this.mainBkg,this.actorTextColor=this.text,this.actorLineColor=this.lineColor,this.signalColor=this.text,this.signalTextColor=this.text,this.labelBoxBkgColor=this.actorBkg,this.labelBoxBorderColor=this.actorBorder,this.labelTextColor=this.text,this.loopTextColor=this.text,this.noteBorderColor="#999",this.noteBkgColor="#666",this.noteTextColor="#fff",this.sectionBkgColor=mt(this.contrast,30),this.sectionBkgColor2=mt(this.contrast,30),this.taskBorderColor=yt(this.contrast,10),this.taskBkgColor=this.contrast,this.taskTextColor=this.taskTextLightColor,this.taskTextDarkColor=this.text,this.taskTextOutsideColor=this.taskTextDarkColor,this.activeTaskBorderColor=this.taskBorderColor,this.activeTaskBkgColor=this.mainBkg,this.gridColor=mt(this.border1,30),this.doneTaskBkgColor=this.done,this.doneTaskBorderColor=this.lineColor,this.critBkgColor=this.critical,this.critBorderColor=yt(this.critBkgColor,10),this.todayLineColor=this.critBkgColor,this.transitionColor=this.transitionColor||"#000",this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||"#f4f4f4",this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.stateBorder=this.stateBorder||"#000",this.innerEndBackground=this.primaryBorderColor,this.specialStateColor="#222",this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.classText=this.primaryTextColor,this.fillType0=this.primaryColor,this.fillType1=this.secondaryColor,this.fillType2=ft(this.primaryColor,{h:64}),this.fillType3=ft(this.secondaryColor,{h:64}),this.fillType4=ft(this.primaryColor,{h:-64}),this.fillType5=ft(this.secondaryColor,{h:-64}),this.fillType6=ft(this.primaryColor,{h:128}),this.fillType7=ft(this.secondaryColor,{h:128}),this.pie1=this.pie1||"#F4F4F4",this.pie2=this.pie2||"#555",this.pie3=this.pie3||"#BBB",this.pie4=this.pie4||"#777",this.pie5=this.pie5||"#999",this.pie6=this.pie6||"#DDD",this.pie7=this.pie7||"#FFF",this.pie8=this.pie8||"#DDD",this.pie9=this.pie9||"#BBB",this.pie10=this.pie10||"#999",this.pie11=this.pie11||"#777",this.pie12=this.pie12||"#555",this.pieTitleTextSize=this.pieTitleTextSize||"25px",this.pieTitleTextColor=this.pieTitleTextColor||this.taskTextDarkColor,this.pieSectionTextSize=this.pieSectionTextSize||"17px",this.pieSectionTextColor=this.pieSectionTextColor||this.textColor,this.pieLegendTextSize=this.pieLegendTextSize||"17px",this.pieLegendTextColor=this.pieLegendTextColor||this.taskTextDarkColor,this.pieStrokeColor=this.pieStrokeColor||"black",this.pieStrokeWidth=this.pieStrokeWidth||"2px",this.pieOpacity=this.pieOpacity||"0.7",this.requirementBackground=this.requirementBackground||this.primaryColor,this.requirementBorderColor=this.requirementBorderColor||this.primaryBorderColor,this.requirementBorderSize=this.requirementBorderSize||this.primaryBorderColor,this.requirementTextColor=this.requirementTextColor||this.primaryTextColor,this.relationColor=this.relationColor||this.lineColor,this.relationLabelBackground=this.relationLabelBackground||this.edgeLabelBackground,this.relationLabelColor=this.relationLabelColor||this.actorTextColor,this.git0=yt(this.pie1,25)||this.primaryColor,this.git1=this.pie2||this.secondaryColor,this.git2=this.pie3||this.tertiaryColor,this.git3=this.pie4||ft(this.primaryColor,{h:-30}),this.git4=this.pie5||ft(this.primaryColor,{h:-60}),this.git5=this.pie6||ft(this.primaryColor,{h:-90}),this.git6=this.pie7||ft(this.primaryColor,{h:60}),this.git7=this.pie8||ft(this.primaryColor,{h:120}),this.gitInv0=this.gitInv0||pt(this.git0),this.gitInv1=this.gitInv1||pt(this.git1),this.gitInv2=this.gitInv2||pt(this.git2),this.gitInv3=this.gitInv3||pt(this.git3),this.gitInv4=this.gitInv4||pt(this.git4),this.gitInv5=this.gitInv5||pt(this.git5),this.gitInv6=this.gitInv6||pt(this.git6),this.gitInv7=this.gitInv7||pt(this.git7),this.branchLabelColor=this.branchLabelColor||this.labelTextColor,this.gitBranchLabel0=this.branchLabelColor,this.gitBranchLabel1="white",this.gitBranchLabel2=this.branchLabelColor,this.gitBranchLabel3="white",this.gitBranchLabel4=this.branchLabelColor,this.gitBranchLabel5=this.branchLabelColor,this.gitBranchLabel6=this.branchLabelColor,this.gitBranchLabel7=this.branchLabelColor,this.tagLabelColor=this.tagLabelColor||this.primaryTextColor,this.tagLabelBackground=this.tagLabelBackground||this.primaryColor,this.tagLabelBorder=this.tagBorder||this.primaryBorderColor,this.tagLabelFontSize=this.tagLabelFontSize||"10px",this.commitLabelColor=this.commitLabelColor||this.secondaryTextColor,this.commitLabelBackground=this.commitLabelBackground||this.secondaryColor,this.commitLabelFontSize=this.commitLabelFontSize||"10px";}},{key:"calculate",value:function(t){var e=this;if("object"===Ot(t)){var n=Object.keys(t);n.forEach((function(n){e[n]=t[n];})),this.updateColors(),n.forEach((function(n){e[n]=t[n];}));}else this.updateColors();}}],n&&Dt(e.prototype,n),Object.defineProperty(e,"prototype",{writable:!1}),t}();const Lt={base:{getThemeVariables:function(t){var e=new xt;return e.calculate(t),e}},dark:{getThemeVariables:function(t){var e=new Tt;return e.calculate(t),e}},default:{getThemeVariables:function(t){var e=new St;return e.calculate(t),e}},forest:{getThemeVariables:function(t){var e=new Nt;return e.calculate(t),e}},neutral:{getThemeVariables:function(t){var e=new Bt;return e.calculate(t),e}}};function It(t){return function(t){if(Array.isArray(t))return Ft(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return Ft(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return "Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ft(t,e):void 0}}(t)||function(){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 Ft(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function Rt(t){return Rt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Rt(t)}var Pt={theme:"default",themeVariables:Lt.default.getThemeVariables(),themeCSS:void 0,maxTextSize:5e4,darkMode:!1,fontFamily:'"trebuchet ms", verdana, arial, sans-serif;',logLevel:5,securityLevel:"strict",startOnLoad:!0,arrowMarkerAbsolute:!1,secure:["secure","securityLevel","startOnLoad","maxTextSize"],deterministicIds:!1,deterministicIDSeed:void 0,flowchart:{diagramPadding:8,htmlLabels:!0,nodeSpacing:50,rankSpacing:50,curve:"basis",padding:15,useMaxWidth:!0,defaultRenderer:"dagre-d3"},sequence:{hideUnusedParticipants:!1,activationWidth:10,diagramMarginX:50,diagramMarginY:10,actorMargin:50,width:150,height:65,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:"center",mirrorActors:!0,forceMenus:!1,bottomMarginAdj:1,useMaxWidth:!0,rightAngles:!1,showSequenceNumbers:!1,actorFontSize:14,actorFontFamily:'"Open Sans", sans-serif',actorFontWeight:400,noteFontSize:14,noteFontFamily:'"trebuchet ms", verdana, arial, sans-serif',noteFontWeight:400,noteAlign:"center",messageFontSize:16,messageFontFamily:'"trebuchet ms", verdana, arial, sans-serif',messageFontWeight:400,wrap:!1,wrapPadding:10,labelBoxWidth:50,labelBoxHeight:20,messageFont:function(){return {fontFamily:this.messageFontFamily,fontSize:this.messageFontSize,fontWeight:this.messageFontWeight}},noteFont:function(){return {fontFamily:this.noteFontFamily,fontSize:this.noteFontSize,fontWeight:this.noteFontWeight}},actorFont:function(){return {fontFamily:this.actorFontFamily,fontSize:this.actorFontSize,fontWeight:this.actorFontWeight}}},gantt:{titleTopMargin:25,barHeight:20,barGap:4,topPadding:50,rightPadding:75,leftPadding:75,gridLineStartPadding:35,fontSize:11,sectionFontSize:11,numberSectionStyles:4,axisFormat:"%Y-%m-%d",useMaxWidth:!0,topAxis:!1,useWidth:void 0},journey:{diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:"center",bottomMarginAdj:1,useMaxWidth:!0,rightAngles:!1,taskFontSize:14,taskFontFamily:'"Open Sans", sans-serif',taskMargin:50,activationWidth:10,textPlacement:"fo",actorColours:["#8FBC8F","#7CFC00","#00FFFF","#20B2AA","#B0E0E6","#FFFFE0"],sectionFills:["#191970","#8B008B","#4B0082","#2F4F4F","#800000","#8B4513","#00008B"],sectionColours:["#fff"]},class:{arrowMarkerAbsolute:!1,dividerMargin:10,padding:5,textHeight:10,useMaxWidth:!0,defaultRenderer:"dagre-wrapper"},state:{dividerMargin:10,sizeUnit:5,padding:8,textHeight:10,titleShift:-15,noteMargin:10,forkWidth:70,forkHeight:7,miniPadding:2,fontSizeFactor:5.02,fontSize:24,labelHeight:16,edgeLengthFactor:"20",compositTitleSize:35,radius:5,useMaxWidth:!0,defaultRenderer:"dagre-wrapper"},er:{diagramPadding:20,layoutDirection:"TB",minEntityWidth:100,minEntityHeight:75,entityPadding:15,stroke:"gray",fill:"honeydew",fontSize:12,useMaxWidth:!0},pie:{useWidth:void 0,useMaxWidth:!0},requirement:{useWidth:void 0,useMaxWidth:!0,rect_fill:"#f9f9f9",text_color:"#333",rect_border_size:"0.5px",rect_border_color:"#bbb",rect_min_width:200,rect_min_height:200,fontSize:14,rect_padding:10,line_height:20},gitGraph:{diagramPadding:8,nodeLabel:{width:75,height:100,x:-25,y:0},mainBranchName:"main",mainBranchOrder:0,showCommitLabel:!0,showBranches:!0,rotateCommitLabel:!0},c4:{useWidth:void 0,diagramMarginX:50,diagramMarginY:10,c4ShapeMargin:50,c4ShapePadding:20,width:216,height:60,boxMargin:10,useMaxWidth:!0,c4ShapeInRow:4,nextLinePaddingX:0,c4BoundaryInRow:2,personFontSize:14,personFontFamily:'"Open Sans", sans-serif',personFontWeight:"normal",external_personFontSize:14,external_personFontFamily:'"Open Sans", sans-serif',external_personFontWeight:"normal",systemFontSize:14,systemFontFamily:'"Open Sans", sans-serif',systemFontWeight:"normal",external_systemFontSize:14,external_systemFontFamily:'"Open Sans", sans-serif',external_systemFontWeight:"normal",system_dbFontSize:14,system_dbFontFamily:'"Open Sans", sans-serif',system_dbFontWeight:"normal",external_system_dbFontSize:14,external_system_dbFontFamily:'"Open Sans", sans-serif',external_system_dbFontWeight:"normal",system_queueFontSize:14,system_queueFontFamily:'"Open Sans", sans-serif',system_queueFontWeight:"normal",external_system_queueFontSize:14,external_system_queueFontFamily:'"Open Sans", sans-serif',external_system_queueFontWeight:"normal",boundaryFontSize:14,boundaryFontFamily:'"Open Sans", sans-serif',boundaryFontWeight:"normal",messageFontSize:12,messageFontFamily:'"Open Sans", sans-serif',messageFontWeight:"normal",containerFontSize:14,containerFontFamily:'"Open Sans", sans-serif',containerFontWeight:"normal",external_containerFontSize:14,external_containerFontFamily:'"Open Sans", sans-serif',external_containerFontWeight:"normal",container_dbFontSize:14,container_dbFontFamily:'"Open Sans", sans-serif',container_dbFontWeight:"normal",external_container_dbFontSize:14,external_container_dbFontFamily:'"Open Sans", sans-serif',external_container_dbFontWeight:"normal",container_queueFontSize:14,container_queueFontFamily:'"Open Sans", sans-serif',container_queueFontWeight:"normal",external_container_queueFontSize:14,external_container_queueFontFamily:'"Open Sans", sans-serif',external_container_queueFontWeight:"normal",componentFontSize:14,componentFontFamily:'"Open Sans", sans-serif',componentFontWeight:"normal",external_componentFontSize:14,external_componentFontFamily:'"Open Sans", sans-serif',external_componentFontWeight:"normal",component_dbFontSize:14,component_dbFontFamily:'"Open Sans", sans-serif',component_dbFontWeight:"normal",external_component_dbFontSize:14,external_component_dbFontFamily:'"Open Sans", sans-serif',external_component_dbFontWeight:"normal",component_queueFontSize:14,component_queueFontFamily:'"Open Sans", sans-serif',component_queueFontWeight:"normal",external_component_queueFontSize:14,external_component_queueFontFamily:'"Open Sans", sans-serif',external_component_queueFontWeight:"normal",wrap:!0,wrapPadding:10,personFont:function(){return {fontFamily:this.personFontFamily,fontSize:this.personFontSize,fontWeight:this.personFontWeight}},external_personFont:function(){return {fontFamily:this.external_personFontFamily,fontSize:this.external_personFontSize,fontWeight:this.external_personFontWeight}},systemFont:function(){return {fontFamily:this.systemFontFamily,fontSize:this.systemFontSize,fontWeight:this.systemFontWeight}},external_systemFont:function(){return {fontFamily:this.external_systemFontFamily,fontSize:this.external_systemFontSize,fontWeight:this.external_systemFontWeight}},system_dbFont:function(){return {fontFamily:this.system_dbFontFamily,fontSize:this.system_dbFontSize,fontWeight:this.system_dbFontWeight}},external_system_dbFont:function(){return {fontFamily:this.external_system_dbFontFamily,fontSize:this.external_system_dbFontSize,fontWeight:this.external_system_dbFontWeight}},system_queueFont:function(){return {fontFamily:this.system_queueFontFamily,fontSize:this.system_queueFontSize,fontWeight:this.system_queueFontWeight}},external_system_queueFont:function(){return {fontFamily:this.external_system_queueFontFamily,fontSize:this.external_system_queueFontSize,fontWeight:this.external_system_queueFontWeight}},containerFont:function(){return {fontFamily:this.containerFontFamily,fontSize:this.containerFontSize,fontWeight:this.containerFontWeight}},external_containerFont:function(){return {fontFamily:this.external_containerFontFamily,fontSize:this.external_containerFontSize,fontWeight:this.external_containerFontWeight}},container_dbFont:function(){return {fontFamily:this.container_dbFontFamily,fontSize:this.container_dbFontSize,fontWeight:this.container_dbFontWeight}},external_container_dbFont:function(){return {fontFamily:this.external_container_dbFontFamily,fontSize:this.external_container_dbFontSize,fontWeight:this.external_container_dbFontWeight}},container_queueFont:function(){return {fontFamily:this.container_queueFontFamily,fontSize:this.container_queueFontSize,fontWeight:this.container_queueFontWeight}},external_container_queueFont:function(){return {fontFamily:this.external_container_queueFontFamily,fontSize:this.external_container_queueFontSize,fontWeight:this.external_container_queueFontWeight}},componentFont:function(){return {fontFamily:this.componentFontFamily,fontSize:this.componentFontSize,fontWeight:this.componentFontWeight}},external_componentFont:function(){return {fontFamily:this.external_componentFontFamily,fontSize:this.external_componentFontSize,fontWeight:this.external_componentFontWeight}},component_dbFont:function(){return {fontFamily:this.component_dbFontFamily,fontSize:this.component_dbFontSize,fontWeight:this.component_dbFontWeight}},external_component_dbFont:function(){return {fontFamily:this.external_component_dbFontFamily,fontSize:this.external_component_dbFontSize,fontWeight:this.external_component_dbFontWeight}},component_queueFont:function(){return {fontFamily:this.component_queueFontFamily,fontSize:this.component_queueFontSize,fontWeight:this.component_queueFontWeight}},external_component_queueFont:function(){return {fontFamily:this.external_component_queueFontFamily,fontSize:this.external_component_queueFontSize,fontWeight:this.external_component_queueFontWeight}},boundaryFont:function(){return {fontFamily:this.boundaryFontFamily,fontSize:this.boundaryFontSize,fontWeight:this.boundaryFontWeight}},messageFont:function(){return {fontFamily:this.messageFontFamily,fontSize:this.messageFontSize,fontWeight:this.messageFontWeight}},person_bg_color:"#08427B",person_border_color:"#073B6F",external_person_bg_color:"#686868",external_person_border_color:"#8A8A8A",system_bg_color:"#1168BD",system_border_color:"#3C7FC0",system_db_bg_color:"#1168BD",system_db_border_color:"#3C7FC0",system_queue_bg_color:"#1168BD",system_queue_border_color:"#3C7FC0",external_system_bg_color:"#999999",external_system_border_color:"#8A8A8A",external_system_db_bg_color:"#999999",external_system_db_border_color:"#8A8A8A",external_system_queue_bg_color:"#999999",external_system_queue_border_color:"#8A8A8A",container_bg_color:"#438DD5",container_border_color:"#3C7FC0",container_db_bg_color:"#438DD5",container_db_border_color:"#3C7FC0",container_queue_bg_color:"#438DD5",container_queue_border_color:"#3C7FC0",external_container_bg_color:"#B3B3B3",external_container_border_color:"#A6A6A6",external_container_db_bg_color:"#B3B3B3",external_container_db_border_color:"#A6A6A6",external_container_queue_bg_color:"#B3B3B3",external_container_queue_border_color:"#A6A6A6",component_bg_color:"#85BBF0",component_border_color:"#78A8D8",component_db_bg_color:"#85BBF0",component_db_border_color:"#78A8D8",component_queue_bg_color:"#85BBF0",component_queue_border_color:"#78A8D8",external_component_bg_color:"#CCCCCC",external_component_border_color:"#BFBFBF",external_component_db_bg_color:"#CCCCCC",external_component_db_border_color:"#BFBFBF",external_component_queue_bg_color:"#CCCCCC",external_component_queue_border_color:"#BFBFBF"}};Pt.class.arrowMarkerAbsolute=Pt.arrowMarkerAbsolute,Pt.gitGraph.arrowMarkerAbsolute=Pt.arrowMarkerAbsolute;var jt=function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return Object.keys(e).reduce((function(r,i){return Array.isArray(e[i])?r:"object"===Rt(e[i])&&null!==e[i]?[].concat(It(r),[n+i],It(t(e[i],""))):[].concat(It(r),[n+i])}),[])}(Pt,"");const zt=Pt;function Yt(t){return Yt="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Yt(t)}var Ut,$t=Object.freeze(zt),Wt=Q({},$t),qt=[],Ht=Q({},$t),Vt=function(t,e){for(var n=Q({},t),r={},i=0;i<e.length;i++){var a=e[i];Zt(a),r=Q(r,a);}if(n=Q(n,r),r.theme&&Lt[r.theme]){var o=Q({},Ut),s=Q(o.themeVariables||{},r.themeVariables);n.themeVariables=Lt[n.theme].getThemeVariables(s);}return Ht=n,n},Gt=function(){return Q({},Wt)},Xt=function(){return Q({},Ht)},Zt=function t(e){Object.keys(Wt.secure).forEach((function(t){void 0!==e[Wt.secure[t]]&&(o.debug("Denied attempt to modify a secure key ".concat(Wt.secure[t]),e[Wt.secure[t]]),delete e[Wt.secure[t]]);})),Object.keys(e).forEach((function(t){0===t.indexOf("__")&&delete e[t];})),Object.keys(e).forEach((function(n){"string"==typeof e[n]&&(e[n].indexOf("<")>-1||e[n].indexOf(">")>-1||e[n].indexOf("url(data:")>-1)&&delete e[n],"object"===Yt(e[n])&&t(e[n]);}));},Qt=function(t){t.fontFamily&&(t.themeVariables&&t.themeVariables.fontFamily||(t.themeVariables={fontFamily:t.fontFamily})),qt.push(t),Vt(Wt,qt);},Kt=function(){Vt(Wt,qt=[]);},Jt=n(7856),te=n.n(Jt),ee=function(t){var e=t.replace(/\\u[\dA-F]{4}/gi,(function(t){return String.fromCharCode(parseInt(t.replace(/\\u/g,""),16))}));return e=(e=(e=e.replace(/\\x([0-9a-f]{2})/gi,(function(t,e){return String.fromCharCode(parseInt(e,16))}))).replace(/\\[\d\d\d]{3}/gi,(function(t){return String.fromCharCode(parseInt(t.replace(/\\/g,""),8))}))).replace(/\\[\d\d\d]{2}/gi,(function(t){return String.fromCharCode(parseInt(t.replace(/\\/g,""),8))}))},ne=function(t){for(var e="",n=0;n>=0;){if(!((n=t.indexOf("<script"))>=0)){e+=t,n=-1;break}e+=t.substr(0,n),(n=(t=t.substr(n+1)).indexOf("<\/script>"))>=0&&(n+=9,t=t.substr(n));}var r=ee(e);return (r=(r=(r=(r=r.replace(/script>/gi,"#")).replace(/javascript:/gi,"#")).replace(/javascript&colon/gi,"#")).replace(/onerror=/gi,"onerror:")).replace(/<iframe/gi,"")},re=function(t,e){var n=t,r=!0;if(!e.flowchart||!1!==e.flowchart.htmlLabels&&"false"!==e.flowchart.htmlLabels||(r=!1),r){var i=e.securityLevel;"antiscript"===i||"strict"===i?n=ne(n):"loose"!==i&&(n=(n=(n=se(n)).replace(/</g,"&lt;").replace(/>/g,"&gt;")).replace(/=/g,"&equals;"),n=oe(n));}return n},ie=function(t,e){return t?e.dompurifyConfig?te().sanitize(re(t,e),e.dompurifyConfig):te().sanitize(re(t,e)):t},ae=/<br\s*\/?>/gi,oe=function(t){return t.replace(/#br#/g,"<br/>")},se=function(t){return t.replace(ae,"#br#")},ce=function(t){return "false"!==t&&!1!==t},le=function t(e){var n=e;return -1!=e.indexOf("~")?t(n=(n=n.replace("~","<")).replace("~",">")):n};const ue={getRows:function(t){if(!t)return 1;var e=se(t);return (e=e.replace(/\\n/g,"#br#")).split("#br#")},sanitizeText:ie,sanitizeTextOrArray:function(t,e){return "string"==typeof t?ie(t,e):t.flat().map((function(t){return ie(t,e)}))},hasBreaks:function(t){return ae.test(t)},splitBreaks:function(t){return t.split(ae)},lineBreakRegex:ae,removeScript:ne,getUrl:function(t){var e="";return t&&(e=(e=(e=window.location.protocol+"//"+window.location.host+window.location.pathname+window.location.search).replace(/\(/g,"\\(")).replace(/\)/g,"\\)")),e},evaluate:ce,removeEscapes:ee};var he="",fe="",de="",pe=function(t){return ie(t,Xt())},ge=function(){he="",de="",fe="";},ye=function(t){he=pe(t).replace(/^\s+/g,"");},me=function(){return he||fe},be=function(t){de=pe(t).replace(/\n\s+/g,"\n");},ve=function(){return de},_e=function(t){fe=pe(t);},xe=function(){return fe};function ke(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,i,a=[],o=!0,s=!1;try{for(n=n.call(t);!(o=(r=n.next()).done)&&(a.push(r.value),!e||a.length!==e);o=!0);}catch(t){s=!0,i=t;}finally{try{o||null==n.return||n.return();}finally{if(s)throw i}}return a}}(t,e)||function(t,e){if(t){if("string"==typeof t)return we(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return "Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?we(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function we(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function Te(t){return Te="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Te(t)}var Ee,Ce=[],Se=[""],Ae="global",Me="",Ne=[{alias:"global",label:{text:"global"},type:{text:"global"},tags:null,link:null,parentBoundary:""}],Oe=[],De="",Be=!1,Le=4,Ie=2,Fe=function(t){return null==t?Ce:Ce.filter((function(e){return e.parentBoundary===t}))},Re=function(){return Be};const Pe={addPersonOrSystem:function(t,e,n,r,i,a,o){if(null!==e&&null!==n){var s={},c=Ce.find((function(t){return t.alias===e}));if(c&&e===c.alias?s=c:(s.alias=e,Ce.push(s)),s.label=null==n?{text:""}:{text:n},null==r)s.descr={text:""};else if("object"===Te(r)){var l=ke(Object.entries(r)[0],2),u=l[0],h=l[1];s[u]={text:h};}else s.descr={text:r};if("object"===Te(i)){var f=ke(Object.entries(i)[0],2),d=f[0],p=f[1];s[d]=p;}else s.sprite=i;if("object"===Te(a)){var g=ke(Object.entries(a)[0],2),y=g[0],m=g[1];s[y]=m;}else s.tags=a;if("object"===Te(o)){var b=ke(Object.entries(o)[0],2),v=b[0],_=b[1];s[v]=_;}else s.link=o;s.typeC4Shape={text:t},s.parentBoundary=Ae,s.wrap=Re();}},addPersonOrSystemBoundary:function(t,e,n,r,i){if(null!==t&&null!==e){var a={},o=Ne.find((function(e){return e.alias===t}));if(o&&t===o.alias?a=o:(a.alias=t,Ne.push(a)),a.label=null==e?{text:""}:{text:e},null==n)a.type={text:"system"};else if("object"===Te(n)){var s=ke(Object.entries(n)[0],2),c=s[0],l=s[1];a[c]={text:l};}else a.type={text:n};if("object"===Te(r)){var u=ke(Object.entries(r)[0],2),h=u[0],f=u[1];a[h]=f;}else a.tags=r;if("object"===Te(i)){var d=ke(Object.entries(i)[0],2),p=d[0],g=d[1];a[p]=g;}else a.link=i;a.parentBoundary=Ae,a.wrap=Re(),Me=Ae,Ae=t,Se.push(Me);}},addContainer:function(t,e,n,r,i,a,o,s){if(null!==e&&null!==n){var c={},l=Ce.find((function(t){return t.alias===e}));if(l&&e===l.alias?c=l:(c.alias=e,Ce.push(c)),c.label=null==n?{text:""}:{text:n},null==r)c.techn={text:""};else if("object"===Te(r)){var u=ke(Object.entries(r)[0],2),h=u[0],f=u[1];c[h]={text:f};}else c.techn={text:r};if(null==i)c.descr={text:""};else if("object"===Te(i)){var d=ke(Object.entries(i)[0],2),p=d[0],g=d[1];c[p]={text:g};}else c.descr={text:i};if("object"===Te(a)){var y=ke(Object.entries(a)[0],2),m=y[0],b=y[1];c[m]=b;}else c.sprite=a;if("object"===Te(o)){var v=ke(Object.entries(o)[0],2),_=v[0],x=v[1];c[_]=x;}else c.tags=o;if("object"===Te(s)){var k=ke(Object.entries(s)[0],2),w=k[0],T=k[1];c[w]=T;}else c.link=s;c.wrap=Re(),c.typeC4Shape={text:t},c.parentBoundary=Ae;}},addContainerBoundary:function(t,e,n,r,i){if(null!==t&&null!==e){var a={},o=Ne.find((function(e){return e.alias===t}));if(o&&t===o.alias?a=o:(a.alias=t,Ne.push(a)),a.label=null==e?{text:""}:{text:e},null==n)a.type={text:"container"};else if("object"===Te(n)){var s=ke(Object.entries(n)[0],2),c=s[0],l=s[1];a[c]={text:l};}else a.type={text:n};if("object"===Te(r)){var u=ke(Object.entries(r)[0],2),h=u[0],f=u[1];a[h]=f;}else a.tags=r;if("object"===Te(i)){var d=ke(Object.entries(i)[0],2),p=d[0],g=d[1];a[p]=g;}else a.link=i;a.parentBoundary=Ae,a.wrap=Re(),Me=Ae,Ae=t,Se.push(Me);}},addComponent:function(t,e,n,r,i,a,o,s){if(null!==e&&null!==n){var c={},l=Ce.find((function(t){return t.alias===e}));if(l&&e===l.alias?c=l:(c.alias=e,Ce.push(c)),c.label=null==n?{text:""}:{text:n},null==r)c.techn={text:""};else if("object"===Te(r)){var u=ke(Object.entries(r)[0],2),h=u[0],f=u[1];c[h]={text:f};}else c.techn={text:r};if(null==i)c.descr={text:""};else if("object"===Te(i)){var d=ke(Object.entries(i)[0],2),p=d[0],g=d[1];c[p]={text:g};}else c.descr={text:i};if("object"===Te(a)){var y=ke(Object.entries(a)[0],2),m=y[0],b=y[1];c[m]=b;}else c.sprite=a;if("object"===Te(o)){var v=ke(Object.entries(o)[0],2),_=v[0],x=v[1];c[_]=x;}else c.tags=o;if("object"===Te(s)){var k=ke(Object.entries(s)[0],2),w=k[0],T=k[1];c[w]=T;}else c.link=s;c.wrap=Re(),c.typeC4Shape={text:t},c.parentBoundary=Ae;}},addDeploymentNode:function(t,e,n,r,i,a,o,s){if(null!==e&&null!==n){var c={},l=Ne.find((function(t){return t.alias===e}));if(l&&e===l.alias?c=l:(c.alias=e,Ne.push(c)),c.label=null==n?{text:""}:{text:n},null==r)c.type={text:"node"};else if("object"===Te(r)){var u=ke(Object.entries(r)[0],2),h=u[0],f=u[1];c[h]={text:f};}else c.type={text:r};if(null==i)c.descr={text:""};else if("object"===Te(i)){var d=ke(Object.entries(i)[0],2),p=d[0],g=d[1];c[p]={text:g};}else c.descr={text:i};if("object"===Te(o)){var y=ke(Object.entries(o)[0],2),m=y[0],b=y[1];c[m]=b;}else c.tags=o;if("object"===Te(s)){var v=ke(Object.entries(s)[0],2),_=v[0],x=v[1];c[_]=x;}else c.link=s;c.nodeType=t,c.parentBoundary=Ae,c.wrap=Re(),Me=Ae,Ae=e,Se.push(Me);}},popBoundaryParseStack:function(){Ae=Me,Se.pop(),Me=Se.pop(),Se.push(Me);},addRel:function(t,e,n,r,i,a,o,s,c){if(null!=t&&null!=e&&null!=n&&null!=r){var l={},u=Oe.find((function(t){return t.from===e&&t.to===n}));if(u?l=u:Oe.push(l),l.type=t,l.from=e,l.to=n,l.label={text:r},null==i)l.techn={text:""};else if("object"===Te(i)){var h=ke(Object.entries(i)[0],2),f=h[0],d=h[1];l[f]={text:d};}else l.techn={text:i};if(null==a)l.descr={text:""};else if("object"===Te(a)){var p=ke(Object.entries(a)[0],2),g=p[0],y=p[1];l[g]={text:y};}else l.descr={text:a};if("object"===Te(o)){var m=ke(Object.entries(o)[0],2),b=m[0],v=m[1];l[b]=v;}else l.sprite=o;if("object"===Te(s)){var _=ke(Object.entries(s)[0],2),x=_[0],k=_[1];l[x]=k;}else l.tags=s;if("object"===Te(c)){var w=ke(Object.entries(c)[0],2),T=w[0],E=w[1];l[T]=E;}else l.link=c;l.wrap=Re();}},updateElStyle:function(t,e,n,r,i,a,o,s,c,l,u){var h=Ce.find((function(t){return t.alias===e}));if(void 0!==h||void 0!==(h=Ne.find((function(t){return t.alias===e})))){if(null!=n)if("object"===Te(n)){var f=ke(Object.entries(n)[0],2),d=f[0],p=f[1];h[d]=p;}else h.bgColor=n;if(null!=r)if("object"===Te(r)){var g=ke(Object.entries(r)[0],2),y=g[0],m=g[1];h[y]=m;}else h.fontColor=r;if(null!=i)if("object"===Te(i)){var b=ke(Object.entries(i)[0],2),v=b[0],_=b[1];h[v]=_;}else h.borderColor=i;if(null!=a)if("object"===Te(a)){var x=ke(Object.entries(a)[0],2),k=x[0],w=x[1];h[k]=w;}else h.shadowing=a;if(null!=o)if("object"===Te(o)){var T=ke(Object.entries(o)[0],2),E=T[0],C=T[1];h[E]=C;}else h.shape=o;if(null!=s)if("object"===Te(s)){var S=ke(Object.entries(s)[0],2),A=S[0],M=S[1];h[A]=M;}else h.sprite=s;if(null!=c)if("object"===Te(c)){var N=ke(Object.entries(c)[0],2),O=N[0],D=N[1];h[O]=D;}else h.techn=c;if(null!=l)if("object"===Te(l)){var B=ke(Object.entries(l)[0],2),L=B[0],I=B[1];h[L]=I;}else h.legendText=l;if(null!=u)if("object"===Te(u)){var F=ke(Object.entries(u)[0],2),R=F[0],P=F[1];h[R]=P;}else h.legendSprite=u;}},updateRelStyle:function(t,e,n,r,i,a,o){var s=Oe.find((function(t){return t.from===e&&t.to===n}));if(void 0!==s){if(null!=r)if("object"===Te(r)){var c=ke(Object.entries(r)[0],2),l=c[0],u=c[1];s[l]=u;}else s.textColor=r;if(null!=i)if("object"===Te(i)){var h=ke(Object.entries(i)[0],2),f=h[0],d=h[1];s[f]=d;}else s.lineColor=i;if(null!=a)if("object"===Te(a)){var p=ke(Object.entries(a)[0],2),g=p[0],y=p[1];s[g]=parseInt(y);}else s.offsetX=parseInt(a);if(null!=o)if("object"===Te(o)){var m=ke(Object.entries(o)[0],2),b=m[0],v=m[1];s[b]=parseInt(v);}else s.offsetY=parseInt(o);}},updateLayoutConfig:function(t,e,n){var r=Le,i=Ie;if("object"===Te(e)){var a=ke(Object.entries(e)[0],2),o=(a[0],a[1]);r=parseInt(o);}else r=parseInt(e);if("object"===Te(n)){var s=ke(Object.entries(n)[0],2),c=(s[0],s[1]);i=parseInt(c);}else i=parseInt(n);r>=1&&(Le=r),i>=1&&(Ie=i);},autoWrap:Re,setWrap:function(t){Be=t;},getC4ShapeArray:Fe,getC4Shape:function(t){return Ce.find((function(e){return e.alias===t}))},getC4ShapeKeys:function(t){return Object.keys(Fe(t))},getBoundarys:function(t){return null==t?Ne:Ne.filter((function(e){return e.parentBoundary===t}))},getCurrentBoundaryParse:function(){return Ae},getParentBoundaryParse:function(){return Me},getRels:function(){return Oe},getTitle:function(){return De},getC4Type:function(){return Ee},getC4ShapeInRow:function(){return Le},getC4BoundaryInRow:function(){return Ie},setAccTitle:ye,getAccTitle:me,getAccDescription:ve,setAccDescription:be,parseDirective:function(t,e,n){cu.parseDirective(this,t,e,n);},getConfig:function(){return Xt().c4},clear:function(){Ce=[],Ne=[{alias:"global",label:{text:"global"},type:{text:"global"},tags:null,link:null,parentBoundary:""}],Me="",Ae="global",Se=[""],Oe=[],Se=[""],De="",Be=!1,Le=4,Ie=2;},LINETYPE:{SOLID:0,DOTTED:1,NOTE:2,SOLID_CROSS:3,DOTTED_CROSS:4,SOLID_OPEN:5,DOTTED_OPEN:6,LOOP_START:10,LOOP_END:11,ALT_START:12,ALT_ELSE:13,ALT_END:14,OPT_START:15,OPT_END:16,ACTIVE_START:17,ACTIVE_END:18,PAR_START:19,PAR_AND:20,PAR_END:21,RECT_START:22,RECT_END:23,SOLID_POINT:24,DOTTED_POINT:25},ARROWTYPE:{FILLED:0,OPEN:1},PLACEMENT:{LEFTOF:0,RIGHTOF:1,OVER:2},setTitle:function(t){var e=ie(t,Xt());De=e;},setC4Type:function(t){var e=ie(t,Xt());Ee=e;}};var je=n(7967);function ze(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}var Ye=function(t,e){var n=t.append("rect");if(n.attr("x",e.x),n.attr("y",e.y),n.attr("fill",e.fill),n.attr("stroke",e.stroke),n.attr("width",e.width),n.attr("height",e.height),n.attr("rx",e.rx),n.attr("ry",e.ry),"undefined"!==e.attrs&&null!==e.attrs)for(var r in e.attrs)n.attr(r,e.attrs[r]);return "undefined"!==e.class&&n.attr("class",e.class),n},Ue=function(){function t(t,e,n,i,a,o,s){r(e.append("text").attr("x",n+a/2).attr("y",i+o/2+5).style("text-anchor","middle").text(t),s);}function e(t,e,n,i,a,o,s,c){for(var l=c.fontSize,u=c.fontFamily,h=c.fontWeight,f=t.split(ue.lineBreakRegex),d=0;d<f.length;d++){var p=d*l-l*(f.length-1)/2,g=e.append("text").attr("x",n+a/2).attr("y",i).style("text-anchor","middle").attr("dominant-baseline","middle").style("font-size",l).style("font-weight",h).style("font-family",u);g.append("tspan").attr("dy",p).text(f[d]).attr("alignment-baseline","mathematical"),r(g,s);}}function n(t,n,i,a,o,s,c,l){var u=n.append("switch"),h=u.append("foreignObject").attr("x",i).attr("y",a).attr("width",o).attr("height",s).append("xhtml:div").style("display","table").style("height","100%").style("width","100%");h.append("div").style("display","table-cell").style("text-align","center").style("vertical-align","middle").text(t),e(t,u,i,a,o,0,c,l),r(h,c);}function r(t,e){for(var n in e)e.hasOwnProperty(n)&&t.attr(n,e[n]);}return function(r){return "fo"===r.textPlacement?n:"old"===r.textPlacement?t:e}}();const $e=function(t,e,n){var r=e.bgColor?e.bgColor:n[e.typeC4Shape.text+"_bg_color"],i=e.borderColor?e.borderColor:n[e.typeC4Shape.text+"_border_color"],a=e.fontColor?e.fontColor:"#FFFFFF",o="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAIAAADYYG7QAAACD0lEQVR4Xu2YoU4EMRCGT+4j8Ai8AhaH4QHgAUjQuFMECUgMIUgwJAgMhgQsAYUiJCiQIBBY+EITsjfTdme6V24v4c8vyGbb+ZjOtN0bNcvjQXmkH83WvYBWto6PLm6v7p7uH1/w2fXD+PBycX1Pv2l3IdDm/vn7x+dXQiAubRzoURa7gRZWd0iGRIiJbOnhnfYBQZNJjNbuyY2eJG8fkDE3bbG4ep6MHUAsgYxmE3nVs6VsBWJSGccsOlFPmLIViMzLOB7pCVO2AtHJMohH7Fh6zqitQK7m0rJvAVYgGcEpe//PLdDz65sM4pF9N7ICcXDKIB5Nv6j7tD0NoSdM2QrU9Gg0ewE1LqBhHR3BBdvj2vapnidjHxD/q6vd7Pvhr31AwcY8eXMTXAKECZZJFXuEq27aLgQK5uLMohCenGGuGewOxSjBvYBqeG6B+Nqiblggdjnc+ZXDy+FNFpFzw76O3UBAROuXh6FoiAcf5g9eTvUgzy0nWg6I8cXHRUpg5bOVBCo+KDpFajOf23GgPme7RSQ+lacIENUgJ6gg1k6HjgOlqnLqip4tEuhv0hNEMXUD0clyXE3p6pZA0S2nnvTlXwLJEZWlb7cTQH1+USgTN4VhAenm/wea1OCAOmqo6fE1WCb9WSKBah+rbUWPWAmE2Rvk0ApiB45eOyNAzU8xcTvj8KvkKEoOaIYeHNA3ZuygAvFMUO0AAAAASUVORK5CYII=";switch(e.typeC4Shape.text){case"person":o="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAIAAADYYG7QAAACD0lEQVR4Xu2YoU4EMRCGT+4j8Ai8AhaH4QHgAUjQuFMECUgMIUgwJAgMhgQsAYUiJCiQIBBY+EITsjfTdme6V24v4c8vyGbb+ZjOtN0bNcvjQXmkH83WvYBWto6PLm6v7p7uH1/w2fXD+PBycX1Pv2l3IdDm/vn7x+dXQiAubRzoURa7gRZWd0iGRIiJbOnhnfYBQZNJjNbuyY2eJG8fkDE3bbG4ep6MHUAsgYxmE3nVs6VsBWJSGccsOlFPmLIViMzLOB7pCVO2AtHJMohH7Fh6zqitQK7m0rJvAVYgGcEpe//PLdDz65sM4pF9N7ICcXDKIB5Nv6j7tD0NoSdM2QrU9Gg0ewE1LqBhHR3BBdvj2vapnidjHxD/q6vd7Pvhr31AwcY8eXMTXAKECZZJFXuEq27aLgQK5uLMohCenGGuGewOxSjBvYBqeG6B+Nqiblggdjnc+ZXDy+FNFpFzw76O3UBAROuXh6FoiAcf5g9eTvUgzy0nWg6I8cXHRUpg5bOVBCo+KDpFajOf23GgPme7RSQ+lacIENUgJ6gg1k6HjgOlqnLqip4tEuhv0hNEMXUD0clyXE3p6pZA0S2nnvTlXwLJEZWlb7cTQH1+USgTN4VhAenm/wea1OCAOmqo6fE1WCb9WSKBah+rbUWPWAmE2Rvk0ApiB45eOyNAzU8xcTvj8KvkKEoOaIYeHNA3ZuygAvFMUO0AAAAASUVORK5CYII=";break;case"external_person":o="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAIAAADYYG7QAAAB6ElEQVR4Xu2YLY+EMBCG9+dWr0aj0Wg0Go1Go0+j8Xdv2uTCvv1gpt0ebHKPuhDaeW4605Z9mJvx4AdXUyTUdd08z+u6flmWZRnHsWkafk9DptAwDPu+f0eAYtu2PEaGWuj5fCIZrBAC2eLBAnRCsEkkxmeaJp7iDJ2QMDdHsLg8SxKFEJaAo8lAXnmuOFIhTMpxxKATebo4UiFknuNo4OniSIXQyRxEA3YsnjGCVEjVXD7yLUAqxBGUyPv/Y4W2beMgGuS7kVQIBycH0fD+oi5pezQETxdHKmQKGk1eQEYldK+jw5GxPfZ9z7Mk0Qnhf1W1m3w//EUn5BDmSZsbR44QQLBEqrBHqOrmSKaQAxdnLArCrxZcM7A7ZKs4ioRq8LFC+NpC3WCBJsvpVw5edm9iEXFuyNfxXAgSwfrFQ1c0iNda8AdejvUgnktOtJQQxmcfFzGglc5WVCj7oDgFqU18boeFSs52CUh8LE8BIVQDT1ABrB0HtgSEYlX5doJnCwv9TXocKCaKbnwhdDKPq4lf3SwU3HLq4V/+WYhHVMa/3b4IlfyikAduCkcBc7mQ3/z/Qq/cTuikhkzB12Ae/mcJC9U+Vo8Ej1gWAtgbeGgFsAMHr50BIWOLCbezvhpBFUdY6EJuJ/QDW0XoMX60zZ0AAAAASUVORK5CYII=";}var s=t.append("g");s.attr("class","person-man");var c={x:0,y:0,fill:"#EDF2AE",stroke:"#666",width:100,anchor:"start",height:100,rx:0,ry:0};switch(e.typeC4Shape.text){case"person":case"external_person":case"system":case"external_system":case"container":case"external_container":case"component":case"external_component":c.x=e.x,c.y=e.y,c.fill=r,c.width=e.width,c.height=e.height,c.style="stroke:"+i+";stroke-width:0.5;",c.rx=2.5,c.ry=2.5,Ye(s,c);break;case"system_db":case"external_system_db":case"container_db":case"external_container_db":case"component_db":case"external_component_db":s.append("path").attr("fill",r).attr("stroke-width","0.5").attr("stroke",i).attr("d","Mstartx,startyc0,-10 half,-10 half,-10c0,0 half,0 half,10l0,heightc0,10 -half,10 -half,10c0,0 -half,0 -half,-10l0,-height".replaceAll("startx",e.x).replaceAll("starty",e.y).replaceAll("half",e.width/2).replaceAll("height",e.height)),s.append("path").attr("fill","none").attr("stroke-width","0.5").attr("stroke",i).attr("d","Mstartx,startyc0,10 half,10 half,10c0,0 half,0 half,-10".replaceAll("startx",e.x).replaceAll("starty",e.y).replaceAll("half",e.width/2));break;case"system_queue":case"external_system_queue":case"container_queue":case"external_container_queue":case"component_queue":case"external_component_queue":s.append("path").attr("fill",r).attr("stroke-width","0.5").attr("stroke",i).attr("d","Mstartx,startylwidth,0c5,0 5,half 5,halfc0,0 0,half -5,halfl-width,0c-5,0 -5,-half -5,-halfc0,0 0,-half 5,-half".replaceAll("startx",e.x).replaceAll("starty",e.y).replaceAll("width",e.width).replaceAll("half",e.height/2)),s.append("path").attr("fill","none").attr("stroke-width","0.5").attr("stroke",i).attr("d","Mstartx,startyc-5,0 -5,half -5,halfc0,half 5,half 5,half".replaceAll("startx",e.x+e.width).replaceAll("starty",e.y).replaceAll("half",e.height/2));}var l,u,h=(l=n,u=e.typeC4Shape.text,{fontFamily:l[u+"FontFamily"],fontSize:l[u+"FontSize"],fontWeight:l[u+"FontWeight"]});switch(s.append("text").attr("fill",a).attr("font-family",h.fontFamily).attr("font-size",h.fontSize-2).attr("font-style","italic").attr("lengthAdjust","spacing").attr("textLength",e.typeC4Shape.width).attr("x",e.x+e.width/2-e.typeC4Shape.width/2).attr("y",e.y+e.typeC4Shape.Y).text("<<"+e.typeC4Shape.text+">>"),e.typeC4Shape.text){case"person":case"external_person":!function(t,e,n,r,i,a){var o=t.append("image");o.attr("width",e),o.attr("height",n),o.attr("x",r),o.attr("y",i);var s=a.startsWith("data:image/png;base64")?a:(0, je.N)(a);o.attr("xlink:href",s);}(s,48,48,e.x+e.width/2-24,e.y+e.image.Y,o);}var f=n[e.typeC4Shape.text+"Font"]();return f.fontWeight="bold",f.fontSize=f.fontSize+2,f.fontColor=a,Ue(n)(e.label.text,s,e.x,e.y+e.label.Y,e.width,e.height,{fill:a},f),(f=n[e.typeC4Shape.text+"Font"]()).fontColor=a,e.thchn&&""!==e.thchn.text?Ue(n)(e.thchn.text,s,e.x,e.y+e.thchn.Y,e.width,e.height,{fill:a,"font-style":"italic"},f):e.type&&""!==e.type.text&&Ue(n)(e.type.text,s,e.x,e.y+e.type.Y,e.width,e.height,{fill:a,"font-style":"italic"},f),e.descr&&""!==e.descr.text&&((f=n.personFont()).fontColor=a,Ue(n)(e.descr.text,s,e.x,e.y+e.descr.Y,e.width,e.height,{fill:a},f)),e.height},We=function(t,e,n){var r,i=t.append("g"),a=0,o=function(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return ze(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return "Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ze(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0,i=function(){};return {s:i,n:function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}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 a,o=!0,s=!1;return {s:function(){n=n.call(t);},n:function(){var t=n.next();return o=t.done,t},e:function(t){s=!0,a=t;},f:function(){try{o||null==n.return||n.return();}finally{if(s)throw a}}}}(e);try{for(o.s();!(r=o.n()).done;){var s=r.value,c=s.textColor?s.textColor:"#444444",l=s.lineColor?s.lineColor:"#444444",u=s.offsetX?parseInt(s.offsetX):0,h=s.offsetY?parseInt(s.offsetY):0;if(0===a){var f=i.append("line");f.attr("x1",s.startPoint.x),f.attr("y1",s.startPoint.y),f.attr("x2",s.endPoint.x),f.attr("y2",s.endPoint.y),f.attr("stroke-width","1"),f.attr("stroke",l),f.style("fill","none"),"rel_b"!==s.type&&f.attr("marker-end","url(#arrowhead)"),"birel"!==s.type&&"rel_b"!==s.type||f.attr("marker-start","url(#arrowend)"),a=-1;}else {var d=i.append("path");d.attr("fill","none").attr("stroke-width","1").attr("stroke",l).attr("d","Mstartx,starty Qcontrolx,controly stopx,stopy ".replaceAll("startx",s.startPoint.x).replaceAll("starty",s.startPoint.y).replaceAll("controlx",s.startPoint.x+(s.endPoint.x-s.startPoint.x)/2-(s.endPoint.x-s.startPoint.x)/4).replaceAll("controly",s.startPoint.y+(s.endPoint.y-s.startPoint.y)/2).replaceAll("stopx",s.endPoint.x).replaceAll("stopy",s.endPoint.y)),"rel_b"!==s.type&&d.attr("marker-end","url(#arrowhead)"),"birel"!==s.type&&"rel_b"!==s.type||d.attr("marker-start","url(#arrowend)");}var p=n.messageFont();Ue(n)(s.label.text,i,Math.min(s.startPoint.x,s.endPoint.x)+Math.abs(s.endPoint.x-s.startPoint.x)/2+u,Math.min(s.startPoint.y,s.endPoint.y)+Math.abs(s.endPoint.y-s.startPoint.y)/2+h,s.label.width,s.label.height,{fill:c},p),s.techn&&""!==s.techn.text&&(p=n.messageFont(),Ue(n)("["+s.techn.text+"]",i,Math.min(s.startPoint.x,s.endPoint.x)+Math.abs(s.endPoint.x-s.startPoint.x)/2+u,Math.min(s.startPoint.y,s.endPoint.y)+Math.abs(s.endPoint.y-s.startPoint.y)/2+n.messageFontSize+5+h,Math.max(s.label.width,s.techn.width),s.techn.height,{fill:c,"font-style":"italic"},p));}}catch(t){o.e(t);}finally{o.f();}};je.N;var qe=n(2536),He=n.n(qe),Ve=/[%]{2}[{]\s*(?:(?:(\w+)\s*:|(\w+))\s*(?:(?:(\w+))|((?:(?![}][%]{2}).|\r?\n)*))?\s*)(?:[}][%]{2})?/gi,Ge=/\s*%%.*\n/gm,Xe={};const Ze=function(t,e){if((t=t.replace(Ve,"").replace(Ge,"\n")).match(/^\s*C4Context|C4Container|C4Component|C4Dynamic|C4Deployment/))return "c4";if("error"===t)return "error";if(t.match(/^\s*sequenceDiagram/))return "sequence";if(t.match(/^\s*gantt/))return "gantt";if(t.match(/^\s*classDiagram-v2/))return "classDiagram";if(t.match(/^\s*classDiagram/))return e&&e.class&&"dagre-wrapper"===e.class.defaultRenderer?"classDiagram":"class";if(t.match(/^\s*stateDiagram-v2/))return "stateDiagram";if(t.match(/^\s*stateDiagram/))return e&&e.class&&"dagre-wrapper"===e.state.defaultRenderer?"stateDiagram":"state";if(t.match(/^\s*flowchart/))return "flowchart-v2";if(t.match(/^\s*info/))return "info";if(t.match(/^\s*pie/))return "pie";if(t.match(/^\s*erDiagram/))return "er";if(t.match(/^\s*journey/))return "journey";if(t.match(/^\s*requirement/)||t.match(/^\s*requirementDiagram/))return "requirement";if(e&&e.flowchart&&"dagre-wrapper"===e.flowchart.defaultRenderer)return "flowchart-v2";for(var n=Object.keys(Xe),r=0;r<n.length;r++){var i=n[r],a=Xe[i];if(a&&a.detector(t))return i}return "flowchart"};var Qe=void 0;function Ke(t){return Ke="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ke(t)}function Je(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r);}}function tn(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=nn(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0,i=function(){};return {s:i,n:function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}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 a,o=!0,s=!1;return {s:function(){n=n.call(t);},n:function(){var t=n.next();return o=t.done,t},e:function(t){s=!0,a=t;},f:function(){try{o||null==n.return||n.return();}finally{if(s)throw a}}}}function en(t){return function(t){if(Array.isArray(t))return rn(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||nn(t)||function(){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 nn(t,e){if(t){if("string"==typeof t)return rn(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return "Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?rn(t,e):void 0}}function rn(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}var an,on={curveBasis:l.curveBasis,curveBasisClosed:l.curveBasisClosed,curveBasisOpen:l.curveBasisOpen,curveLinear:l.curveLinear,curveLinearClosed:l.curveLinearClosed,curveMonotoneX:l.curveMonotoneX,curveMonotoneY:l.curveMonotoneY,curveNatural:l.curveNatural,curveStep:l.curveStep,curveStepAfter:l.curveStepAfter,curveStepBefore:l.curveStepBefore},sn=/[%]{2}[{]\s*(?:(?:(\w+)\s*:|(\w+))\s*(?:(?:(\w+))|((?:(?![}][%]{2}).|\r?\n)*))?\s*)(?:[}][%]{2})?/gi,cn=/\s*(?:(?:(\w+)(?=:):|(\w+))\s*(?:(?:(\w+))|((?:(?![}][%]{2}).|\r?\n)*))?\s*)(?:[}][%]{2})?/gi,ln=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;try{var n=new RegExp("[%]{2}(?![{]".concat(cn.source,")(?=[}][%]{2}).*\n"),"ig");t=t.trim().replace(n,"").replace(/'/gm,'"'),o.debug("Detecting diagram directive".concat(null!==e?" type:"+e:""," based on the text:").concat(t));for(var r,i=[];null!==(r=sn.exec(t));)if(r.index===sn.lastIndex&&sn.lastIndex++,r&&!e||e&&r[1]&&r[1].match(e)||e&&r[2]&&r[2].match(e)){var a=r[1]?r[1]:r[2],s=r[3]?r[3].trim():r[4]?JSON.parse(r[4].trim()):null;i.push({type:a,args:s});}return 0===i.length&&i.push({type:t,args:null}),1===i.length?i[0]:i}catch(n){return o.error("ERROR: ".concat(n.message," - Unable to parse directive\n ").concat(null!==e?" type:"+e:""," based on the text:").concat(t)),{type:null,args:null}}},un=function(t,e){var n={};return function(){for(var r=arguments.length,i=new Array(r),a=0;a<r;a++)i[a]=arguments[a];var o=e?e.apply(Qe,i):i[0];if(o in n)return n[o];var s=t.apply(void 0,i);return n[o]=s,s}},hn=function(t,e){if(!t)return e;var n="curve".concat(t.charAt(0).toUpperCase()+t.slice(1));return on[n]||e},fn=function(t,e){return t&&e?Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2)):0},dn=function(t){for(var e="",n="",r=0;r<t.length;r++)void 0!==t[r]&&(t[r].startsWith("color:")||t[r].startsWith("text-align:")?n=n+t[r]+";":e=e+t[r]+";");return {style:e,labelStyle:n}},pn=0,gn=function(){return pn++,"id-"+Math.random().toString(36).substr(2,12)+"-"+pn},yn=function(t){return function(t){for(var e="",n="0123456789abcdef",r=n.length,i=0;i<t;i++)e+=n.charAt(Math.floor(Math.random()*r));return e}(t.length)},mn=function(t,e){var n=e.text.replace(ue.lineBreakRegex," "),r=t.append("text");r.attr("x",e.x),r.attr("y",e.y),r.style("text-anchor",e.anchor),r.style("font-family",e.fontFamily),r.style("font-size",e.fontSize),r.style("font-weight",e.fontWeight),r.attr("fill",e.fill),void 0!==e.class&&r.attr("class",e.class);var i=r.append("tspan");return i.attr("x",e.x+2*e.textMargin),i.attr("fill",e.fill),i.text(n),r},bn=un((function(t,e,n){if(!t)return t;if(n=Object.assign({fontSize:12,fontWeight:400,fontFamily:"Arial",joinWith:"<br/>"},n),ue.lineBreakRegex.test(t))return t;var r=t.split(" "),i=[],a="";return r.forEach((function(t,o){var s=xn("".concat(t," "),n),c=xn(a,n);if(s>e){var l=vn(t,e,"-",n),u=l.hyphenatedStrings,h=l.remainingWord;i.push.apply(i,[a].concat(en(u))),a=h;}else c+s>=e?(i.push(a),a=t):a=[a,t].filter(Boolean).join(" ");o+1===r.length&&i.push(a);})),i.filter((function(t){return ""!==t})).join(n.joinWith)}),(function(t,e,n){return "".concat(t,"-").concat(e,"-").concat(n.fontSize,"-").concat(n.fontWeight,"-").concat(n.fontFamily,"-").concat(n.joinWith)})),vn=un((function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"-",r=arguments.length>3?arguments[3]:void 0;r=Object.assign({fontSize:12,fontWeight:400,fontFamily:"Arial",margin:0},r);var i=t.split(""),a=[],o="";return i.forEach((function(t,s){var c="".concat(o).concat(t);if(xn(c,r)>=e){var l=s+1,u=i.length===l,h="".concat(c).concat(n);a.push(u?c:h),o="";}else o=c;})),{hyphenatedStrings:a,remainingWord:o}}),(function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"-",r=arguments.length>3?arguments[3]:void 0;return "".concat(t,"-").concat(e,"-").concat(n,"-").concat(r.fontSize,"-").concat(r.fontWeight,"-").concat(r.fontFamily)})),_n=function(t,e){return e=Object.assign({fontSize:12,fontWeight:400,fontFamily:"Arial",margin:15},e),kn(t,e).height},xn=function(t,e){return e=Object.assign({fontSize:12,fontWeight:400,fontFamily:"Arial"},e),kn(t,e).width},kn=un((function(t,e){var n=e=Object.assign({fontSize:12,fontWeight:400,fontFamily:"Arial"},e),r=n.fontSize,i=n.fontFamily,a=n.fontWeight;if(!t)return {width:0,height:0};var o=["sans-serif",i],s=t.split(ue.lineBreakRegex),c=[],u=(0, l.select)("body");if(!u.remove)return {width:0,height:0,lineHeight:0};for(var h=u.append("svg"),f=0,d=o;f<d.length;f++){var p,g=d[f],y=0,m={width:0,height:0,lineHeight:0},b=tn(s);try{for(b.s();!(p=b.n()).done;){var v=p.value,_={x:0,y:0,fill:void 0,anchor:"start",style:"#666",width:100,height:100,textMargin:0,rx:0,ry:0,valign:void 0};_.text=v;var x=mn(h,_).style("font-size",r).style("font-weight",a).style("font-family",g),k=(x._groups||x)[0][0].getBBox();m.width=Math.round(Math.max(m.width,k.width)),y=Math.round(k.height),m.height+=y,m.lineHeight=Math.round(Math.max(m.lineHeight,y));}}catch(t){b.e(t);}finally{b.f();}c.push(m);}return h.remove(),c[isNaN(c[1].height)||isNaN(c[1].width)||isNaN(c[1].lineHeight)||c[0].height>c[1].height&&c[0].width>c[1].width&&c[0].lineHeight>c[1].lineHeight?0:1]}),(function(t,e){return "".concat(t,"-").concat(e.fontSize,"-").concat(e.fontWeight,"-").concat(e.fontFamily)})),wn=function(t,e,n){var r=new Map;return n?(r.set("width","100%"),r.set("style","max-width: ".concat(e,"px;"))):r.set("width",e),r},Tn=function(t,e,n,r){!function(t,e){var n,r=tn(e);try{for(r.s();!(n=r.n()).done;){var i=n.value;t.attr(i[0],i[1]);}}catch(t){r.e(t);}finally{r.f();}}(t,wn(0,1*n,r));},En=function(t,e,n,r){var i=e.node().getBBox(),a=i.width,s=i.height;o.info("SVG bounds: ".concat(a,"x").concat(s),i);var c=t._label.width,l=t._label.height;o.info("Graph bounds: ".concat(c,"x").concat(l),t),c=a+2*n,l=s+2*n,o.info("Calculated bounds: ".concat(c,"x").concat(l)),Tn(e,0,c,r);var u="".concat(i.x-n," ").concat(i.y-n," ").concat(i.width+2*n," ").concat(i.height+2*n);o.info("Graph.label",t._label,"swidth",a,"sheight",s,"width",c,"height",l,"vBox",u),e.attr("viewBox",u);},Cn=function t(e){if(o.debug("directiveSanitizer called with",e),"object"===Ke(e)&&(e.length?e.forEach((function(e){return t(e)})):Object.keys(e).forEach((function(n){o.debug("Checking key",n),0===n.indexOf("__")&&(o.debug("sanitize deleting __ option",n),delete e[n]),n.indexOf("proto")>=0&&(o.debug("sanitize deleting proto option",n),delete e[n]),n.indexOf("constr")>=0&&(o.debug("sanitize deleting constr option",n),delete e[n]),n.indexOf("themeCSS")>=0&&(o.debug("sanitizing themeCss option"),e[n]=Sn(e[n])),n.indexOf("fontFamily")>=0&&(o.debug("sanitizing fontFamily option"),e[n]=Sn(e[n])),n.indexOf("altFontFamily")>=0&&(o.debug("sanitizing altFontFamily option"),e[n]=Sn(e[n])),jt.indexOf(n)<0?(o.debug("sanitize deleting option",n),delete e[n]):"object"===Ke(e[n])&&(o.debug("sanitize deleting object",n),t(e[n]));}))),e.themeVariables)for(var n=Object.keys(e.themeVariables),r=0;r<n.length;r++){var i=n[r],a=e.themeVariables[i];a&&a.match&&!a.match(/^[a-zA-Z0-9#,";()%. ]+$/)&&(e.themeVariables[i]="");}o.debug("After sanitization",e);},Sn=function(t){for(var e=0,n=0,r=0;r<t.length;r++){if(e<n)return "{ /* ERROR: Unbalanced CSS */ }";"{"===t[r]?e++:"}"===t[r]&&n++;}return e!==n?"{ /* ERROR: Unbalanced CSS */ }":t};const An={assignWithDepth:Q,wrapLabel:bn,calculateTextHeight:_n,calculateTextWidth:xn,calculateTextDimensions:kn,calculateSvgSizeAttrs:wn,configureSvgSize:Tn,setupGraphViewbox:En,detectInit:function(t,e){var n=ln(t,/(?:init\b)|(?:initialize\b)/),r={};if(Array.isArray(n)){var i=n.map((function(t){return t.args}));Cn(i),r=Q(r,en(i));}else r=n.args;if(r){var a=Ze(t,e);["config"].forEach((function(t){void 0!==r[t]&&("flowchart-v2"===a&&(a="flowchart"),r[a]=r[t],delete r[t]);}));}return r},detectDirective:ln,isSubstringInArray:function(t,e){for(var n=0;n<e.length;n++)if(e[n].match(t))return n;return -1},interpolateToCurve:hn,calcLabelPosition:function(t){return 1===t.length?t[0]:function(t){var e,n=0;t.forEach((function(t){n+=fn(t,e),e=t;}));var r=n/2,i=void 0;return e=void 0,t.forEach((function(t){if(e&&!i){var n=fn(t,e);if(n<r)r-=n;else {var a=r/n;a<=0&&(i=e),a>=1&&(i={x:t.x,y:t.y}),a>0&&a<1&&(i={x:(1-a)*e.x+a*t.x,y:(1-a)*e.y+a*t.y});}}e=t;})),i}(t)},calcCardinalityPosition:function(t,e,n){var r;o.info("our points",e),e[0]!==n&&(e=e.reverse()),e.forEach((function(t){fn(t,r),r=t;}));var i,a=25;r=void 0,e.forEach((function(t){if(r&&!i){var e=fn(t,r);if(e<a)a-=e;else {var n=a/e;n<=0&&(i=r),n>=1&&(i={x:t.x,y:t.y}),n>0&&n<1&&(i={x:(1-n)*r.x+n*t.x,y:(1-n)*r.y+n*t.y});}}r=t;}));var s=t?10:5,c=Math.atan2(e[0].y-i.y,e[0].x-i.x),l={x:0,y:0};return l.x=Math.sin(c)*s+(e[0].x+i.x)/2,l.y=-Math.cos(c)*s+(e[0].y+i.y)/2,l},calcTerminalLabelPosition:function(t,e,n){var r,i=JSON.parse(JSON.stringify(n));o.info("our points",i),"start_left"!==e&&"start_right"!==e&&(i=i.reverse()),i.forEach((function(t){fn(t,r),r=t;}));var a,s=25+t;r=void 0,i.forEach((function(t){if(r&&!a){var e=fn(t,r);if(e<s)s-=e;else {var n=s/e;n<=0&&(a=r),n>=1&&(a={x:t.x,y:t.y}),n>0&&n<1&&(a={x:(1-n)*r.x+n*t.x,y:(1-n)*r.y+n*t.y});}}r=t;}));var c=10+.5*t,l=Math.atan2(i[0].y-a.y,i[0].x-a.x),u={x:0,y:0};return u.x=Math.sin(l)*c+(i[0].x+a.x)/2,u.y=-Math.cos(l)*c+(i[0].y+a.y)/2,"start_left"===e&&(u.x=Math.sin(l+Math.PI)*c+(i[0].x+a.x)/2,u.y=-Math.cos(l+Math.PI)*c+(i[0].y+a.y)/2),"end_right"===e&&(u.x=Math.sin(l-Math.PI)*c+(i[0].x+a.x)/2-5,u.y=-Math.cos(l-Math.PI)*c+(i[0].y+a.y)/2-5),"end_left"===e&&(u.x=Math.sin(l)*c+(i[0].x+a.x)/2-5,u.y=-Math.cos(l)*c+(i[0].y+a.y)/2-5),u},formatUrl:function(t,e){var n=t.trim();if(n)return "loose"!==e.securityLevel?(0, je.N)(n):n},getStylesFromArray:dn,generateId:gn,random:yn,memoize:un,runFunc:function(t){for(var e,n=t.split("."),r=n.length-1,i=n[r],a=window,o=0;o<r;o++)if(!(a=a[n[o]]))return;for(var s=arguments.length,c=new Array(s>1?s-1:0),l=1;l<s;l++)c[l-1]=arguments[l];(e=a)[i].apply(e,c);},entityDecode:function(t){return an=an||document.createElement("div"),t=escape(t).replace(/%26/g,"&").replace(/%23/g,"#").replace(/%3B/g,";"),an.innerHTML=t,unescape(an.textContent)},initIdGenerator:function(){function t(e,n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.deterministic=e,this.seed=n,this.count=n?n.length:0;}var e,n;return e=t,(n=[{key:"next",value:function(){return this.deterministic?this.count++:Date.now()}}])&&Je(e.prototype,n),Object.defineProperty(e,"prototype",{writable:!1}),t}(),directiveSanitizer:Cn,sanitizeCss:Sn};function Mn(t,e,n){if(void 0!==e.insert){var r=t.getAccTitle(),i=t.getAccDescription();e.attr("role","img").attr("aria-labelledby","chart-title-"+n+" chart-desc-"+n),e.insert("desc",":first-child").attr("id","chart-desc-"+n).text(i),e.insert("title",":first-child").attr("id","chart-title-"+n).text(r);}}function Nn(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function On(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function Dn(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r);}}function Bn(t,e,n){return e&&Dn(t.prototype,e),n&&Dn(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}var Ln=0,In=0,Fn=4,Rn=2;qe.parser.yy=Pe;var Pn={},jn=function(){function t(e){On(this,t),this.name="",this.data={},this.data.startx=void 0,this.data.stopx=void 0,this.data.starty=void 0,this.data.stopy=void 0,this.data.widthLimit=void 0,this.nextData={},this.nextData.startx=void 0,this.nextData.stopx=void 0,this.nextData.starty=void 0,this.nextData.stopy=void 0,this.nextData.cnt=0,zn(e.db.getConfig());}return Bn(t,[{key:"setData",value:function(t,e,n,r){this.nextData.startx=this.data.startx=t,this.nextData.stopx=this.data.stopx=e,this.nextData.starty=this.data.starty=n,this.nextData.stopy=this.data.stopy=r;}},{key:"updateVal",value:function(t,e,n,r){void 0===t[e]?t[e]=n:t[e]=r(n,t[e]);}},{key:"insert",value:function(t){this.nextData.cnt=this.nextData.cnt+1;var e=this.nextData.startx===this.nextData.stopx?this.nextData.stopx+t.margin:this.nextData.stopx+2*t.margin,n=e+t.width,r=this.nextData.starty+2*t.margin,i=r+t.height;(e>=this.data.widthLimit||n>=this.data.widthLimit||this.nextData.cnt>Fn)&&(e=this.nextData.startx+t.margin+Pn.nextLinePaddingX,r=this.nextData.stopy+2*t.margin,this.nextData.stopx=n=e+t.width,this.nextData.starty=this.nextData.stopy,this.nextData.stopy=i=r+t.height,this.nextData.cnt=1),t.x=e,t.y=r,this.updateVal(this.data,"startx",e,Math.min),this.updateVal(this.data,"starty",r,Math.min),this.updateVal(this.data,"stopx",n,Math.max),this.updateVal(this.data,"stopy",i,Math.max),this.updateVal(this.nextData,"startx",e,Math.min),this.updateVal(this.nextData,"starty",r,Math.min),this.updateVal(this.nextData,"stopx",n,Math.max),this.updateVal(this.nextData,"stopy",i,Math.max);}},{key:"init",value:function(t){this.name="",this.data={startx:void 0,stopx:void 0,starty:void 0,stopy:void 0,widthLimit:void 0},this.nextData={startx:void 0,stopx:void 0,starty:void 0,stopy:void 0,cnt:0},zn(t.db.getConfig());}},{key:"bumpLastMargin",value:function(t){this.data.stopx+=t,this.data.stopy+=t;}}]),t}(),zn=function(t){Q(Pn,t),t.fontFamily&&(Pn.personFontFamily=Pn.systemFontFamily=Pn.messageFontFamily=t.fontFamily),t.fontSize&&(Pn.personFontSize=Pn.systemFontSize=Pn.messageFontSize=t.fontSize),t.fontWeight&&(Pn.personFontWeight=Pn.systemFontWeight=Pn.messageFontWeight=t.fontWeight);},Yn=function(t,e){return {fontFamily:t[e+"FontFamily"],fontSize:t[e+"FontSize"],fontWeight:t[e+"FontWeight"]}},Un=function(t){return {fontFamily:t.boundaryFontFamily,fontSize:t.boundaryFontSize,fontWeight:t.boundaryFontWeight}};function $n(t,e,n,r,i){if(!e[t].width)if(n)e[t].text=bn(e[t].text,i,r),e[t].textLines=e[t].text.split(ue.lineBreakRegex).length,e[t].width=i,e[t].height=_n(e[t].text,r);else {var a=e[t].text.split(ue.lineBreakRegex);e[t].textLines=a.length;var o=0;e[t].height=0,e[t].width=0;for(var s=0;s<a.length;s++)e[t].width=Math.max(xn(a[s],r),e[t].width),o=_n(a[s],r),e[t].height=e[t].height+o;}}var Wn=function(t,e,n){e.x=n.data.startx,e.y=n.data.starty,e.width=n.data.stopx-n.data.startx,e.height=n.data.stopy-n.data.starty,e.label.y=Pn.c4ShapeMargin-35;var r=e.wrap&&Pn.wrap,i=Un(Pn);i.fontSize=i.fontSize+2,i.fontWeight="bold",$n("label",e,r,i,xn(e.label.text,i)),function(t,e,n){var r=t.append("g"),i=e.bgColor?e.bgColor:"none",a=e.borderColor?e.borderColor:"#444444",o=e.fontColor?e.fontColor:"black",s={"stroke-width":1,"stroke-dasharray":"7.0,7.0"};e.nodeType&&(s={"stroke-width":1});var c={x:e.x,y:e.y,fill:i,stroke:a,width:e.width,height:e.height,rx:2.5,ry:2.5,attrs:s};Ye(r,c);var l=n.boundaryFont();l.fontWeight="bold",l.fontSize=l.fontSize+2,l.fontColor=o,Ue(n)(e.label.text,r,e.x,e.y+e.label.Y,e.width,e.height,{fill:"#444444"},l),e.type&&""!==e.type.text&&((l=n.boundaryFont()).fontColor=o,Ue(n)(e.type.text,r,e.x,e.y+e.type.Y,e.width,e.height,{fill:"#444444"},l)),e.descr&&""!==e.descr.text&&((l=n.boundaryFont()).fontSize=l.fontSize-2,l.fontColor=o,Ue(n)(e.descr.text,r,e.x,e.y+e.descr.Y,e.width,e.height,{fill:"#444444"},l));}(t,e,Pn);},qn=function(t,e,n,r){for(var i=0,a=0;a<r.length;a++){i=0;var o=n[r[a]],s=Yn(Pn,o.typeC4Shape.text);switch(s.fontSize=s.fontSize-2,o.typeC4Shape.width=xn("<<"+o.typeC4Shape.text+">>",s),o.typeC4Shape.height=s.fontSize+2,o.typeC4Shape.Y=Pn.c4ShapePadding,i=o.typeC4Shape.Y+o.typeC4Shape.height-4,o.image={width:0,height:0,Y:0},o.typeC4Shape.text){case"person":case"external_person":o.image.width=48,o.image.height=48,o.image.Y=i,i=o.image.Y+o.image.height;}o.sprite&&(o.image.width=48,o.image.height=48,o.image.Y=i,i=o.image.Y+o.image.height);var c=o.wrap&&Pn.wrap,l=Pn.width-2*Pn.c4ShapePadding,u=Yn(Pn,o.typeC4Shape.text);u.fontSize=u.fontSize+2,u.fontWeight="bold",$n("label",o,c,u,l),o.label.Y=i+8,i=o.label.Y+o.label.height,o.type&&""!==o.type.text?(o.type.text="["+o.type.text+"]",$n("type",o,c,Yn(Pn,o.typeC4Shape.text),l),o.type.Y=i+5,i=o.type.Y+o.type.height):o.techn&&""!==o.techn.text&&(o.techn.text="["+o.techn.text+"]",$n("techn",o,c,Yn(Pn,o.techn.text),l),o.techn.Y=i+5,i=o.techn.Y+o.techn.height);var h=i,f=o.label.width;o.descr&&""!==o.descr.text&&($n("descr",o,c,Yn(Pn,o.typeC4Shape.text),l),o.descr.Y=i+20,i=o.descr.Y+o.descr.height,f=Math.max(o.label.width,o.descr.width),h=i-5*o.descr.textLines),f+=Pn.c4ShapePadding,o.width=Math.max(o.width||Pn.width,f,Pn.width),o.height=Math.max(o.height||Pn.height,h,Pn.height),o.margin=o.margin||Pn.c4ShapeMargin,t.insert(o),$e(e,o,Pn);}t.bumpLastMargin(Pn.c4ShapeMargin);},Hn=Bn((function t(e,n){On(this,t),this.x=e,this.y=n;})),Vn=function(t,e){var n=t.x,r=t.y,i=e.x,a=e.y,o=n+t.width/2,s=r+t.height/2,c=Math.abs(n-i),l=Math.abs(r-a),u=l/c,h=t.height/t.width,f=null;return r==a&&n<i?f=new Hn(n+t.width,s):r==a&&n>i?f=new Hn(n,s):n==i&&r<a?f=new Hn(o,r+t.height):n==i&&r>a&&(f=new Hn(o,r)),n>i&&r<a?f=h>=u?new Hn(n,s+u*t.width/2):new Hn(o-c/l*t.height/2,r+t.height):n<i&&r<a?f=h>=u?new Hn(n+t.width,s+u*t.width/2):new Hn(o+c/l*t.height/2,r+t.height):n<i&&r>a?f=h>=u?new Hn(n+t.width,s-u*t.width/2):new Hn(o+t.height/2*c/l,r):n>i&&r>a&&(f=h>=u?new Hn(n,s-t.width/2*u):new Hn(o-t.height/2*c/l,r)),f},Gn=function(t,e){var n={x:0,y:0};n.x=e.x+e.width/2,n.y=e.y+e.height/2;var r=Vn(t,n);return n.x=t.x+t.width/2,n.y=t.y+t.height/2,{startPoint:r,endPoint:Vn(e,n)}};function Xn(t,e,n,r,i){var a=new jn(i);a.data.widthLimit=n.data.widthLimit/Math.min(Rn,r.length);for(var o=0;o<r.length;o++){var s=r[o],c=0;s.image={width:0,height:0,Y:0},s.sprite&&(s.image.width=48,s.image.height=48,s.image.Y=c,c=s.image.Y+s.image.height);var l=s.wrap&&Pn.wrap,u=Un(Pn);if(u.fontSize=u.fontSize+2,u.fontWeight="bold",$n("label",s,l,u,a.data.widthLimit),s.label.Y=c+8,c=s.label.Y+s.label.height,s.type&&""!==s.type.text&&(s.type.text="["+s.type.text+"]",$n("type",s,l,Un(Pn),a.data.widthLimit),s.type.Y=c+5,c=s.type.Y+s.type.height),s.descr&&""!==s.descr.text){var h=Un(Pn);h.fontSize=h.fontSize-2,$n("descr",s,l,h,a.data.widthLimit),s.descr.Y=c+20,c=s.descr.Y+s.descr.height;}if(0==o||o%Rn==0){var f=n.data.startx+Pn.diagramMarginX,d=n.data.stopy+Pn.diagramMarginY+c;a.setData(f,f,d,d);}else {var p=a.data.stopx!==a.data.startx?a.data.stopx+Pn.diagramMarginX:a.data.startx,g=a.data.starty;a.setData(p,p,g,g);}a.name=s.alias;var y=i.db.getC4ShapeArray(s.alias),m=i.db.getC4ShapeKeys(s.alias);m.length>0&&qn(a,t,y,m),e=s.alias;var b=i.db.getBoundarys(e);b.length>0&&Xn(t,e,a,b,i),"global"!==s.alias&&Wn(t,s,a),n.data.stopy=Math.max(a.data.stopy+Pn.c4ShapeMargin,n.data.stopy),n.data.stopx=Math.max(a.data.stopx+Pn.c4ShapeMargin,n.data.stopx),Ln=Math.max(Ln,n.data.stopx),In=Math.max(In,n.data.stopy);}}const Zn={drawPersonOrSystemArray:qn,drawBoundary:Wn,setConf:zn,draw:function(t,e,n,r){Pn=Xt().c4;var i,a=Xt().securityLevel;"sandbox"===a&&(i=(0, l.select)("#i"+e));var s="sandbox"===a?(0, l.select)(i.nodes()[0].contentDocument.body):(0, l.select)("body"),c=r.db;r.db.setWrap(Pn.wrap),Fn=c.getC4ShapeInRow(),Rn=c.getC4BoundaryInRow(),o.debug("C:".concat(JSON.stringify(Pn,null,2)));var u="sandbox"===a?s.select('[id="'.concat(e,'"]')):(0, l.select)('[id="'.concat(e,'"]'));u.append("defs").append("symbol").attr("id","computer").attr("width","24").attr("height","24").append("path").attr("transform","scale(.5)").attr("d","M2 2v13h20v-13h-20zm18 11h-16v-9h16v9zm-10.228 6l.466-1h3.524l.467 1h-4.457zm14.228 3h-24l2-6h2.104l-1.33 4h18.45l-1.297-4h2.073l2 6zm-5-10h-14v-7h14v7z"),function(t){t.append("defs").append("symbol").attr("id","database").attr("fill-rule","evenodd").attr("clip-rule","evenodd").append("path").attr("transform","scale(.5)").attr("d","M12.258.001l.256.004.255.005.253.008.251.01.249.012.247.015.246.016.242.019.241.02.239.023.236.024.233.027.231.028.229.031.225.032.223.034.22.036.217.038.214.04.211.041.208.043.205.045.201.046.198.048.194.05.191.051.187.053.183.054.18.056.175.057.172.059.168.06.163.061.16.063.155.064.15.066.074.033.073.033.071.034.07.034.069.035.068.035.067.035.066.035.064.036.064.036.062.036.06.036.06.037.058.037.058.037.055.038.055.038.053.038.052.038.051.039.05.039.048.039.047.039.045.04.044.04.043.04.041.04.04.041.039.041.037.041.036.041.034.041.033.042.032.042.03.042.029.042.027.042.026.043.024.043.023.043.021.043.02.043.018.044.017.043.015.044.013.044.012.044.011.045.009.044.007.045.006.045.004.045.002.045.001.045v17l-.001.045-.002.045-.004.045-.006.045-.007.045-.009.044-.011.045-.012.044-.013.044-.015.044-.017.043-.018.044-.02.043-.021.043-.023.043-.024.043-.026.043-.027.042-.029.042-.03.042-.032.042-.033.042-.034.041-.036.041-.037.041-.039.041-.04.041-.041.04-.043.04-.044.04-.045.04-.047.039-.048.039-.05.039-.051.039-.052.038-.053.038-.055.038-.055.038-.058.037-.058.037-.06.037-.06.036-.062.036-.064.036-.064.036-.066.035-.067.035-.068.035-.069.035-.07.034-.071.034-.073.033-.074.033-.15.066-.155.064-.16.063-.163.061-.168.06-.172.059-.175.057-.18.056-.183.054-.187.053-.191.051-.194.05-.198.048-.201.046-.205.045-.208.043-.211.041-.214.04-.217.038-.22.036-.223.034-.225.032-.229.031-.231.028-.233.027-.236.024-.239.023-.241.02-.242.019-.246.016-.247.015-.249.012-.251.01-.253.008-.255.005-.256.004-.258.001-.258-.001-.256-.004-.255-.005-.253-.008-.251-.01-.249-.012-.247-.015-.245-.016-.243-.019-.241-.02-.238-.023-.236-.024-.234-.027-.231-.028-.228-.031-.226-.032-.223-.034-.22-.036-.217-.038-.214-.04-.211-.041-.208-.043-.204-.045-.201-.046-.198-.048-.195-.05-.19-.051-.187-.053-.184-.054-.179-.056-.176-.057-.172-.059-.167-.06-.164-.061-.159-.063-.155-.064-.151-.066-.074-.033-.072-.033-.072-.034-.07-.034-.069-.035-.068-.035-.067-.035-.066-.035-.064-.036-.063-.036-.062-.036-.061-.036-.06-.037-.058-.037-.057-.037-.056-.038-.055-.038-.053-.038-.052-.038-.051-.039-.049-.039-.049-.039-.046-.039-.046-.04-.044-.04-.043-.04-.041-.04-.04-.041-.039-.041-.037-.041-.036-.041-.034-.041-.033-.042-.032-.042-.03-.042-.029-.042-.027-.042-.026-.043-.024-.043-.023-.043-.021-.043-.02-.043-.018-.044-.017-.043-.015-.044-.013-.044-.012-.044-.011-.045-.009-.044-.007-.045-.006-.045-.004-.045-.002-.045-.001-.045v-17l.001-.045.002-.045.004-.045.006-.045.007-.045.009-.044.011-.045.012-.044.013-.044.015-.044.017-.043.018-.044.02-.043.021-.043.023-.043.024-.043.026-.043.027-.042.029-.042.03-.042.032-.042.033-.042.034-.041.036-.041.037-.041.039-.041.04-.041.041-.04.043-.04.044-.04.046-.04.046-.039.049-.039.049-.039.051-.039.052-.038.053-.038.055-.038.056-.038.057-.037.058-.037.06-.037.061-.036.062-.036.063-.036.064-.036.066-.035.067-.035.068-.035.069-.035.07-.034.072-.034.072-.033.074-.033.151-.066.155-.064.159-.063.164-.061.167-.06.172-.059.176-.057.179-.056.184-.054.187-.053.19-.051.195-.05.198-.048.201-.046.204-.045.208-.043.211-.041.214-.04.217-.038.22-.036.223-.034.226-.032.228-.031.231-.028.234-.027.236-.024.238-.023.241-.02.243-.019.245-.016.247-.015.249-.012.251-.01.253-.008.255-.005.256-.004.258-.001.258.001zm-9.258 20.499v.01l.001.021.003.021.004.022.005.021.006.022.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.023.018.024.019.024.021.024.022.025.023.024.024.025.052.049.056.05.061.051.066.051.07.051.075.051.079.052.084.052.088.052.092.052.097.052.102.051.105.052.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.048.144.049.147.047.152.047.155.047.16.045.163.045.167.043.171.043.176.041.178.041.183.039.187.039.19.037.194.035.197.035.202.033.204.031.209.03.212.029.216.027.219.025.222.024.226.021.23.02.233.018.236.016.24.015.243.012.246.01.249.008.253.005.256.004.259.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.021.224-.024.22-.026.216-.027.212-.028.21-.031.205-.031.202-.034.198-.034.194-.036.191-.037.187-.039.183-.04.179-.04.175-.042.172-.043.168-.044.163-.045.16-.046.155-.046.152-.047.148-.048.143-.049.139-.049.136-.05.131-.05.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.053.083-.051.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.05.023-.024.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.023.01-.022.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.127l-.077.055-.08.053-.083.054-.085.053-.087.052-.09.052-.093.051-.095.05-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.045-.118.044-.12.043-.122.042-.124.042-.126.041-.128.04-.13.04-.132.038-.134.038-.135.037-.138.037-.139.035-.142.035-.143.034-.144.033-.147.032-.148.031-.15.03-.151.03-.153.029-.154.027-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.01-.179.008-.179.008-.181.006-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.006-.179-.008-.179-.008-.178-.01-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.027-.153-.029-.151-.03-.15-.03-.148-.031-.146-.032-.145-.033-.143-.034-.141-.035-.14-.035-.137-.037-.136-.037-.134-.038-.132-.038-.13-.04-.128-.04-.126-.041-.124-.042-.122-.042-.12-.044-.117-.043-.116-.045-.113-.045-.112-.046-.109-.047-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.05-.093-.052-.09-.051-.087-.052-.085-.053-.083-.054-.08-.054-.077-.054v4.127zm0-5.654v.011l.001.021.003.021.004.021.005.022.006.022.007.022.009.022.01.022.011.023.012.023.013.023.015.024.016.023.017.024.018.024.019.024.021.024.022.024.023.025.024.024.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.052.11.051.114.051.119.052.123.05.127.051.131.05.135.049.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.044.171.042.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.022.23.02.233.018.236.016.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.012.241-.015.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.048.139-.05.136-.049.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.051.051-.049.023-.025.023-.024.021-.025.02-.024.019-.024.018-.024.017-.024.015-.023.014-.023.013-.024.012-.022.01-.023.01-.023.008-.022.006-.022.006-.022.004-.021.004-.022.001-.021.001-.021v-4.139l-.077.054-.08.054-.083.054-.085.052-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.044-.118.044-.12.044-.122.042-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.035-.143.033-.144.033-.147.033-.148.031-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.009-.179.009-.179.007-.181.007-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.007-.179-.007-.179-.009-.178-.009-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.031-.146-.033-.145-.033-.143-.033-.141-.035-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.04-.126-.041-.124-.042-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.051-.093-.051-.09-.051-.087-.053-.085-.052-.083-.054-.08-.054-.077-.054v4.139zm0-5.666v.011l.001.02.003.022.004.021.005.022.006.021.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.024.018.023.019.024.021.025.022.024.023.024.024.025.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.051.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.043.171.043.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.021.23.02.233.018.236.017.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.013.241-.014.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.049.139-.049.136-.049.131-.051.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.049.023-.025.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.022.01-.023.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.153l-.077.054-.08.054-.083.053-.085.053-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.048-.105.048-.106.048-.109.046-.111.046-.114.046-.115.044-.118.044-.12.043-.122.043-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.034-.143.034-.144.033-.147.032-.148.032-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.024-.161.024-.162.023-.163.023-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.01-.178.01-.179.009-.179.007-.181.006-.182.006-.182.004-.184.003-.184.001-.185.001-.185-.001-.184-.001-.184-.003-.182-.004-.182-.006-.181-.006-.179-.007-.179-.009-.178-.01-.176-.01-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.023-.162-.023-.161-.024-.159-.024-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.032-.146-.032-.145-.033-.143-.034-.141-.034-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.041-.126-.041-.124-.041-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.048-.105-.048-.102-.048-.1-.05-.097-.049-.095-.051-.093-.051-.09-.052-.087-.052-.085-.053-.083-.053-.08-.054-.077-.054v4.153zm8.74-8.179l-.257.004-.254.005-.25.008-.247.011-.244.012-.241.014-.237.016-.233.018-.231.021-.226.022-.224.023-.22.026-.216.027-.212.028-.21.031-.205.032-.202.033-.198.034-.194.036-.191.038-.187.038-.183.04-.179.041-.175.042-.172.043-.168.043-.163.045-.16.046-.155.046-.152.048-.148.048-.143.048-.139.049-.136.05-.131.05-.126.051-.123.051-.118.051-.114.052-.11.052-.106.052-.101.052-.096.052-.092.052-.088.052-.083.052-.079.052-.074.051-.07.052-.065.051-.06.05-.056.05-.051.05-.023.025-.023.024-.021.024-.02.025-.019.024-.018.024-.017.023-.015.024-.014.023-.013.023-.012.023-.01.023-.01.022-.008.022-.006.023-.006.021-.004.022-.004.021-.001.021-.001.021.001.021.001.021.004.021.004.022.006.021.006.023.008.022.01.022.01.023.012.023.013.023.014.023.015.024.017.023.018.024.019.024.02.025.021.024.023.024.023.025.051.05.056.05.06.05.065.051.07.052.074.051.079.052.083.052.088.052.092.052.096.052.101.052.106.052.11.052.114.052.118.051.123.051.126.051.131.05.136.05.139.049.143.048.148.048.152.048.155.046.16.046.163.045.168.043.172.043.175.042.179.041.183.04.187.038.191.038.194.036.198.034.202.033.205.032.21.031.212.028.216.027.22.026.224.023.226.022.231.021.233.018.237.016.241.014.244.012.247.011.25.008.254.005.257.004.26.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.022.224-.023.22-.026.216-.027.212-.028.21-.031.205-.032.202-.033.198-.034.194-.036.191-.038.187-.038.183-.04.179-.041.175-.042.172-.043.168-.043.163-.045.16-.046.155-.046.152-.048.148-.048.143-.048.139-.049.136-.05.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.05.051-.05.023-.025.023-.024.021-.024.02-.025.019-.024.018-.024.017-.023.015-.024.014-.023.013-.023.012-.023.01-.023.01-.022.008-.022.006-.023.006-.021.004-.022.004-.021.001-.021.001-.021-.001-.021-.001-.021-.004-.021-.004-.022-.006-.021-.006-.023-.008-.022-.01-.022-.01-.023-.012-.023-.013-.023-.014-.023-.015-.024-.017-.023-.018-.024-.019-.024-.02-.025-.021-.024-.023-.024-.023-.025-.051-.05-.056-.05-.06-.05-.065-.051-.07-.052-.074-.051-.079-.052-.083-.052-.088-.052-.092-.052-.096-.052-.101-.052-.106-.052-.11-.052-.114-.052-.118-.051-.123-.051-.126-.051-.131-.05-.136-.05-.139-.049-.143-.048-.148-.048-.152-.048-.155-.046-.16-.046-.163-.045-.168-.043-.172-.043-.175-.042-.179-.041-.183-.04-.187-.038-.191-.038-.194-.036-.198-.034-.202-.033-.205-.032-.21-.031-.212-.028-.216-.027-.22-.026-.224-.023-.226-.022-.231-.021-.233-.018-.237-.016-.241-.014-.244-.012-.247-.011-.25-.008-.254-.005-.257-.004-.26-.001-.26.001z");}(u),function(t){t.append("defs").append("symbol").attr("id","clock").attr("width","24").attr("height","24").append("path").attr("transform","scale(.5)").attr("d","M12 2c5.514 0 10 4.486 10 10s-4.486 10-10 10-10-4.486-10-10 4.486-10 10-10zm0-2c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm5.848 12.459c.202.038.202.333.001.372-1.907.361-6.045 1.111-6.547 1.111-.719 0-1.301-.582-1.301-1.301 0-.512.77-5.447 1.125-7.445.034-.192.312-.181.343.014l.985 6.238 5.394 1.011z");}(u);var h=new jn(r);h.setData(Pn.diagramMarginX,Pn.diagramMarginX,Pn.diagramMarginY,Pn.diagramMarginY),h.data.widthLimit=screen.availWidth,Ln=Pn.diagramMarginX,In=Pn.diagramMarginY;var f=r.db.getTitle();r.db.getC4Type(),Xn(u,"",h,r.db.getBoundarys(""),r),function(t){t.append("defs").append("marker").attr("id","arrowhead").attr("refX",9).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",12).attr("markerHeight",12).attr("orient","auto").append("path").attr("d","M 0 0 L 10 5 L 0 10 z");}(u),function(t){t.append("defs").append("marker").attr("id","arrowend").attr("refX",1).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",12).attr("markerHeight",12).attr("orient","auto").append("path").attr("d","M 10 0 L 0 5 L 10 10 z");}(u),function(t){var e=t.append("defs").append("marker").attr("id","crosshead").attr("markerWidth",15).attr("markerHeight",8).attr("orient","auto").attr("refX",16).attr("refY",4);e.append("path").attr("fill","black").attr("stroke","#000000").style("stroke-dasharray","0, 0").attr("stroke-width","1px").attr("d","M 9,2 V 6 L16,4 Z"),e.append("path").attr("fill","none").attr("stroke","#000000").style("stroke-dasharray","0, 0").attr("stroke-width","1px").attr("d","M 0,1 L 6,7 M 6,1 L 0,7");}(u),function(t){t.append("defs").append("marker").attr("id","filled-head").attr("refX",18).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L14,7 L9,1 Z");}(u),function(t,e,n,r){var i,a,o=0,s=function(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Nn(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return "Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Nn(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0,i=function(){};return {s:i,n:function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}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 a,o=!0,s=!1;return {s:function(){n=n.call(t);},n:function(){var t=n.next();return o=t.done,t},e:function(t){s=!0,a=t;},f:function(){try{o||null==n.return||n.return();}finally{if(s)throw a}}}}(e);try{for(s.s();!(i=s.n()).done;){var c=i.value;o+=1;var l=c.wrap&&Pn.wrap,u={fontFamily:(a=Pn).messageFontFamily,fontSize:a.messageFontSize,fontWeight:a.messageFontWeight};"C4Dynamic"===r.db.getC4Type()&&(c.label.text=o+": "+c.label.text);var h=xn(c.label.text,u);$n("label",c,l,u,h),c.techn&&""!==c.techn.text&&$n("techn",c,l,u,h=xn(c.techn.text,u)),c.descr&&""!==c.descr.text&&$n("descr",c,l,u,h=xn(c.descr.text,u));var f=n(c.from),d=n(c.to),p=Gn(f,d);c.startPoint=p.startPoint,c.endPoint=p.endPoint;}}catch(t){s.e(t);}finally{s.f();}We(t,e,Pn);}(u,r.db.getRels(),r.db.getC4Shape,r),h.data.stopx=Ln,h.data.stopy=In;var d=h.data,p=d.stopy-d.starty+2*Pn.diagramMarginY,g=d.stopx-d.startx+2*Pn.diagramMarginX;f&&u.append("text").text(f).attr("x",(d.stopx-d.startx)/2-4*Pn.diagramMarginX).attr("y",d.starty+Pn.diagramMarginY),Tn(u,0,g,Pn.useMaxWidth);var y=f?60:0;u.attr("viewBox",d.startx-Pn.diagramMarginX+" -"+(Pn.diagramMarginY+y)+" "+g+" "+(p+y)),Mn(qe.parser.yy,u,e),o.debug("models:",d);}};function Qn(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}var Kn="classid-",Jn=[],tr={},er=0,nr=[],rr=function(t){return ue.sanitizeText(t,Xt())},ir=function(t){var e="",n=t;if(t.indexOf("~")>0){var r=t.split("~");n=r[0],e=ue.sanitizeText(r[1],Xt());}return {className:n,type:e}},ar=function(t){var e=ir(t);void 0===tr[e.className]&&(tr[e.className]={id:e.className,type:e.type,cssClasses:[],methods:[],members:[],annotations:[],domId:Kn+e.className+"-"+er},er++);},or=function(t){for(var e=Object.keys(tr),n=0;n<e.length;n++)if(tr[e[n]].id===t)return tr[e[n]].domId},sr=function(t,e){var n=ir(t).className,r=tr[n];if("string"==typeof e){var i=e.trim();i.startsWith("<<")&&i.endsWith(">>")?r.annotations.push(rr(i.substring(2,i.length-2))):i.indexOf(")")>0?r.methods.push(rr(i)):i&&r.members.push(rr(i));}},cr=function(t,e){t.split(",").forEach((function(t){var n=t;t[0].match(/\d/)&&(n=Kn+n),void 0!==tr[n]&&tr[n].cssClasses.push(e);}));},lr=function(t,e,n){var r=Xt(),i=t,a=or(i);if("loose"===r.securityLevel&&void 0!==e&&void 0!==tr[i]){var o=[];if("string"==typeof n){o=n.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);for(var s=0;s<o.length;s++){var c=o[s].trim();'"'===c.charAt(0)&&'"'===c.charAt(c.length-1)&&(c=c.substr(1,c.length-2)),o[s]=c;}}0===o.length&&o.push(a),nr.push((function(){var t=document.querySelector('[id="'.concat(a,'"]'));null!==t&&t.addEventListener("click",(function(){var t;An.runFunc.apply(An,[e].concat(function(t){if(Array.isArray(t))return Qn(t)}(t=o)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return Qn(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return "Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Qn(t,e):void 0}}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()));}),!1);}));}},ur=function(t){var e=(0, l.select)(".mermaidTooltip");null===(e._groups||e)[0][0]&&(e=(0, l.select)("body").append("div").attr("class","mermaidTooltip").style("opacity",0)),(0, l.select)(t).select("svg").selectAll("g.node").on("mouseover",(function(){var t=(0, l.select)(this);if(null!==t.attr("title")){var n=this.getBoundingClientRect();e.transition().duration(200).style("opacity",".9"),e.text(t.attr("title")).style("left",window.scrollX+n.left+(n.right-n.left)/2+"px").style("top",window.scrollY+n.top-14+document.body.scrollTop+"px"),e.html(e.html().replace(/&lt;br\/&gt;/g,"<br/>")),t.classed("hover",!0);}})).on("mouseout",(function(){e.transition().duration(500).style("opacity",0),(0, l.select)(this).classed("hover",!1);}));};nr.push(ur);var hr="TB";const fr={parseDirective:function(t,e,n){cu.parseDirective(this,t,e,n);},setAccTitle:ye,getAccTitle:me,getAccDescription:ve,setAccDescription:be,getConfig:function(){return Xt().class},addClass:ar,bindFunctions:function(t){nr.forEach((function(e){e(t);}));},clear:function(){Jn=[],tr={},(nr=[]).push(ur),ge();},getClass:function(t){return tr[t]},getClasses:function(){return tr},addAnnotation:function(t,e){var n=ir(t).className;tr[n].annotations.push(e);},getRelations:function(){return Jn},addRelation:function(t){o.debug("Adding relation: "+JSON.stringify(t)),ar(t.id1),ar(t.id2),t.id1=ir(t.id1).className,t.id2=ir(t.id2).className,t.relationTitle1=ue.sanitizeText(t.relationTitle1.trim(),Xt()),t.relationTitle2=ue.sanitizeText(t.relationTitle2.trim(),Xt()),Jn.push(t);},getDirection:function(){return hr},setDirection:function(t){hr=t;},addMember:sr,addMembers:function(t,e){Array.isArray(e)&&(e.reverse(),e.forEach((function(e){return sr(t,e)})));},cleanupLabel:function(t){return ":"===t.substring(0,1)?ue.sanitizeText(t.substr(1).trim(),Xt()):rr(t.trim())},lineType:{LINE:0,DOTTED_LINE:1},relationType:{AGGREGATION:0,EXTENSION:1,COMPOSITION:2,DEPENDENCY:3,LOLLIPOP:4},setClickEvent:function(t,e,n){t.split(",").forEach((function(t){lr(t,e,n),tr[t].haveCallback=!0;})),cr(t,"clickable");},setCssClass:cr,setLink:function(t,e,n){var r=Xt();t.split(",").forEach((function(t){var i=t;t[0].match(/\d/)&&(i=Kn+i),void 0!==tr[i]&&(tr[i].link=An.formatUrl(e,r),"sandbox"===r.securityLevel?tr[i].linkTarget="_top":tr[i].linkTarget="string"==typeof n?rr(n):"_blank");})),cr(t,"clickable");},getTooltip:function(t){return tr[t].tooltip},setTooltip:function(t,e){var n=Xt();t.split(",").forEach((function(t){void 0!==e&&(tr[t].tooltip=ue.sanitizeText(e,n));}));},lookUpDomId:or};var dr=n(681),pr=n.n(dr),gr=n(8282),yr=n.n(gr),mr=0,br=function(t){var e=t.match(/^(\+|-|~|#)?(\w+)(~\w+~|\[\])?\s+(\w+) *(\*|\$)?$/),n=t.match(/^([+|\-|~|#])?(\w+) *\( *(.*)\) *(\*|\$)? *(\w*[~|[\]]*\s*\w*~?)$/);return e&&!n?vr(e):n?_r(n):xr(t)},vr=function(t){var e="",n="";try{var r=t[1]?t[1].trim():"",i=t[2]?t[2].trim():"",a=t[3]?le(t[3].trim()):"",o=t[4]?t[4].trim():"",s=t[5]?t[5].trim():"";n=r+i+a+" "+o,e=wr(s);}catch(e){n=t;}return {displayText:n,cssStyle:e}},_r=function(t){var e="",n="";try{var r=t[1]?t[1].trim():"",i=t[2]?t[2].trim():"",a=t[3]?le(t[3].trim()):"",o=t[4]?t[4].trim():"";n=r+i+"("+a+")"+(t[5]?" : "+le(t[5]).trim():""),e=wr(o);}catch(e){n=t;}return {displayText:n,cssStyle:e}},xr=function(t){var e="",n="",r="",i=t.indexOf("("),a=t.indexOf(")");if(i>1&&a>i&&a<=t.length){var o="",s="",c=t.substring(0,1);c.match(/\w/)?s=t.substring(0,i).trim():(c.match(/\+|-|~|#/)&&(o=c),s=t.substring(1,i).trim());var l=t.substring(i+1,a),u=t.substring(a+1,1);n=wr(u),e=o+s+"("+le(l.trim())+")",a<"".length&&""!==(r=t.substring(a+2).trim())&&(r=" : "+le(r));}else e=le(t);return {displayText:e,cssStyle:n}},kr=function(t,e,n,r){var i=br(e),a=t.append("tspan").attr("x",r.padding).text(i.displayText);""!==i.cssStyle&&a.attr("style",i.cssStyle),n||a.attr("dy",r.textHeight);},wr=function(t){switch(t){case"*":return "font-style:italic;";case"$":return "text-decoration:underline;";default:return ""}};const Tr=function(t,e,n,r){o.debug("Rendering class ",e,n);var i,a=e.id,s={id:a,label:e.id,width:0,height:0},c=t.append("g").attr("id",r.db.lookUpDomId(a)).attr("class","classGroup");i=e.link?c.append("svg:a").attr("xlink:href",e.link).attr("target",e.linkTarget).append("text").attr("y",n.textHeight+n.padding).attr("x",0):c.append("text").attr("y",n.textHeight+n.padding).attr("x",0);var l=!0;e.annotations.forEach((function(t){var e=i.append("tspan").text("«"+t+"»");l||e.attr("dy",n.textHeight),l=!1;}));var u=e.id;void 0!==e.type&&""!==e.type&&(u+="<"+e.type+">");var h=i.append("tspan").text(u).attr("class","title");l||h.attr("dy",n.textHeight);var f=i.node().getBBox().height,d=c.append("line").attr("x1",0).attr("y1",n.padding+f+n.dividerMargin/2).attr("y2",n.padding+f+n.dividerMargin/2),p=c.append("text").attr("x",n.padding).attr("y",f+n.dividerMargin+n.textHeight).attr("fill","white").attr("class","classText");l=!0,e.members.forEach((function(t){kr(p,t,l,n),l=!1;}));var g=p.node().getBBox(),y=c.append("line").attr("x1",0).attr("y1",n.padding+f+n.dividerMargin+g.height).attr("y2",n.padding+f+n.dividerMargin+g.height),m=c.append("text").attr("x",n.padding).attr("y",f+2*n.dividerMargin+g.height+n.textHeight).attr("fill","white").attr("class","classText");l=!0,e.methods.forEach((function(t){kr(m,t,l,n),l=!1;}));var b=c.node().getBBox(),v=" ";e.cssClasses.length>0&&(v+=e.cssClasses.join(" "));var _=c.insert("rect",":first-child").attr("x",0).attr("y",0).attr("width",b.width+2*n.padding).attr("height",b.height+n.padding+.5*n.dividerMargin).attr("class",v).node().getBBox().width;return i.node().childNodes.forEach((function(t){t.setAttribute("x",(_-t.getBBox().width)/2);})),e.tooltip&&i.insert("title").text(e.tooltip),d.attr("x2",_),y.attr("x2",_),s.width=_,s.height=b.height+n.padding+.5*n.dividerMargin,s};var Er={},Cr=function(t){var e=Object.entries(Er).find((function(e){return e[1].label===t}));if(e)return e[0]};const Sr={draw:function(t,e,n,r){var i=Xt().class;Er={},o.info("Rendering diagram "+t);var a,s=Xt().securityLevel;"sandbox"===s&&(a=(0, l.select)("#i"+e));var c,u="sandbox"===s?(0, l.select)(a.nodes()[0].contentDocument.body):(0, l.select)("body"),h=("sandbox"===s?a.nodes()[0].contentDocument:document,u.select("[id='".concat(e,"']")));(c=h).append("defs").append("marker").attr("id","extensionStart").attr("class","extension").attr("refX",0).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 1,7 L18,13 V 1 Z"),c.append("defs").append("marker").attr("id","extensionEnd").attr("refX",19).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 1,1 V 13 L18,7 Z"),c.append("defs").append("marker").attr("id","compositionStart").attr("class","extension").attr("refX",0).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z"),c.append("defs").append("marker").attr("id","compositionEnd").attr("refX",19).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z"),c.append("defs").append("marker").attr("id","aggregationStart").attr("class","extension").attr("refX",0).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z"),c.append("defs").append("marker").attr("id","aggregationEnd").attr("refX",19).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z"),c.append("defs").append("marker").attr("id","dependencyStart").attr("class","extension").attr("refX",0).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 5,7 L9,13 L1,7 L9,1 Z"),c.append("defs").append("marker").attr("id","dependencyEnd").attr("refX",19).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L14,7 L9,1 Z");var f=new(yr().Graph)({multigraph:!0});f.setGraph({isMultiGraph:!0}),f.setDefaultEdgeLabel((function(){return {}}));for(var d=r.db.getClasses(),p=Object.keys(d),g=0;g<p.length;g++){var y=d[p[g]],m=Tr(h,y,i,r);Er[m.id]=m,f.setNode(m.id,m),o.info("Org height: "+m.height);}r.db.getRelations().forEach((function(t){o.info("tjoho"+Cr(t.id1)+Cr(t.id2)+JSON.stringify(t)),f.setEdge(Cr(t.id1),Cr(t.id2),{relation:t},t.title||"DEFAULT");})),pr().layout(f),f.nodes().forEach((function(t){void 0!==t&&void 0!==f.node(t)&&(o.debug("Node "+t+": "+JSON.stringify(f.node(t))),u.select("#"+r.db.lookUpDomId(t)).attr("transform","translate("+(f.node(t).x-f.node(t).width/2)+","+(f.node(t).y-f.node(t).height/2)+" )"));})),f.edges().forEach((function(t){void 0!==t&&void 0!==f.edge(t)&&(o.debug("Edge "+t.v+" -> "+t.w+": "+JSON.stringify(f.edge(t))),function(t,e,n,r,i){var a=function(t){switch(t){case i.db.relationType.AGGREGATION:return "aggregation";case i.db.EXTENSION:return "extension";case i.db.COMPOSITION:return "composition";case i.db.DEPENDENCY:return "dependency";case i.db.LOLLIPOP:return "lollipop"}};e.points=e.points.filter((function(t){return !Number.isNaN(t.y)}));var s,c,u=e.points,h=(0, l.line)().x((function(t){return t.x})).y((function(t){return t.y})).curve(l.curveBasis),f=t.append("path").attr("d",h(u)).attr("id","edge"+mr).attr("class","relation"),d="";r.arrowMarkerAbsolute&&(d=(d=(d=window.location.protocol+"//"+window.location.host+window.location.pathname+window.location.search).replace(/\(/g,"\\(")).replace(/\)/g,"\\)")),1==n.relation.lineType&&f.attr("class","relation dashed-line"),"none"!==n.relation.type1&&f.attr("marker-start","url("+d+"#"+a(n.relation.type1)+"Start)"),"none"!==n.relation.type2&&f.attr("marker-end","url("+d+"#"+a(n.relation.type2)+"End)");var p,g,y,m,b=e.points.length,v=An.calcLabelPosition(e.points);if(s=v.x,c=v.y,b%2!=0&&b>1){var _=An.calcCardinalityPosition("none"!==n.relation.type1,e.points,e.points[0]),x=An.calcCardinalityPosition("none"!==n.relation.type2,e.points,e.points[b-1]);o.debug("cardinality_1_point "+JSON.stringify(_)),o.debug("cardinality_2_point "+JSON.stringify(x)),p=_.x,g=_.y,y=x.x,m=x.y;}if(void 0!==n.title){var k=t.append("g").attr("class","classLabel"),w=k.append("text").attr("class","label").attr("x",s).attr("y",c).attr("fill","red").attr("text-anchor","middle").text(n.title);window.label=w;var T=w.node().getBBox();k.insert("rect",":first-child").attr("class","box").attr("x",T.x-r.padding/2).attr("y",T.y-r.padding/2).attr("width",T.width+r.padding).attr("height",T.height+r.padding);}o.info("Rendering relation "+JSON.stringify(n)),void 0!==n.relationTitle1&&"none"!==n.relationTitle1&&t.append("g").attr("class","cardinality").append("text").attr("class","type1").attr("x",p).attr("y",g).attr("fill","black").attr("font-size","6").text(n.relationTitle1),void 0!==n.relationTitle2&&"none"!==n.relationTitle2&&t.append("g").attr("class","cardinality").append("text").attr("class","type2").attr("x",y).attr("y",m).attr("fill","black").attr("font-size","6").text(n.relationTitle2),mr++;}(h,f.edge(t),f.edge(t).relation,i,r));}));var b=h.node().getBBox(),v=b.width+40,_=b.height+40;Tn(h,0,v,i.useMaxWidth);var x="".concat(b.x-20," ").concat(b.y-20," ").concat(v," ").concat(_);o.debug("viewBox ".concat(x)),h.attr("viewBox",x),Mn(r.db,h,e);}};var Ar={extension:function(t,e,n){o.trace("Making markers for ",n),t.append("defs").append("marker").attr("id",e+"-extensionStart").attr("class","marker extension "+e).attr("refX",0).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 1,7 L18,13 V 1 Z"),t.append("defs").append("marker").attr("id",e+"-extensionEnd").attr("class","marker extension "+e).attr("refX",19).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 1,1 V 13 L18,7 Z");},composition:function(t,e){t.append("defs").append("marker").attr("id",e+"-compositionStart").attr("class","marker composition "+e).attr("refX",0).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z"),t.append("defs").append("marker").attr("id",e+"-compositionEnd").attr("class","marker composition "+e).attr("refX",19).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z");},aggregation:function(t,e){t.append("defs").append("marker").attr("id",e+"-aggregationStart").attr("class","marker aggregation "+e).attr("refX",0).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z"),t.append("defs").append("marker").attr("id",e+"-aggregationEnd").attr("class","marker aggregation "+e).attr("refX",19).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z");},dependency:function(t,e){t.append("defs").append("marker").attr("id",e+"-dependencyStart").attr("class","marker dependency "+e).attr("refX",0).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 5,7 L9,13 L1,7 L9,1 Z"),t.append("defs").append("marker").attr("id",e+"-dependencyEnd").attr("class","marker dependency "+e).attr("refX",19).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L14,7 L9,1 Z");},lollipop:function(t,e,n){t.append("defs").append("marker").attr("id",e+"-lollipopStart").attr("class","marker lollipop "+e).attr("refX",0).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("circle").attr("stroke","black").attr("fill","white").attr("cx",6).attr("cy",7).attr("r",6);},point:function(t,e){t.append("marker").attr("id",e+"-pointEnd").attr("class","marker "+e).attr("viewBox","0 0 10 10").attr("refX",9).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",12).attr("markerHeight",12).attr("orient","auto").append("path").attr("d","M 0 0 L 10 5 L 0 10 z").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0"),t.append("marker").attr("id",e+"-pointStart").attr("class","marker "+e).attr("viewBox","0 0 10 10").attr("refX",0).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",12).attr("markerHeight",12).attr("orient","auto").append("path").attr("d","M 0 5 L 10 10 L 10 0 z").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0");},circle:function(t,e){t.append("marker").attr("id",e+"-circleEnd").attr("class","marker "+e).attr("viewBox","0 0 10 10").attr("refX",11).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("circle").attr("cx","5").attr("cy","5").attr("r","5").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0"),t.append("marker").attr("id",e+"-circleStart").attr("class","marker "+e).attr("viewBox","0 0 10 10").attr("refX",-1).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("circle").attr("cx","5").attr("cy","5").attr("r","5").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0");},cross:function(t,e){t.append("marker").attr("id",e+"-crossEnd").attr("class","marker cross "+e).attr("viewBox","0 0 11 11").attr("refX",12).attr("refY",5.2).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("path").attr("d","M 1,1 l 9,9 M 10,1 l -9,9").attr("class","arrowMarkerPath").style("stroke-width",2).style("stroke-dasharray","1,0"),t.append("marker").attr("id",e+"-crossStart").attr("class","marker cross "+e).attr("viewBox","0 0 11 11").attr("refX",-1).attr("refY",5.2).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("path").attr("d","M 1,1 l 9,9 M 10,1 l -9,9").attr("class","arrowMarkerPath").style("stroke-width",2).style("stroke-dasharray","1,0");},barb:function(t,e){t.append("defs").append("marker").attr("id",e+"-barbEnd").attr("refX",19).attr("refY",7).attr("markerWidth",20).attr("markerHeight",14).attr("markerUnits","strokeWidth").attr("orient","auto").append("path").attr("d","M 19,7 L9,13 L14,7 L9,1 Z");}};const Mr=function(t,e,n,r){e.forEach((function(e){Ar[e](t,n,r);}));};function Nr(t){return Nr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Nr(t)}const Or=function(t,e,n,r){var i=t||"";if("object"===Nr(i)&&(i=i[0]),ce(Xt().flowchart.htmlLabels)){i=i.replace(/\\n|\n/g,"<br />"),o.info("vertexText"+i);var a=function(t){var e,n=(0, l.select)(document.createElementNS("http://www.w3.org/2000/svg","foreignObject")),r=n.append("xhtml:div"),i=t.label,a=t.isNode?"nodeLabel":"edgeLabel";return r.html('<span class="'+a+'" '+(t.labelStyle?'style="'+t.labelStyle+'"':"")+">"+i+"</span>"),(e=t.labelStyle)&&r.attr("style",e),r.style("display","inline-block"),r.style("white-space","nowrap"),r.attr("xmlns","http://www.w3.org/1999/xhtml"),n.node()}({isNode:r,label:iu(i).replace(/fa[lrsb]?:fa-[\w-]+/g,(function(t){return "<i class='".concat(t.replace(":"," "),"'></i>")})),labelStyle:e.replace("fill:","color:")});return a}var s=document.createElementNS("http://www.w3.org/2000/svg","text");s.setAttribute("style",e.replace("color:","fill:"));var c=[];c="string"==typeof i?i.split(/\\n|\n|<br\s*\/?>/gi):Array.isArray(i)?i:[];for(var u=0;u<c.length;u++){var h=document.createElementNS("http://www.w3.org/2000/svg","tspan");h.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve"),h.setAttribute("dy","1em"),h.setAttribute("x","0"),n?h.setAttribute("class","title-row"):h.setAttribute("class","row"),h.textContent=c[u].trim(),s.appendChild(h);}return s};var Dr=function(t,e,n,r){var i;i=n||"node default";var a=t.insert("g").attr("class",i).attr("id",e.domId||e.id),o=a.insert("g").attr("class","label").attr("style",e.labelStyle),s="string"==typeof e.labelText?e.labelText:e.labelText[0],c=o.node().appendChild(Or(ie(iu(s),Xt()),e.labelStyle,!1,r)),u=c.getBBox();if(ce(Xt().flowchart.htmlLabels)){var h=c.children[0],f=(0, l.select)(c);u=h.getBoundingClientRect(),f.attr("width",u.width),f.attr("height",u.height);}var d=e.padding/2;return o.attr("transform","translate("+-u.width/2+", "+-u.height/2+")"),{shapeSvg:a,bbox:u,halfPadding:d,label:o}},Br=function(t,e){var n=e.node().getBBox();t.width=n.width,t.height=n.height;};function Lr(t,e,n,r){return t.insert("polygon",":first-child").attr("points",r.map((function(t){return t.x+","+t.y})).join(" ")).attr("class","label-container").attr("transform","translate("+-e/2+","+n/2+")")}var Ir={},Fr={},Rr={},Pr=function(t,e){return o.trace("In isDecendant",e," ",t," = ",Fr[e].indexOf(t)>=0),Fr[e].indexOf(t)>=0},jr=function t(e,n,r,i){o.warn("Copying children of ",e,"root",i,"data",n.node(e),i);var a=n.children(e)||[];e!==i&&a.push(e),o.warn("Copying (nodes) clusterId",e,"nodes",a),a.forEach((function(a){if(n.children(a).length>0)t(a,n,r,i);else {var s=n.node(a);o.info("cp ",a," to ",i," with parent ",e),r.setNode(a,s),i!==n.parent(a)&&(o.warn("Setting parent",a,n.parent(a)),r.setParent(a,n.parent(a))),e!==i&&a!==e?(o.debug("Setting parent",a,e),r.setParent(a,e)):(o.info("In copy ",e,"root",i,"data",n.node(e),i),o.debug("Not Setting parent for node=",a,"cluster!==rootId",e!==i,"node!==clusterId",a!==e));var c=n.edges(a);o.debug("Copying Edges",c),c.forEach((function(t){o.info("Edge",t);var a=n.edge(t.v,t.w,t.name);o.info("Edge data",a,i);try{!function(t,e){return o.info("Decendants of ",e," is ",Fr[e]),o.info("Edge is ",t),t.v!==e&&t.w!==e&&(Fr[e]?(o.info("Here "),Fr[e].indexOf(t.v)>=0||!!Pr(t.v,e)||!!Pr(t.w,e)||Fr[e].indexOf(t.w)>=0):(o.debug("Tilt, ",e,",not in decendants"),!1))}(t,i)?o.info("Skipping copy of edge ",t.v,"--\x3e",t.w," rootId: ",i," clusterId:",e):(o.info("Copying as ",t.v,t.w,a,t.name),r.setEdge(t.v,t.w,a,t.name),o.info("newGraph edges ",r.edges(),r.edge(r.edges()[0])));}catch(t){o.error(t);}}));}o.debug("Removing node",a),n.removeNode(a);}));},zr=function t(e,n){for(var r=n.children(e),i=[].concat(r),a=0;a<r.length;a++)Rr[r[a]]=e,i=i.concat(t(r[a],n));return i},Yr=function t(e,n){o.trace("Searching",e);var r=n.children(e);if(o.trace("Searching children of id ",e,r),r.length<1)return o.trace("This is a valid node",e),e;for(var i=0;i<r.length;i++){var a=t(r[i],n);if(a)return o.trace("Found replacement for",e," => ",a),a}},Ur=function(t){return Ir[t]&&Ir[t].externalConnections&&Ir[t]?Ir[t].id:t},$r=function(t,e){!t||e>10?o.debug("Opting out, no graph "):(o.debug("Opting in, graph "),t.nodes().forEach((function(e){t.children(e).length>0&&(o.warn("Cluster identified",e," Replacement id in edges: ",Yr(e,t)),Fr[e]=zr(e,t),Ir[e]={id:Yr(e,t),clusterData:t.node(e)});})),t.nodes().forEach((function(e){var n=t.children(e),r=t.edges();n.length>0?(o.debug("Cluster identified",e,Fr),r.forEach((function(t){t.v!==e&&t.w!==e&&Pr(t.v,e)^Pr(t.w,e)&&(o.warn("Edge: ",t," leaves cluster ",e),o.warn("Decendants of XXX ",e,": ",Fr[e]),Ir[e].externalConnections=!0);}))):o.debug("Not a cluster ",e,Fr);})),t.edges().forEach((function(e){var n=t.edge(e);o.warn("Edge "+e.v+" -> "+e.w+": "+JSON.stringify(e)),o.warn("Edge "+e.v+" -> "+e.w+": "+JSON.stringify(t.edge(e)));var r=e.v,i=e.w;if(o.warn("Fix XXX",Ir,"ids:",e.v,e.w,"Translateing: ",Ir[e.v]," --- ",Ir[e.w]),Ir[e.v]&&Ir[e.w]&&Ir[e.v]===Ir[e.w]){o.warn("Fixing and trixing link to self - removing XXX",e.v,e.w,e.name),o.warn("Fixing and trixing - removing XXX",e.v,e.w,e.name),r=Ur(e.v),i=Ur(e.w),t.removeEdge(e.v,e.w,e.name);var a=e.w+"---"+e.v;t.setNode(a,{domId:a,id:a,labelStyle:"",labelText:n.label,padding:0,shape:"labelRect",style:""});var s=JSON.parse(JSON.stringify(n)),c=JSON.parse(JSON.stringify(n));s.label="",s.arrowTypeEnd="none",c.label="",s.fromCluster=e.v,c.toCluster=e.v,t.setEdge(r,a,s,e.name+"-cyclic-special"),t.setEdge(a,i,c,e.name+"-cyclic-special");}else (Ir[e.v]||Ir[e.w])&&(o.warn("Fixing and trixing - removing XXX",e.v,e.w,e.name),r=Ur(e.v),i=Ur(e.w),t.removeEdge(e.v,e.w,e.name),r!==e.v&&(n.fromCluster=e.v),i!==e.w&&(n.toCluster=e.w),o.warn("Fix Replacing with XXX",r,i,e.name),t.setEdge(r,i,n,e.name));})),o.warn("Adjusted Graph",yr().json.write(t)),Wr(t,0),o.trace(Ir));},Wr=function t(e,n){if(o.warn("extractor - ",n,yr().json.write(e),e.children("D")),n>10)o.error("Bailing out");else {for(var r=e.nodes(),i=!1,a=0;a<r.length;a++){var s=r[a],c=e.children(s);i=i||c.length>0;}if(i){o.debug("Nodes = ",r,n);for(var l=0;l<r.length;l++){var u=r[l];if(o.debug("Extracting node",u,Ir,Ir[u]&&!Ir[u].externalConnections,!e.parent(u),e.node(u),e.children("D")," Depth ",n),Ir[u])if(!Ir[u].externalConnections&&e.children(u)&&e.children(u).length>0){o.warn("Cluster without external connections, without a parent and with children",u,n);var h="TB"===e.graph().rankdir?"LR":"TB";Ir[u]&&Ir[u].clusterData&&Ir[u].clusterData.dir&&(h=Ir[u].clusterData.dir,o.warn("Fixing dir",Ir[u].clusterData.dir,h));var f=new(yr().Graph)({multigraph:!0,compound:!0}).setGraph({rankdir:h,nodesep:50,ranksep:50,marginx:8,marginy:8}).setDefaultEdgeLabel((function(){return {}}));o.warn("Old graph before copy",yr().json.write(e)),jr(u,e,f,u),e.setNode(u,{clusterNode:!0,id:u,clusterData:Ir[u].clusterData,labelText:Ir[u].labelText,graph:f}),o.warn("New graph after copy node: (",u,")",yr().json.write(f)),o.debug("Old graph after copy",yr().json.write(e));}else o.warn("Cluster ** ",u," **not meeting the criteria !externalConnections:",!Ir[u].externalConnections," no parent: ",!e.parent(u)," children ",e.children(u)&&e.children(u).length>0,e.children("D"),n),o.debug(Ir);else o.debug("Not a cluster",u,n);}r=e.nodes(),o.warn("New list of nodes",r);for(var d=0;d<r.length;d++){var p=r[d],g=e.node(p);o.warn(" Now next level",p,g),g.clusterNode&&t(g.graph,n+1);}}else o.debug("Done, no node has children",e.nodes());}},qr=function t(e,n){if(0===n.length)return [];var r=Object.assign(n);return n.forEach((function(n){var i=e.children(n),a=t(e,i);r=r.concat(a);})),r},Hr=function(t){return qr(t,t.children())},Vr=n(3841);const Gr=function(t,e,n,r){var i=t.x,a=t.y,o=i-r.x,s=a-r.y,c=Math.sqrt(e*e*s*s+n*n*o*o),l=Math.abs(e*n*o/c);r.x<i&&(l=-l);var u=Math.abs(e*n*s/c);return r.y<a&&(u=-u),{x:i+l,y:a+u}};function Xr(t,e){return t*e>0}const Zr=function(t,e,n,r){var i,a,o,s,c,l,u,h,f,d,p,g,y;if(i=e.y-t.y,o=t.x-e.x,c=e.x*t.y-t.x*e.y,f=i*n.x+o*n.y+c,d=i*r.x+o*r.y+c,!(0!==f&&0!==d&&Xr(f,d)||(a=r.y-n.y,s=n.x-r.x,l=r.x*n.y-n.x*r.y,u=a*t.x+s*t.y+l,h=a*e.x+s*e.y+l,0!==u&&0!==h&&Xr(u,h)||0==(p=i*s-a*o))))return g=Math.abs(p/2),{x:(y=o*l-s*c)<0?(y-g)/p:(y+g)/p,y:(y=a*c-i*l)<0?(y-g)/p:(y+g)/p}},Qr=function(t,e){var n,r,i=t.x,a=t.y,o=e.x-i,s=e.y-a,c=t.width/2,l=t.height/2;return Math.abs(s)*c>Math.abs(o)*l?(s<0&&(l=-l),n=0===s?0:l*o/s,r=l):(o<0&&(c=-c),n=c,r=0===o?0:c*s/o),{x:i+n,y:a+r}},Kr=(n.n(Vr)(),function(t,e,n){return Gr(t,e,e,n)}),Jr=function(t,e,n){var r=t.x,i=t.y,a=[],o=Number.POSITIVE_INFINITY,s=Number.POSITIVE_INFINITY;"function"==typeof e.forEach?e.forEach((function(t){o=Math.min(o,t.x),s=Math.min(s,t.y);})):(o=Math.min(o,e.x),s=Math.min(s,e.y));for(var c=r-t.width/2-o,l=i-t.height/2-s,u=0;u<e.length;u++){var h=e[u],f=e[u<e.length-1?u+1:0],d=Zr(t,n,{x:c+h.x,y:l+h.y},{x:c+f.x,y:l+f.y});d&&a.push(d);}return a.length?(a.length>1&&a.sort((function(t,e){var r=t.x-n.x,i=t.y-n.y,a=Math.sqrt(r*r+i*i),o=e.x-n.x,s=e.y-n.y,c=Math.sqrt(o*o+s*s);return a<c?-1:a===c?0:1})),a[0]):t},ti=Qr;function ei(t){return ei="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ei(t)}function ni(t,e,n,r){var i=[],a=function(t){i.push(t),i.push(0);},s=function(t){i.push(0),i.push(t);};e.includes("t")?(o.debug("add top border"),a(n)):s(n),e.includes("r")?(o.debug("add right border"),a(r)):s(r),e.includes("b")?(o.debug("add bottom border"),a(n)):s(n),e.includes("l")?(o.debug("add left border"),a(r)):s(r),t.attr("stroke-dasharray",i.join(" "));}var ri=function(t,e,n){var r=t.insert("g").attr("class","node default").attr("id",e.domId||e.id),i=70,a=10;"LR"===n&&(i=10,a=70);var o=r.append("rect").attr("x",-1*i/2).attr("y",-1*a/2).attr("width",i).attr("height",a).attr("class","fork-join");return Br(e,o),e.height=e.height+e.padding/2,e.width=e.width+e.padding/2,e.intersect=function(t){return ti(e,t)},r},ii={question:function(t,e){var n=Dr(t,e,void 0,!0),r=n.shapeSvg,i=n.bbox,a=i.width+e.padding+(i.height+e.padding),s=[{x:a/2,y:0},{x:a,y:-a/2},{x:a/2,y:-a},{x:0,y:-a/2}];o.info("Question main (Circle)");var c=Lr(r,a,a,s);return c.attr("style",e.style),Br(e,c),e.intersect=function(t){return o.warn("Intersect called"),Jr(e,s,t)},r},rect:function(t,e){var n=Dr(t,e,"node "+e.classes,!0),r=n.shapeSvg,i=n.bbox,a=n.halfPadding;o.trace("Classes = ",e.classes);var s=r.insert("rect",":first-child"),c=i.width+e.padding,l=i.height+e.padding;if(s.attr("class","basic label-container").attr("style",e.style).attr("rx",e.rx).attr("ry",e.ry).attr("x",-i.width/2-a).attr("y",-i.height/2-a).attr("width",c).attr("height",l),e.props){var u=new Set(Object.keys(e.props));e.props.borders&&(ni(s,e.props.borders,c,l),u.delete("borders")),u.forEach((function(t){o.warn("Unknown node property ".concat(t));}));}return Br(e,s),e.intersect=function(t){return ti(e,t)},r},labelRect:function(t,e){var n=Dr(t,e,"label",!0),r=n.shapeSvg;o.trace("Classes = ",e.classes);var i=r.insert("rect",":first-child");if(i.attr("width",0).attr("height",0),r.attr("class","label edgeLabel"),e.props){var a=new Set(Object.keys(e.props));e.props.borders&&(ni(i,e.props.borders,0,0),a.delete("borders")),a.forEach((function(t){o.warn("Unknown node property ".concat(t));}));}return Br(e,i),e.intersect=function(t){return ti(e,t)},r},rectWithTitle:function(t,e){var n;n=e.classes?"node "+e.classes:"node default";var r,i=t.insert("g").attr("class",n).attr("id",e.domId||e.id),a=i.insert("rect",":first-child"),s=i.insert("line"),c=i.insert("g").attr("class","label"),u=e.labelText.flat?e.labelText.flat():e.labelText;r="object"===ei(u)?u[0]:u,o.info("Label text abc79",r,u,"object"===ei(u));var h=c.node().appendChild(Or(r,e.labelStyle,!0,!0)),f={width:0,height:0};if(ce(Xt().flowchart.htmlLabels)){var d=h.children[0],p=(0, l.select)(h);f=d.getBoundingClientRect(),p.attr("width",f.width),p.attr("height",f.height);}o.info("Text 2",u);var g=u.slice(1,u.length),y=h.getBBox(),m=c.node().appendChild(Or(g.join?g.join("<br/>"):g,e.labelStyle,!0,!0));if(ce(Xt().flowchart.htmlLabels)){var b=m.children[0],v=(0, l.select)(m);f=b.getBoundingClientRect(),v.attr("width",f.width),v.attr("height",f.height);}var _=e.padding/2;return (0, l.select)(m).attr("transform","translate( "+(f.width>y.width?0:(y.width-f.width)/2)+", "+(y.height+_+5)+")"),(0, l.select)(h).attr("transform","translate( "+(f.width<y.width?0:-(y.width-f.width)/2)+", 0)"),f=c.node().getBBox(),c.attr("transform","translate("+-f.width/2+", "+(-f.height/2-_+3)+")"),a.attr("class","outer title-state").attr("x",-f.width/2-_).attr("y",-f.height/2-_).attr("width",f.width+e.padding).attr("height",f.height+e.padding),s.attr("class","divider").attr("x1",-f.width/2-_).attr("x2",f.width/2+_).attr("y1",-f.height/2-_+y.height+_).attr("y2",-f.height/2-_+y.height+_),Br(e,a),e.intersect=function(t){return ti(e,t)},i},choice:function(t,e){var n=t.insert("g").attr("class","node default").attr("id",e.domId||e.id);return n.insert("polygon",":first-child").attr("points",[{x:0,y:14},{x:14,y:0},{x:0,y:-14},{x:-14,y:0}].map((function(t){return t.x+","+t.y})).join(" ")).attr("class","state-start").attr("r",7).attr("width",28).attr("height",28),e.width=28,e.height=28,e.intersect=function(t){return Kr(e,14,t)},n},circle:function(t,e){var n=Dr(t,e,void 0,!0),r=n.shapeSvg,i=n.bbox,a=n.halfPadding,s=r.insert("circle",":first-child");return s.attr("style",e.style).attr("rx",e.rx).attr("ry",e.ry).attr("r",i.width/2+a).attr("width",i.width+e.padding).attr("height",i.height+e.padding),o.info("Circle main"),Br(e,s),e.intersect=function(t){return o.info("Circle intersect",e,i.width/2+a,t),Kr(e,i.width/2+a,t)},r},doublecircle:function(t,e){var n=Dr(t,e,void 0,!0),r=n.shapeSvg,i=n.bbox,a=n.halfPadding,s=r.insert("g",":first-child"),c=s.insert("circle"),l=s.insert("circle");return c.attr("style",e.style).attr("rx",e.rx).attr("ry",e.ry).attr("r",i.width/2+a+5).attr("width",i.width+e.padding+10).attr("height",i.height+e.padding+10),l.attr("style",e.style).attr("rx",e.rx).attr("ry",e.ry).attr("r",i.width/2+a).attr("width",i.width+e.padding).attr("height",i.height+e.padding),o.info("DoubleCircle main"),Br(e,c),e.intersect=function(t){return o.info("DoubleCircle intersect",e,i.width/2+a+5,t),Kr(e,i.width/2+a+5,t)},r},stadium:function(t,e){var n=Dr(t,e,void 0,!0),r=n.shapeSvg,i=n.bbox,a=i.height+e.padding,o=i.width+a/4+e.padding,s=r.insert("rect",":first-child").attr("style",e.style).attr("rx",a/2).attr("ry",a/2).attr("x",-o/2).attr("y",-a/2).attr("width",o).attr("height",a);return Br(e,s),e.intersect=function(t){return ti(e,t)},r},hexagon:function(t,e){var n=Dr(t,e,void 0,!0),r=n.shapeSvg,i=n.bbox,a=i.height+e.padding,o=a/4,s=i.width+2*o+e.padding,c=[{x:o,y:0},{x:s-o,y:0},{x:s,y:-a/2},{x:s-o,y:-a},{x:o,y:-a},{x:0,y:-a/2}],l=Lr(r,s,a,c);return l.attr("style",e.style),Br(e,l),e.intersect=function(t){return Jr(e,c,t)},r},rect_left_inv_arrow:function(t,e){var n=Dr(t,e,void 0,!0),r=n.shapeSvg,i=n.bbox,a=i.width+e.padding,o=i.height+e.padding,s=[{x:-o/2,y:0},{x:a,y:0},{x:a,y:-o},{x:-o/2,y:-o},{x:0,y:-o/2}];return Lr(r,a,o,s).attr("style",e.style),e.width=a+o,e.height=o,e.intersect=function(t){return Jr(e,s,t)},r},lean_right:function(t,e){var n=Dr(t,e,void 0,!0),r=n.shapeSvg,i=n.bbox,a=i.width+e.padding,o=i.height+e.padding,s=[{x:-2*o/6,y:0},{x:a-o/6,y:0},{x:a+2*o/6,y:-o},{x:o/6,y:-o}],c=Lr(r,a,o,s);return c.attr("style",e.style),Br(e,c),e.intersect=function(t){return Jr(e,s,t)},r},lean_left:function(t,e){var n=Dr(t,e,void 0,!0),r=n.shapeSvg,i=n.bbox,a=i.width+e.padding,o=i.height+e.padding,s=[{x:2*o/6,y:0},{x:a+o/6,y:0},{x:a-2*o/6,y:-o},{x:-o/6,y:-o}],c=Lr(r,a,o,s);return c.attr("style",e.style),Br(e,c),e.intersect=function(t){return Jr(e,s,t)},r},trapezoid:function(t,e){var n=Dr(t,e,void 0,!0),r=n.shapeSvg,i=n.bbox,a=i.width+e.padding,o=i.height+e.padding,s=[{x:-2*o/6,y:0},{x:a+2*o/6,y:0},{x:a-o/6,y:-o},{x:o/6,y:-o}],c=Lr(r,a,o,s);return c.attr("style",e.style),Br(e,c),e.intersect=function(t){return Jr(e,s,t)},r},inv_trapezoid:function(t,e){var n=Dr(t,e,void 0,!0),r=n.shapeSvg,i=n.bbox,a=i.width+e.padding,o=i.height+e.padding,s=[{x:o/6,y:0},{x:a-o/6,y:0},{x:a+2*o/6,y:-o},{x:-2*o/6,y:-o}],c=Lr(r,a,o,s);return c.attr("style",e.style),Br(e,c),e.intersect=function(t){return Jr(e,s,t)},r},rect_right_inv_arrow:function(t,e){var n=Dr(t,e,void 0,!0),r=n.shapeSvg,i=n.bbox,a=i.width+e.padding,o=i.height+e.padding,s=[{x:0,y:0},{x:a+o/2,y:0},{x:a,y:-o/2},{x:a+o/2,y:-o},{x:0,y:-o}],c=Lr(r,a,o,s);return c.attr("style",e.style),Br(e,c),e.intersect=function(t){return Jr(e,s,t)},r},cylinder:function(t,e){var n=Dr(t,e,void 0,!0),r=n.shapeSvg,i=n.bbox,a=i.width+e.padding,o=a/2,s=o/(2.5+a/50),c=i.height+s+e.padding,l="M 0,"+s+" a "+o+","+s+" 0,0,0 "+a+" 0 a "+o+","+s+" 0,0,0 "+-a+" 0 l 0,"+c+" a "+o+","+s+" 0,0,0 "+a+" 0 l 0,"+-c,u=r.attr("label-offset-y",s).insert("path",":first-child").attr("style",e.style).attr("d",l).attr("transform","translate("+-a/2+","+-(c/2+s)+")");return Br(e,u),e.intersect=function(t){var n=ti(e,t),r=n.x-e.x;if(0!=o&&(Math.abs(r)<e.width/2||Math.abs(r)==e.width/2&&Math.abs(n.y-e.y)>e.height/2-s)){var i=s*s*(1-r*r/(o*o));0!=i&&(i=Math.sqrt(i)),i=s-i,t.y-e.y>0&&(i=-i),n.y+=i;}return n},r},start:function(t,e){var n=t.insert("g").attr("class","node default").attr("id",e.domId||e.id),r=n.insert("circle",":first-child");return r.attr("class","state-start").attr("r",7).attr("width",14).attr("height",14),Br(e,r),e.intersect=function(t){return Kr(e,7,t)},n},end:function(t,e){var n=t.insert("g").attr("class","node default").attr("id",e.domId||e.id),r=n.insert("circle",":first-child"),i=n.insert("circle",":first-child");return i.attr("class","state-start").attr("r",7).attr("width",14).attr("height",14),r.attr("class","state-end").attr("r",5).attr("width",10).attr("height",10),Br(e,i),e.intersect=function(t){return Kr(e,7,t)},n},note:function(t,e){var n=Dr(t,e,"node "+e.classes,!0),r=n.shapeSvg,i=n.bbox,a=n.halfPadding;o.info("Classes = ",e.classes);var s=r.insert("rect",":first-child");return s.attr("rx",e.rx).attr("ry",e.ry).attr("x",-i.width/2-a).attr("y",-i.height/2-a).attr("width",i.width+e.padding).attr("height",i.height+e.padding),Br(e,s),e.intersect=function(t){return ti(e,t)},r},subroutine:function(t,e){var n=Dr(t,e,void 0,!0),r=n.shapeSvg,i=n.bbox,a=i.width+e.padding,o=i.height+e.padding,s=[{x:0,y:0},{x:a,y:0},{x:a,y:-o},{x:0,y:-o},{x:0,y:0},{x:-8,y:0},{x:a+8,y:0},{x:a+8,y:-o},{x:-8,y:-o},{x:-8,y:0}],c=Lr(r,a,o,s);return c.attr("style",e.style),Br(e,c),e.intersect=function(t){return Jr(e,s,t)},r},fork:ri,join:ri,class_box:function(t,e){var n,r=e.padding/2;n=e.classes?"node "+e.classes:"node default";var i=t.insert("g").attr("class",n).attr("id",e.domId||e.id),a=i.insert("rect",":first-child"),o=i.insert("line"),s=i.insert("line"),c=0,u=4,h=i.insert("g").attr("class","label"),f=0,d=e.classData.annotations&&e.classData.annotations[0],p=e.classData.annotations[0]?"«"+e.classData.annotations[0]+"»":"",g=h.node().appendChild(Or(p,e.labelStyle,!0,!0)),y=g.getBBox();if(ce(Xt().flowchart.htmlLabels)){var m=g.children[0],b=(0, l.select)(g);y=m.getBoundingClientRect(),b.attr("width",y.width),b.attr("height",y.height);}e.classData.annotations[0]&&(u+=y.height+4,c+=y.width);var v=e.classData.id;void 0!==e.classData.type&&""!==e.classData.type&&(Xt().flowchart.htmlLabels?v+="&lt;"+e.classData.type+"&gt;":v+="<"+e.classData.type+">");var _=h.node().appendChild(Or(v,e.labelStyle,!0,!0));(0, l.select)(_).attr("class","classTitle");var x=_.getBBox();if(ce(Xt().flowchart.htmlLabels)){var k=_.children[0],w=(0, l.select)(_);x=k.getBoundingClientRect(),w.attr("width",x.width),w.attr("height",x.height);}u+=x.height+4,x.width>c&&(c=x.width);var T=[];e.classData.members.forEach((function(t){var n=br(t),r=n.displayText;Xt().flowchart.htmlLabels&&(r=r.replace(/</g,"&lt;").replace(/>/g,"&gt;"));var i=h.node().appendChild(Or(r,n.cssStyle?n.cssStyle:e.labelStyle,!0,!0)),a=i.getBBox();if(ce(Xt().flowchart.htmlLabels)){var o=i.children[0],s=(0, l.select)(i);a=o.getBoundingClientRect(),s.attr("width",a.width),s.attr("height",a.height);}a.width>c&&(c=a.width),u+=a.height+4,T.push(i);})),u+=8;var E=[];if(e.classData.methods.forEach((function(t){var n=br(t),r=n.displayText;Xt().flowchart.htmlLabels&&(r=r.replace(/</g,"&lt;").replace(/>/g,"&gt;"));var i=h.node().appendChild(Or(r,n.cssStyle?n.cssStyle:e.labelStyle,!0,!0)),a=i.getBBox();if(ce(Xt().flowchart.htmlLabels)){var o=i.children[0],s=(0, l.select)(i);a=o.getBoundingClientRect(),s.attr("width",a.width),s.attr("height",a.height);}a.width>c&&(c=a.width),u+=a.height+4,E.push(i);})),u+=8,d){var C=(c-y.width)/2;(0, l.select)(g).attr("transform","translate( "+(-1*c/2+C)+", "+-1*u/2+")"),f=y.height+4;}var S=(c-x.width)/2;return (0, l.select)(_).attr("transform","translate( "+(-1*c/2+S)+", "+(-1*u/2+f)+")"),f+=x.height+4,o.attr("class","divider").attr("x1",-c/2-r).attr("x2",c/2+r).attr("y1",-u/2-r+8+f).attr("y2",-u/2-r+8+f),f+=8,T.forEach((function(t){(0, l.select)(t).attr("transform","translate( "+-c/2+", "+(-1*u/2+f+4)+")"),f+=x.height+4;})),f+=8,s.attr("class","divider").attr("x1",-c/2-r).attr("x2",c/2+r).attr("y1",-u/2-r+8+f).attr("y2",-u/2-r+8+f),f+=8,E.forEach((function(t){(0, l.select)(t).attr("transform","translate( "+-c/2+", "+(-1*u/2+f)+")"),f+=x.height+4;})),a.attr("class","outer title-state").attr("x",-c/2-r).attr("y",-u/2-r).attr("width",c+e.padding).attr("height",u+e.padding),Br(e,a),e.intersect=function(t){return ti(e,t)},i}},ai={},oi=function(t){var e=ai[t.id];o.trace("Transforming node",t.diff,t,"translate("+(t.x-t.width/2-5)+", "+t.width/2+")");var n=t.diff||0;return t.clusterNode?e.attr("transform","translate("+(t.x+n-t.width/2)+", "+(t.y-t.height/2-8)+")"):e.attr("transform","translate("+t.x+", "+t.y+")"),n},si={rect:function(t,e){o.trace("Creating subgraph rect for ",e.id,e);var n=t.insert("g").attr("class","cluster"+(e.class?" "+e.class:"")).attr("id",e.id),r=n.insert("rect",":first-child"),i=n.insert("g").attr("class","cluster-label"),a=i.node().appendChild(Or(e.labelText,e.labelStyle,void 0,!0)),s=a.getBBox();if(ce(Xt().flowchart.htmlLabels)){var c=a.children[0],u=(0, l.select)(a);s=c.getBoundingClientRect(),u.attr("width",s.width),u.attr("height",s.height);}var h=0*e.padding,f=h/2,d=e.width<=s.width+h?s.width+h:e.width;e.width<=s.width+h?e.diff=(s.width-e.width)/2-e.padding/2:e.diff=-e.padding/2,o.trace("Data ",e,JSON.stringify(e)),r.attr("style",e.style).attr("rx",e.rx).attr("ry",e.ry).attr("x",e.x-d/2).attr("y",e.y-e.height/2-f).attr("width",d).attr("height",e.height+h),i.attr("transform","translate("+(e.x-s.width/2)+", "+(e.y-e.height/2+e.padding/3)+")");var p=r.node().getBBox();return e.width=p.width,e.height=p.height,e.intersect=function(t){return Qr(e,t)},n},roundedWithTitle:function(t,e){var n=t.insert("g").attr("class",e.classes).attr("id",e.id),r=n.insert("rect",":first-child"),i=n.insert("g").attr("class","cluster-label"),a=n.append("rect"),o=i.node().appendChild(Or(e.labelText,e.labelStyle,void 0,!0)),s=o.getBBox();if(ce(Xt().flowchart.htmlLabels)){var c=o.children[0],u=(0, l.select)(o);s=c.getBoundingClientRect(),u.attr("width",s.width),u.attr("height",s.height);}s=o.getBBox();var h=0*e.padding,f=h/2,d=e.width<=s.width+e.padding?s.width+e.padding:e.width;e.width<=s.width+e.padding?e.diff=(s.width+0*e.padding-e.width)/2:e.diff=-e.padding/2,r.attr("class","outer").attr("x",e.x-d/2-f).attr("y",e.y-e.height/2-f).attr("width",d+h).attr("height",e.height+h),a.attr("class","inner").attr("x",e.x-d/2-f).attr("y",e.y-e.height/2-f+s.height-1).attr("width",d+h).attr("height",e.height+h-s.height-3),i.attr("transform","translate("+(e.x-s.width/2)+", "+(e.y-e.height/2-e.padding/3+(ce(Xt().flowchart.htmlLabels)?5:3))+")");var p=r.node().getBBox();return e.height=p.height,e.intersect=function(t){return Qr(e,t)},n},noteGroup:function(t,e){var n=t.insert("g").attr("class","note-cluster").attr("id",e.id),r=n.insert("rect",":first-child"),i=0*e.padding,a=i/2;r.attr("rx",e.rx).attr("ry",e.ry).attr("x",e.x-e.width/2-a).attr("y",e.y-e.height/2-a).attr("width",e.width+i).attr("height",e.height+i).attr("fill","none");var o=r.node().getBBox();return e.width=o.width,e.height=o.height,e.intersect=function(t){return Qr(e,t)},n},divider:function(t,e){var n=t.insert("g").attr("class",e.classes).attr("id",e.id),r=n.insert("rect",":first-child"),i=0*e.padding,a=i/2;r.attr("class","divider").attr("x",e.x-e.width/2-a).attr("y",e.y-e.height/2).attr("width",e.width+i).attr("height",e.height+i);var o=r.node().getBBox();return e.width=o.width,e.height=o.height,e.diff=-e.padding/2,e.intersect=function(t){return Qr(e,t)},n}},ci={},li={},ui={},hi=function(t,e){var n=Or(e.label,e.labelStyle),r=t.insert("g").attr("class","edgeLabel"),i=r.insert("g").attr("class","label");i.node().appendChild(n);var a,o=n.getBBox();if(ce(Xt().flowchart.htmlLabels)){var s=n.children[0],c=(0, l.select)(n);o=s.getBoundingClientRect(),c.attr("width",o.width),c.attr("height",o.height);}if(i.attr("transform","translate("+-o.width/2+", "+-o.height/2+")"),li[e.id]=r,e.width=o.width,e.height=o.height,e.startLabelLeft){var u=Or(e.startLabelLeft,e.labelStyle),h=t.insert("g").attr("class","edgeTerminals"),f=h.insert("g").attr("class","inner");a=f.node().appendChild(u);var d=u.getBBox();f.attr("transform","translate("+-d.width/2+", "+-d.height/2+")"),ui[e.id]||(ui[e.id]={}),ui[e.id].startLeft=h,fi(a,e.startLabelLeft);}if(e.startLabelRight){var p=Or(e.startLabelRight,e.labelStyle),g=t.insert("g").attr("class","edgeTerminals"),y=g.insert("g").attr("class","inner");a=g.node().appendChild(p),y.node().appendChild(p);var m=p.getBBox();y.attr("transform","translate("+-m.width/2+", "+-m.height/2+")"),ui[e.id]||(ui[e.id]={}),ui[e.id].startRight=g,fi(a,e.startLabelRight);}if(e.endLabelLeft){var b=Or(e.endLabelLeft,e.labelStyle),v=t.insert("g").attr("class","edgeTerminals"),_=v.insert("g").attr("class","inner");a=_.node().appendChild(b);var x=b.getBBox();_.attr("transform","translate("+-x.width/2+", "+-x.height/2+")"),v.node().appendChild(b),ui[e.id]||(ui[e.id]={}),ui[e.id].endLeft=v,fi(a,e.endLabelLeft);}if(e.endLabelRight){var k=Or(e.endLabelRight,e.labelStyle),w=t.insert("g").attr("class","edgeTerminals"),T=w.insert("g").attr("class","inner");a=T.node().appendChild(k);var E=k.getBBox();T.attr("transform","translate("+-E.width/2+", "+-E.height/2+")"),w.node().appendChild(k),ui[e.id]||(ui[e.id]={}),ui[e.id].endRight=w,fi(a,e.endLabelRight);}};function fi(t,e){Xt().flowchart.htmlLabels&&t&&(t.style.width=9*e.length+"px",t.style.height="12px");}var di=function(t,e){o.info("Moving label abc78 ",t.id,t.label,li[t.id]);var n=e.updatedPath?e.updatedPath:e.originalPath;if(t.label){var r=li[t.id],i=t.x,a=t.y;if(n){var s=An.calcLabelPosition(n);o.info("Moving label from (",i,",",a,") to (",s.x,",",s.y,") abc78");}r.attr("transform","translate("+i+", "+a+")");}if(t.startLabelLeft){var c=ui[t.id].startLeft,l=t.x,u=t.y;if(n){var h=An.calcTerminalLabelPosition(t.arrowTypeStart?10:0,"start_left",n);l=h.x,u=h.y;}c.attr("transform","translate("+l+", "+u+")");}if(t.startLabelRight){var f=ui[t.id].startRight,d=t.x,p=t.y;if(n){var g=An.calcTerminalLabelPosition(t.arrowTypeStart?10:0,"start_right",n);d=g.x,p=g.y;}f.attr("transform","translate("+d+", "+p+")");}if(t.endLabelLeft){var y=ui[t.id].endLeft,m=t.x,b=t.y;if(n){var v=An.calcTerminalLabelPosition(t.arrowTypeEnd?10:0,"end_left",n);m=v.x,b=v.y;}y.attr("transform","translate("+m+", "+b+")");}if(t.endLabelRight){var _=ui[t.id].endRight,x=t.x,k=t.y;if(n){var w=An.calcTerminalLabelPosition(t.arrowTypeEnd?10:0,"end_right",n);x=w.x,k=w.y;}_.attr("transform","translate("+x+", "+k+")");}},pi=function(t,e){o.warn("abc88 cutPathAtIntersect",t,e);var n=[],r=t[0],i=!1;return t.forEach((function(t){if(o.info("abc88 checking point",t,e),function(t,e){var n=t.x,r=t.y,i=Math.abs(e.x-n),a=Math.abs(e.y-r),o=t.width/2,s=t.height/2;return i>=o||a>=s}(e,t)||i)o.warn("abc88 outside",t,r),r=t,i||n.push(t);else {var a=function(t,e,n){o.warn("intersection calc abc89:\n outsidePoint: ".concat(JSON.stringify(e),"\n insidePoint : ").concat(JSON.stringify(n),"\n node : x:").concat(t.x," y:").concat(t.y," w:").concat(t.width," h:").concat(t.height));var r=t.x,i=t.y,a=Math.abs(r-n.x),s=t.width/2,c=n.x<e.x?s-a:s+a,l=t.height/2,u=Math.abs(e.y-n.y),h=Math.abs(e.x-n.x);if(Math.abs(i-e.y)*s>Math.abs(r-e.x)*l){var f=n.y<e.y?e.y-l-i:i-l-e.y;c=h*f/u;var d={x:n.x<e.x?n.x+c:n.x-h+c,y:n.y<e.y?n.y+u-f:n.y-u+f};return 0===c&&(d.x=e.x,d.y=e.y),0===h&&(d.x=e.x),0===u&&(d.y=e.y),o.warn("abc89 topp/bott calc, Q ".concat(u,", q ").concat(f,", R ").concat(h,", r ").concat(c),d),d}var p=u*(c=n.x<e.x?e.x-s-r:r-s-e.x)/h,g=n.x<e.x?n.x+h-c:n.x-h+c,y=n.y<e.y?n.y+p:n.y-p;return o.warn("sides calc abc89, Q ".concat(u,", q ").concat(p,", R ").concat(h,", r ").concat(c),{_x:g,_y:y}),0===c&&(g=e.x,y=e.y),0===h&&(g=e.x),0===u&&(y=e.y),{x:g,y}}(e,r,t);o.warn("abc88 inside",t,r,a),o.warn("abc88 intersection",a);var s=!1;n.forEach((function(t){s=s||t.x===a.x&&t.y===a.y;})),n.find((function(t){return t.x===a.x&&t.y===a.y}))?o.warn("abc88 no intersect",a,n):n.push(a),i=!0;}})),o.warn("abc88 returning points",n),n},gi=function t(e,n,r,i){o.info("Graph in recursive render: XXX",yr().json.write(n),i);var a=n.graph().rankdir;o.trace("Dir in recursive render - dir:",a);var s=e.insert("g").attr("class","root");n.nodes()?o.info("Recursive render XXX",n.nodes()):o.info("No nodes found for",n),n.edges().length>0&&o.trace("Recursive edges",n.edge(n.edges()[0]));var c=s.insert("g").attr("class","clusters"),u=s.insert("g").attr("class","edgePaths"),h=s.insert("g").attr("class","edgeLabels"),f=s.insert("g").attr("class","nodes");n.nodes().forEach((function(e){var s=n.node(e);if(void 0!==i){var c=JSON.parse(JSON.stringify(i.clusterData));o.info("Setting data for cluster XXX (",e,") ",c,i),n.setNode(i.id,c),n.parent(e)||(o.trace("Setting parent",e,i.id),n.setParent(e,i.id,c));}if(o.info("(Insert) Node XXX"+e+": "+JSON.stringify(n.node(e))),s&&s.clusterNode){o.info("Cluster identified",e,s.width,n.node(e));var l=t(f,s.graph,r,n.node(e)),u=l.elem;Br(s,u),s.diff=l.diff||0,o.info("Node bounds (abc123)",e,s,s.width,s.x,s.y),function(t,e){ai[e.id]=t;}(u,s),o.warn("Recursive render complete ",u,s);}else n.children(e).length>0?(o.info("Cluster - the non recursive path XXX",e,s.id,s,n),o.info(Yr(s.id,n)),Ir[s.id]={id:Yr(s.id,n),node:s}):(o.info("Node - the non recursive path",e,s.id,s),function(t,e,n){var r,i,a;e.link?("sandbox"===Xt().securityLevel?a="_top":e.linkTarget&&(a=e.linkTarget||"_blank"),r=t.insert("svg:a").attr("xlink:href",e.link).attr("target",a),i=ii[e.shape](r,e,n)):r=i=ii[e.shape](t,e,n),e.tooltip&&i.attr("title",e.tooltip),e.class&&i.attr("class","node default "+e.class),ai[e.id]=r,e.haveCallback&&ai[e.id].attr("class",ai[e.id].attr("class")+" clickable");}(f,n.node(e),a));})),n.edges().forEach((function(t){var e=n.edge(t.v,t.w,t.name);o.info("Edge "+t.v+" -> "+t.w+": "+JSON.stringify(t)),o.info("Edge "+t.v+" -> "+t.w+": ",t," ",JSON.stringify(n.edge(t))),o.info("Fix",Ir,"ids:",t.v,t.w,"Translateing: ",Ir[t.v],Ir[t.w]),hi(h,e);})),n.edges().forEach((function(t){o.info("Edge "+t.v+" -> "+t.w+": "+JSON.stringify(t));})),o.info("#############################################"),o.info("### Layout ###"),o.info("#############################################"),o.info(n),pr().layout(n),o.info("Graph after layout:",yr().json.write(n));var d=0;return Hr(n).forEach((function(t){var e=n.node(t);o.info("Position "+t+": "+JSON.stringify(n.node(t))),o.info("Position "+t+": ("+e.x,","+e.y,") width: ",e.width," height: ",e.height),e&&e.clusterNode?oi(e):n.children(t).length>0?(function(t,e){o.trace("Inserting cluster");var n=e.shape||"rect";ci[e.id]=si[n](t,e);}(c,e),Ir[e.id].node=e):oi(e);})),n.edges().forEach((function(t){var e=n.edge(t);o.info("Edge "+t.v+" -> "+t.w+": "+JSON.stringify(e),e);var i=function(t,e,n,r,i,a){var s=n.points,c=!1,u=a.node(e.v),h=a.node(e.w);o.info("abc88 InsertEdge: ",n),h.intersect&&u.intersect&&((s=s.slice(1,n.points.length-1)).unshift(u.intersect(s[0])),o.info("Last point",s[s.length-1],h,h.intersect(s[s.length-1])),s.push(h.intersect(s[s.length-1]))),n.toCluster&&(o.info("to cluster abc88",r[n.toCluster]),s=pi(n.points,r[n.toCluster].node),c=!0),n.fromCluster&&(o.info("from cluster abc88",r[n.fromCluster]),s=pi(s.reverse(),r[n.fromCluster].node).reverse(),c=!0);var f,d=s.filter((function(t){return !Number.isNaN(t.y)}));f=("graph"===i||"flowchart"===i)&&n.curve||l.curveBasis;var p,g=(0, l.line)().x((function(t){return t.x})).y((function(t){return t.y})).curve(f);switch(n.thickness){case"normal":p="edge-thickness-normal";break;case"thick":p="edge-thickness-thick";break;default:p="";}switch(n.pattern){case"solid":p+=" edge-pattern-solid";break;case"dotted":p+=" edge-pattern-dotted";break;case"dashed":p+=" edge-pattern-dashed";}var y=t.append("path").attr("d",g(d)).attr("id",n.id).attr("class"," "+p+(n.classes?" "+n.classes:"")).attr("style",n.style),m="";switch(Xt().state.arrowMarkerAbsolute&&(m=(m=(m=window.location.protocol+"//"+window.location.host+window.location.pathname+window.location.search).replace(/\(/g,"\\(")).replace(/\)/g,"\\)")),o.info("arrowTypeStart",n.arrowTypeStart),o.info("arrowTypeEnd",n.arrowTypeEnd),n.arrowTypeStart){case"arrow_cross":y.attr("marker-start","url("+m+"#"+i+"-crossStart)");break;case"arrow_point":y.attr("marker-start","url("+m+"#"+i+"-pointStart)");break;case"arrow_barb":y.attr("marker-start","url("+m+"#"+i+"-barbStart)");break;case"arrow_circle":y.attr("marker-start","url("+m+"#"+i+"-circleStart)");break;case"aggregation":y.attr("marker-start","url("+m+"#"+i+"-aggregationStart)");break;case"extension":y.attr("marker-start","url("+m+"#"+i+"-extensionStart)");break;case"composition":y.attr("marker-start","url("+m+"#"+i+"-compositionStart)");break;case"dependency":y.attr("marker-start","url("+m+"#"+i+"-dependencyStart)");break;case"lollipop":y.attr("marker-start","url("+m+"#"+i+"-lollipopStart)");}switch(n.arrowTypeEnd){case"arrow_cross":y.attr("marker-end","url("+m+"#"+i+"-crossEnd)");break;case"arrow_point":y.attr("marker-end","url("+m+"#"+i+"-pointEnd)");break;case"arrow_barb":y.attr("marker-end","url("+m+"#"+i+"-barbEnd)");break;case"arrow_circle":y.attr("marker-end","url("+m+"#"+i+"-circleEnd)");break;case"aggregation":y.attr("marker-end","url("+m+"#"+i+"-aggregationEnd)");break;case"extension":y.attr("marker-end","url("+m+"#"+i+"-extensionEnd)");break;case"composition":y.attr("marker-end","url("+m+"#"+i+"-compositionEnd)");break;case"dependency":y.attr("marker-end","url("+m+"#"+i+"-dependencyEnd)");break;case"lollipop":y.attr("marker-end","url("+m+"#"+i+"-lollipopEnd)");}var b={};return c&&(b.updatedPath=s),b.originalPath=n.points,b}(u,t,e,Ir,r,n);di(e,i);})),n.nodes().forEach((function(t){var e=n.node(t);o.info(t,e.type,e.diff),"group"===e.type&&(d=e.diff);})),{elem:s,diff:d}},yi=function(t,e,n,r,i){Mr(t,n,r,i),ai={},li={},ui={},ci={},Fr={},Rr={},Ir={},o.warn("Graph at first:",yr().json.write(e)),$r(e),o.warn("Graph after:",yr().json.write(e)),gi(t,e,r);},mi={dividerMargin:10,padding:5,textHeight:10};function bi(t){var e;switch(t){case 0:e="aggregation";break;case 1:e="extension";break;case 2:e="composition";break;case 3:e="dependency";break;case 4:e="lollipop";break;default:e="none";}return e}const vi={setConf:function(t){Object.keys(t).forEach((function(e){mi[e]=t[e];}));},draw:function(t,e,n,r){o.info("Drawing class - ",e);var i=Xt().flowchart,a=Xt().securityLevel;o.info("config:",i);var s,c=i.nodeSpacing||50,u=i.rankSpacing||50,h=new(yr().Graph)({multigraph:!0,compound:!0}).setGraph({rankdir:r.db.getDirection(),nodesep:c,ranksep:u,marginx:8,marginy:8}).setDefaultEdgeLabel((function(){return {}})),f=r.db.getClasses(),d=r.db.getRelations();o.info(d),function(t,e,n,r){var i=Object.keys(t);o.info("keys:",i),o.info(t),i.forEach((function(n){var i=t[n],a="";i.cssClasses.length>0&&(a=a+" "+i.cssClasses.join(" "));var s,c,l={labelStyle:""},u=void 0!==i.text?i.text:i.id;i.type,c="class_box",e.setNode(i.id,{labelStyle:l.labelStyle,shape:c,labelText:(s=u,ue.sanitizeText(s,Xt())),classData:i,rx:0,ry:0,class:a,style:l.style,id:i.id,domId:i.domId,tooltip:r.db.getTooltip(i.id)||"",haveCallback:i.haveCallback,link:i.link,width:"group"===i.type?500:void 0,type:i.type,padding:Xt().flowchart.padding}),o.info("setNode",{labelStyle:l.labelStyle,shape:c,labelText:u,rx:0,ry:0,class:a,style:l.style,id:i.id,width:"group"===i.type?500:void 0,type:i.type,padding:Xt().flowchart.padding});}));}(f,h,0,r),function(t,e){var n=Xt().flowchart,r=0;t.forEach((function(i){r++;var a={classes:"relation"};a.pattern=1==i.relation.lineType?"dashed":"solid",a.id="id"+r,"arrow_open"===i.type?a.arrowhead="none":a.arrowhead="normal",o.info(a,i),a.startLabelRight="none"===i.relationTitle1?"":i.relationTitle1,a.endLabelLeft="none"===i.relationTitle2?"":i.relationTitle2,a.arrowTypeStart=bi(i.relation.type1),a.arrowTypeEnd=bi(i.relation.type2);var s="",c="";if(void 0!==i.style){var u=dn(i.style);s=u.style,c=u.labelStyle;}else s="fill:none";a.style=s,a.labelStyle=c,void 0!==i.interpolate?a.curve=hn(i.interpolate,l.curveLinear):void 0!==t.defaultInterpolate?a.curve=hn(t.defaultInterpolate,l.curveLinear):a.curve=hn(n.curve,l.curveLinear),i.text=i.title,void 0===i.text?void 0!==i.style&&(a.arrowheadStyle="fill: #333"):(a.arrowheadStyle="fill: #333",a.labelpos="c",Xt().flowchart.htmlLabels?(a.labelType="html",a.label='<span class="edgeLabel">'+i.text+"</span>"):(a.labelType="text",a.label=i.text.replace(ue.lineBreakRegex,"\n"),void 0===i.style&&(a.style=a.style||"stroke: #333; stroke-width: 1.5px;fill:none"),a.labelStyle=a.labelStyle.replace("color:","fill:"))),e.setEdge(i.id1,i.id2,a,r);}));}(d,h),"sandbox"===a&&(s=(0, l.select)("#i"+e));var p="sandbox"===a?(0, l.select)(s.nodes()[0].contentDocument.body):(0, l.select)("body"),g=p.select('[id="'.concat(e,'"]')),y=p.select("#"+e+" g");if(yi(y,h,["aggregation","extension","composition","dependency","lollipop"],"classDiagram",e),En(h,g,i.diagramPadding,i.useMaxWidth),!i.htmlLabels)for(var m="sandbox"===a?s.nodes()[0].contentDocument:document,b=m.querySelectorAll('[id="'+e+'"] .edgeLabel .label'),v=0;v<b.length;v++){var _=b[v],x=_.getBBox(),k=m.createElementNS("http://www.w3.org/2000/svg","rect");k.setAttribute("rx",0),k.setAttribute("ry",0),k.setAttribute("width",x.width),k.setAttribute("height",x.height),_.insertBefore(k,_.firstChild);}Mn(r.db,g,e);}};var _i=n(1362),xi=n.n(_i),ki={},wi=[],Ti=function(t){return void 0===ki[t]&&(ki[t]={attributes:[]},o.info("Added new entity :",t)),ki[t]};const Ei={Cardinality:{ZERO_OR_ONE:"ZERO_OR_ONE",ZERO_OR_MORE:"ZERO_OR_MORE",ONE_OR_MORE:"ONE_OR_MORE",ONLY_ONE:"ONLY_ONE"},Identification:{NON_IDENTIFYING:"NON_IDENTIFYING",IDENTIFYING:"IDENTIFYING"},parseDirective:function(t,e,n){cu.parseDirective(this,t,e,n);},getConfig:function(){return Xt().er},addEntity:Ti,addAttributes:function(t,e){var n,r=Ti(t);for(n=e.length-1;n>=0;n--)r.attributes.push(e[n]),o.debug("Added attribute ",e[n].attributeName);},getEntities:function(){return ki},addRelationship:function(t,e,n,r){var i={entityA:t,roleA:e,entityB:n,relSpec:r};wi.push(i),o.debug("Added new relationship :",i);},getRelationships:function(){return wi},clear:function(){ki={},wi=[],ge();},setAccTitle:ye,getAccTitle:me,setAccDescription:be,getAccDescription:ve};var Ci={ONLY_ONE_START:"ONLY_ONE_START",ONLY_ONE_END:"ONLY_ONE_END",ZERO_OR_ONE_START:"ZERO_OR_ONE_START",ZERO_OR_ONE_END:"ZERO_OR_ONE_END",ONE_OR_MORE_START:"ONE_OR_MORE_START",ONE_OR_MORE_END:"ONE_OR_MORE_END",ZERO_OR_MORE_START:"ZERO_OR_MORE_START",ZERO_OR_MORE_END:"ZERO_OR_MORE_END"};const Si=Ci;var Ai={},Mi=function(t){return (t.entityA+t.roleA+t.entityB).replace(/\s/g,"")},Ni=0;const Oi={setConf:function(t){for(var e=Object.keys(t),n=0;n<e.length;n++)Ai[e[n]]=t[e[n]];},draw:function(t,e,n,r){Ai=Xt().er,o.info("Drawing ER diagram");var i,a=Xt().securityLevel;"sandbox"===a&&(i=(0, l.select)("#i"+e));var s,c=("sandbox"===a?(0, l.select)(i.nodes()[0].contentDocument.body):(0, l.select)("body")).select("[id='".concat(e,"']"));(function(t,e){var n;t.append("defs").append("marker").attr("id",Ci.ONLY_ONE_START).attr("refX",0).attr("refY",9).attr("markerWidth",18).attr("markerHeight",18).attr("orient","auto").append("path").attr("stroke",e.stroke).attr("fill","none").attr("d","M9,0 L9,18 M15,0 L15,18"),t.append("defs").append("marker").attr("id",Ci.ONLY_ONE_END).attr("refX",18).attr("refY",9).attr("markerWidth",18).attr("markerHeight",18).attr("orient","auto").append("path").attr("stroke",e.stroke).attr("fill","none").attr("d","M3,0 L3,18 M9,0 L9,18"),(n=t.append("defs").append("marker").attr("id",Ci.ZERO_OR_ONE_START).attr("refX",0).attr("refY",9).attr("markerWidth",30).attr("markerHeight",18).attr("orient","auto")).append("circle").attr("stroke",e.stroke).attr("fill","white").attr("cx",21).attr("cy",9).attr("r",6),n.append("path").attr("stroke",e.stroke).attr("fill","none").attr("d","M9,0 L9,18"),(n=t.append("defs").append("marker").attr("id",Ci.ZERO_OR_ONE_END).attr("refX",30).attr("refY",9).attr("markerWidth",30).attr("markerHeight",18).attr("orient","auto")).append("circle").attr("stroke",e.stroke).attr("fill","white").attr("cx",9).attr("cy",9).attr("r",6),n.append("path").attr("stroke",e.stroke).attr("fill","none").attr("d","M21,0 L21,18"),t.append("defs").append("marker").attr("id",Ci.ONE_OR_MORE_START).attr("refX",18).attr("refY",18).attr("markerWidth",45).attr("markerHeight",36).attr("orient","auto").append("path").attr("stroke",e.stroke).attr("fill","none").attr("d","M0,18 Q 18,0 36,18 Q 18,36 0,18 M42,9 L42,27"),t.append("defs").append("marker").attr("id",Ci.ONE_OR_MORE_END).attr("refX",27).attr("refY",18).attr("markerWidth",45).attr("markerHeight",36).attr("orient","auto").append("path").attr("stroke",e.stroke).attr("fill","none").attr("d","M3,9 L3,27 M9,18 Q27,0 45,18 Q27,36 9,18"),(n=t.append("defs").append("marker").attr("id",Ci.ZERO_OR_MORE_START).attr("refX",18).attr("refY",18).attr("markerWidth",57).attr("markerHeight",36).attr("orient","auto")).append("circle").attr("stroke",e.stroke).attr("fill","white").attr("cx",48).attr("cy",18).attr("r",6),n.append("path").attr("stroke",e.stroke).attr("fill","none").attr("d","M0,18 Q18,0 36,18 Q18,36 0,18"),(n=t.append("defs").append("marker").attr("id",Ci.ZERO_OR_MORE_END).attr("refX",39).attr("refY",18).attr("markerWidth",57).attr("markerHeight",36).attr("orient","auto")).append("circle").attr("stroke",e.stroke).attr("fill","white").attr("cx",9).attr("cy",18).attr("r",6),n.append("path").attr("stroke",e.stroke).attr("fill","none").attr("d","M21,18 Q39,0 57,18 Q39,36 21,18");})(c,Ai),s=new(yr().Graph)({multigraph:!0,directed:!0,compound:!1}).setGraph({rankdir:Ai.layoutDirection,marginx:20,marginy:20,nodesep:100,edgesep:100,ranksep:100}).setDefaultEdgeLabel((function(){return {}}));var u,h,f=function(t,e,n){var r;return Object.keys(e).forEach((function(i){var a=t.append("g").attr("id",i);r=void 0===r?i:r;var o="entity-"+i,s=a.append("text").attr("class","er entityLabel").attr("id",o).attr("x",0).attr("y",0).attr("dominant-baseline","middle").attr("text-anchor","middle").attr("style","font-family: "+Xt().fontFamily+"; font-size: "+Ai.fontSize+"px").text(i),c=function(t,e,n){var r=Ai.entityPadding/3,i=Ai.entityPadding/3,a=.85*Ai.fontSize,o=e.node().getBBox(),s=[],c=!1,l=!1,u=0,h=0,f=0,d=0,p=o.height+2*r,g=1;n.forEach((function(t){void 0!==t.attributeKeyType&&(c=!0),void 0!==t.attributeComment&&(l=!0);})),n.forEach((function(n){var i="".concat(e.node().id,"-attr-").concat(g),o=0,y=le(n.attributeType),m=t.append("text").attr("class","er entityLabel").attr("id","".concat(i,"-type")).attr("x",0).attr("y",0).attr("dominant-baseline","middle").attr("text-anchor","left").attr("style","font-family: "+Xt().fontFamily+"; font-size: "+a+"px").text(y),b=t.append("text").attr("class","er entityLabel").attr("id","".concat(i,"-name")).attr("x",0).attr("y",0).attr("dominant-baseline","middle").attr("text-anchor","left").attr("style","font-family: "+Xt().fontFamily+"; font-size: "+a+"px").text(n.attributeName),v={};v.tn=m,v.nn=b;var _=m.node().getBBox(),x=b.node().getBBox();if(u=Math.max(u,_.width),h=Math.max(h,x.width),o=Math.max(_.height,x.height),c){var k=t.append("text").attr("class","er entityLabel").attr("id","".concat(i,"-key")).attr("x",0).attr("y",0).attr("dominant-baseline","middle").attr("text-anchor","left").attr("style","font-family: "+Xt().fontFamily+"; font-size: "+a+"px").text(n.attributeKeyType||"");v.kn=k;var w=k.node().getBBox();f=Math.max(f,w.width),o=Math.max(o,w.height);}if(l){var T=t.append("text").attr("class","er entityLabel").attr("id","".concat(i,"-comment")).attr("x",0).attr("y",0).attr("dominant-baseline","middle").attr("text-anchor","left").attr("style","font-family: "+Xt().fontFamily+"; font-size: "+a+"px").text(n.attributeComment||"");v.cn=T;var E=T.node().getBBox();d=Math.max(d,E.width),o=Math.max(o,E.height);}v.height=o,s.push(v),p+=o+2*r,g+=1;}));var y=4;c&&(y+=2),l&&(y+=2);var m=u+h+f+d,b={width:Math.max(Ai.minEntityWidth,Math.max(o.width+2*Ai.entityPadding,m+i*y)),height:n.length>0?p:Math.max(Ai.minEntityHeight,o.height+2*Ai.entityPadding)};if(n.length>0){var v=Math.max(0,(b.width-m-i*y)/(y/2));e.attr("transform","translate("+b.width/2+","+(r+o.height/2)+")");var _=o.height+2*r,x="attributeBoxOdd";s.forEach((function(e){var n=_+r+e.height/2;e.tn.attr("transform","translate("+i+","+n+")");var a=t.insert("rect","#"+e.tn.node().id).attr("class","er ".concat(x)).attr("fill",Ai.fill).attr("fill-opacity","100%").attr("stroke",Ai.stroke).attr("x",0).attr("y",_).attr("width",u+2*i+v).attr("height",e.height+2*r),o=parseFloat(a.attr("x"))+parseFloat(a.attr("width"));e.nn.attr("transform","translate("+(o+i)+","+n+")");var s=t.insert("rect","#"+e.nn.node().id).attr("class","er ".concat(x)).attr("fill",Ai.fill).attr("fill-opacity","100%").attr("stroke",Ai.stroke).attr("x",o).attr("y",_).attr("width",h+2*i+v).attr("height",e.height+2*r),p=parseFloat(s.attr("x"))+parseFloat(s.attr("width"));if(c){e.kn.attr("transform","translate("+(p+i)+","+n+")");var g=t.insert("rect","#"+e.kn.node().id).attr("class","er ".concat(x)).attr("fill",Ai.fill).attr("fill-opacity","100%").attr("stroke",Ai.stroke).attr("x",p).attr("y",_).attr("width",f+2*i+v).attr("height",e.height+2*r);p=parseFloat(g.attr("x"))+parseFloat(g.attr("width"));}l&&(e.cn.attr("transform","translate("+(p+i)+","+n+")"),t.insert("rect","#"+e.cn.node().id).attr("class","er ".concat(x)).attr("fill",Ai.fill).attr("fill-opacity","100%").attr("stroke",Ai.stroke).attr("x",p).attr("y",_).attr("width",d+2*i+v).attr("height",e.height+2*r)),_+=e.height+2*r,x="attributeBoxOdd"==x?"attributeBoxEven":"attributeBoxOdd";}));}else b.height=Math.max(Ai.minEntityHeight,p),e.attr("transform","translate("+b.width/2+","+b.height/2+")");return b}(a,s,e[i].attributes),l=c.width,u=c.height,h=a.insert("rect","#"+o).attr("class","er entityBox").attr("fill",Ai.fill).attr("fill-opacity","100%").attr("stroke",Ai.stroke).attr("x",0).attr("y",0).attr("width",l).attr("height",u).node().getBBox();n.setNode(i,{width:h.width,height:h.height,shape:"rect",id:i});})),r}(c,r.db.getEntities(),s),d=function(t,e){return t.forEach((function(t){e.setEdge(t.entityA,t.entityB,{relationship:t},Mi(t));})),t}(r.db.getRelationships(),s);pr().layout(s),u=c,(h=s).nodes().forEach((function(t){void 0!==t&&void 0!==h.node(t)&&u.select("#"+t).attr("transform","translate("+(h.node(t).x-h.node(t).width/2)+","+(h.node(t).y-h.node(t).height/2)+" )");})),d.forEach((function(t){!function(t,e,n,r,i){Ni++;var a=n.edge(e.entityA,e.entityB,Mi(e)),o=(0, l.line)().x((function(t){return t.x})).y((function(t){return t.y})).curve(l.curveBasis),s=t.insert("path","#"+r).attr("class","er relationshipLine").attr("d",o(a.points)).attr("stroke",Ai.stroke).attr("fill","none");e.relSpec.relType===i.db.Identification.NON_IDENTIFYING&&s.attr("stroke-dasharray","8,8");var c="";switch(Ai.arrowMarkerAbsolute&&(c=(c=(c=window.location.protocol+"//"+window.location.host+window.location.pathname+window.location.search).replace(/\(/g,"\\(")).replace(/\)/g,"\\)")),e.relSpec.cardA){case i.db.Cardinality.ZERO_OR_ONE:s.attr("marker-end","url("+c+"#"+Si.ZERO_OR_ONE_END+")");break;case i.db.Cardinality.ZERO_OR_MORE:s.attr("marker-end","url("+c+"#"+Si.ZERO_OR_MORE_END+")");break;case i.db.Cardinality.ONE_OR_MORE:s.attr("marker-end","url("+c+"#"+Si.ONE_OR_MORE_END+")");break;case i.db.Cardinality.ONLY_ONE:s.attr("marker-end","url("+c+"#"+Si.ONLY_ONE_END+")");}switch(e.relSpec.cardB){case i.db.Cardinality.ZERO_OR_ONE:s.attr("marker-start","url("+c+"#"+Si.ZERO_OR_ONE_START+")");break;case i.db.Cardinality.ZERO_OR_MORE:s.attr("marker-start","url("+c+"#"+Si.ZERO_OR_MORE_START+")");break;case i.db.Cardinality.ONE_OR_MORE:s.attr("marker-start","url("+c+"#"+Si.ONE_OR_MORE_START+")");break;case i.db.Cardinality.ONLY_ONE:s.attr("marker-start","url("+c+"#"+Si.ONLY_ONE_START+")");}var u=s.node().getTotalLength(),h=s.node().getPointAtLength(.5*u),f="rel"+Ni,d=t.append("text").attr("class","er relationshipLabel").attr("id",f).attr("x",h.x).attr("y",h.y).attr("text-anchor","middle").attr("dominant-baseline","middle").attr("style","font-family: "+Xt().fontFamily+"; font-size: "+Ai.fontSize+"px").text(e.roleA).node().getBBox();t.insert("rect","#"+f).attr("class","er relationshipLabelBox").attr("x",h.x-d.width/2).attr("y",h.y-d.height/2).attr("width",d.width).attr("height",d.height).attr("fill","white").attr("fill-opacity","85%");}(c,t,s,f,r);}));var p=Ai.diagramPadding,g=c.node().getBBox(),y=g.width+2*p,m=g.height+2*p;Tn(c,0,y,Ai.useMaxWidth),c.attr("viewBox","".concat(g.x-p," ").concat(g.y-p," ").concat(y," ").concat(m)),Mn(r.db,c,e);}};var Di={};const Bi={setConf:function(t){Object.keys(t).forEach((function(e){Di[e]=t[e];}));},draw:function(t,e,n){try{o.debug("Renering svg for syntax error\n");var r=(0,l.select)("#"+e),i=r.append("g");i.append("path").attr("class","error-icon").attr("d","m411.313,123.313c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32-9.375,9.375-20.688-20.688c-12.484-12.5-32.766-12.5-45.25,0l-16,16c-1.261,1.261-2.304,2.648-3.31,4.051-21.739-8.561-45.324-13.426-70.065-13.426-105.867,0-192,86.133-192,192s86.133,192 192,192 192-86.133 192-192c0-24.741-4.864-48.327-13.426-70.065 1.402-1.007 2.79-2.049 4.051-3.31l16-16c12.5-12.492 12.5-32.758 0-45.25l-20.688-20.688 9.375-9.375 32.001-31.999zm-219.313,100.687c-52.938,0-96,43.063-96,96 0,8.836-7.164,16-16,16s-16-7.164-16-16c0-70.578 57.422-128 128-128 8.836,0 16,7.164 16,16s-7.164,16-16,16z"),i.append("path").attr("class","error-icon").attr("d","m459.02,148.98c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l16,16c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16.001-16z"),i.append("path").attr("class","error-icon").attr("d","m340.395,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16-16c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l15.999,16z"),i.append("path").attr("class","error-icon").attr("d","m400,64c8.844,0 16-7.164 16-16v-32c0-8.836-7.156-16-16-16-8.844,0-16,7.164-16,16v32c0,8.836 7.156,16 16,16z"),i.append("path").attr("class","error-icon").attr("d","m496,96.586h-32c-8.844,0-16,7.164-16,16 0,8.836 7.156,16 16,16h32c8.844,0 16-7.164 16-16 0-8.836-7.156-16-16-16z"),i.append("path").attr("class","error-icon").attr("d","m436.98,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688l32-32c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32c-6.251,6.25-6.251,16.375-0.001,22.625z"),i.append("text").attr("class","error-text").attr("x",1440).attr("y",250).attr("font-size","150px").style("text-anchor","middle").text("Syntax error in graph"),i.append("text").attr("class","error-text").attr("x",1250).attr("y",400).attr("font-size","100px").style("text-anchor","middle").text("mermaid version "+n),r.attr("height",100),r.attr("width",500),r.attr("viewBox","768 0 912 512");}catch(t){o.error("Error while rendering info diagram"),o.error(t.message);}}};var Li=n(5890),Ii=n.n(Li);function Fi(t){return Fi="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Fi(t)}function Ri(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}var Pi,ji,zi="flowchart-",Yi=0,Ui=Xt(),$i={},Wi=[],qi=[],Hi=[],Vi={},Gi={},Xi=0,Zi=!0,Qi=[],Ki=function(t){return ue.sanitizeText(t,Ui)},Ji=function(t){for(var e=Object.keys($i),n=0;n<e.length;n++)if($i[e[n]].id===t)return $i[e[n]].domId;return t},ta=function(t,e,n,r){var i={start:t,end:e,type:void 0,text:""};void 0!==(r=n.text)&&(i.text=Ki(r.trim()),'"'===i.text[0]&&'"'===i.text[i.text.length-1]&&(i.text=i.text.substring(1,i.text.length-1))),void 0!==n&&(i.type=n.type,i.stroke=n.stroke,i.length=n.length),Wi.push(i);},ea=function(t,e){t.split(",").forEach((function(t){var n=t;void 0!==$i[n]&&$i[n].classes.push(e),void 0!==Vi[n]&&Vi[n].classes.push(e);}));},na=function(t){var e=(0, l.select)(".mermaidTooltip");null===(e._groups||e)[0][0]&&(e=(0, l.select)("body").append("div").attr("class","mermaidTooltip").style("opacity",0)),(0, l.select)(t).select("svg").selectAll("g.node").on("mouseover",(function(){var t=(0, l.select)(this);if(null!==t.attr("title")){var n=this.getBoundingClientRect();e.transition().duration(200).style("opacity",".9"),e.text(t.attr("title")).style("left",window.scrollX+n.left+(n.right-n.left)/2+"px").style("top",window.scrollY+n.top-14+document.body.scrollTop+"px"),e.html(e.html().replace(/&lt;br\/&gt;/g,"<br/>")),t.classed("hover",!0);}})).on("mouseout",(function(){e.transition().duration(500).style("opacity",0),(0, l.select)(this).classed("hover",!1);}));};Qi.push(na);var ra=function(t){for(var e=0;e<Hi.length;e++)if(Hi[e].id===t)return e;return -1},ia=-1,aa=[],oa=function t(e,n){var r=Hi[n].nodes;if(!((ia+=1)>2e3)){if(aa[ia]=n,Hi[n].id===e)return {result:!0,count:0};for(var i=0,a=1;i<r.length;){var o=ra(r[i]);if(o>=0){var s=t(e,o);if(s.result)return {result:!0,count:a+s.count};a+=s.count;}i+=1;}return {result:!1,count:a}}},sa=function(t,e){var n=!1;return t.forEach((function(t){t.nodes.indexOf(e)>=0&&(n=!0);})),n},ca=function(t,e){var n=[];return t.nodes.forEach((function(r,i){sa(e,r)||n.push(t.nodes[i]);})),{nodes:n}};const la={parseDirective:function(t,e,n){cu.parseDirective(this,t,e,n);},defaultConfig:function(){return $t.flowchart},setAccTitle:ye,getAccTitle:me,getAccDescription:ve,setAccDescription:be,addVertex:function(t,e,n,r,i,a){var o,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:{},c=t;void 0!==c&&0!==c.trim().length&&(void 0===$i[c]&&($i[c]={id:c,domId:zi+c+"-"+Yi,styles:[],classes:[]}),Yi++,void 0!==e?(Ui=Xt(),'"'===(o=Ki(e.trim()))[0]&&'"'===o[o.length-1]&&(o=o.substring(1,o.length-1)),$i[c].text=o):void 0===$i[c].text&&($i[c].text=t),void 0!==n&&($i[c].type=n),null!=r&&r.forEach((function(t){$i[c].styles.push(t);})),null!=i&&i.forEach((function(t){$i[c].classes.push(t);})),void 0!==a&&($i[c].dir=a),$i[c].props=s);},lookUpDomId:Ji,addLink:function(t,e,n,r){var i,a;for(i=0;i<t.length;i++)for(a=0;a<e.length;a++)ta(t[i],e[a],n,r);},updateLinkInterpolate:function(t,e){t.forEach((function(t){"default"===t?Wi.defaultInterpolate=e:Wi[t].interpolate=e;}));},updateLink:function(t,e){t.forEach((function(t){"default"===t?Wi.defaultStyle=e:(-1===An.isSubstringInArray("fill",e)&&e.push("fill:none"),Wi[t].style=e);}));},addClass:function(t,e){void 0===qi[t]&&(qi[t]={id:t,styles:[],textStyles:[]}),null!=e&&e.forEach((function(e){if(e.match("color")){var n=e.replace("fill","bgFill").replace("color","fill");qi[t].textStyles.push(n);}qi[t].styles.push(e);}));},setDirection:function(t){(Pi=t).match(/.*</)&&(Pi="RL"),Pi.match(/.*\^/)&&(Pi="BT"),Pi.match(/.*>/)&&(Pi="LR"),Pi.match(/.*v/)&&(Pi="TB");},setClass:ea,setTooltip:function(t,e){t.split(",").forEach((function(t){void 0!==e&&(Gi["gen-1"===ji?Ji(t):t]=Ki(e));}));},getTooltip:function(t){return Gi[t]},setClickEvent:function(t,e,n){t.split(",").forEach((function(t){!function(t,e,n){var r=Ji(t);if("loose"===Xt().securityLevel&&void 0!==e){var i=[];if("string"==typeof n){i=n.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);for(var a=0;a<i.length;a++){var o=i[a].trim();'"'===o.charAt(0)&&'"'===o.charAt(o.length-1)&&(o=o.substr(1,o.length-2)),i[a]=o;}}0===i.length&&i.push(t),void 0!==$i[t]&&($i[t].haveCallback=!0,Qi.push((function(){var t=document.querySelector('[id="'.concat(r,'"]'));null!==t&&t.addEventListener("click",(function(){var t;An.runFunc.apply(An,[e].concat(function(t){if(Array.isArray(t))return Ri(t)}(t=i)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return Ri(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return "Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ri(t,e):void 0}}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()));}),!1);})));}}(t,e,n);})),ea(t,"clickable");},setLink:function(t,e,n){t.split(",").forEach((function(t){void 0!==$i[t]&&($i[t].link=An.formatUrl(e,Ui),$i[t].linkTarget=n);})),ea(t,"clickable");},bindFunctions:function(t){Qi.forEach((function(e){e(t);}));},getDirection:function(){return Pi.trim()},getVertices:function(){return $i},getEdges:function(){return Wi},getClasses:function(){return qi},clear:function(t){$i={},qi={},Wi=[],(Qi=[]).push(na),Hi=[],Vi={},Xi=0,Gi=[],Zi=!0,ji=t||"gen-1",ge();},setGen:function(t){ji=t||"gen-1";},defaultStyle:function(){return "fill:#ffa;stroke: #f66; stroke-width: 3px; stroke-dasharray: 5, 5;fill:#ffa;stroke: #666;"},addSubGraph:function(t,e,n){var r=t.trim(),i=n;t===n&&n.match(/\s/)&&(r=void 0);var a=[],s=function(t){var e,n={boolean:{},number:{},string:{}},r=[],i=t.filter((function(t){var i=Fi(t);return t.stmt&&"dir"===t.stmt?(e=t.value,!1):""!==t.trim()&&(i in n?!n[i].hasOwnProperty(t)&&(n[i][t]=!0):!(r.indexOf(t)>=0)&&r.push(t))}));return {nodeList:i,dir:e}}(a.concat.apply(a,e)),c=s.nodeList,l=s.dir;if(a=c,"gen-1"===ji)for(var u=0;u<a.length;u++)a[u]=Ji(a[u]);r=r||"subGraph"+Xi,i=Ki(i=i||""),Xi+=1;var h={id:r,nodes:a,title:i.trim(),classes:[],dir:l};return o.info("Adding",h.id,h.nodes,h.dir),h.nodes=ca(h,Hi).nodes,Hi.push(h),Vi[r]=h,r},getDepthFirstPos:function(t){return aa[t]},indexNodes:function(){ia=-1,Hi.length>0&&oa("none",Hi.length-1);},getSubGraphs:function(){return Hi},destructLink:function(t,e){var n,r=function(t){var e=t.trim(),n=e.slice(0,-1),r="arrow_open";switch(e.slice(-1)){case"x":r="arrow_cross","x"===e[0]&&(r="double_"+r,n=n.slice(1));break;case">":r="arrow_point","<"===e[0]&&(r="double_"+r,n=n.slice(1));break;case"o":r="arrow_circle","o"===e[0]&&(r="double_"+r,n=n.slice(1));}var i="normal",a=n.length-1;"="===n[0]&&(i="thick");var o=function(t,e){for(var n=e.length,r=0,i=0;i<n;++i)"."===e[i]&&++r;return r}(0,n);return o&&(i="dotted",a=o),{type:r,stroke:i,length:a}}(t);if(e){if(n=function(t){var e=t.trim(),n="arrow_open";switch(e[0]){case"<":n="arrow_point",e=e.slice(1);break;case"x":n="arrow_cross",e=e.slice(1);break;case"o":n="arrow_circle",e=e.slice(1);}var r="normal";return -1!==e.indexOf("=")&&(r="thick"),-1!==e.indexOf(".")&&(r="dotted"),{type:n,stroke:r}}(e),n.stroke!==r.stroke)return {type:"INVALID",stroke:"INVALID"};if("arrow_open"===n.type)n.type=r.type;else {if(n.type!==r.type)return {type:"INVALID",stroke:"INVALID"};n.type="double_"+n.type;}return "double_arrow"===n.type&&(n.type="double_arrow_point"),n.length=r.length,n}return r},lex:{firstGraph:function(){return !!Zi&&(Zi=!1,!0)}},exists:sa,makeUniq:ca};var ua=n(4949),ha=n.n(ua),fa=n(8284),da=n.n(fa);function pa(t,e,n){var r=.9*(e.width+e.height),i=[{x:r/2,y:0},{x:r,y:-r/2},{x:r/2,y:-r},{x:0,y:-r/2}],a=Ea(t,r,r,i);return n.intersect=function(t){return ha().intersect.polygon(n,i,t)},a}function ga(t,e,n){var r=e.height,i=r/4,a=e.width+2*i,o=[{x:i,y:0},{x:a-i,y:0},{x:a,y:-r/2},{x:a-i,y:-r},{x:i,y:-r},{x:0,y:-r/2}],s=Ea(t,a,r,o);return n.intersect=function(t){return ha().intersect.polygon(n,o,t)},s}function ya(t,e,n){var r=e.width,i=e.height,a=[{x:-i/2,y:0},{x:r,y:0},{x:r,y:-i},{x:-i/2,y:-i},{x:0,y:-i/2}],o=Ea(t,r,i,a);return n.intersect=function(t){return ha().intersect.polygon(n,a,t)},o}function ma(t,e,n){var r=e.width,i=e.height,a=[{x:-2*i/6,y:0},{x:r-i/6,y:0},{x:r+2*i/6,y:-i},{x:i/6,y:-i}],o=Ea(t,r,i,a);return n.intersect=function(t){return ha().intersect.polygon(n,a,t)},o}function ba(t,e,n){var r=e.width,i=e.height,a=[{x:2*i/6,y:0},{x:r+i/6,y:0},{x:r-2*i/6,y:-i},{x:-i/6,y:-i}],o=Ea(t,r,i,a);return n.intersect=function(t){return ha().intersect.polygon(n,a,t)},o}function va(t,e,n){var r=e.width,i=e.height,a=[{x:-2*i/6,y:0},{x:r+2*i/6,y:0},{x:r-i/6,y:-i},{x:i/6,y:-i}],o=Ea(t,r,i,a);return n.intersect=function(t){return ha().intersect.polygon(n,a,t)},o}function _a(t,e,n){var r=e.width,i=e.height,a=[{x:i/6,y:0},{x:r-i/6,y:0},{x:r+2*i/6,y:-i},{x:-2*i/6,y:-i}],o=Ea(t,r,i,a);return n.intersect=function(t){return ha().intersect.polygon(n,a,t)},o}function xa(t,e,n){var r=e.width,i=e.height,a=[{x:0,y:0},{x:r+i/2,y:0},{x:r,y:-i/2},{x:r+i/2,y:-i},{x:0,y:-i}],o=Ea(t,r,i,a);return n.intersect=function(t){return ha().intersect.polygon(n,a,t)},o}function ka(t,e,n){var r=e.height,i=e.width+r/4,a=t.insert("rect",":first-child").attr("rx",r/2).attr("ry",r/2).attr("x",-i/2).attr("y",-r/2).attr("width",i).attr("height",r);return n.intersect=function(t){return ha().intersect.rect(n,t)},a}function wa(t,e,n){var r=e.width,i=e.height,a=[{x:0,y:0},{x:r,y:0},{x:r,y:-i},{x:0,y:-i},{x:0,y:0},{x:-8,y:0},{x:r+8,y:0},{x:r+8,y:-i},{x:-8,y:-i},{x:-8,y:0}],o=Ea(t,r,i,a);return n.intersect=function(t){return ha().intersect.polygon(n,a,t)},o}function Ta(t,e,n){var r=e.width,i=r/2,a=i/(2.5+r/50),o=e.height+a,s="M 0,"+a+" a "+i+","+a+" 0,0,0 "+r+" 0 a "+i+","+a+" 0,0,0 "+-r+" 0 l 0,"+o+" a "+i+","+a+" 0,0,0 "+r+" 0 l 0,"+-o,c=t.attr("label-offset-y",a).insert("path",":first-child").attr("d",s).attr("transform","translate("+-r/2+","+-(o/2+a)+")");return n.intersect=function(t){var e=ha().intersect.rect(n,t),r=e.x-n.x;if(0!=i&&(Math.abs(r)<n.width/2||Math.abs(r)==n.width/2&&Math.abs(e.y-n.y)>n.height/2-a)){var o=a*a*(1-r*r/(i*i));0!=o&&(o=Math.sqrt(o)),o=a-o,t.y-n.y>0&&(o=-o),e.y+=o;}return e},c}function Ea(t,e,n,r){return t.insert("polygon",":first-child").attr("points",r.map((function(t){return t.x+","+t.y})).join(" ")).attr("transform","translate("+-e/2+","+n/2+")")}const Ca=function(t){t.shapes().question=pa,t.shapes().hexagon=ga,t.shapes().stadium=ka,t.shapes().subroutine=wa,t.shapes().cylinder=Ta,t.shapes().rect_left_inv_arrow=ya,t.shapes().lean_right=ma,t.shapes().lean_left=ba,t.shapes().trapezoid=va,t.shapes().inv_trapezoid=_a,t.shapes().rect_right_inv_arrow=xa;};var Sa={},Aa=function(t,e,n,r,i,a){Xt().securityLevel;var s=r?r.select('[id="'.concat(n,'"]')):(0, l.select)('[id="'.concat(n,'"]')),c=i||document;Object.keys(t).forEach((function(n){var r=t[n],i="default";r.classes.length>0&&(i=r.classes.join(" "));var l,u=dn(r.styles),h=void 0!==r.text?r.text:r.id;if(ce(Xt().flowchart.htmlLabels)){var f={label:h.replace(/fa[lrsb]?:fa-[\w-]+/g,(function(t){return "<i class='".concat(t.replace(":"," "),"'></i>")}))};(l=da()(s,f).node()).parentNode.removeChild(l);}else {var d=c.createElementNS("http://www.w3.org/2000/svg","text");d.setAttribute("style",u.labelStyle.replace("color:","fill:"));for(var p=h.split(ue.lineBreakRegex),g=0;g<p.length;g++){var y=c.createElementNS("http://www.w3.org/2000/svg","tspan");y.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve"),y.setAttribute("dy","1em"),y.setAttribute("x","1"),y.textContent=p[g],d.appendChild(y);}l=d;}var m=0,b="";switch(r.type){case"round":m=5,b="rect";break;case"square":case"group":default:b="rect";break;case"diamond":b="question";break;case"hexagon":b="hexagon";break;case"odd":case"odd_right":b="rect_left_inv_arrow";break;case"lean_right":b="lean_right";break;case"lean_left":b="lean_left";break;case"trapezoid":b="trapezoid";break;case"inv_trapezoid":b="inv_trapezoid";break;case"circle":b="circle";break;case"ellipse":b="ellipse";break;case"stadium":b="stadium";break;case"subroutine":b="subroutine";break;case"cylinder":b="cylinder";}o.warn("Adding node",r.id,r.domId),e.setNode(a.db.lookUpDomId(r.id),{labelType:"svg",labelStyle:u.labelStyle,shape:b,label:l,rx:m,ry:m,class:i,style:u.style,id:a.db.lookUpDomId(r.id)});}));},Ma=function(t,e,n){var r,i,a=0;if(void 0!==t.defaultStyle){var o=dn(t.defaultStyle);r=o.style,i=o.labelStyle;}t.forEach((function(o){a++;var s="L-"+o.start+"-"+o.end,c="LS-"+o.start,u="LE-"+o.end,h={};"arrow_open"===o.type?h.arrowhead="none":h.arrowhead="normal";var f="",d="";if(void 0!==o.style){var p=dn(o.style);f=p.style,d=p.labelStyle;}else switch(o.stroke){case"normal":f="fill:none",void 0!==r&&(f=r),void 0!==i&&(d=i);break;case"dotted":f="fill:none;stroke-width:2px;stroke-dasharray:3;";break;case"thick":f=" stroke-width: 3.5px;fill:none";}h.style=f,h.labelStyle=d,void 0!==o.interpolate?h.curve=hn(o.interpolate,l.curveLinear):void 0!==t.defaultInterpolate?h.curve=hn(t.defaultInterpolate,l.curveLinear):h.curve=hn(Sa.curve,l.curveLinear),void 0===o.text?void 0!==o.style&&(h.arrowheadStyle="fill: #333"):(h.arrowheadStyle="fill: #333",h.labelpos="c",ce(Xt().flowchart.htmlLabels)?(h.labelType="html",h.label='<span id="L-'.concat(s,'" class="edgeLabel L-').concat(c,"' L-").concat(u,'" style="').concat(h.labelStyle,'">').concat(o.text.replace(/fa[lrsb]?:fa-[\w-]+/g,(function(t){return "<i class='".concat(t.replace(":"," "),"'></i>")})),"</span>")):(h.labelType="text",h.label=o.text.replace(ue.lineBreakRegex,"\n"),void 0===o.style&&(h.style=h.style||"stroke: #333; stroke-width: 1.5px;fill:none"),h.labelStyle=h.labelStyle.replace("color:","fill:"))),h.id=s,h.class=c+" "+u,h.minlen=o.length||1,e.setEdge(n.db.lookUpDomId(o.start),n.db.lookUpDomId(o.end),h,a);}));};const Na={setConf:function(t){for(var e=Object.keys(t),n=0;n<e.length;n++)Sa[e[n]]=t[e[n]];},addVertices:Aa,addEdges:Ma,getClasses:function(t,e){o.info("Extracting classes"),e.db.clear();try{return e.parse(t),e.db.getClasses()}catch(t){return}},draw:function(t,e,n,r){o.info("Drawing flowchart"),r.db.clear();var i,a=Xt().securityLevel;"sandbox"===a&&(i=(0, l.select)("#i"+e));var s="sandbox"===a?(0, l.select)(i.nodes()[0].contentDocument.body):(0, l.select)("body"),c="sandbox"===a?i.nodes()[0].contentDocument:document;try{r.parser.parse(t);}catch(t){o.debug("Parsing failed");}var u=r.db.getDirection();void 0===u&&(u="TD");for(var h,f=Xt().flowchart,d=f.nodeSpacing||50,p=f.rankSpacing||50,g=new(yr().Graph)({multigraph:!0,compound:!0}).setGraph({rankdir:u,nodesep:d,ranksep:p,marginx:8,marginy:8}).setDefaultEdgeLabel((function(){return {}})),y=r.db.getSubGraphs(),m=y.length-1;m>=0;m--)h=y[m],r.db.addVertex(h.id,h.title,"group",void 0,h.classes);var b=r.db.getVertices();o.warn("Get vertices",b);var v=r.db.getEdges(),_=0;for(_=y.length-1;_>=0;_--){h=y[_],(0, l.selectAll)("cluster").append("text");for(var x=0;x<h.nodes.length;x++)o.warn("Setting subgraph",h.nodes[x],r.db.lookUpDomId(h.nodes[x]),r.db.lookUpDomId(h.id)),g.setParent(r.db.lookUpDomId(h.nodes[x]),r.db.lookUpDomId(h.id));}Aa(b,g,e,s,c,r),Ma(v,g,r);var k=new(ha().render);Ca(k),k.arrows().none=function(t,e,n,r){var i=t.append("marker").attr("id",e).attr("viewBox","0 0 10 10").attr("refX",9).attr("refY",5).attr("markerUnits","strokeWidth").attr("markerWidth",8).attr("markerHeight",6).attr("orient","auto").append("path").attr("d","M 0 0 L 0 0 L 0 0 z");ha().util.applyStyle(i,n[r+"Style"]);},k.arrows().normal=function(t,e){t.append("marker").attr("id",e).attr("viewBox","0 0 10 10").attr("refX",9).attr("refY",5).attr("markerUnits","strokeWidth").attr("markerWidth",8).attr("markerHeight",6).attr("orient","auto").append("path").attr("d","M 0 0 L 10 5 L 0 10 z").attr("class","arrowheadPath").style("stroke-width",1).style("stroke-dasharray","1,0");};var w=s.select('[id="'.concat(e,'"]'));Mn(r.db,w,e);var T=s.select("#"+e+" g");for(k(T,g),T.selectAll("g.node").attr("title",(function(){return r.db.getTooltip(this.id)})),r.db.indexNodes("subGraph"+_),_=0;_<y.length;_++)if("undefined"!==(h=y[_]).title){var E=c.querySelectorAll("#"+e+' [id="'+r.db.lookUpDomId(h.id)+'"] rect'),C=c.querySelectorAll("#"+e+' [id="'+r.db.lookUpDomId(h.id)+'"]'),S=E[0].x.baseVal.value,A=E[0].y.baseVal.value,M=E[0].width.baseVal.value,N=(0, l.select)(C[0]).select(".label");N.attr("transform","translate(".concat(S+M/2,", ").concat(A+14,")")),N.attr("id",e+"Text");for(var O=0;O<h.classes.length;O++)C[0].classList.add(h.classes[O]);}ce(f.htmlLabels);for(var D=c.querySelectorAll('[id="'+e+'"] .edgeLabel .label'),B=0;B<D.length;B++){var L=D[B],I=L.getBBox(),F=c.createElementNS("http://www.w3.org/2000/svg","rect");F.setAttribute("rx",0),F.setAttribute("ry",0),F.setAttribute("width",I.width),F.setAttribute("height",I.height),L.insertBefore(F,L.firstChild);}En(g,w,f.diagramPadding,f.useMaxWidth),Object.keys(b).forEach((function(t){var n=b[t];if(n.link){var i=s.select("#"+e+' [id="'+r.db.lookUpDomId(t)+'"]');if(i){var o=c.createElementNS("http://www.w3.org/2000/svg","a");o.setAttributeNS("http://www.w3.org/2000/svg","class",n.classes.join(" ")),o.setAttributeNS("http://www.w3.org/2000/svg","href",n.link),o.setAttributeNS("http://www.w3.org/2000/svg","rel","noopener"),"sandbox"===a?o.setAttributeNS("http://www.w3.org/2000/svg","target","_top"):n.linkTarget&&o.setAttributeNS("http://www.w3.org/2000/svg","target",n.linkTarget);var l=i.insert((function(){return o}),":first-child"),u=i.select(".label-container");u&&l.append((function(){return u.node()}));var h=i.select(".label");h&&l.append((function(){return h.node()}));}}}));}};var Oa={},Da=function(t,e,n,r,i,a){var s=r.select('[id="'.concat(n,'"]'));Object.keys(t).forEach((function(n){var r=t[n],c="default";r.classes.length>0&&(c=r.classes.join(" "));var l,u=dn(r.styles),h=void 0!==r.text?r.text:r.id;if(ce(Xt().flowchart.htmlLabels)){var f={label:h.replace(/fa[lrsb]?:fa-[\w-]+/g,(function(t){return "<i class='".concat(t.replace(":"," "),"'></i>")}))};(l=da()(s,f).node()).parentNode.removeChild(l);}else {var d=i.createElementNS("http://www.w3.org/2000/svg","text");d.setAttribute("style",u.labelStyle.replace("color:","fill:"));for(var p=h.split(ue.lineBreakRegex),g=0;g<p.length;g++){var y=i.createElementNS("http://www.w3.org/2000/svg","tspan");y.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve"),y.setAttribute("dy","1em"),y.setAttribute("x","1"),y.textContent=p[g],d.appendChild(y);}l=d;}var m=0,b="";switch(r.type){case"round":m=5,b="rect";break;case"square":case"group":default:b="rect";break;case"diamond":b="question";break;case"hexagon":b="hexagon";break;case"odd":case"odd_right":b="rect_left_inv_arrow";break;case"lean_right":b="lean_right";break;case"lean_left":b="lean_left";break;case"trapezoid":b="trapezoid";break;case"inv_trapezoid":b="inv_trapezoid";break;case"circle":b="circle";break;case"ellipse":b="ellipse";break;case"stadium":b="stadium";break;case"subroutine":b="subroutine";break;case"cylinder":b="cylinder";break;case"doublecircle":b="doublecircle";}e.setNode(r.id,{labelStyle:u.labelStyle,shape:b,labelText:h,rx:m,ry:m,class:c,style:u.style,id:r.id,link:r.link,linkTarget:r.linkTarget,tooltip:a.db.getTooltip(r.id)||"",domId:a.db.lookUpDomId(r.id),haveCallback:r.haveCallback,width:"group"===r.type?500:void 0,dir:r.dir,type:r.type,props:r.props,padding:Xt().flowchart.padding}),o.info("setNode",{labelStyle:u.labelStyle,shape:b,labelText:h,rx:m,ry:m,class:c,style:u.style,id:r.id,domId:a.db.lookUpDomId(r.id),width:"group"===r.type?500:void 0,type:r.type,dir:r.dir,props:r.props,padding:Xt().flowchart.padding});}));},Ba=function(t,e,n){o.info("abc78 edges = ",t);var r,i,a=0,s={};if(void 0!==t.defaultStyle){var c=dn(t.defaultStyle);r=c.style,i=c.labelStyle;}t.forEach((function(n){a++;var c="L-"+n.start+"-"+n.end;void 0===s[c]?(s[c]=0,o.info("abc78 new entry",c,s[c])):(s[c]++,o.info("abc78 new entry",c,s[c]));var u=c+"-"+s[c];o.info("abc78 new link id to be used is",c,u,s[c]);var h="LS-"+n.start,f="LE-"+n.end,d={style:"",labelStyle:""};switch(d.minlen=n.length||1,"arrow_open"===n.type?d.arrowhead="none":d.arrowhead="normal",d.arrowTypeStart="arrow_open",d.arrowTypeEnd="arrow_open",n.type){case"double_arrow_cross":d.arrowTypeStart="arrow_cross";case"arrow_cross":d.arrowTypeEnd="arrow_cross";break;case"double_arrow_point":d.arrowTypeStart="arrow_point";case"arrow_point":d.arrowTypeEnd="arrow_point";break;case"double_arrow_circle":d.arrowTypeStart="arrow_circle";case"arrow_circle":d.arrowTypeEnd="arrow_circle";}var p="",g="";switch(n.stroke){case"normal":p="fill:none;",void 0!==r&&(p=r),void 0!==i&&(g=i),d.thickness="normal",d.pattern="solid";break;case"dotted":d.thickness="normal",d.pattern="dotted",d.style="fill:none;stroke-width:2px;stroke-dasharray:3;";break;case"thick":d.thickness="thick",d.pattern="solid",d.style="stroke-width: 3.5px;fill:none;";}if(void 0!==n.style){var y=dn(n.style);p=y.style,g=y.labelStyle;}d.style=d.style+=p,d.labelStyle=d.labelStyle+=g,void 0!==n.interpolate?d.curve=hn(n.interpolate,l.curveLinear):void 0!==t.defaultInterpolate?d.curve=hn(t.defaultInterpolate,l.curveLinear):d.curve=hn(Oa.curve,l.curveLinear),void 0===n.text?void 0!==n.style&&(d.arrowheadStyle="fill: #333"):(d.arrowheadStyle="fill: #333",d.labelpos="c"),d.labelType="text",d.label=n.text.replace(ue.lineBreakRegex,"\n"),void 0===n.style&&(d.style=d.style||"stroke: #333; stroke-width: 1.5px;fill:none;"),d.labelStyle=d.labelStyle.replace("color:","fill:"),d.id=u,d.classes="flowchart-link "+h+" "+f,e.setEdge(n.start,n.end,d,a);}));};const La={setConf:function(t){for(var e=Object.keys(t),n=0;n<e.length;n++)Oa[e[n]]=t[e[n]];},addVertices:Da,addEdges:Ba,getClasses:function(t,e){o.info("Extracting classes"),e.db.clear();try{return e.parse(t),e.db.getClasses()}catch(t){return}},draw:function(t,e,n,r){o.info("Drawing flowchart"),r.db.clear(),la.setGen("gen-2"),r.parser.parse(t);var i=r.db.getDirection();void 0===i&&(i="TD");var a,s=Xt().flowchart,c=s.nodeSpacing||50,u=s.rankSpacing||50,h=Xt().securityLevel;"sandbox"===h&&(a=(0, l.select)("#i"+e));var f,d="sandbox"===h?(0, l.select)(a.nodes()[0].contentDocument.body):(0, l.select)("body"),p="sandbox"===h?a.nodes()[0].contentDocument:document,g=new(yr().Graph)({multigraph:!0,compound:!0}).setGraph({rankdir:i,nodesep:c,ranksep:u,marginx:0,marginy:0}).setDefaultEdgeLabel((function(){return {}})),y=r.db.getSubGraphs();o.info("Subgraphs - ",y);for(var m=y.length-1;m>=0;m--)f=y[m],o.info("Subgraph - ",f),r.db.addVertex(f.id,f.title,"group",void 0,f.classes,f.dir);var b=r.db.getVertices(),v=r.db.getEdges();o.info(v);var _=0;for(_=y.length-1;_>=0;_--){f=y[_],(0, l.selectAll)("cluster").append("text");for(var x=0;x<f.nodes.length;x++)o.info("Setting up subgraphs",f.nodes[x],f.id),g.setParent(f.nodes[x],f.id);}Da(b,g,e,d,p,r),Ba(v,g);var k=d.select('[id="'.concat(e,'"]'));Mn(r.db,k,e);var w=d.select("#"+e+" g");if(yi(w,g,["point","circle","cross"],"flowchart",e),En(g,k,s.diagramPadding,s.useMaxWidth),r.db.indexNodes("subGraph"+_),!s.htmlLabels)for(var T=p.querySelectorAll('[id="'+e+'"] .edgeLabel .label'),E=0;E<T.length;E++){var C=T[E],S=C.getBBox(),A=p.createElementNS("http://www.w3.org/2000/svg","rect");A.setAttribute("rx",0),A.setAttribute("ry",0),A.setAttribute("width",S.width),A.setAttribute("height",S.height),C.insertBefore(A,C.firstChild);}Object.keys(b).forEach((function(t){var n=b[t];if(n.link){var r=(0, l.select)("#"+e+' [id="'+t+'"]');if(r){var i=p.createElementNS("http://www.w3.org/2000/svg","a");i.setAttributeNS("http://www.w3.org/2000/svg","class",n.classes.join(" ")),i.setAttributeNS("http://www.w3.org/2000/svg","href",n.link),i.setAttributeNS("http://www.w3.org/2000/svg","rel","noopener"),"sandbox"===h?i.setAttributeNS("http://www.w3.org/2000/svg","target","_top"):n.linkTarget&&i.setAttributeNS("http://www.w3.org/2000/svg","target",n.linkTarget);var a=r.insert((function(){return i}),":first-child"),o=r.select(".label-container");o&&a.append((function(){return o.node()}));var s=r.select(".label");s&&a.append((function(){return s.node()}));}}}));}};var Ia=n(3602),Fa=n.n(Ia);function Ra(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}var Pa,ja,za="",Ya="",Ua="",$a=[],Wa=[],qa={},Ha=[],Va=[],Ga="",Xa=["active","done","crit","milestone"],Za=[],Qa=!1,Ka=!1,Ja=0,to=function(t,e,n,r){return !(r.indexOf(t.format(e.trim()))>=0)&&(t.isoWeekday()>=6&&n.indexOf("weekends")>=0||n.indexOf(t.format("dddd").toLowerCase())>=0||n.indexOf(t.format(e.trim()))>=0)},eo=function(t,e,n,r){if(n.length&&!t.manualEndTime){var a=i()(t.startTime,e,!0);a.add(1,"d");var o=i()(t.endTime,e,!0),s=no(a,o,e,n,r);t.endTime=o.toDate(),t.renderEndTime=s;}},no=function(t,e,n,r,i){for(var a=!1,o=null;t<=e;)a||(o=e.toDate()),(a=to(t,n,r,i))&&e.add(1,"d"),t.add(1,"d");return o},ro=function(t,e,n){n=n.trim();var r=/^after\s+([\d\w- ]+)/.exec(n.trim());if(null!==r){var a=null;if(r[1].split(" ").forEach((function(t){var e=uo(t);void 0!==e&&(a?e.endTime>a.endTime&&(a=e):a=e);})),a)return a.endTime;var s=new Date;return s.setHours(0,0,0,0),s}var c=i()(n,e.trim(),!0);return c.isValid()?c.toDate():(o.debug("Invalid date:"+n),o.debug("With date format:"+e.trim()),new Date)},io=function(t,e){if(null!==t)switch(t[2]){case"ms":e.add(t[1],"milliseconds");break;case"s":e.add(t[1],"seconds");break;case"m":e.add(t[1],"minutes");break;case"h":e.add(t[1],"hours");break;case"d":e.add(t[1],"days");break;case"w":e.add(t[1],"weeks");}return e.toDate()},ao=function(t,e,n,r){r=r||!1,n=n.trim();var a=i()(n,e.trim(),!0);return a.isValid()?(r&&a.add(1,"d"),a.toDate()):io(/^([\d]+)([wdhms]|ms)$/.exec(n.trim()),i()(t))},oo=0,so=function(t){return void 0===t?"task"+(oo+=1):t},co=[],lo={},uo=function(t){var e=lo[t];return co[e]},ho=function(){for(var t=function(t){var e=co[t],n="";switch(co[t].raw.startTime.type){case"prevTaskEnd":var r=uo(e.prevTaskId);e.startTime=r.endTime;break;case"getStartDate":(n=ro(0,za,co[t].raw.startTime.startData))&&(co[t].startTime=n);}return co[t].startTime&&(co[t].endTime=ao(co[t].startTime,za,co[t].raw.endTime.data,Qa),co[t].endTime&&(co[t].processed=!0,co[t].manualEndTime=i()(co[t].raw.endTime.data,"YYYY-MM-DD",!0).isValid(),eo(co[t],za,Wa,$a))),co[t].processed},e=!0,n=0;n<co.length;n++)t(n),e=e&&co[n].processed;return e},fo=function(t,e){t.split(",").forEach((function(t){var n=uo(t);void 0!==n&&n.classes.push(e);}));},po=function(t,e){Za.push((function(){var n=document.querySelector('[id="'.concat(t,'"]'));null!==n&&n.addEventListener("click",(function(){e();}));})),Za.push((function(){var n=document.querySelector('[id="'.concat(t,'-text"]'));null!==n&&n.addEventListener("click",(function(){e();}));}));};const go={parseDirective:function(t,e,n){cu.parseDirective(this,t,e,n);},getConfig:function(){return Xt().gantt},clear:function(){Ha=[],Va=[],Ga="",Za=[],oo=0,Pa=void 0,ja=void 0,co=[],za="",Ya="",Ua="",$a=[],Wa=[],Qa=!1,Ka=!1,Ja=0,qa={},ge();},setDateFormat:function(t){za=t;},getDateFormat:function(){return za},enableInclusiveEndDates:function(){Qa=!0;},endDatesAreInclusive:function(){return Qa},enableTopAxis:function(){Ka=!0;},topAxisEnabled:function(){return Ka},setAxisFormat:function(t){Ya=t;},getAxisFormat:function(){return Ya},setTodayMarker:function(t){Ua=t;},getTodayMarker:function(){return Ua},setAccTitle:ye,getAccTitle:me,setDiagramTitle:_e,getDiagramTitle:xe,setAccDescription:be,getAccDescription:ve,addSection:function(t){Ga=t,Ha.push(t);},getSections:function(){return Ha},getTasks:function(){for(var t=ho(),e=0;!t&&e<10;)t=ho(),e++;return Va=co},addTask:function(t,e){var n={section:Ga,type:Ga,processed:!1,manualEndTime:!1,renderEndTime:null,raw:{data:e},task:t,classes:[]},r=function(t,e){var n=(":"===e.substr(0,1)?e.substr(1,e.length):e).split(","),r={};yo(n,r,Xa);for(var i=0;i<n.length;i++)n[i]=n[i].trim();switch(n.length){case 1:r.id=so(),r.startTime={type:"prevTaskEnd",id:t},r.endTime={data:n[0]};break;case 2:r.id=so(),r.startTime={type:"getStartDate",startData:n[0]},r.endTime={data:n[1]};break;case 3:r.id=so(n[0]),r.startTime={type:"getStartDate",startData:n[1]},r.endTime={data:n[2]};}return r}(ja,e);n.raw.startTime=r.startTime,n.raw.endTime=r.endTime,n.id=r.id,n.prevTaskId=ja,n.active=r.active,n.done=r.done,n.crit=r.crit,n.milestone=r.milestone,n.order=Ja,Ja++;var i=co.push(n);ja=n.id,lo[n.id]=i-1;},findTaskById:uo,addTaskOrg:function(t,e){var n={section:Ga,type:Ga,description:t,task:t,classes:[]},r=function(t,e){var n=(":"===e.substr(0,1)?e.substr(1,e.length):e).split(","),r={};yo(n,r,Xa);for(var a=0;a<n.length;a++)n[a]=n[a].trim();var o="";switch(n.length){case 1:r.id=so(),r.startTime=t.endTime,o=n[0];break;case 2:r.id=so(),r.startTime=ro(0,za,n[0]),o=n[1];break;case 3:r.id=so(n[0]),r.startTime=ro(0,za,n[1]),o=n[2];}return o&&(r.endTime=ao(r.startTime,za,o,Qa),r.manualEndTime=i()(o,"YYYY-MM-DD",!0).isValid(),eo(r,za,Wa,$a)),r}(Pa,e);n.startTime=r.startTime,n.endTime=r.endTime,n.id=r.id,n.active=r.active,n.done=r.done,n.crit=r.crit,n.milestone=r.milestone,Pa=n,Va.push(n);},setIncludes:function(t){$a=t.toLowerCase().split(/[\s,]+/);},getIncludes:function(){return $a},setExcludes:function(t){Wa=t.toLowerCase().split(/[\s,]+/);},getExcludes:function(){return Wa},setClickEvent:function(t,e,n){t.split(",").forEach((function(t){!function(t,e,n){if("loose"===Xt().securityLevel&&void 0!==e){var r=[];if("string"==typeof n){r=n.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);for(var i=0;i<r.length;i++){var a=r[i].trim();'"'===a.charAt(0)&&'"'===a.charAt(a.length-1)&&(a=a.substr(1,a.length-2)),r[i]=a;}}0===r.length&&r.push(t),void 0!==uo(t)&&po(t,(function(){var t;An.runFunc.apply(An,[e].concat(function(t){if(Array.isArray(t))return Ra(t)}(t=r)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return Ra(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return "Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ra(t,e):void 0}}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()));}));}}(t,e,n);})),fo(t,"clickable");},setLink:function(t,e){var n=e;"loose"!==Xt().securityLevel&&(n=(0, je.N)(e)),t.split(",").forEach((function(t){void 0!==uo(t)&&(po(t,(function(){window.open(n,"_self");})),qa[t]=n);})),fo(t,"clickable");},getLinks:function(){return qa},bindFunctions:function(t){Za.forEach((function(e){e(t);}));},durationToDate:io,isInvalidDate:to};function yo(t,e,n){for(var r=!0;r;)r=!1,n.forEach((function(n){var i=new RegExp("^\\s*"+n+"\\s*$");t[0].match(i)&&(e[n]=!0,t.shift(1),r=!0);}));}var mo;const bo={setConf:function(){o.debug("Something is calling, setConf, remove the call");},draw:function(t,e,n,r){var a,o=Xt().gantt,s=Xt().securityLevel;"sandbox"===s&&(a=(0, l.select)("#i"+e));var c="sandbox"===s?(0, l.select)(a.nodes()[0].contentDocument.body):(0, l.select)("body"),u="sandbox"===s?a.nodes()[0].contentDocument:document,h=u.getElementById(e);void 0===(mo=h.parentElement.offsetWidth)&&(mo=1200),void 0!==o.useWidth&&(mo=o.useWidth);var f=r.db.getTasks(),d=f.length*(o.barHeight+o.barGap)+2*o.topPadding;h.setAttribute("viewBox","0 0 "+mo+" "+d);for(var p=c.select('[id="'.concat(e,'"]')),g=(0, l.scaleTime)().domain([(0, l.min)(f,(function(t){return t.startTime})),(0, l.max)(f,(function(t){return t.endTime}))]).rangeRound([0,mo-o.leftPadding-o.rightPadding]),y=[],m=0;m<f.length;m++)y.push(f[m].type);var b=y;y=function(t){for(var e={},n=[],r=0,i=t.length;r<i;++r)Object.prototype.hasOwnProperty.call(e,t[r])||(e[t[r]]=!0,n.push(t[r]));return n}(y),f.sort((function(t,e){var n=t.startTime,r=e.startTime,i=0;return n>r?i=1:n<r&&(i=-1),i})),function(t,n,a){var s=o.barHeight,c=s+o.barGap,h=o.topPadding,f=o.leftPadding;(0, l.scaleLinear)().domain([0,y.length]).range(["#00B9FA","#F95002"]).interpolate(l.interpolateHcl),function(t,e,n,a,s,c,l,u){var h=c.reduce((function(t,e){var n=e.startTime;return t?Math.min(t,n):n}),0),f=c.reduce((function(t,e){var n=e.endTime;return t?Math.max(t,n):n}),0),d=r.db.getDateFormat();if(h&&f){for(var y=[],m=null,b=i()(h);b.valueOf()<=f;)r.db.isInvalidDate(b,d,l,u)?m?m.end=b.clone():m={start:b.clone(),end:b.clone()}:m&&(y.push(m),m=null),b.add(1,"d");p.append("g").selectAll("rect").data(y).enter().append("rect").attr("id",(function(t){return "exclude-"+t.start.format("YYYY-MM-DD")})).attr("x",(function(t){return g(t.start)+n})).attr("y",o.gridLineStartPadding).attr("width",(function(t){var e=t.end.clone().add(1,"day");return g(e)-g(t.start)})).attr("height",s-e-o.gridLineStartPadding).attr("transform-origin",(function(e,r){return (g(e.start)+n+.5*(g(e.end)-g(e.start))).toString()+"px "+(r*t+.5*s).toString()+"px"})).attr("class","exclude-range");}}(c,h,f,0,a,t,r.db.getExcludes(),r.db.getIncludes()),function(t,e,n,i){var a=(0, l.axisBottom)(g).tickSize(-i+e+o.gridLineStartPadding).tickFormat((0, l.timeFormat)(r.db.getAxisFormat()||o.axisFormat||"%Y-%m-%d"));if(p.append("g").attr("class","grid").attr("transform","translate("+t+", "+(i-50)+")").call(a).selectAll("text").style("text-anchor","middle").attr("fill","#000").attr("stroke","none").attr("font-size",10).attr("dy","1em"),r.db.topAxisEnabled()||o.topAxis){var s=(0, l.axisTop)(g).tickSize(-i+e+o.gridLineStartPadding).tickFormat((0, l.timeFormat)(r.db.getAxisFormat()||o.axisFormat||"%Y-%m-%d"));p.append("g").attr("class","grid").attr("transform","translate("+t+", "+e+")").call(s).selectAll("text").style("text-anchor","middle").attr("fill","#000").attr("stroke","none").attr("font-size",10);}}(f,h,0,a),function(t,n,i,a,s,c,u){p.append("g").selectAll("rect").data(t).enter().append("rect").attr("x",0).attr("y",(function(t,e){return t.order*n+i-2})).attr("width",(function(){return u-o.rightPadding/2})).attr("height",n).attr("class",(function(t){for(var e=0;e<y.length;e++)if(t.type===y[e])return "section section"+e%o.numberSectionStyles;return "section section0"}));var h=p.append("g").selectAll("rect").data(t).enter(),f=r.db.getLinks();if(h.append("rect").attr("id",(function(t){return t.id})).attr("rx",3).attr("ry",3).attr("x",(function(t){return t.milestone?g(t.startTime)+a+.5*(g(t.endTime)-g(t.startTime))-.5*s:g(t.startTime)+a})).attr("y",(function(t,e){return t.order*n+i})).attr("width",(function(t){return t.milestone?s:g(t.renderEndTime||t.endTime)-g(t.startTime)})).attr("height",s).attr("transform-origin",(function(t,e){return e=t.order,(g(t.startTime)+a+.5*(g(t.endTime)-g(t.startTime))).toString()+"px "+(e*n+i+.5*s).toString()+"px"})).attr("class",(function(t){var e="";t.classes.length>0&&(e=t.classes.join(" "));for(var n=0,r=0;r<y.length;r++)t.type===y[r]&&(n=r%o.numberSectionStyles);var i="";return t.active?t.crit?i+=" activeCrit":i=" active":t.done?i=t.crit?" doneCrit":" done":t.crit&&(i+=" crit"),0===i.length&&(i=" task"),t.milestone&&(i=" milestone "+i),"task"+(i+=n)+" "+e})),h.append("text").attr("id",(function(t){return t.id+"-text"})).text((function(t){return t.task})).attr("font-size",o.fontSize).attr("x",(function(t){var e=g(t.startTime),n=g(t.renderEndTime||t.endTime);t.milestone&&(e+=.5*(g(t.endTime)-g(t.startTime))-.5*s),t.milestone&&(n=e+s);var r=this.getBBox().width;return r>n-e?n+r+1.5*o.leftPadding>u?e+a-5:n+a+5:(n-e)/2+e+a})).attr("y",(function(t,e){return t.order*n+o.barHeight/2+(o.fontSize/2-2)+i})).attr("text-height",s).attr("class",(function(t){var e=g(t.startTime),n=g(t.endTime);t.milestone&&(n=e+s);var r=this.getBBox().width,i="";t.classes.length>0&&(i=t.classes.join(" "));for(var a=0,c=0;c<y.length;c++)t.type===y[c]&&(a=c%o.numberSectionStyles);var l="";return t.active&&(l=t.crit?"activeCritText"+a:"activeText"+a),t.done?l=t.crit?l+" doneCritText"+a:l+" doneText"+a:t.crit&&(l=l+" critText"+a),t.milestone&&(l+=" milestoneText"),r>n-e?n+r+1.5*o.leftPadding>u?i+" taskTextOutsideLeft taskTextOutside"+a+" "+l:i+" taskTextOutsideRight taskTextOutside"+a+" "+l+" width-"+r:i+" taskText taskText"+a+" "+l+" width-"+r})),"sandbox"===Xt().securityLevel){var d;d=(0, l.select)("#i"+e),(0, l.select)(d.nodes()[0].contentDocument.body);var m=d.nodes()[0].contentDocument;h.filter((function(t){return void 0!==f[t.id]})).each((function(t){var e=m.querySelector("#"+t.id),n=m.querySelector("#"+t.id+"-text"),r=e.parentNode,i=m.createElement("a");i.setAttribute("xlink:href",f[t.id]),i.setAttribute("target","_top"),r.appendChild(i),i.appendChild(e),i.appendChild(n);}));}}(t,c,h,f,s,0,n),function(t,e){for(var n=[],r=0,i=0;i<y.length;i++)n[i]=[y[i],(a=y[i],s=b,function(t){for(var e=t.length,n={};e;)n[t[--e]]=(n[t[e]]||0)+1;return n}(s)[a]||0)];var a,s;p.append("g").selectAll("text").data(n).enter().append((function(t){var e=t[0].split(ue.lineBreakRegex),n=-(e.length-1)/2,r=u.createElementNS("http://www.w3.org/2000/svg","text");r.setAttribute("dy",n+"em");for(var i=0;i<e.length;i++){var a=u.createElementNS("http://www.w3.org/2000/svg","tspan");a.setAttribute("alignment-baseline","central"),a.setAttribute("x","10"),i>0&&a.setAttribute("dy","1em"),a.textContent=e[i],r.appendChild(a);}return r})).attr("x",10).attr("y",(function(i,a){if(!(a>0))return i[1]*t/2+e;for(var o=0;o<a;o++)return r+=n[a-1][1],i[1]*t/2+r*t+e})).attr("font-size",o.sectionFontSize).attr("font-size",o.sectionFontSize).attr("class",(function(t){for(var e=0;e<y.length;e++)if(t[0]===y[e])return "sectionTitle sectionTitle"+e%o.numberSectionStyles;return "sectionTitle"}));}(c,h),function(t,e,n,i){var a=r.db.getTodayMarker();if("off"!==a){var s=p.append("g").attr("class","today"),c=new Date,l=s.append("line");l.attr("x1",g(c)+t).attr("x2",g(c)+t).attr("y1",o.titleTopMargin).attr("y2",i-o.titleTopMargin).attr("class","today"),""!==a&&l.attr("style",a.replace(/,/g,";"));}}(f,0,0,a);}(f,mo,d),Tn(p,0,mo,o.useMaxWidth),p.append("text").text(r.db.getDiagramTitle()).attr("x",mo/2).attr("y",o.titleTopMargin).attr("class","titleText"),Mn(r.db,p,e);}};var vo=n(9959),_o=n.n(vo),xo="",ko=!1;const wo={setMessage:function(t){o.debug("Setting message to: "+t),xo=t;},getMessage:function(){return xo},setInfo:function(t){ko=t;},getInfo:function(){return ko}},To={draw:function(t,e,n,r){try{o.debug("Renering info diagram\n"+t);var i,a=Xt().securityLevel;"sandbox"===a&&(i=(0,l.select)("#i"+e));var s="sandbox"===a?(0,l.select)(i.nodes()[0].contentDocument.body):(0,l.select)("body"),c=("sandbox"===a?i.nodes()[0].contentDocument:document,s.select("#"+e));c.append("g").append("text").attr("x",100).attr("y",40).attr("class","version").attr("font-size","32px").style("text-anchor","middle").text("v "+n),c.attr("height",100),c.attr("width",400);}catch(t){o.error("Error while rendering info diagram"),o.error(t.message);}}};var Eo=n(6765),Co=n.n(Eo),So=n(7062),Ao=n.n(So),Mo={},No=!1;const Oo={parseDirective:function(t,e,n){cu.parseDirective(this,t,e,n);},getConfig:function(){return Xt().pie},addSection:function(t,e){t=ue.sanitizeText(t,Xt()),void 0===Mo[t]&&(Mo[t]=e,o.debug("Added new section :",t));},getSections:function(){return Mo},cleanupValue:function(t){return ":"===t.substring(0,1)?(t=t.substring(1).trim(),Number(t.trim())):Number(t.trim())},clear:function(){Mo={},No=!1,ge();},setAccTitle:ye,getAccTitle:me,setDiagramTitle:_e,getDiagramTitle:xe,setShowData:function(t){No=t;},getShowData:function(){return No},getAccDescription:ve,setAccDescription:be};var Do,Bo=Xt();const Lo={draw:function(t,e,n,r){try{Bo=Xt(),o.debug("Rendering info diagram\n"+t);var i,a=Xt().securityLevel;"sandbox"===a&&(i=(0,l.select)("#i"+e));var s="sandbox"===a?(0,l.select)(i.nodes()[0].contentDocument.body):(0,l.select)("body"),c="sandbox"===a?i.nodes()[0].contentDocument:document;r.db.clear(),r.parser.parse(t),o.debug("Parsed info diagram");var u=c.getElementById(e);void 0===(Do=u.parentElement.offsetWidth)&&(Do=1200),void 0!==Bo.useWidth&&(Do=Bo.useWidth),void 0!==Bo.pie.useWidth&&(Do=Bo.pie.useWidth);var h=s.select("#"+e);Tn(h,0,Do,Bo.pie.useMaxWidth),Mn(r.db,h,e),u.setAttribute("viewBox","0 0 "+Do+" 450");var f=Math.min(Do,450)/2-40,d=h.append("g").attr("transform","translate("+Do/2+",225)"),p=r.db.getSections(),g=0;Object.keys(p).forEach((function(t){g+=p[t];}));var y=Bo.themeVariables,m=[y.pie1,y.pie2,y.pie3,y.pie4,y.pie5,y.pie6,y.pie7,y.pie8,y.pie9,y.pie10,y.pie11,y.pie12],b=(0,l.scaleOrdinal)().range(m),v=(0,l.pie)().value((function(t){return t[1]}))(Object.entries(p)),_=(0,l.arc)().innerRadius(0).outerRadius(f);d.selectAll("mySlices").data(v).enter().append("path").attr("d",_).attr("fill",(function(t){return b(t.data[0])})).attr("class","pieCircle"),d.selectAll("mySlices").data(v).enter().append("text").text((function(t){return (t.data[1]/g*100).toFixed(0)+"%"})).attr("transform",(function(t){return "translate("+_.centroid(t)+")"})).style("text-anchor","middle").attr("class","slice"),d.append("text").text(r.db.getDiagramTitle()).attr("x",0).attr("y",-200).attr("class","pieTitleText");var x=d.selectAll(".legend").data(b.domain()).enter().append("g").attr("class","legend").attr("transform",(function(t,e){return "translate(216,"+(22*e-22*b.domain().length/2)+")"}));x.append("rect").attr("width",18).attr("height",18).style("fill",b).style("stroke",b),x.data(v).append("text").attr("x",22).attr("y",14).text((function(t){return r.db.getShowData()||Bo.showData||Bo.pie.showData?t.data[0]+" ["+t.data[1]+"]":t.data[0]}));}catch(t){o.error("Error while rendering info diagram"),o.error(t);}}};var Io=n(3176),Fo=n.n(Io),Ro=[],Po={},jo={},zo={},Yo={};const Uo={RequirementType:{REQUIREMENT:"Requirement",FUNCTIONAL_REQUIREMENT:"Functional Requirement",INTERFACE_REQUIREMENT:"Interface Requirement",PERFORMANCE_REQUIREMENT:"Performance Requirement",PHYSICAL_REQUIREMENT:"Physical Requirement",DESIGN_CONSTRAINT:"Design Constraint"},RiskLevel:{LOW_RISK:"Low",MED_RISK:"Medium",HIGH_RISK:"High"},VerifyType:{VERIFY_ANALYSIS:"Analysis",VERIFY_DEMONSTRATION:"Demonstration",VERIFY_INSPECTION:"Inspection",VERIFY_TEST:"Test"},Relationships:{CONTAINS:"contains",COPIES:"copies",DERIVES:"derives",SATISFIES:"satisfies",VERIFIES:"verifies",REFINES:"refines",TRACES:"traces"},parseDirective:function(t,e,n){cu.parseDirective(this,t,e,n);},getConfig:function(){return Xt().req},addRequirement:function(t,e){return void 0===jo[t]&&(jo[t]={name:t,type:e,id:Po.id,text:Po.text,risk:Po.risk,verifyMethod:Po.verifyMethod}),Po={},jo[t]},getRequirements:function(){return jo},setNewReqId:function(t){void 0!==Po&&(Po.id=t);},setNewReqText:function(t){void 0!==Po&&(Po.text=t);},setNewReqRisk:function(t){void 0!==Po&&(Po.risk=t);},setNewReqVerifyMethod:function(t){void 0!==Po&&(Po.verifyMethod=t);},setAccTitle:ye,getAccTitle:me,setAccDescription:be,getAccDescription:ve,addElement:function(t){return void 0===Yo[t]&&(Yo[t]={name:t,type:zo.type,docRef:zo.docRef},o.info("Added new requirement: ",t)),zo={},Yo[t]},getElements:function(){return Yo},setNewElementType:function(t){void 0!==zo&&(zo.type=t);},setNewElementDocRef:function(t){void 0!==zo&&(zo.docRef=t);},addRelationship:function(t,e,n){Ro.push({type:t,src:e,dst:n});},getRelationships:function(){return Ro},clear:function(){Ro=[],Po={},jo={},zo={},Yo={},ge();}};var $o={CONTAINS:"contains",ARROW:"arrow"};const Wo=$o;var qo={},Ho=0,Vo=function(t,e){return t.insert("rect","#"+e).attr("class","req reqBox").attr("x",0).attr("y",0).attr("width",qo.rect_min_width+"px").attr("height",qo.rect_min_height+"px")},Go=function(t,e,n){var r=qo.rect_min_width/2,i=t.append("text").attr("class","req reqLabel reqTitle").attr("id",e).attr("x",r).attr("y",qo.rect_padding).attr("dominant-baseline","hanging"),a=0;n.forEach((function(t){0==a?i.append("tspan").attr("text-anchor","middle").attr("x",qo.rect_min_width/2).attr("dy",0).text(t):i.append("tspan").attr("text-anchor","middle").attr("x",qo.rect_min_width/2).attr("dy",.75*qo.line_height).text(t),a++;}));var o=1.5*qo.rect_padding+a*qo.line_height*.75;return t.append("line").attr("class","req-title-line").attr("x1","0").attr("x2",qo.rect_min_width).attr("y1",o).attr("y2",o),{titleNode:i,y:o}},Xo=function(t,e,n,r){var i=t.append("text").attr("class","req reqLabel").attr("id",e).attr("x",qo.rect_padding).attr("y",r).attr("dominant-baseline","hanging"),a=0,o=[];return n.forEach((function(t){for(var e=t.length;e>30&&a<3;){var n=t.substring(0,30);e=(t=t.substring(30,t.length)).length,o[o.length]=n,a++;}if(3==a){var r=o[o.length-1];o[o.length-1]=r.substring(0,r.length-4)+"...";}else o[o.length]=t;a=0;})),o.forEach((function(t){i.append("tspan").attr("x",qo.rect_padding).attr("dy",qo.line_height).text(t);})),i},Zo=function(t){return t.replace(/\s/g,"").replace(/\./g,"_")};const Qo={draw:function(t,e,n,r){qo=Xt().requirement,r.db.clear(),r.parser.parse(t);var i,a=qo.securityLevel;"sandbox"===a&&(i=(0, l.select)("#i"+e));var s="sandbox"===a?(0, l.select)(i.nodes()[0].contentDocument.body):(0, l.select)("body"),c=("sandbox"===a?i.nodes()[0].contentDocument:document,s.select("[id='".concat(e,"']")));!function(t,e){var n=t.append("defs").append("marker").attr("id",$o.CONTAINS+"_line_ending").attr("refX",0).attr("refY",e.line_height/2).attr("markerWidth",e.line_height).attr("markerHeight",e.line_height).attr("orient","auto").append("g");n.append("circle").attr("cx",e.line_height/2).attr("cy",e.line_height/2).attr("r",e.line_height/2).attr("fill","none"),n.append("line").attr("x1",0).attr("x2",e.line_height).attr("y1",e.line_height/2).attr("y2",e.line_height/2).attr("stroke-width",1),n.append("line").attr("y1",0).attr("y2",e.line_height).attr("x1",e.line_height/2).attr("x2",e.line_height/2).attr("stroke-width",1),t.append("defs").append("marker").attr("id",$o.ARROW+"_line_ending").attr("refX",e.line_height).attr("refY",.5*e.line_height).attr("markerWidth",e.line_height).attr("markerHeight",e.line_height).attr("orient","auto").append("path").attr("d","M0,0\n L".concat(e.line_height,",").concat(e.line_height/2,"\n M").concat(e.line_height,",").concat(e.line_height/2,"\n L0,").concat(e.line_height)).attr("stroke-width",1);}(c,qo);var u,h,f,d=new(yr().Graph)({multigraph:!1,compound:!1,directed:!0}).setGraph({rankdir:qo.layoutDirection,marginx:20,marginy:20,nodesep:100,edgesep:100,ranksep:100}).setDefaultEdgeLabel((function(){return {}})),p=r.db.getRequirements(),g=r.db.getElements(),y=r.db.getRelationships();u=p,h=d,f=c,Object.keys(u).forEach((function(t){var e=u[t];t=Zo(t),o.info("Added new requirement: ",t);var n=f.append("g").attr("id",t),r=Vo(n,"req-"+t),a=Go(n,t+"_title",["<<".concat(e.type,">>"),"".concat(e.name)]);var s=Xo(n,t+"_body",["Id: ".concat(e.id),"Text: ".concat(e.text),"Risk: ".concat(e.risk),"Verification: ".concat(e.verifyMethod)],a.y);var c=r.node().getBBox();h.setNode(t,{width:c.width,height:c.height,shape:"rect",id:t});})),function(t,e,n){Object.keys(t).forEach((function(r){var i=t[r],a=Zo(r),o=n.append("g").attr("id",a),s="element-"+a,c=Vo(o,s),u=Go(o,s+"_title",["<<Element>>","".concat(r)]);var h=Xo(o,s+"_body",["Type: ".concat(i.type||"Not Specified"),"Doc Ref: ".concat(i.docRef||"None")],u.y);var f=c.node().getBBox();e.setNode(a,{width:f.width,height:f.height,shape:"rect",id:a});}));}(g,d,c),function(t,e){t.forEach((function(t){var n=Zo(t.src),r=Zo(t.dst);e.setEdge(n,r,{relationship:t});}));}(y,d),pr().layout(d),function(t,e){e.nodes().forEach((function(n){void 0!==n&&void 0!==e.node(n)&&(t.select("#"+n),t.select("#"+n).attr("transform","translate("+(e.node(n).x-e.node(n).width/2)+","+(e.node(n).y-e.node(n).height/2)+" )"));}));}(c,d),y.forEach((function(t){!function(t,e,n,r,i){var a=n.edge(Zo(e.src),Zo(e.dst)),o=(0, l.line)().x((function(t){return t.x})).y((function(t){return t.y})),s=t.insert("path","#"+r).attr("class","er relationshipLine").attr("d",o(a.points)).attr("fill","none");e.type==i.db.Relationships.CONTAINS?s.attr("marker-start","url("+ue.getUrl(qo.arrowMarkerAbsolute)+"#"+e.type+"_line_ending)"):(s.attr("stroke-dasharray","10,7"),s.attr("marker-end","url("+ue.getUrl(qo.arrowMarkerAbsolute)+"#"+Wo.ARROW+"_line_ending)")),function(t,e,n,r){var i=e.node().getTotalLength(),a=e.node().getPointAtLength(.5*i),o="rel"+Ho;Ho++;var s=t.append("text").attr("class","req relationshipLabel").attr("id",o).attr("x",a.x).attr("y",a.y).attr("text-anchor","middle").attr("dominant-baseline","middle").text(r).node().getBBox();t.insert("rect","#"+o).attr("class","req reqLabelBox").attr("x",a.x-s.width/2).attr("y",a.y-s.height/2).attr("width",s.width).attr("height",s.height).attr("fill","white").attr("fill-opacity","85%");}(t,s,0,"<<".concat(e.type,">>"));}(c,t,d,e,r);}));var m=qo.rect_padding,b=c.node().getBBox(),v=b.width+2*m,_=b.height+2*m;Tn(c,0,v,qo.useMaxWidth),c.attr("viewBox","".concat(b.x-m," ").concat(b.y-m," ").concat(v," ").concat(_)),Mn(r.db,c,e);}};var Ko,Jo=n(6876),ts=n.n(Jo),es=void 0,ns={},rs=[],as=!1,os=function(t,e,n,r){var i=ns[t];i&&e===i.name&&null==n||(null!=n&&null!=n.text||(n={text:e,wrap:null,type:r}),null!=r&&null!=n.text||(n={text:e,wrap:null,type:r}),ns[t]={name:e,description:n.text,wrap:void 0===n.wrap&&us()||!!n.wrap,prevActor:es,links:{},properties:{},actorCnt:null,rectData:null,type:r||"participant"},es&&ns[es]&&(ns[es].nextActor=t),es=t);},ss=function(t){var e,n=0;for(e=0;e<rs.length;e++)rs[e].type===hs.ACTIVE_START&&rs[e].from.actor===t&&n++,rs[e].type===hs.ACTIVE_END&&rs[e].from.actor===t&&n--;return n},cs=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{text:void 0,wrap:void 0},r=arguments.length>3?arguments[3]:void 0;if(r===hs.ACTIVE_END){var i=ss(t.actor);if(i<1){var a=new Error("Trying to inactivate an inactive participant ("+t.actor+")");throw a.hash={text:"->>-",token:"->>-",line:"1",loc:{first_line:1,last_line:1,first_column:1,last_column:1},expected:["'ACTIVE_PARTICIPANT'"]},a}}return rs.push({from:t,to:e,message:n.text,wrap:void 0===n.wrap&&us()||!!n.wrap,type:r}),!0},ls=function(t){return ns[t]},us=function(){return void 0!==Ko?Ko:Xt().sequence.wrap},hs={SOLID:0,DOTTED:1,NOTE:2,SOLID_CROSS:3,DOTTED_CROSS:4,SOLID_OPEN:5,DOTTED_OPEN:6,LOOP_START:10,LOOP_END:11,ALT_START:12,ALT_ELSE:13,ALT_END:14,OPT_START:15,OPT_END:16,ACTIVE_START:17,ACTIVE_END:18,PAR_START:19,PAR_AND:20,PAR_END:21,RECT_START:22,RECT_END:23,SOLID_POINT:24,DOTTED_POINT:25,AUTONUMBER:26,CRITICAL_START:27,CRITICAL_OPTION:28,CRITICAL_END:29,BREAK_START:30,BREAK_END:31},fs=function(t,e,n){var r={actor:t,placement:e,message:n.text,wrap:void 0===n.wrap&&us()||!!n.wrap},i=[].concat(t,t);rs.push({from:i[0],to:i[1],message:n.text,wrap:void 0===n.wrap&&us()||!!n.wrap,type:hs.NOTE,placement:e});},ds=function(t,e){var n=ls(t);try{var r=ie(e.text,Xt());r=(r=r.replace(/&amp;/g,"&")).replace(/&equals;/g,"="),ps(n,JSON.parse(r));}catch(t){o.error("error while parsing actor link text",t);}};function ps(t,e){if(null==t.links)t.links=e;else for(var n in e)t.links[n]=e[n];}var gs=function(t,e){var n=ls(t);try{var r=ie(e.text,Xt());ys(n,JSON.parse(r));}catch(t){o.error("error while parsing actor properties text",t);}};function ys(t,e){if(null==t.properties)t.properties=e;else for(var n in e)t.properties[n]=e[n];}var ms=function(t,e){var n=ls(t),r=document.getElementById(e.text);try{var i=r.innerHTML,a=JSON.parse(i);a.properties&&ys(n,a.properties),a.links&&ps(n,a.links);}catch(t){o.error("error while parsing actor details text",t);}};const bs={addActor:os,addMessage:function(t,e,n,r){rs.push({from:t,to:e,message:n.text,wrap:void 0===n.wrap&&us()||!!n.wrap,answer:r});},addSignal:cs,addLinks:ds,addDetails:ms,addProperties:gs,autoWrap:us,setWrap:function(t){Ko=t;},enableSequenceNumbers:function(){as=!0;},disableSequenceNumbers:function(){as=!1;},showSequenceNumbers:function(){return as},getMessages:function(){return rs},getActors:function(){return ns},getActor:ls,getActorKeys:function(){return Object.keys(ns)},getActorProperty:function(t,e){if(void 0!==t&&void 0!==t.properties)return t.properties[e]},getAccTitle:me,getDiagramTitle:xe,setDiagramTitle:_e,parseDirective:function(t,e,n){cu.parseDirective(this,t,e,n);},getConfig:function(){return Xt().sequence},clear:function(){ns={},rs=[],as=!1,ge();},parseMessage:function(t){var e=t.trim(),n={text:e.replace(/^[:]?(?:no)?wrap:/,"").trim(),wrap:null!==e.match(/^[:]?wrap:/)||null===e.match(/^[:]?nowrap:/)&&void 0};return o.debug("parseMessage:",n),n},LINETYPE:hs,ARROWTYPE:{FILLED:0,OPEN:1},PLACEMENT:{LEFTOF:0,RIGHTOF:1,OVER:2},addNote:fs,setAccTitle:ye,apply:function t(e){if(e instanceof Array)e.forEach((function(e){t(e);}));else switch(e.type){case"sequenceIndex":rs.push({from:void 0,to:void 0,message:{start:e.sequenceIndex,step:e.sequenceIndexStep,visible:e.sequenceVisible},wrap:!1,type:e.signalType});break;case"addParticipant":os(e.actor,e.actor,e.description,"participant");break;case"addActor":os(e.actor,e.actor,e.description,"actor");break;case"activeStart":case"activeEnd":cs(e.actor,void 0,void 0,e.signalType);break;case"addNote":fs(e.actor,e.placement,e.text);break;case"addLinks":ds(e.actor,e.text);break;case"addALink":!function(t,e){var n=ls(t);try{var r={},i=ie(e.text,Xt()),a=i.indexOf("@"),s=(i=(i=i.replace(/&amp;/g,"&")).replace(/&equals;/g,"=")).slice(0,a-1).trim(),c=i.slice(a+1).trim();r[s]=c,ps(n,r);}catch(t){o.error("error while parsing actor link text",t);}}(e.actor,e.text);break;case"addProperties":gs(e.actor,e.text);break;case"addDetails":ms(e.actor,e.text);break;case"addMessage":cs(e.from,e.to,e.msg,e.signalType);break;case"loopStart":cs(void 0,void 0,e.loopText,e.signalType);break;case"loopEnd":case"rectEnd":case"optEnd":case"altEnd":case"parEnd":case"criticalEnd":case"breakEnd":cs(void 0,void 0,void 0,e.signalType);break;case"rectStart":cs(void 0,void 0,e.color,e.signalType);break;case"optStart":cs(void 0,void 0,e.optText,e.signalType);break;case"altStart":case"else":cs(void 0,void 0,e.altText,e.signalType);break;case"setAccTitle":ye(e.text);break;case"parStart":case"and":cs(void 0,void 0,e.parText,e.signalType);break;case"criticalStart":cs(void 0,void 0,e.criticalText,e.signalType);break;case"option":cs(void 0,void 0,e.optionText,e.signalType);break;case"breakStart":cs(void 0,void 0,e.breakText,e.signalType);}},setAccDescription:be,getAccDescription:ve};var vs=[],_s=function(t,e){var n=t.append("rect");return n.attr("x",e.x),n.attr("y",e.y),n.attr("fill",e.fill),n.attr("stroke",e.stroke),n.attr("width",e.width),n.attr("height",e.height),n.attr("rx",e.rx),n.attr("ry",e.ry),void 0!==e.class&&n.attr("class",e.class),n},xs=function(t,e){var n;n=function(){var n=document.querySelectorAll(t);0!==n.length&&(n[0].addEventListener("mouseover",(function(){Ts("actor"+e+"_popup");})),n[0].addEventListener("mouseout",(function(){Es("actor"+e+"_popup");})));},vs.push(n);},ks=function(t,e,n,r){var i=t.append("image");i.attr("x",e),i.attr("y",n);var a=(0, je.N)(r);i.attr("xlink:href",a);},ws=function(t,e,n,r){var i=t.append("use");i.attr("x",e),i.attr("y",n);var a=(0, je.N)(r);i.attr("xlink:href","#"+a);},Ts=function(t){var e=document.getElementById(t);null!=e&&(e.style.display="block");},Es=function(t){var e=document.getElementById(t);null!=e&&(e.style.display="none");},Cs=function(t,e){var n=0,r=0,i=e.text.split(ue.lineBreakRegex),a=[],o=0,s=function(){return e.y};if(void 0!==e.valign&&void 0!==e.textMargin&&e.textMargin>0)switch(e.valign){case"top":case"start":s=function(){return Math.round(e.y+e.textMargin)};break;case"middle":case"center":s=function(){return Math.round(e.y+(n+r+e.textMargin)/2)};break;case"bottom":case"end":s=function(){return Math.round(e.y+(n+r+2*e.textMargin)-e.textMargin)};}if(void 0!==e.anchor&&void 0!==e.textMargin&&void 0!==e.width)switch(e.anchor){case"left":case"start":e.x=Math.round(e.x+e.textMargin),e.anchor="start",e.dominantBaseline="middle",e.alignmentBaseline="middle";break;case"middle":case"center":e.x=Math.round(e.x+e.width/2),e.anchor="middle",e.dominantBaseline="middle",e.alignmentBaseline="middle";break;case"right":case"end":e.x=Math.round(e.x+e.width-e.textMargin),e.anchor="end",e.dominantBaseline="middle",e.alignmentBaseline="middle";}for(var c=0;c<i.length;c++){var l=i[c];void 0!==e.textMargin&&0===e.textMargin&&void 0!==e.fontSize&&(o=c*e.fontSize);var u=t.append("text");if(u.attr("x",e.x),u.attr("y",s()),void 0!==e.anchor&&u.attr("text-anchor",e.anchor).attr("dominant-baseline",e.dominantBaseline).attr("alignment-baseline",e.alignmentBaseline),void 0!==e.fontFamily&&u.style("font-family",e.fontFamily),void 0!==e.fontSize&&u.style("font-size",e.fontSize),void 0!==e.fontWeight&&u.style("font-weight",e.fontWeight),void 0!==e.fill&&u.attr("fill",e.fill),void 0!==e.class&&u.attr("class",e.class),void 0!==e.dy?u.attr("dy",e.dy):0!==o&&u.attr("dy",o),e.tspan){var h=u.append("tspan");h.attr("x",e.x),void 0!==e.fill&&h.attr("fill",e.fill),h.text(l);}else u.text(l);void 0!==e.valign&&void 0!==e.textMargin&&e.textMargin>0&&(r+=(u._groups||u)[0][0].getBBox().height,n=r),a.push(u);}return a},Ss=function(t,e){var n=t.append("polygon");return n.attr("points",function(t,e,n,r,i){return t+","+e+" "+(t+n)+","+e+" "+(t+n)+","+(e+r-7)+" "+(t+n-8.4)+","+(e+r)+" "+t+","+(e+r)}(e.x,e.y,e.width,e.height)),n.attr("class","labelBox"),e.y=e.y+e.height/2,Cs(t,e),n},As=-1,Ms=function(t,e){t.selectAll&&t.selectAll(".actor-line").attr("class","200").attr("y2",e-55);},Ns=function(){return {x:0,y:0,fill:void 0,anchor:void 0,style:"#666",width:void 0,height:void 0,textMargin:0,rx:0,ry:0,tspan:!0,valign:void 0}},Os=function(){return {x:0,y:0,fill:"#EDF2AE",stroke:"#666",width:100,anchor:"start",height:100,rx:0,ry:0}},Ds=function(){function t(t,e,n,i,a,o,s){r(e.append("text").attr("x",n+a/2).attr("y",i+o/2+5).style("text-anchor","middle").text(t),s);}function e(t,e,n,i,a,o,s,c){for(var l=c.actorFontSize,u=c.actorFontFamily,h=c.actorFontWeight,f=l&&l.replace?l.replace("px",""):l,d=t.split(ue.lineBreakRegex),p=0;p<d.length;p++){var g=p*f-f*(d.length-1)/2,y=e.append("text").attr("x",n+a/2).attr("y",i).style("text-anchor","middle").style("font-size",l).style("font-weight",h).style("font-family",u);y.append("tspan").attr("x",n+a/2).attr("dy",g).text(d[p]),y.attr("y",i+o/2).attr("dominant-baseline","central").attr("alignment-baseline","central"),r(y,s);}}function n(t,n,i,a,o,s,c,l){var u=n.append("switch"),h=u.append("foreignObject").attr("x",i).attr("y",a).attr("width",o).attr("height",s).append("xhtml:div").style("display","table").style("height","100%").style("width","100%");h.append("div").style("display","table-cell").style("text-align","center").style("vertical-align","middle").text(t),e(t,u,i,a,o,s,c,l),r(h,c);}function r(t,e){for(var n in e)e.hasOwnProperty(n)&&t.attr(n,e[n]);}return function(r){return "fo"===r.textPlacement?n:"old"===r.textPlacement?t:e}}(),Bs=function(){function t(t,e,n,i,a,o,s){r(e.append("text").attr("x",n).attr("y",i).style("text-anchor","start").text(t),s);}function e(t,e,n,i,a,o,s,c){for(var l=c.actorFontSize,u=c.actorFontFamily,h=c.actorFontWeight,f=t.split(ue.lineBreakRegex),d=0;d<f.length;d++){var p=d*l-l*(f.length-1)/2,g=e.append("text").attr("x",n).attr("y",i).style("text-anchor","start").style("font-size",l).style("font-weight",h).style("font-family",u);g.append("tspan").attr("x",n).attr("dy",p).text(f[d]),g.attr("y",i+o/2).attr("dominant-baseline","central").attr("alignment-baseline","central"),r(g,s);}}function n(t,n,i,a,o,s,c,l){var u=n.append("switch"),h=u.append("foreignObject").attr("x",i).attr("y",a).attr("width",o).attr("height",s).append("xhtml:div").style("display","table").style("height","100%").style("width","100%");h.append("div").style("display","table-cell").style("text-align","center").style("vertical-align","middle").text(t),e(t,u,i,a,0,s,c,l),r(h,c);}function r(t,e){for(var n in e)e.hasOwnProperty(n)&&t.attr(n,e[n]);}return function(r){return "fo"===r.textPlacement?n:"old"===r.textPlacement?t:e}}();const Ls=_s,Is=function(t,e,n){switch(e.type){case"actor":return function(t,e,n){var r=e.x+e.width/2;0===e.y&&(As++,t.append("line").attr("id","actor"+As).attr("x1",r).attr("y1",80).attr("x2",r).attr("y2",2e3).attr("class","actor-line").attr("stroke-width","0.5px").attr("stroke","#999"));var i=t.append("g");i.attr("class","actor-man");var a={x:0,y:0,fill:"#EDF2AE",stroke:"#666",width:100,anchor:"start",height:100,rx:0,ry:0};a.x=e.x,a.y=e.y,a.fill="#eaeaea",a.width=e.width,a.height=e.height,a.class="actor",a.rx=3,a.ry=3,i.append("line").attr("id","actor-man-torso"+As).attr("x1",r).attr("y1",e.y+25).attr("x2",r).attr("y2",e.y+45),i.append("line").attr("id","actor-man-arms"+As).attr("x1",r-18).attr("y1",e.y+33).attr("x2",r+18).attr("y2",e.y+33),i.append("line").attr("x1",r-18).attr("y1",e.y+60).attr("x2",r).attr("y2",e.y+45),i.append("line").attr("x1",r).attr("y1",e.y+45).attr("x2",r+16).attr("y2",e.y+60);var o=i.append("circle");o.attr("cx",e.x+e.width/2),o.attr("cy",e.y+10),o.attr("r",15),o.attr("width",e.width),o.attr("height",e.height);var s=i.node().getBBox();return e.height=s.height,Ds(n)(e.description,i,a.x,a.y+35,a.width,a.height,{class:"actor"},n),e.height}(t,e,n);case"participant":return function(t,e,n){var r=e.x+e.width/2,i=t.append("g"),a=i;0===e.y&&(As++,a.append("line").attr("id","actor"+As).attr("x1",r).attr("y1",5).attr("x2",r).attr("y2",2e3).attr("class","actor-line").attr("stroke-width","0.5px").attr("stroke","#999"),a=i.append("g"),e.actorCnt=As,null!=e.links&&(a.attr("id","root-"+As),xs("#root-"+As,As)));var o={x:0,y:0,fill:"#EDF2AE",stroke:"#666",width:100,anchor:"start",height:100,rx:0,ry:0},s="actor";null!=e.properties&&e.properties.class?s=e.properties.class:o.fill="#eaeaea",o.x=e.x,o.y=e.y,o.width=e.width,o.height=e.height,o.class=s,o.rx=3,o.ry=3;var c=_s(a,o);if(e.rectData=o,null!=e.properties&&e.properties.icon){var l=e.properties.icon.trim();"@"===l.charAt(0)?ws(a,o.x+o.width-20,o.y+10,l.substr(1)):ks(a,o.x+o.width-20,o.y+10,l);}Ds(n)(e.description,a,o.x,o.y,o.width,o.height,{class:"actor"},n);var u=e.height;if(c.node){var h=c.node().getBBox();e.height=h.height,u=h.height;}return u}(t,e,n)}},Fs=function(t,e,n,r,i){if(void 0===e.links||null===e.links||0===Object.keys(e.links).length)return {height:0,width:0};var a=e.links,o=e.actorCnt,s=e.rectData,c="none";i&&(c="block !important");var l=t.append("g");l.attr("id","actor"+o+"_popup"),l.attr("class","actorPopupMenu"),l.attr("display",c),xs("#actor"+o+"_popup",o);var u="";void 0!==s.class&&(u=" "+s.class);var h=s.width>n?s.width:n,f=l.append("rect");if(f.attr("class","actorPopupMenuPanel"+u),f.attr("x",s.x),f.attr("y",s.height),f.attr("fill",s.fill),f.attr("stroke",s.stroke),f.attr("width",h),f.attr("height",s.height),f.attr("rx",s.rx),f.attr("ry",s.ry),null!=a){var d=20;for(var p in a){var g=l.append("a"),y=(0, je.N)(a[p]);g.attr("xlink:href",y),g.attr("target","_blank"),Bs(r)(p,g,s.x+10,s.height+d,h,20,{class:"actor"},r),d+=30;}}return f.attr("height",d),{height:s.height+d,width:h}},Rs=function(t){return t.append("g")},Ps=function(t,e,n,r,i){var a={x:0,y:0,fill:"#EDF2AE",stroke:"#666",width:100,anchor:"start",height:100,rx:0,ry:0},o=e.anchored;a.x=e.startx,a.y=e.starty,a.class="activation"+i%3,a.width=e.stopx-e.startx,a.height=n-e.starty,_s(o,a);},js=function(t,e,n,r){var i=r.boxMargin,a=r.boxTextMargin,o=r.labelBoxHeight,s=r.labelBoxWidth,c=r.messageFontFamily,l=r.messageFontSize,u=r.messageFontWeight,h=t.append("g"),f=function(t,e,n,r){return h.append("line").attr("x1",t).attr("y1",e).attr("x2",n).attr("y2",r).attr("class","loopLine")};f(e.startx,e.starty,e.stopx,e.starty),f(e.stopx,e.starty,e.stopx,e.stopy),f(e.startx,e.stopy,e.stopx,e.stopy),f(e.startx,e.starty,e.startx,e.stopy),void 0!==e.sections&&e.sections.forEach((function(t){f(e.startx,t.y,e.stopx,t.y).style("stroke-dasharray","3, 3");}));var d={x:0,y:0,fill:void 0,anchor:void 0,style:"#666",width:void 0,height:void 0,textMargin:0,rx:0,ry:0,tspan:!0,valign:void 0};d.text=n,d.x=e.startx,d.y=e.starty,d.fontFamily=c,d.fontSize=l,d.fontWeight=u,d.anchor="middle",d.valign="middle",d.tspan=!1,d.width=s||50,d.height=o||20,d.textMargin=a,d.class="labelText",Ss(h,d),(d={x:0,y:0,fill:void 0,anchor:void 0,style:"#666",width:void 0,height:void 0,textMargin:0,rx:0,ry:0,tspan:!0,valign:void 0}).text=e.title,d.x=e.startx+s/2+(e.stopx-e.startx)/2,d.y=e.starty+i+a,d.anchor="middle",d.valign="middle",d.textMargin=a,d.class="loopText",d.fontFamily=c,d.fontSize=l,d.fontWeight=u,d.wrap=!0;var p=Cs(h,d);return void 0!==e.sectionTitles&&e.sectionTitles.forEach((function(t,n){if(t.message){d.text=t.message,d.x=e.startx+(e.stopx-e.startx)/2,d.y=e.sections[n].y+i+a,d.class="loopText",d.anchor="middle",d.valign="middle",d.tspan=!1,d.fontFamily=c,d.fontSize=l,d.fontWeight=u,d.wrap=e.wrap,p=Cs(h,d);var r=Math.round(p.map((function(t){return (t._groups||t)[0][0].getBBox().height})).reduce((function(t,e){return t+e})));e.sections[n].height+=r-(i+a);}})),e.height=Math.round(e.stopy-e.starty),h},zs=function(t,e){_s(t,{x:e.startx,y:e.starty,width:e.stopx-e.startx,height:e.stopy-e.starty,fill:e.fill,class:"rect"}).lower();},Ys=function(t){t.append("defs").append("marker").attr("id","arrowhead").attr("refX",9).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",12).attr("markerHeight",12).attr("orient","auto").append("path").attr("d","M 0 0 L 10 5 L 0 10 z");},Us=function(t){t.append("defs").append("marker").attr("id","filled-head").attr("refX",18).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L14,7 L9,1 Z");},$s=function(t){t.append("defs").append("marker").attr("id","sequencenumber").attr("refX",15).attr("refY",15).attr("markerWidth",60).attr("markerHeight",40).attr("orient","auto").append("circle").attr("cx",15).attr("cy",15).attr("r",6);},Ws=function(t){var e=t.append("defs").append("marker").attr("id","crosshead").attr("markerWidth",15).attr("markerHeight",8).attr("orient","auto").attr("refX",16).attr("refY",4);e.append("path").attr("fill","black").attr("stroke","#000000").style("stroke-dasharray","0, 0").attr("stroke-width","1px").attr("d","M 9,2 V 6 L16,4 Z"),e.append("path").attr("fill","none").attr("stroke","#000000").style("stroke-dasharray","0, 0").attr("stroke-width","1px").attr("d","M 0,1 L 6,7 M 6,1 L 0,7");},qs=function(t){t.append("defs").append("symbol").attr("id","database").attr("fill-rule","evenodd").attr("clip-rule","evenodd").append("path").attr("transform","scale(.5)").attr("d","M12.258.001l.256.004.255.005.253.008.251.01.249.012.247.015.246.016.242.019.241.02.239.023.236.024.233.027.231.028.229.031.225.032.223.034.22.036.217.038.214.04.211.041.208.043.205.045.201.046.198.048.194.05.191.051.187.053.183.054.18.056.175.057.172.059.168.06.163.061.16.063.155.064.15.066.074.033.073.033.071.034.07.034.069.035.068.035.067.035.066.035.064.036.064.036.062.036.06.036.06.037.058.037.058.037.055.038.055.038.053.038.052.038.051.039.05.039.048.039.047.039.045.04.044.04.043.04.041.04.04.041.039.041.037.041.036.041.034.041.033.042.032.042.03.042.029.042.027.042.026.043.024.043.023.043.021.043.02.043.018.044.017.043.015.044.013.044.012.044.011.045.009.044.007.045.006.045.004.045.002.045.001.045v17l-.001.045-.002.045-.004.045-.006.045-.007.045-.009.044-.011.045-.012.044-.013.044-.015.044-.017.043-.018.044-.02.043-.021.043-.023.043-.024.043-.026.043-.027.042-.029.042-.03.042-.032.042-.033.042-.034.041-.036.041-.037.041-.039.041-.04.041-.041.04-.043.04-.044.04-.045.04-.047.039-.048.039-.05.039-.051.039-.052.038-.053.038-.055.038-.055.038-.058.037-.058.037-.06.037-.06.036-.062.036-.064.036-.064.036-.066.035-.067.035-.068.035-.069.035-.07.034-.071.034-.073.033-.074.033-.15.066-.155.064-.16.063-.163.061-.168.06-.172.059-.175.057-.18.056-.183.054-.187.053-.191.051-.194.05-.198.048-.201.046-.205.045-.208.043-.211.041-.214.04-.217.038-.22.036-.223.034-.225.032-.229.031-.231.028-.233.027-.236.024-.239.023-.241.02-.242.019-.246.016-.247.015-.249.012-.251.01-.253.008-.255.005-.256.004-.258.001-.258-.001-.256-.004-.255-.005-.253-.008-.251-.01-.249-.012-.247-.015-.245-.016-.243-.019-.241-.02-.238-.023-.236-.024-.234-.027-.231-.028-.228-.031-.226-.032-.223-.034-.22-.036-.217-.038-.214-.04-.211-.041-.208-.043-.204-.045-.201-.046-.198-.048-.195-.05-.19-.051-.187-.053-.184-.054-.179-.056-.176-.057-.172-.059-.167-.06-.164-.061-.159-.063-.155-.064-.151-.066-.074-.033-.072-.033-.072-.034-.07-.034-.069-.035-.068-.035-.067-.035-.066-.035-.064-.036-.063-.036-.062-.036-.061-.036-.06-.037-.058-.037-.057-.037-.056-.038-.055-.038-.053-.038-.052-.038-.051-.039-.049-.039-.049-.039-.046-.039-.046-.04-.044-.04-.043-.04-.041-.04-.04-.041-.039-.041-.037-.041-.036-.041-.034-.041-.033-.042-.032-.042-.03-.042-.029-.042-.027-.042-.026-.043-.024-.043-.023-.043-.021-.043-.02-.043-.018-.044-.017-.043-.015-.044-.013-.044-.012-.044-.011-.045-.009-.044-.007-.045-.006-.045-.004-.045-.002-.045-.001-.045v-17l.001-.045.002-.045.004-.045.006-.045.007-.045.009-.044.011-.045.012-.044.013-.044.015-.044.017-.043.018-.044.02-.043.021-.043.023-.043.024-.043.026-.043.027-.042.029-.042.03-.042.032-.042.033-.042.034-.041.036-.041.037-.041.039-.041.04-.041.041-.04.043-.04.044-.04.046-.04.046-.039.049-.039.049-.039.051-.039.052-.038.053-.038.055-.038.056-.038.057-.037.058-.037.06-.037.061-.036.062-.036.063-.036.064-.036.066-.035.067-.035.068-.035.069-.035.07-.034.072-.034.072-.033.074-.033.151-.066.155-.064.159-.063.164-.061.167-.06.172-.059.176-.057.179-.056.184-.054.187-.053.19-.051.195-.05.198-.048.201-.046.204-.045.208-.043.211-.041.214-.04.217-.038.22-.036.223-.034.226-.032.228-.031.231-.028.234-.027.236-.024.238-.023.241-.02.243-.019.245-.016.247-.015.249-.012.251-.01.253-.008.255-.005.256-.004.258-.001.258.001zm-9.258 20.499v.01l.001.021.003.021.004.022.005.021.006.022.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.023.018.024.019.024.021.024.022.025.023.024.024.025.052.049.056.05.061.051.066.051.07.051.075.051.079.052.084.052.088.052.092.052.097.052.102.051.105.052.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.048.144.049.147.047.152.047.155.047.16.045.163.045.167.043.171.043.176.041.178.041.183.039.187.039.19.037.194.035.197.035.202.033.204.031.209.03.212.029.216.027.219.025.222.024.226.021.23.02.233.018.236.016.24.015.243.012.246.01.249.008.253.005.256.004.259.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.021.224-.024.22-.026.216-.027.212-.028.21-.031.205-.031.202-.034.198-.034.194-.036.191-.037.187-.039.183-.04.179-.04.175-.042.172-.043.168-.044.163-.045.16-.046.155-.046.152-.047.148-.048.143-.049.139-.049.136-.05.131-.05.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.053.083-.051.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.05.023-.024.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.023.01-.022.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.127l-.077.055-.08.053-.083.054-.085.053-.087.052-.09.052-.093.051-.095.05-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.045-.118.044-.12.043-.122.042-.124.042-.126.041-.128.04-.13.04-.132.038-.134.038-.135.037-.138.037-.139.035-.142.035-.143.034-.144.033-.147.032-.148.031-.15.03-.151.03-.153.029-.154.027-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.01-.179.008-.179.008-.181.006-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.006-.179-.008-.179-.008-.178-.01-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.027-.153-.029-.151-.03-.15-.03-.148-.031-.146-.032-.145-.033-.143-.034-.141-.035-.14-.035-.137-.037-.136-.037-.134-.038-.132-.038-.13-.04-.128-.04-.126-.041-.124-.042-.122-.042-.12-.044-.117-.043-.116-.045-.113-.045-.112-.046-.109-.047-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.05-.093-.052-.09-.051-.087-.052-.085-.053-.083-.054-.08-.054-.077-.054v4.127zm0-5.654v.011l.001.021.003.021.004.021.005.022.006.022.007.022.009.022.01.022.011.023.012.023.013.023.015.024.016.023.017.024.018.024.019.024.021.024.022.024.023.025.024.024.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.052.11.051.114.051.119.052.123.05.127.051.131.05.135.049.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.044.171.042.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.022.23.02.233.018.236.016.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.012.241-.015.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.048.139-.05.136-.049.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.051.051-.049.023-.025.023-.024.021-.025.02-.024.019-.024.018-.024.017-.024.015-.023.014-.023.013-.024.012-.022.01-.023.01-.023.008-.022.006-.022.006-.022.004-.021.004-.022.001-.021.001-.021v-4.139l-.077.054-.08.054-.083.054-.085.052-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.044-.118.044-.12.044-.122.042-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.035-.143.033-.144.033-.147.033-.148.031-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.009-.179.009-.179.007-.181.007-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.007-.179-.007-.179-.009-.178-.009-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.031-.146-.033-.145-.033-.143-.033-.141-.035-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.04-.126-.041-.124-.042-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.051-.093-.051-.09-.051-.087-.053-.085-.052-.083-.054-.08-.054-.077-.054v4.139zm0-5.666v.011l.001.02.003.022.004.021.005.022.006.021.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.024.018.023.019.024.021.025.022.024.023.024.024.025.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.051.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.043.171.043.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.021.23.02.233.018.236.017.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.013.241-.014.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.049.139-.049.136-.049.131-.051.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.049.023-.025.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.022.01-.023.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.153l-.077.054-.08.054-.083.053-.085.053-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.048-.105.048-.106.048-.109.046-.111.046-.114.046-.115.044-.118.044-.12.043-.122.043-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.034-.143.034-.144.033-.147.032-.148.032-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.024-.161.024-.162.023-.163.023-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.01-.178.01-.179.009-.179.007-.181.006-.182.006-.182.004-.184.003-.184.001-.185.001-.185-.001-.184-.001-.184-.003-.182-.004-.182-.006-.181-.006-.179-.007-.179-.009-.178-.01-.176-.01-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.023-.162-.023-.161-.024-.159-.024-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.032-.146-.032-.145-.033-.143-.034-.141-.034-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.041-.126-.041-.124-.041-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.048-.105-.048-.102-.048-.1-.05-.097-.049-.095-.051-.093-.051-.09-.052-.087-.052-.085-.053-.083-.053-.08-.054-.077-.054v4.153zm8.74-8.179l-.257.004-.254.005-.25.008-.247.011-.244.012-.241.014-.237.016-.233.018-.231.021-.226.022-.224.023-.22.026-.216.027-.212.028-.21.031-.205.032-.202.033-.198.034-.194.036-.191.038-.187.038-.183.04-.179.041-.175.042-.172.043-.168.043-.163.045-.16.046-.155.046-.152.048-.148.048-.143.048-.139.049-.136.05-.131.05-.126.051-.123.051-.118.051-.114.052-.11.052-.106.052-.101.052-.096.052-.092.052-.088.052-.083.052-.079.052-.074.051-.07.052-.065.051-.06.05-.056.05-.051.05-.023.025-.023.024-.021.024-.02.025-.019.024-.018.024-.017.023-.015.024-.014.023-.013.023-.012.023-.01.023-.01.022-.008.022-.006.023-.006.021-.004.022-.004.021-.001.021-.001.021.001.021.001.021.004.021.004.022.006.021.006.023.008.022.01.022.01.023.012.023.013.023.014.023.015.024.017.023.018.024.019.024.02.025.021.024.023.024.023.025.051.05.056.05.06.05.065.051.07.052.074.051.079.052.083.052.088.052.092.052.096.052.101.052.106.052.11.052.114.052.118.051.123.051.126.051.131.05.136.05.139.049.143.048.148.048.152.048.155.046.16.046.163.045.168.043.172.043.175.042.179.041.183.04.187.038.191.038.194.036.198.034.202.033.205.032.21.031.212.028.216.027.22.026.224.023.226.022.231.021.233.018.237.016.241.014.244.012.247.011.25.008.254.005.257.004.26.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.022.224-.023.22-.026.216-.027.212-.028.21-.031.205-.032.202-.033.198-.034.194-.036.191-.038.187-.038.183-.04.179-.041.175-.042.172-.043.168-.043.163-.045.16-.046.155-.046.152-.048.148-.048.143-.048.139-.049.136-.05.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.05.051-.05.023-.025.023-.024.021-.024.02-.025.019-.024.018-.024.017-.023.015-.024.014-.023.013-.023.012-.023.01-.023.01-.022.008-.022.006-.023.006-.021.004-.022.004-.021.001-.021.001-.021-.001-.021-.001-.021-.004-.021-.004-.022-.006-.021-.006-.023-.008-.022-.01-.022-.01-.023-.012-.023-.013-.023-.014-.023-.015-.024-.017-.023-.018-.024-.019-.024-.02-.025-.021-.024-.023-.024-.023-.025-.051-.05-.056-.05-.06-.05-.065-.051-.07-.052-.074-.051-.079-.052-.083-.052-.088-.052-.092-.052-.096-.052-.101-.052-.106-.052-.11-.052-.114-.052-.118-.051-.123-.051-.126-.051-.131-.05-.136-.05-.139-.049-.143-.048-.148-.048-.152-.048-.155-.046-.16-.046-.163-.045-.168-.043-.172-.043-.175-.042-.179-.041-.183-.04-.187-.038-.191-.038-.194-.036-.198-.034-.202-.033-.205-.032-.21-.031-.212-.028-.216-.027-.22-.026-.224-.023-.226-.022-.231-.021-.233-.018-.237-.016-.241-.014-.244-.012-.247-.011-.25-.008-.254-.005-.257-.004-.26-.001-.26.001z");},Hs=function(t){t.append("defs").append("symbol").attr("id","computer").attr("width","24").attr("height","24").append("path").attr("transform","scale(.5)").attr("d","M2 2v13h20v-13h-20zm18 11h-16v-9h16v9zm-10.228 6l.466-1h3.524l.467 1h-4.457zm14.228 3h-24l2-6h2.104l-1.33 4h18.45l-1.297-4h2.073l2 6zm-5-10h-14v-7h14v7z");},Vs=function(t){t.append("defs").append("symbol").attr("id","clock").attr("width","24").attr("height","24").append("path").attr("transform","scale(.5)").attr("d","M12 2c5.514 0 10 4.486 10 10s-4.486 10-10 10-10-4.486-10-10 4.486-10 10-10zm0-2c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm5.848 12.459c.202.038.202.333.001.372-1.907.361-6.045 1.111-6.547 1.111-.719 0-1.301-.582-1.301-1.301 0-.512.77-5.447 1.125-7.445.034-.192.312-.181.343.014l.985 6.238 5.394 1.011z");},Gs=Ns,Xs=Os;je.N;var Zs={},Qs={data:{startx:void 0,stopx:void 0,starty:void 0,stopy:void 0},verticalPos:0,sequenceItems:[],activations:[],models:{getHeight:function(){return Math.max.apply(null,0===this.actors.length?[0]:this.actors.map((function(t){return t.height||0})))+(0===this.loops.length?0:this.loops.map((function(t){return t.height||0})).reduce((function(t,e){return t+e})))+(0===this.messages.length?0:this.messages.map((function(t){return t.height||0})).reduce((function(t,e){return t+e})))+(0===this.notes.length?0:this.notes.map((function(t){return t.height||0})).reduce((function(t,e){return t+e})))},clear:function(){this.actors=[],this.loops=[],this.messages=[],this.notes=[];},addActor:function(t){this.actors.push(t);},addLoop:function(t){this.loops.push(t);},addMessage:function(t){this.messages.push(t);},addNote:function(t){this.notes.push(t);},lastActor:function(){return this.actors[this.actors.length-1]},lastLoop:function(){return this.loops[this.loops.length-1]},lastMessage:function(){return this.messages[this.messages.length-1]},lastNote:function(){return this.notes[this.notes.length-1]},actors:[],loops:[],messages:[],notes:[]},init:function(){this.sequenceItems=[],this.activations=[],this.models.clear(),this.data={startx:void 0,stopx:void 0,starty:void 0,stopy:void 0},this.verticalPos=0,rc(Xt());},updateVal:function(t,e,n,r){void 0===t[e]?t[e]=n:t[e]=r(n,t[e]);},updateBounds:function(t,e,n,r){var i=this,a=0;function o(o){return function(s){a++;var c=i.sequenceItems.length-a+1;i.updateVal(s,"starty",e-c*Zs.boxMargin,Math.min),i.updateVal(s,"stopy",r+c*Zs.boxMargin,Math.max),i.updateVal(Qs.data,"startx",t-c*Zs.boxMargin,Math.min),i.updateVal(Qs.data,"stopx",n+c*Zs.boxMargin,Math.max),"activation"!==o&&(i.updateVal(s,"startx",t-c*Zs.boxMargin,Math.min),i.updateVal(s,"stopx",n+c*Zs.boxMargin,Math.max),i.updateVal(Qs.data,"starty",e-c*Zs.boxMargin,Math.min),i.updateVal(Qs.data,"stopy",r+c*Zs.boxMargin,Math.max));}}this.sequenceItems.forEach(o()),this.activations.forEach(o("activation"));},insert:function(t,e,n,r){var i=Math.min(t,n),a=Math.max(t,n),o=Math.min(e,r),s=Math.max(e,r);this.updateVal(Qs.data,"startx",i,Math.min),this.updateVal(Qs.data,"starty",o,Math.min),this.updateVal(Qs.data,"stopx",a,Math.max),this.updateVal(Qs.data,"stopy",s,Math.max),this.updateBounds(i,o,a,s);},newActivation:function(t,e,n){var r=n[t.from.actor],i=ic(t.from.actor).length||0,a=r.x+r.width/2+(i-1)*Zs.activationWidth/2;this.activations.push({startx:a,starty:this.verticalPos+2,stopx:a+Zs.activationWidth,stopy:void 0,actor:t.from.actor,anchored:Rs(e)});},endActivation:function(t){var e=this.activations.map((function(t){return t.actor})).lastIndexOf(t.from.actor);return this.activations.splice(e,1)[0]},createLoop:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{message:void 0,wrap:!1,width:void 0},e=arguments.length>1?arguments[1]:void 0;return {startx:void 0,starty:this.verticalPos,stopx:void 0,stopy:void 0,title:t.message,wrap:t.wrap,width:t.width,height:0,fill:e}},newLoop:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{message:void 0,wrap:!1,width:void 0},e=arguments.length>1?arguments[1]:void 0;this.sequenceItems.push(this.createLoop(t,e));},endLoop:function(){return this.sequenceItems.pop()},addSectionToLoop:function(t){var e=this.sequenceItems.pop();e.sections=e.sections||[],e.sectionTitles=e.sectionTitles||[],e.sections.push({y:Qs.getVerticalPos(),height:0}),e.sectionTitles.push(t),this.sequenceItems.push(e);},bumpVerticalPos:function(t){this.verticalPos=this.verticalPos+t,this.data.stopy=this.verticalPos;},getVerticalPos:function(){return this.verticalPos},getBounds:function(){return {bounds:this.data,models:this.models}}},Ks=function(t){return {fontFamily:t.messageFontFamily,fontSize:t.messageFontSize,fontWeight:t.messageFontWeight}},Js=function(t){return {fontFamily:t.noteFontFamily,fontSize:t.noteFontSize,fontWeight:t.noteFontWeight}},tc=function(t){return {fontFamily:t.actorFontFamily,fontSize:t.actorFontSize,fontWeight:t.actorFontWeight}},ec=function(t,e,n,r,i,a){if(!0===i.hideUnusedParticipants){var o=new Set;a.forEach((function(t){o.add(t.from),o.add(t.to);})),n=n.filter((function(t){return o.has(t)}));}for(var s=0,c=0,l=0,u=0;u<n.length;u++){var h=e[n[u]];h.width=h.width||Zs.width,h.height=Math.max(h.height||Zs.height,Zs.height),h.margin=h.margin||Zs.actorMargin,h.x=s+c,h.y=r;var f=Is(t,h,Zs);l=Math.max(l,f),Qs.insert(h.x,r,h.x+h.width,h.height),s+=h.width,c+=h.margin,Qs.models.addActor(h);}Qs.bumpVerticalPos(l);},nc=function(t,e,n,r){for(var i=0,a=0,o=0;o<n.length;o++){var s=e[n[o]],c=sc(s),l=Fs(t,s,c,Zs,Zs.forceMenus);l.height>i&&(i=l.height),l.width+s.x>a&&(a=l.width+s.x);}return {maxHeight:i,maxWidth:a}},rc=function(t){Q(Zs,t),t.fontFamily&&(Zs.actorFontFamily=Zs.noteFontFamily=Zs.messageFontFamily=t.fontFamily),t.fontSize&&(Zs.actorFontSize=Zs.noteFontSize=Zs.messageFontSize=t.fontSize),t.fontWeight&&(Zs.actorFontWeight=Zs.noteFontWeight=Zs.messageFontWeight=t.fontWeight);},ic=function(t){return Qs.activations.filter((function(e){return e.actor===t}))},ac=function(t,e){var n=e[t],r=ic(t);return [r.reduce((function(t,e){return Math.min(t,e.startx)}),n.x+n.width/2),r.reduce((function(t,e){return Math.max(t,e.stopx)}),n.x+n.width/2)]};function oc(t,e,n,r,i){Qs.bumpVerticalPos(n);var a=r;if(e.id&&e.message&&t[e.id]){var s=t[e.id].width,c=Ks(Zs);e.message=An.wrapLabel("[".concat(e.message,"]"),s-2*Zs.wrapPadding,c),e.width=s,e.wrap=!0;var l=An.calculateTextDimensions(e.message,c),u=Math.max(l.height,Zs.labelBoxHeight);a=r+u,o.debug("".concat(u," - ").concat(e.message));}i(e),Qs.bumpVerticalPos(a);}var sc=function(t){var e=0,n=tc(Zs);for(var r in t.links){var i=An.calculateTextDimensions(r,n).width+2*Zs.wrapPadding+2*Zs.boxMargin;e<i&&(e=i);}return e};const cc={bounds:Qs,drawActors:ec,drawActorsPopup:nc,setConf:rc,draw:function(t,e,n,r){Zs=Xt().sequence;var i,a=Xt().securityLevel;"sandbox"===a&&(i=(0, l.select)("#i"+e));var s="sandbox"===a?(0, l.select)(i.nodes()[0].contentDocument.body):(0, l.select)("body"),c="sandbox"===a?i.nodes()[0].contentDocument:document;Qs.init(),o.debug(r.db);var u="sandbox"===a?s.select('[id="'.concat(e,'"]')):(0, l.select)('[id="'.concat(e,'"]')),h=r.db.getActors(),f=r.db.getActorKeys(),d=r.db.getMessages(),p=r.db.getDiagramTitle(),g=function(t,e,n){var r={};return e.forEach((function(e){if(t[e.to]&&t[e.from]){var i=t[e.to];if(e.placement===n.db.PLACEMENT.LEFTOF&&!i.prevActor)return;if(e.placement===n.db.PLACEMENT.RIGHTOF&&!i.nextActor)return;var a=void 0!==e.placement,o=!a,s=a?Js(Zs):Ks(Zs),c=e.wrap?An.wrapLabel(e.message,Zs.width-2*Zs.wrapPadding,s):e.message,l=An.calculateTextDimensions(c,s).width+2*Zs.wrapPadding;o&&e.from===i.nextActor?r[e.to]=Math.max(r[e.to]||0,l):o&&e.from===i.prevActor?r[e.from]=Math.max(r[e.from]||0,l):o&&e.from===e.to?(r[e.from]=Math.max(r[e.from]||0,l/2),r[e.to]=Math.max(r[e.to]||0,l/2)):e.placement===n.db.PLACEMENT.RIGHTOF?r[e.from]=Math.max(r[e.from]||0,l):e.placement===n.db.PLACEMENT.LEFTOF?r[i.prevActor]=Math.max(r[i.prevActor]||0,l):e.placement===n.db.PLACEMENT.OVER&&(i.prevActor&&(r[i.prevActor]=Math.max(r[i.prevActor]||0,l/2)),i.nextActor&&(r[e.from]=Math.max(r[e.from]||0,l/2)));}})),o.debug("maxMessageWidthPerActor:",r),r}(h,d,r);Zs.height=function(t,e){var n=0;for(var r in Object.keys(t).forEach((function(e){var r=t[e];r.wrap&&(r.description=An.wrapLabel(r.description,Zs.width-2*Zs.wrapPadding,tc(Zs)));var i=An.calculateTextDimensions(r.description,tc(Zs));r.width=r.wrap?Zs.width:Math.max(Zs.width,i.width+2*Zs.wrapPadding),r.height=r.wrap?Math.max(i.height,Zs.height):Zs.height,n=Math.max(n,r.height);})),e){var i=t[r];if(i){var a=t[i.nextActor];if(a){var o=e[r]+Zs.actorMargin-i.width/2-a.width/2;i.margin=Math.max(o,Zs.actorMargin);}}}return Math.max(n,Zs.height)}(h,g),Hs(u),qs(u),Vs(u),ec(u,h,f,0,Zs,d);var y=function(t,e,n,r){var i,a,s,c={},l=[];return t.forEach((function(t){switch(t.id=An.random({length:10}),t.type){case r.db.LINETYPE.LOOP_START:case r.db.LINETYPE.ALT_START:case r.db.LINETYPE.OPT_START:case r.db.LINETYPE.PAR_START:case r.db.LINETYPE.CRITICAL_START:case r.db.LINETYPE.BREAK_START:l.push({id:t.id,msg:t.message,from:Number.MAX_SAFE_INTEGER,to:Number.MIN_SAFE_INTEGER,width:0});break;case r.db.LINETYPE.ALT_ELSE:case r.db.LINETYPE.PAR_AND:case r.db.LINETYPE.CRITICAL_OPTION:t.message&&(i=l.pop(),c[i.id]=i,c[t.id]=i,l.push(i));break;case r.db.LINETYPE.LOOP_END:case r.db.LINETYPE.ALT_END:case r.db.LINETYPE.OPT_END:case r.db.LINETYPE.PAR_END:case r.db.LINETYPE.CRITICAL_END:case r.db.LINETYPE.BREAK_END:i=l.pop(),c[i.id]=i;break;case r.db.LINETYPE.ACTIVE_START:var n=e[t.from?t.from.actor:t.to.actor],u=ic(t.from?t.from.actor:t.to.actor).length,h=n.x+n.width/2+(u-1)*Zs.activationWidth/2,f={startx:h,stopx:h+Zs.activationWidth,actor:t.from.actor,enabled:!0};Qs.activations.push(f);break;case r.db.LINETYPE.ACTIVE_END:var d=Qs.activations.map((function(t){return t.actor})).lastIndexOf(t.from.actor);delete Qs.activations.splice(d,1)[0];}void 0!==t.placement?(a=function(t,e,n){var r=e[t.from].x,i=e[t.to].x,a=t.wrap&&t.message,s=An.calculateTextDimensions(a?An.wrapLabel(t.message,Zs.width,Js(Zs)):t.message,Js(Zs)),c={width:a?Zs.width:Math.max(Zs.width,s.width+2*Zs.noteMargin),height:0,startx:e[t.from].x,stopx:0,starty:0,stopy:0,message:t.message};return t.placement===n.db.PLACEMENT.RIGHTOF?(c.width=a?Math.max(Zs.width,s.width):Math.max(e[t.from].width/2+e[t.to].width/2,s.width+2*Zs.noteMargin),c.startx=r+(e[t.from].width+Zs.actorMargin)/2):t.placement===n.db.PLACEMENT.LEFTOF?(c.width=a?Math.max(Zs.width,s.width+2*Zs.noteMargin):Math.max(e[t.from].width/2+e[t.to].width/2,s.width+2*Zs.noteMargin),c.startx=r-c.width+(e[t.from].width-Zs.actorMargin)/2):t.to===t.from?(s=An.calculateTextDimensions(a?An.wrapLabel(t.message,Math.max(Zs.width,e[t.from].width),Js(Zs)):t.message,Js(Zs)),c.width=a?Math.max(Zs.width,e[t.from].width):Math.max(e[t.from].width,Zs.width,s.width+2*Zs.noteMargin),c.startx=r+(e[t.from].width-c.width)/2):(c.width=Math.abs(r+e[t.from].width/2-(i+e[t.to].width/2))+Zs.actorMargin,c.startx=r<i?r+e[t.from].width/2-Zs.actorMargin/2:i+e[t.to].width/2-Zs.actorMargin/2),a&&(c.message=An.wrapLabel(t.message,c.width-2*Zs.wrapPadding,Js(Zs))),o.debug("NM:[".concat(c.startx,",").concat(c.stopx,",").concat(c.starty,",").concat(c.stopy,":").concat(c.width,",").concat(c.height,"=").concat(t.message,"]")),c}(t,e,r),t.noteModel=a,l.forEach((function(t){(i=t).from=Math.min(i.from,a.startx),i.to=Math.max(i.to,a.startx+a.width),i.width=Math.max(i.width,Math.abs(i.from-i.to))-Zs.labelBoxWidth;}))):(s=function(t,e,n){var r=!1;if([n.db.LINETYPE.SOLID_OPEN,n.db.LINETYPE.DOTTED_OPEN,n.db.LINETYPE.SOLID,n.db.LINETYPE.DOTTED,n.db.LINETYPE.SOLID_CROSS,n.db.LINETYPE.DOTTED_CROSS,n.db.LINETYPE.SOLID_POINT,n.db.LINETYPE.DOTTED_POINT].includes(t.type)&&(r=!0),!r)return {};var i=ac(t.from,e),a=ac(t.to,e),o=i[0]<=a[0]?1:0,s=i[0]<a[0]?0:1,c=i.concat(a),l=Math.abs(a[s]-i[o]);t.wrap&&t.message&&(t.message=An.wrapLabel(t.message,Math.max(l+2*Zs.wrapPadding,Zs.width),Ks(Zs)));var u=An.calculateTextDimensions(t.message,Ks(Zs));return {width:Math.max(t.wrap?0:u.width+2*Zs.wrapPadding,l+2*Zs.wrapPadding,Zs.width),height:0,startx:i[o],stopx:a[s],starty:0,stopy:0,message:t.message,type:t.type,wrap:t.wrap,fromBounds:Math.min.apply(null,c),toBounds:Math.max.apply(null,c)}}(t,e,r),t.msgModel=s,s.startx&&s.stopx&&l.length>0&&l.forEach((function(n){if(i=n,s.startx===s.stopx){var r=e[t.from],a=e[t.to];i.from=Math.min(r.x-s.width/2,r.x-r.width/2,i.from),i.to=Math.max(a.x+s.width/2,a.x+r.width/2,i.to),i.width=Math.max(i.width,Math.abs(i.to-i.from))-Zs.labelBoxWidth;}else i.from=Math.min(s.startx,i.from),i.to=Math.max(s.stopx,i.to),i.width=Math.max(i.width,s.width)-Zs.labelBoxWidth;})));})),Qs.activations=[],o.debug("Loop type widths:",c),c}(d,h,0,r);Ys(u),Ws(u),Us(u),$s(u);var m=1,b=1,v=Array();d.forEach((function(t){var e,n,i;switch(t.type){case r.db.LINETYPE.NOTE:n=t.noteModel,function(t,e){Qs.bumpVerticalPos(Zs.boxMargin),e.height=Zs.boxMargin,e.starty=Qs.getVerticalPos();var n=Xs();n.x=e.startx,n.y=e.starty,n.width=e.width||Zs.width,n.class="note";var r=t.append("g"),i=Ls(r,n),a=Gs();a.x=e.startx,a.y=e.starty,a.width=n.width,a.dy="1em",a.text=e.message,a.class="noteText",a.fontFamily=Zs.noteFontFamily,a.fontSize=Zs.noteFontSize,a.fontWeight=Zs.noteFontWeight,a.anchor=Zs.noteAlign,a.textMargin=Zs.noteMargin,a.valign="center";var o=Cs(r,a),s=Math.round(o.map((function(t){return (t._groups||t)[0][0].getBBox().height})).reduce((function(t,e){return t+e})));i.attr("height",s+2*Zs.noteMargin),e.height+=s+2*Zs.noteMargin,Qs.bumpVerticalPos(s+2*Zs.noteMargin),e.stopy=e.starty+s+2*Zs.noteMargin,e.stopx=e.startx+n.width,Qs.insert(e.startx,e.starty,e.stopx,e.stopy),Qs.models.addNote(e);}(u,n);break;case r.db.LINETYPE.ACTIVE_START:Qs.newActivation(t,u,h);break;case r.db.LINETYPE.ACTIVE_END:!function(t,e){var n=Qs.endActivation(t);n.starty+18>e&&(n.starty=e-6,e+=12),Ps(u,n,e,Zs,ic(t.from.actor).length),Qs.insert(n.startx,e-10,n.stopx,e);}(t,Qs.getVerticalPos());break;case r.db.LINETYPE.LOOP_START:oc(y,t,Zs.boxMargin,Zs.boxMargin+Zs.boxTextMargin,(function(t){return Qs.newLoop(t)}));break;case r.db.LINETYPE.LOOP_END:e=Qs.endLoop(),js(u,e,"loop",Zs),Qs.bumpVerticalPos(e.stopy-Qs.getVerticalPos()),Qs.models.addLoop(e);break;case r.db.LINETYPE.RECT_START:oc(y,t,Zs.boxMargin,Zs.boxMargin,(function(t){return Qs.newLoop(void 0,t.message)}));break;case r.db.LINETYPE.RECT_END:e=Qs.endLoop(),zs(u,e),Qs.models.addLoop(e),Qs.bumpVerticalPos(e.stopy-Qs.getVerticalPos());break;case r.db.LINETYPE.OPT_START:oc(y,t,Zs.boxMargin,Zs.boxMargin+Zs.boxTextMargin,(function(t){return Qs.newLoop(t)}));break;case r.db.LINETYPE.OPT_END:e=Qs.endLoop(),js(u,e,"opt",Zs),Qs.bumpVerticalPos(e.stopy-Qs.getVerticalPos()),Qs.models.addLoop(e);break;case r.db.LINETYPE.ALT_START:oc(y,t,Zs.boxMargin,Zs.boxMargin+Zs.boxTextMargin,(function(t){return Qs.newLoop(t)}));break;case r.db.LINETYPE.ALT_ELSE:oc(y,t,Zs.boxMargin+Zs.boxTextMargin,Zs.boxMargin,(function(t){return Qs.addSectionToLoop(t)}));break;case r.db.LINETYPE.ALT_END:e=Qs.endLoop(),js(u,e,"alt",Zs),Qs.bumpVerticalPos(e.stopy-Qs.getVerticalPos()),Qs.models.addLoop(e);break;case r.db.LINETYPE.PAR_START:oc(y,t,Zs.boxMargin,Zs.boxMargin+Zs.boxTextMargin,(function(t){return Qs.newLoop(t)}));break;case r.db.LINETYPE.PAR_AND:oc(y,t,Zs.boxMargin+Zs.boxTextMargin,Zs.boxMargin,(function(t){return Qs.addSectionToLoop(t)}));break;case r.db.LINETYPE.PAR_END:e=Qs.endLoop(),js(u,e,"par",Zs),Qs.bumpVerticalPos(e.stopy-Qs.getVerticalPos()),Qs.models.addLoop(e);break;case r.db.LINETYPE.AUTONUMBER:m=t.message.start||m,b=t.message.step||b,t.message.visible?r.db.enableSequenceNumbers():r.db.disableSequenceNumbers();break;case r.db.LINETYPE.CRITICAL_START:oc(y,t,Zs.boxMargin,Zs.boxMargin+Zs.boxTextMargin,(function(t){return Qs.newLoop(t)}));break;case r.db.LINETYPE.CRITICAL_OPTION:oc(y,t,Zs.boxMargin+Zs.boxTextMargin,Zs.boxMargin,(function(t){return Qs.addSectionToLoop(t)}));break;case r.db.LINETYPE.CRITICAL_END:e=Qs.endLoop(),js(u,e,"critical",Zs),Qs.bumpVerticalPos(e.stopy-Qs.getVerticalPos()),Qs.models.addLoop(e);break;case r.db.LINETYPE.BREAK_START:oc(y,t,Zs.boxMargin,Zs.boxMargin+Zs.boxTextMargin,(function(t){return Qs.newLoop(t)}));break;case r.db.LINETYPE.BREAK_END:e=Qs.endLoop(),js(u,e,"break",Zs),Qs.bumpVerticalPos(e.stopy-Qs.getVerticalPos()),Qs.models.addLoop(e);break;default:try{(i=t.msgModel).starty=Qs.getVerticalPos(),i.sequenceIndex=m,i.sequenceVisible=r.db.showSequenceNumbers();var a=function(t,e){Qs.bumpVerticalPos(10);var n,r=e.startx,i=e.stopx,a=e.message,o=ue.splitBreaks(a).length,s=An.calculateTextDimensions(a,Ks(Zs)),c=s.height/o;e.height+=c,Qs.bumpVerticalPos(c);var l=s.height-10,u=s.width;if(r===i){n=Qs.getVerticalPos()+l,Zs.rightAngles||(l+=Zs.boxMargin,n=Qs.getVerticalPos()+l),l+=30;var h=Math.max(u/2,Zs.width/2);Qs.insert(r-h,Qs.getVerticalPos()-10+l,i+h,Qs.getVerticalPos()+30+l);}else l+=Zs.boxMargin,n=Qs.getVerticalPos()+l,Qs.insert(r,n-10,i,n);return Qs.bumpVerticalPos(l),e.height+=l,e.stopy=e.starty+e.height,Qs.insert(e.fromBounds,e.starty,e.toBounds,e.stopy),n}(0,i);v.push({messageModel:i,lineStarty:a}),Qs.models.addMessage(i);}catch(t){o.error("error while drawing message",t);}}[r.db.LINETYPE.SOLID_OPEN,r.db.LINETYPE.DOTTED_OPEN,r.db.LINETYPE.SOLID,r.db.LINETYPE.DOTTED,r.db.LINETYPE.SOLID_CROSS,r.db.LINETYPE.DOTTED_CROSS,r.db.LINETYPE.SOLID_POINT,r.db.LINETYPE.DOTTED_POINT].includes(t.type)&&(m+=b);})),v.forEach((function(t){return function(t,e,n,r){var i=e.startx,a=e.stopx,o=e.starty,s=e.message,c=e.type,l=e.sequenceIndex,u=e.sequenceVisible,h=An.calculateTextDimensions(s,Ks(Zs)),f=Gs();f.x=i,f.y=o+10,f.width=a-i,f.class="messageText",f.dy="1em",f.text=s,f.fontFamily=Zs.messageFontFamily,f.fontSize=Zs.messageFontSize,f.fontWeight=Zs.messageFontWeight,f.anchor=Zs.messageAlign,f.valign="center",f.textMargin=Zs.wrapPadding,f.tspan=!1,Cs(t,f);var d,p=h.width;i===a?d=Zs.rightAngles?t.append("path").attr("d","M ".concat(i,",").concat(n," H ").concat(i+Math.max(Zs.width/2,p/2)," V ").concat(n+25," H ").concat(i)):t.append("path").attr("d","M "+i+","+n+" C "+(i+60)+","+(n-10)+" "+(i+60)+","+(n+30)+" "+i+","+(n+20)):((d=t.append("line")).attr("x1",i),d.attr("y1",n),d.attr("x2",a),d.attr("y2",n)),c===r.db.LINETYPE.DOTTED||c===r.db.LINETYPE.DOTTED_CROSS||c===r.db.LINETYPE.DOTTED_POINT||c===r.db.LINETYPE.DOTTED_OPEN?(d.style("stroke-dasharray","3, 3"),d.attr("class","messageLine1")):d.attr("class","messageLine0");var g="";Zs.arrowMarkerAbsolute&&(g=(g=(g=window.location.protocol+"//"+window.location.host+window.location.pathname+window.location.search).replace(/\(/g,"\\(")).replace(/\)/g,"\\)")),d.attr("stroke-width",2),d.attr("stroke","none"),d.style("fill","none"),c!==r.db.LINETYPE.SOLID&&c!==r.db.LINETYPE.DOTTED||d.attr("marker-end","url("+g+"#arrowhead)"),c!==r.db.LINETYPE.SOLID_POINT&&c!==r.db.LINETYPE.DOTTED_POINT||d.attr("marker-end","url("+g+"#filled-head)"),c!==r.db.LINETYPE.SOLID_CROSS&&c!==r.db.LINETYPE.DOTTED_CROSS||d.attr("marker-end","url("+g+"#crosshead)"),(u||Zs.showSequenceNumbers)&&(d.attr("marker-start","url("+g+"#sequencenumber)"),t.append("text").attr("x",i).attr("y",n+4).attr("font-family","sans-serif").attr("font-size","12px").attr("text-anchor","middle").attr("class","sequenceNumber").text(l));}(u,t.messageModel,t.lineStarty,r)})),Zs.mirrorActors&&(Qs.bumpVerticalPos(2*Zs.boxMargin),ec(u,h,f,Qs.getVerticalPos(),Zs,d),Qs.bumpVerticalPos(Zs.boxMargin),Ms(u,Qs.getVerticalPos()));var _=nc(u,h,f),x=Qs.getBounds().bounds;o.debug("For line height fix Querying: #"+e+" .actor-line"),(0, l.selectAll)("#"+e+" .actor-line").attr("y2",x.stopy);var k=x.stopy-x.starty;k<_.maxHeight&&(k=_.maxHeight);var w=k+2*Zs.diagramMarginY;Zs.mirrorActors&&(w=w-Zs.boxMargin+Zs.bottomMarginAdj);var T=x.stopx-x.startx;T<_.maxWidth&&(T=_.maxWidth);var E=T+2*Zs.diagramMarginX;p&&u.append("text").text(p).attr("x",(x.stopx-x.startx)/2-2*Zs.diagramMarginX).attr("y",-25),Tn(u,0,E,Zs.useMaxWidth);var C=p?40:0;u.attr("viewBox",x.startx-Zs.diagramMarginX+" -"+(Zs.diagramMarginY+C)+" "+E+" "+(w+C)),Mn(r.db,u,e),o.debug("models:",Qs.models);}};var lc=n(3584),uc=n.n(lc);function hc(t){return hc="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},hc(t)}var fc=function(t){return JSON.parse(JSON.stringify(t))},dc=[],pc=function t(e,n,r){if("relation"===n.stmt)t(e,n.state1,!0),t(e,n.state2,!1);else if("state"===n.stmt&&"[*]"===n.id&&(n.id=r?e.id+"_start":e.id+"_end",n.start=r),n.doc){var i=[],a=0,o=[];for(a=0;a<n.doc.length;a++)if("divider"===n.doc[a].type){var s=fc(n.doc[a]);s.doc=fc(o),i.push(s),o=[];}else o.push(n.doc[a]);if(i.length>0&&o.length>0){var c={stmt:"state",id:gn(),type:"divider",doc:fc(o)};i.push(fc(c)),n.doc=i;}n.doc.forEach((function(e){return t(n,e,!0)}));}},gc={root:{relations:[],states:{},documents:{}}},yc=gc.root,mc=0,bc=function(t,e,n,r,i){void 0===yc.states[t]?yc.states[t]={id:t,descriptions:[],type:e,doc:n,note:i}:(yc.states[t].doc||(yc.states[t].doc=n),yc.states[t].type||(yc.states[t].type=e)),r&&(o.info("Adding state ",t,r),"string"==typeof r&&xc(t,r.trim()),"object"===hc(r)&&r.forEach((function(e){return xc(t,e.trim())}))),i&&(yc.states[t].note=i,yc.states[t].note.text=ue.sanitizeText(yc.states[t].note.text,Xt()));},vc=function(t){yc=(gc={root:{relations:[],states:{},documents:{}}}).root,yc=gc.root,mc=0,wc=[],t||ge();},_c=function(t,e,n){var r=t,i=e,a="default",o="default";"[*]"===t&&(r="start"+ ++mc,a="start"),"[*]"===e&&(i="end"+mc,o="end"),bc(r,a),bc(i,o),yc.relations.push({id1:r,id2:i,title:ue.sanitizeText(n,Xt())});},xc=function(t,e){var n=yc.states[t],r=e;":"===r[0]&&(r=r.substr(1).trim()),n.descriptions.push(ue.sanitizeText(r,Xt()));},kc=0,wc=[],Tc="TB";const Ec={parseDirective:function(t,e,n){cu.parseDirective(this,t,e,n);},getConfig:function(){return Xt().state},addState:bc,clear:vc,getState:function(t){return yc.states[t]},getStates:function(){return yc.states},getRelations:function(){return yc.relations},getClasses:function(){return wc},getDirection:function(){return Tc},addRelation:_c,getDividerId:function(){return "divider-id-"+ ++kc},setDirection:function(t){Tc=t;},cleanupLabel:function(t){return ":"===t.substring(0,1)?t.substr(2).trim():t.trim()},lineType:{LINE:0,DOTTED_LINE:1},relationType:{AGGREGATION:0,EXTENSION:1,COMPOSITION:2,DEPENDENCY:3},logDocuments:function(){o.info("Documents = ",gc);},getRootDoc:function(){return dc},setRootDoc:function(t){o.info("Setting root doc",t),dc=t;},getRootDocV2:function(){return pc({id:"root"},{id:"root",doc:dc},!0),{id:"root",doc:dc}},extract:function(t){var e;e=t.doc?t.doc:t,o.info(e),vc(!0),o.info("Extract",e),e.forEach((function(t){"state"===t.stmt&&bc(t.id,t.type,t.doc,t.description,t.note),"relation"===t.stmt&&_c(t.state1.id,t.state2.id,t.description);}));},trimColon:function(t){return t&&":"===t[0]?t.substr(1).trim():t.trim()},getAccTitle:me,setAccTitle:ye,getAccDescription:ve,setAccDescription:be};function Sc(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}var Ac,Mc=function(t,e,n){var r,i=Xt().state.padding,a=2*Xt().state.padding,o=t.node().getBBox(),s=o.width,c=o.x,l=t.append("text").attr("x",0).attr("y",Xt().state.titleShift).attr("font-size",Xt().state.fontSize).attr("class","state-title").text(e.id),u=l.node().getBBox().width+a,h=Math.max(u,s);h===s&&(h+=a);var f=t.node().getBBox();e.doc,r=c-i,u>s&&(r=(s-h)/2+i),Math.abs(c-f.x)<i&&u>s&&(r=c-(u-s)/2);var d=1-Xt().state.textHeight;return t.insert("rect",":first-child").attr("x",r).attr("y",d).attr("class",n?"alt-composit":"composit").attr("width",h).attr("height",f.height+Xt().state.textHeight+Xt().state.titleShift+1).attr("rx","0"),l.attr("x",r+i),u<=s&&l.attr("x",c+(h-a)/2-u/2+i),t.insert("rect",":first-child").attr("x",r).attr("y",Xt().state.titleShift-Xt().state.textHeight-Xt().state.padding).attr("width",h).attr("height",3*Xt().state.textHeight).attr("rx",Xt().state.radius),t.insert("rect",":first-child").attr("x",r).attr("y",Xt().state.titleShift-Xt().state.textHeight-Xt().state.padding).attr("width",h).attr("height",f.height+3+2*Xt().state.textHeight).attr("rx",Xt().state.radius),t},Nc=function(t,e){e.attr("class","state-note");var n=e.append("rect").attr("x",0).attr("y",Xt().state.padding),r=function(t,e,n,r){var i=0,a=r.append("text");a.style("text-anchor","start"),a.attr("class","noteText");var o,s=t.replace(/\r\n/g,"<br/>"),c=(s=s.replace(/\n/g,"<br/>")).split(ue.lineBreakRegex),l=1.25*Xt().state.noteMargin,u=function(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return Sc(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return "Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Sc(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0,i=function(){};return {s:i,n:function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}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 a,o=!0,s=!1;return {s:function(){n=n.call(t);},n:function(){var t=n.next();return o=t.done,t},e:function(t){s=!0,a=t;},f:function(){try{o||null==n.return||n.return();}finally{if(s)throw a}}}}(c);try{for(u.s();!(o=u.n()).done;){var h=o.value.trim();if(h.length>0){var f=a.append("tspan");f.text(h),0===l&&(l+=f.node().getBBox().height),i+=l,f.attr("x",0+Xt().state.noteMargin),f.attr("y",0+i+1.25*Xt().state.noteMargin);}}}catch(t){u.e(t);}finally{u.f();}return {textWidth:a.node().getBBox().width,textHeight:i}}(t,0,0,e.append("g")),i=r.textWidth,a=r.textHeight;return n.attr("height",a+2*Xt().state.noteMargin),n.attr("width",i+2*Xt().state.noteMargin),n},Oc=function(t,e){var n=e.id,r={id:n,label:e.id,width:0,height:0},i=t.append("g").attr("id",n).attr("class","stateGroup");"start"===e.type&&function(t){t.append("circle").attr("class","start-state").attr("r",Xt().state.sizeUnit).attr("cx",Xt().state.padding+Xt().state.sizeUnit).attr("cy",Xt().state.padding+Xt().state.sizeUnit);}(i),"end"===e.type&&function(t){t.append("circle").attr("class","end-state-outer").attr("r",Xt().state.sizeUnit+Xt().state.miniPadding).attr("cx",Xt().state.padding+Xt().state.sizeUnit+Xt().state.miniPadding).attr("cy",Xt().state.padding+Xt().state.sizeUnit+Xt().state.miniPadding),t.append("circle").attr("class","end-state-inner").attr("r",Xt().state.sizeUnit).attr("cx",Xt().state.padding+Xt().state.sizeUnit+2).attr("cy",Xt().state.padding+Xt().state.sizeUnit+2);}(i),"fork"!==e.type&&"join"!==e.type||function(t,e){var n=Xt().state.forkWidth,r=Xt().state.forkHeight;if(e.parentId){var i=n;n=r,r=i;}t.append("rect").style("stroke","black").style("fill","black").attr("width",n).attr("height",r).attr("x",Xt().state.padding).attr("y",Xt().state.padding);}(i,e),"note"===e.type&&Nc(e.note.text,i),"divider"===e.type&&function(t){t.append("line").style("stroke","grey").style("stroke-dasharray","3").attr("x1",Xt().state.textHeight).attr("class","divider").attr("x2",2*Xt().state.textHeight).attr("y1",0).attr("y2",0);}(i),"default"===e.type&&0===e.descriptions.length&&function(t,e){var n=t.append("text").attr("x",2*Xt().state.padding).attr("y",Xt().state.textHeight+2*Xt().state.padding).attr("font-size",Xt().state.fontSize).attr("class","state-title").text(e.id).node().getBBox();t.insert("rect",":first-child").attr("x",Xt().state.padding).attr("y",Xt().state.padding).attr("width",n.width+2*Xt().state.padding).attr("height",n.height+2*Xt().state.padding).attr("rx",Xt().state.radius);}(i,e),"default"===e.type&&e.descriptions.length>0&&function(t,e){var n=t.append("text").attr("x",2*Xt().state.padding).attr("y",Xt().state.textHeight+1.3*Xt().state.padding).attr("font-size",Xt().state.fontSize).attr("class","state-title").text(e.descriptions[0]).node().getBBox(),r=n.height,i=t.append("text").attr("x",Xt().state.padding).attr("y",r+.4*Xt().state.padding+Xt().state.dividerMargin+Xt().state.textHeight).attr("class","state-description"),a=!0,o=!0;e.descriptions.forEach((function(t){a||(function(t,e,n){var r=t.append("tspan").attr("x",2*Xt().state.padding).text(e);n||r.attr("dy",Xt().state.textHeight);}(i,t,o),o=!1),a=!1;}));var s=t.append("line").attr("x1",Xt().state.padding).attr("y1",Xt().state.padding+r+Xt().state.dividerMargin/2).attr("y2",Xt().state.padding+r+Xt().state.dividerMargin/2).attr("class","descr-divider"),c=i.node().getBBox(),l=Math.max(c.width,n.width);s.attr("x2",l+3*Xt().state.padding),t.insert("rect",":first-child").attr("x",Xt().state.padding).attr("y",Xt().state.padding).attr("width",l+2*Xt().state.padding).attr("height",c.height+r+2*Xt().state.padding).attr("rx",Xt().state.radius);}(i,e);var o=i.node().getBBox();return r.width=o.width+2*Xt().state.padding,r.height=o.height+2*Xt().state.padding,r},Dc=0,Bc={},Lc=function t(e,n,r,i,a,s,c){var u,h=new(yr().Graph)({compound:!0,multigraph:!0}),f=!0;for(u=0;u<e.length;u++)if("relation"===e[u].stmt){f=!1;break}r?h.setGraph({rankdir:"LR",multigraph:!0,compound:!0,ranker:"tight-tree",ranksep:f?1:Ac.edgeLengthFactor,nodeSep:f?1:50,isMultiGraph:!0}):h.setGraph({rankdir:"TB",multigraph:!0,compound:!0,ranksep:f?1:Ac.edgeLengthFactor,nodeSep:f?1:50,ranker:"tight-tree",isMultiGraph:!0}),h.setDefaultEdgeLabel((function(){return {}})),c.db.extract(e);for(var d=c.db.getStates(),p=c.db.getRelations(),g=Object.keys(d),y=0;y<g.length;y++){var m=d[g[y]];r&&(m.parentId=r);var b=void 0;if(m.doc){var v=n.append("g").attr("id",m.id).attr("class","stateGroup");b=t(m.doc,v,m.id,!i,a,s,c);var _=(v=Mc(v,m,i)).node().getBBox();b.width=_.width,b.height=_.height+Ac.padding/2,Bc[m.id]={y:Ac.compositTitleSize};}else b=Oc(n,m);if(m.note){var x={descriptions:[],id:m.id+"-note",note:m.note,type:"note"},k=Oc(n,x);"left of"===m.note.position?(h.setNode(b.id+"-note",k),h.setNode(b.id,b)):(h.setNode(b.id,b),h.setNode(b.id+"-note",k)),h.setParent(b.id,b.id+"-group"),h.setParent(b.id+"-note",b.id+"-group");}else h.setNode(b.id,b);}o.debug("Count=",h.nodeCount(),h);var w=0;p.forEach((function(t){var e;w++,o.debug("Setting edge",t),h.setEdge(t.id1,t.id2,{relation:t,width:(e=t.title,e?e.length*Ac.fontSizeFactor:1),height:Ac.labelHeight*ue.getRows(t.title).length,labelpos:"c"},"id"+w);})),pr().layout(h),o.debug("Graph after layout",h.nodes());var T=n.node();h.nodes().forEach((function(t){void 0!==t&&void 0!==h.node(t)?(o.warn("Node "+t+": "+JSON.stringify(h.node(t))),a.select("#"+T.id+" #"+t).attr("transform","translate("+(h.node(t).x-h.node(t).width/2)+","+(h.node(t).y+(Bc[t]?Bc[t].y:0)-h.node(t).height/2)+" )"),a.select("#"+T.id+" #"+t).attr("data-x-shift",h.node(t).x-h.node(t).width/2),s.querySelectorAll("#"+T.id+" #"+t+" .divider").forEach((function(t){var e=t.parentElement,n=0,r=0;e&&(e.parentElement&&(n=e.parentElement.getBBox().width),r=parseInt(e.getAttribute("data-x-shift"),10),Number.isNaN(r)&&(r=0)),t.setAttribute("x1",0-r+8),t.setAttribute("x2",n-r-8);}))):o.debug("No Node "+t+": "+JSON.stringify(h.node(t)));}));var E=T.getBBox();h.edges().forEach((function(t){void 0!==t&&void 0!==h.edge(t)&&(o.debug("Edge "+t.v+" -> "+t.w+": "+JSON.stringify(h.edge(t))),function(t,e,n){e.points=e.points.filter((function(t){return !Number.isNaN(t.y)}));var r=e.points,i=(0, l.line)().x((function(t){return t.x})).y((function(t){return t.y})).curve(l.curveBasis),a=t.append("path").attr("d",i(r)).attr("id","edge"+Dc).attr("class","transition"),s="";if(Xt().state.arrowMarkerAbsolute&&(s=(s=(s=window.location.protocol+"//"+window.location.host+window.location.pathname+window.location.search).replace(/\(/g,"\\(")).replace(/\)/g,"\\)")),a.attr("marker-end","url("+s+"#"+function(t){switch(t){case Ec.relationType.AGGREGATION:return "aggregation";case Ec.relationType.EXTENSION:return "extension";case Ec.relationType.COMPOSITION:return "composition";case Ec.relationType.DEPENDENCY:return "dependency"}}(Ec.relationType.DEPENDENCY)+"End)"),void 0!==n.title){for(var c=t.append("g").attr("class","stateLabel"),u=An.calcLabelPosition(e.points),h=u.x,f=u.y,d=ue.getRows(n.title),p=0,g=[],y=0,m=0,b=0;b<=d.length;b++){var v=c.append("text").attr("text-anchor","middle").text(d[b]).attr("x",h).attr("y",f+p),_=v.node().getBBox();if(y=Math.max(y,_.width),m=Math.min(m,_.x),o.info(_.x,h,f+p),0===p){var x=v.node().getBBox();p=x.height,o.info("Title height",p,f);}g.push(v);}var k=p*d.length;if(d.length>1){var w=(d.length-1)*p*.5;g.forEach((function(t,e){return t.attr("y",f+e*p-w)})),k=p*d.length;}var T=c.node().getBBox();c.insert("rect",":first-child").attr("class","box").attr("x",h-y/2-Xt().state.padding/2).attr("y",f-k/2-Xt().state.padding/2-3.5).attr("width",y+Xt().state.padding).attr("height",k+Xt().state.padding),o.info(T);}Dc++;}(n,h.edge(t),h.edge(t).relation));})),E=T.getBBox();var C={id:r||"root",label:r||"root",width:0,height:0};return C.width=E.width+2*Ac.padding,C.height=E.height+2*Ac.padding,o.debug("Doc rendered",C,h),C};const Ic={setConf:function(){},draw:function(t,e,n,r){Ac=Xt().state;var i,a=Xt().securityLevel;"sandbox"===a&&(i=(0, l.select)("#i"+e));var s="sandbox"===a?(0, l.select)(i.nodes()[0].contentDocument.body):(0, l.select)("body"),c="sandbox"===a?i.nodes()[0].contentDocument:document;o.debug("Rendering diagram "+t);var u=s.select("[id='".concat(e,"']"));u.append("defs").append("marker").attr("id","dependencyEnd").attr("refX",19).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 19,7 L9,13 L14,7 L9,1 Z"),new(yr().Graph)({multigraph:!0,compound:!0,rankdir:"RL"}).setDefaultEdgeLabel((function(){return {}}));var h=r.db.getRootDoc();Lc(h,u,void 0,!1,s,c,r);var f=Ac.padding,d=u.node().getBBox(),p=d.width+2*f,g=d.height+2*f;Tn(u,0,1.75*p,Ac.useMaxWidth),u.attr("viewBox","".concat(d.x-Ac.padding," ").concat(d.y-Ac.padding," ")+p+" "+g),Mn(r.db,u,e);}};var Fc={},Rc={},Pc=function(t,e,n,r){if("root"!==n.id){var i="rect";!0===n.start&&(i="start"),!1===n.start&&(i="end"),"default"!==n.type&&(i=n.type),Rc[n.id]||(Rc[n.id]={id:n.id,shape:i,description:ue.sanitizeText(n.id,Xt()),classes:"statediagram-state"}),n.description&&(Array.isArray(Rc[n.id].description)?(Rc[n.id].shape="rectWithTitle",Rc[n.id].description.push(n.description)):Rc[n.id].description.length>0?(Rc[n.id].shape="rectWithTitle",Rc[n.id].description===n.id?Rc[n.id].description=[n.description]:Rc[n.id].description=[Rc[n.id].description,n.description]):(Rc[n.id].shape="rect",Rc[n.id].description=n.description),Rc[n.id].description=ue.sanitizeTextOrArray(Rc[n.id].description,Xt())),1===Rc[n.id].description.length&&"rectWithTitle"===Rc[n.id].shape&&(Rc[n.id].shape="rect"),!Rc[n.id].type&&n.doc&&(o.info("Setting cluster for ",n.id,Yc(n)),Rc[n.id].type="group",Rc[n.id].dir=Yc(n),Rc[n.id].shape="divider"===n.type?"divider":"roundedWithTitle",Rc[n.id].classes=Rc[n.id].classes+" "+(r?"statediagram-cluster statediagram-cluster-alt":"statediagram-cluster"));var a={labelStyle:"",shape:Rc[n.id].shape,labelText:Rc[n.id].description,classes:Rc[n.id].classes,style:"",id:n.id,dir:Rc[n.id].dir,domId:"state-"+n.id+"-"+jc,type:Rc[n.id].type,padding:15};if(n.note){var s={labelStyle:"",shape:"note",labelText:n.note.text,classes:"statediagram-note",style:"",id:n.id+"----note-"+jc,domId:"state-"+n.id+"----note-"+jc,type:Rc[n.id].type,padding:15},c={labelStyle:"",shape:"noteGroup",labelText:n.note.text,classes:Rc[n.id].classes,style:"",id:n.id+"----parent",domId:"state-"+n.id+"----parent-"+jc,type:"group",padding:0};jc++,t.setNode(n.id+"----parent",c),t.setNode(s.id,s),t.setNode(n.id,a),t.setParent(n.id,n.id+"----parent"),t.setParent(s.id,n.id+"----parent");var l=n.id,u=s.id;"left of"===n.note.position&&(l=s.id,u=n.id),t.setEdge(l,u,{arrowhead:"none",arrowType:"",style:"fill:none",labelStyle:"",classes:"transition note-edge",arrowheadStyle:"fill: #333",labelpos:"c",labelType:"text",thickness:"normal"});}else t.setNode(n.id,a);}e&&"root"!==e.id&&(o.trace("Setting node ",n.id," to be child of its parent ",e.id),t.setParent(n.id,e.id)),n.doc&&(o.trace("Adding nodes children "),zc(t,n,n.doc,!r));},jc=0,zc=function(t,e,n,r){o.trace("items",n),n.forEach((function(n){if("state"===n.stmt||"default"===n.stmt)Pc(t,e,n,r);else if("relation"===n.stmt){Pc(t,e,n.state1,r),Pc(t,e,n.state2,r);var i={id:"edge"+jc,arrowhead:"normal",arrowTypeEnd:"arrow_barb",style:"fill:none",labelStyle:"",label:ue.sanitizeText(n.description,Xt()),arrowheadStyle:"fill: #333",labelpos:"c",labelType:"text",thickness:"normal",classes:"transition"},a=n.state1.id,o=n.state2.id;t.setEdge(a,o,i,jc),jc++;}}));},Yc=function(t,e){var n=e||"TB";if(t.doc)for(var r=0;r<t.doc.length;r++){var i=t.doc[r];"dir"===i.stmt&&(n=i.value);}return n};const Uc={setConf:function(t){for(var e=Object.keys(t),n=0;n<e.length;n++)Fc[e[n]]=t[e[n]];},getClasses:function(t,e){return o.trace("Extracting classes"),e.sb.clear(),e.parser.parse(t),e.sb.getClasses()},draw:function(t,e,n,r){o.info("Drawing state diagram (v2)",e),Rc={};var i=r.db.getDirection();void 0===i&&(i="LR");var a=Xt().state,s=a.nodeSpacing||50,c=a.rankSpacing||50,u=Xt().securityLevel;o.info(r.db.getRootDocV2()),r.db.extract(r.db.getRootDocV2()),o.info(r.db.getRootDocV2());var h,f=new(yr().Graph)({multigraph:!0,compound:!0}).setGraph({rankdir:Yc(r.db.getRootDocV2()),nodesep:s,ranksep:c,marginx:8,marginy:8}).setDefaultEdgeLabel((function(){return {}}));Pc(f,void 0,r.db.getRootDocV2(),!0),"sandbox"===u&&(h=(0, l.select)("#i"+e));var d="sandbox"===u?(0, l.select)(h.nodes()[0].contentDocument.body):(0, l.select)("body"),p=("sandbox"===u?h.nodes()[0].contentDocument:document,d.select('[id="'.concat(e,'"]'))),g=d.select("#"+e+" g");yi(g,f,["barb"],"statediagram",e);var y=p.node().getBBox(),m=y.width+16,b=y.height+16;p.attr("class","statediagram");var v=p.node().getBBox();Tn(p,0,m,a.useMaxWidth);var _="".concat(v.x-8," ").concat(v.y-8," ").concat(m," ").concat(b);o.debug("viewBox ".concat(_)),p.attr("viewBox",_);for(var x=document.querySelectorAll('[id="'+e+'"] .edgeLabel .label'),k=0;k<x.length;k++){var w=x[k],T=w.getBBox(),E=document.createElementNS("http://www.w3.org/2000/svg","rect");E.setAttribute("rx",0),E.setAttribute("ry",0),E.setAttribute("width",T.width),E.setAttribute("height",T.height),w.insertBefore(E,w.firstChild);}Mn(r.db,p,e);}};function $c(t){return function(t){if(Array.isArray(t))return Wc(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return Wc(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return "Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Wc(t,e):void 0}}(t)||function(){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 Wc(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}var qc="",Hc=[],Vc=[],Gc=[],Xc=function(){for(var t=!0,e=0;e<Gc.length;e++)Gc[e].processed,t=t&&Gc[e].processed;return t};const Zc={parseDirective:function(t,e,n){cu.parseDirective(this,t,e,n);},getConfig:function(){return Xt().journey},clear:function(){Hc.length=0,Vc.length=0,qc="",Gc.length=0,ge();},setDiagramTitle:_e,getDiagramTitle:xe,setAccTitle:ye,getAccTitle:me,setAccDescription:be,getAccDescription:ve,addSection:function(t){qc=t,Hc.push(t);},getSections:function(){return Hc},getTasks:function(){for(var t=Xc(),e=0;!t&&e<100;)t=Xc(),e++;return Vc.push.apply(Vc,Gc),Vc},addTask:function(t,e){var n=e.substr(1).split(":"),r=0,i=[];1===n.length?(r=Number(n[0]),i=[]):(r=Number(n[0]),i=n[1].split(","));var a=i.map((function(t){return t.trim()})),o={section:qc,type:qc,people:a,task:t,score:r};Gc.push(o);},addTaskOrg:function(t){var e={section:qc,type:qc,description:t,task:t,classes:[]};Vc.push(e);},getActors:function(){return t=[],Vc.forEach((function(e){e.people&&t.push.apply(t,$c(e.people));})),$c(new Set(t)).sort();var t;}};var Qc=function(t,e){var n=t.append("rect");return n.attr("x",e.x),n.attr("y",e.y),n.attr("fill",e.fill),n.attr("stroke",e.stroke),n.attr("width",e.width),n.attr("height",e.height),n.attr("rx",e.rx),n.attr("ry",e.ry),void 0!==e.class&&n.attr("class",e.class),n},Kc=function(t,e){var n=t.append("circle");return n.attr("cx",e.cx),n.attr("cy",e.cy),n.attr("class","actor-"+e.pos),n.attr("fill",e.fill),n.attr("stroke",e.stroke),n.attr("r",e.r),void 0!==n.class&&n.attr("class",n.class),void 0!==e.title&&n.append("title").text(e.title),n},Jc=-1,tl=function(){function t(t,e,n,i,a,o,s,c){r(e.append("text").attr("x",n+a/2).attr("y",i+o/2+5).style("font-color",c).style("text-anchor","middle").text(t),s);}function e(t,e,n,i,a,o,s,c,l){for(var u=c.taskFontSize,h=c.taskFontFamily,f=t.split(/<br\s*\/?>/gi),d=0;d<f.length;d++){var p=d*u-u*(f.length-1)/2,g=e.append("text").attr("x",n+a/2).attr("y",i).attr("fill",l).style("text-anchor","middle").style("font-size",u).style("font-family",h);g.append("tspan").attr("x",n+a/2).attr("dy",p).text(f[d]),g.attr("y",i+o/2).attr("dominant-baseline","central").attr("alignment-baseline","central"),r(g,s);}}function n(t,n,i,a,o,s,c,l){var u=n.append("switch"),h=u.append("foreignObject").attr("x",i).attr("y",a).attr("width",o).attr("height",s).attr("position","fixed").append("xhtml:div").style("display","table").style("height","100%").style("width","100%");h.append("div").attr("class","label").style("display","table-cell").style("text-align","center").style("vertical-align","middle").text(t),e(t,u,i,a,o,s,c,l),r(h,c);}function r(t,e){for(var n in e)n in e&&t.attr(n,e[n]);}return function(r){return "fo"===r.textPlacement?n:"old"===r.textPlacement?t:e}}();const el=Kc,nl=function(t,e,n){var r=t.append("g"),i={x:0,y:0,width:100,anchor:"start",height:100,rx:0,ry:0};i.x=e.x,i.y=e.y,i.fill=e.fill,i.width=n.width,i.height=n.height,i.class="journey-section section-type-"+e.num,i.rx=3,i.ry=3,Qc(r,i),tl(n)(e.text,r,i.x,i.y,i.width,i.height,{class:"journey-section section-type-"+e.num},n,e.colour);},rl=function(t,e){var n=e.text.replace(/<br\s*\/?>/gi," "),r=t.append("text");r.attr("x",e.x),r.attr("y",e.y),r.attr("class","legend"),r.style("text-anchor",e.anchor),void 0!==e.class&&r.attr("class",e.class);var i=r.append("tspan");return i.attr("x",e.x+2*e.textMargin),i.text(n),r},il=function(t,e,n){var r,i,a,o=e.x+n.width/2,s=t.append("g");Jc++,s.append("line").attr("id","task"+Jc).attr("x1",o).attr("y1",e.y).attr("x2",o).attr("y2",450).attr("class","task-line").attr("stroke-width","1px").attr("stroke-dasharray","4 2").attr("stroke","#666"),r=s,i={cx:o,cy:300+30*(5-e.score),score:e.score},r.append("circle").attr("cx",i.cx).attr("cy",i.cy).attr("class","face").attr("r",15).attr("stroke-width",2).attr("overflow","visible"),(a=r.append("g")).append("circle").attr("cx",i.cx-5).attr("cy",i.cy-5).attr("r",1.5).attr("stroke-width",2).attr("fill","#666").attr("stroke","#666"),a.append("circle").attr("cx",i.cx+5).attr("cy",i.cy-5).attr("r",1.5).attr("stroke-width",2).attr("fill","#666").attr("stroke","#666"),i.score>3?function(t){var e=(0, l.arc)().startAngle(Math.PI/2).endAngle(Math.PI/2*3).innerRadius(7.5).outerRadius(15/2.2);t.append("path").attr("class","mouth").attr("d",e).attr("transform","translate("+i.cx+","+(i.cy+2)+")");}(a):i.score<3?function(t){var e=(0, l.arc)().startAngle(3*Math.PI/2).endAngle(Math.PI/2*5).innerRadius(7.5).outerRadius(15/2.2);t.append("path").attr("class","mouth").attr("d",e).attr("transform","translate("+i.cx+","+(i.cy+7)+")");}(a):function(t){t.append("line").attr("class","mouth").attr("stroke",2).attr("x1",i.cx-5).attr("y1",i.cy+7).attr("x2",i.cx+5).attr("y2",i.cy+7).attr("class","mouth").attr("stroke-width","1px").attr("stroke","#666");}(a);var c={x:0,y:0,width:100,anchor:"start",height:100,rx:0,ry:0};c.x=e.x,c.y=e.y,c.fill=e.fill,c.width=n.width,c.height=n.height,c.class="task task-type-"+e.num,c.rx=3,c.ry=3,Qc(s,c);var u=e.x+14;e.people.forEach((function(t){var n=e.actors[t].color,r={cx:u,cy:e.y,r:7,fill:n,stroke:"#000",title:t,pos:e.actors[t].position};Kc(s,r),u+=10;})),tl(n)(e.task,s,c.x,c.y,c.width,c.height,{class:"task"},n,e.colour);};var al={},ol=Xt().journey,sl=Xt().journey.leftMargin,cl={data:{startx:void 0,stopx:void 0,starty:void 0,stopy:void 0},verticalPos:0,sequenceItems:[],init:function(){this.sequenceItems=[],this.data={startx:void 0,stopx:void 0,starty:void 0,stopy:void 0},this.verticalPos=0;},updateVal:function(t,e,n,r){void 0===t[e]?t[e]=n:t[e]=r(n,t[e]);},updateBounds:function(t,e,n,r){var i=Xt().journey,a=this,o=0;this.sequenceItems.forEach((function(s){o++;var c=a.sequenceItems.length-o+1;a.updateVal(s,"starty",e-c*i.boxMargin,Math.min),a.updateVal(s,"stopy",r+c*i.boxMargin,Math.max),a.updateVal(cl.data,"startx",t-c*i.boxMargin,Math.min),a.updateVal(cl.data,"stopx",n+c*i.boxMargin,Math.max),a.updateVal(s,"startx",t-c*i.boxMargin,Math.min),a.updateVal(s,"stopx",n+c*i.boxMargin,Math.max),a.updateVal(cl.data,"starty",e-c*i.boxMargin,Math.min),a.updateVal(cl.data,"stopy",r+c*i.boxMargin,Math.max);}));},insert:function(t,e,n,r){var i=Math.min(t,n),a=Math.max(t,n),o=Math.min(e,r),s=Math.max(e,r);this.updateVal(cl.data,"startx",i,Math.min),this.updateVal(cl.data,"starty",o,Math.min),this.updateVal(cl.data,"stopx",a,Math.max),this.updateVal(cl.data,"stopy",s,Math.max),this.updateBounds(i,o,a,s);},bumpVerticalPos:function(t){this.verticalPos=this.verticalPos+t,this.data.stopy=this.verticalPos;},getVerticalPos:function(){return this.verticalPos},getBounds:function(){return this.data}},ll=ol.sectionFills,ul=ol.sectionColours;const hl={setConf:function(t){Object.keys(t).forEach((function(e){ol[e]=t[e];}));},draw:function(t,e,n,r){var i=Xt().journey;r.db.clear(),r.parser.parse(t+"\n");var a,o=Xt().securityLevel;"sandbox"===o&&(a=(0, l.select)("#i"+e));var s="sandbox"===o?(0, l.select)(a.nodes()[0].contentDocument.body):(0, l.select)("body");cl.init();var c=s.select("#"+e);c.append("defs").append("marker").attr("id","arrowhead").attr("refX",5).attr("refY",2).attr("markerWidth",6).attr("markerHeight",4).attr("orient","auto").append("path").attr("d","M 0,0 V 4 L6,2 Z");var u=r.db.getTasks(),h=r.db.getDiagramTitle(),f=r.db.getActors();for(var d in al)delete al[d];var p=0;f.forEach((function(t){al[t]={color:i.actorColours[p%i.actorColours.length],position:p},p++;})),function(t){var e=Xt().journey,n=60;Object.keys(al).forEach((function(r){var i=al[r].color,a={cx:20,cy:n,r:7,fill:i,stroke:"#000",pos:al[r].position};el(t,a);var o={x:40,y:n+7,fill:"#666",text:r,textMargin:5|e.boxTextMargin};rl(t,o),n+=20;}));}(c),cl.insert(0,0,sl,50*Object.keys(al).length),function(t,e,n){for(var r=Xt().journey,i="",a=n+(2*r.height+r.diagramMarginY),o=0,s="#CCC",c="black",l=0,u=0;u<e.length;u++){var h=e[u];if(i!==h.section){s=ll[o%ll.length],l=o%ll.length,c=ul[o%ul.length];var f={x:u*r.taskMargin+u*r.width+sl,y:50,text:h.section,fill:s,num:l,colour:c};nl(t,f,r),i=h.section,o++;}var d=h.people.reduce((function(t,e){return al[e]&&(t[e]=al[e]),t}),{});h.x=u*r.taskMargin+u*r.width+sl,h.y=a,h.width=r.diagramMarginX,h.height=r.diagramMarginY,h.colour=c,h.fill=s,h.num=l,h.actors=d,il(t,h,r),cl.insert(h.x,h.y,h.x+h.width+r.taskMargin,450);}}(c,u,0);var g=cl.getBounds();h&&c.append("text").text(h).attr("x",sl).attr("font-size","4ex").attr("font-weight","bold").attr("y",25);var y=g.stopy-g.starty+2*i.diagramMarginY,m=sl+g.stopx+2*i.diagramMarginX;Tn(c,0,m,i.useMaxWidth),c.append("line").attr("x1",sl).attr("y1",4*i.height).attr("x2",m-sl-4).attr("y2",4*i.height).attr("stroke-width",4).attr("stroke","black").attr("marker-end","url(#arrowhead)");var b=h?70:0;c.attr("viewBox","".concat(g.startx," -25 ").concat(m," ").concat(y+b)),c.attr("preserveAspectRatio","xMinYMin meet"),c.attr("height",y+b+25),Mn(r.db,c,e);}};var fl=n(9763),dl=n.n(fl),pl={c4:{db:Pe,renderer:Zn,parser:He(),init:function(t){Zn.setConf(t.c4);}},class:{db:fr,renderer:Sr,parser:xi(),init:function(t){t.class.arrowMarkerAbsolute=t.arrowMarkerAbsolute,fr.clear();}},error:{db:{},renderer:Bi,parser:{parser:{yy:{}},parse:function(){}},init:function(){}},classDiagram:{db:fr,renderer:vi,parser:xi(),init:function(t){t.class.arrowMarkerAbsolute=t.arrowMarkerAbsolute,fr.clear();}},er:{db:Ei,renderer:Oi,parser:Ii()},flowchart:{db:la,renderer:Na,parser:Fa(),init:function(t){Na.setConf(t.flowchart),t.flowchart.arrowMarkerAbsolute=t.arrowMarkerAbsolute,la.clear(),la.setGen("gen-1");}},"flowchart-v2":{db:la,renderer:La,parser:Fa(),init:function(t){La.setConf(t.flowchart),t.flowchart.arrowMarkerAbsolute=t.arrowMarkerAbsolute,la.clear(),la.setGen("gen-2");}},gantt:{db:go,renderer:bo,parser:_o(),init:function(t){bo.setConf(t.gantt);}},info:{db:wo,renderer:To,parser:Co()},pie:{db:Oo,renderer:Lo,parser:Ao()},requirement:{db:Uo,renderer:Qo,parser:Fo()},sequence:{db:bs,renderer:cc,parser:ts(),init:function(t){t.sequence.arrowMarkerAbsolute=t.arrowMarkerAbsolute,t.sequenceDiagram&&(cc.setConf(Object.assign(t.sequence,t.sequenceDiagram)),console.error("`mermaid config.sequenceDiagram` has been renamed to `config.sequence`. Please update your mermaid config.")),bs.setWrap(t.wrap),cc.setConf(t.sequence);}},state:{db:Ec,renderer:Ic,parser:uc(),init:function(t){t.class.arrowMarkerAbsolute=t.arrowMarkerAbsolute,Ec.clear();}},stateDiagram:{db:Ec,renderer:Uc,parser:uc(),init:function(t){t.class.arrowMarkerAbsolute=t.arrowMarkerAbsolute,Ec.clear();}},journey:{db:Zc,renderer:hl,parser:dl(),init:function(t){hl.setConf(t.journey),Zc.clear();}}},gl=function(){return pl};function yl(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r);}return n}function ml(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?yl(Object(n),!0).forEach((function(e){bl(t,e,n[e]);})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):yl(Object(n)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e));}));}return t}function bl(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var vl=Xt().gitGraph.mainBranchName,_l=Xt().gitGraph.mainBranchOrder,xl={},kl=null,wl={};wl[vl]={name:vl,order:_l};var Tl={};Tl[vl]=kl;var El=vl,Cl="LR",Sl=0;function Al(){return yn({length:7})}var Ml={},Nl=function(t){if(t=ue.sanitizeText(t,Xt()),void 0===Tl[t]){var e=new Error('Trying to checkout branch which is not yet created. (Help try using "branch '+t+'")');throw e.hash={text:"checkout "+t,token:"checkout "+t,line:"1",loc:{first_line:1,last_line:1,first_column:1,last_column:1},expected:['"branch '+t+'"']},e}var n=Tl[El=t];kl=xl[n];};function Ol(t,e,n){var r=t.indexOf(e);-1===r?t.push(n):t.splice(r,1,n);}function Dl(t){var e=t.reduce((function(t,e){return t.seq>e.seq?t:e}),t[0]),n="";t.forEach((function(t){n+=t===e?"\t*":"\t|";}));var r,i,a,s=[n,e.id,e.seq];for(var c in Tl)Tl[c]===e.id&&s.push(c);if(o.debug(s.join(" ")),e.parents&&2==e.parents.length){var l=xl[e.parents[0]];Ol(t,e,l),t.push(xl[e.parents[1]]);}else {if(0==e.parents.length)return;var u=xl[e.parents];Ol(t,e,u);}r=t,i=function(t){return t.id},a=Object.create(null),Dl(t=r.reduce((function(t,e){var n=i(e);return a[n]||(a[n]=!0,t.push(e)),t}),[]));}var Bl=function(){var t=Object.keys(xl).map((function(t){return xl[t]}));return t.forEach((function(t){o.debug(t.id);})),t.sort((function(t,e){return t.seq-e.seq})),t},Ll={NORMAL:0,REVERSE:1,HIGHLIGHT:2,MERGE:3,CHERRY_PICK:4};const Il={parseDirective:function(t,e,n){cu.parseDirective(this,t,e,n);},getConfig:function(){return Xt().gitGraph},setDirection:function(t){Cl=t;},setOptions:function(t){o.debug("options str",t),t=(t=t&&t.trim())||"{}";try{Ml=JSON.parse(t);}catch(t){o.error("error while parsing gitGraph options",t.message);}},getOptions:function(){return Ml},commit:function(t,e,n,r){o.debug("Entering commit:",t,e,n,r),e=ue.sanitizeText(e,Xt()),t=ue.sanitizeText(t,Xt()),r=ue.sanitizeText(r,Xt());var i={id:e||Sl+"-"+Al(),message:t,seq:Sl++,type:n||Ll.NORMAL,tag:r||"",parents:null==kl?[]:[kl.id],branch:El};kl=i,xl[i.id]=i,Tl[El]=i.id,o.debug("in pushCommit "+i.id);},branch:function(t,e){if(t=ue.sanitizeText(t,Xt()),void 0!==Tl[t]){var n=new Error('Trying to create an existing branch. (Help: Either use a new name if you want create a new branch or try using "checkout '+t+'")');throw n.hash={text:"branch "+t,token:"branch "+t,line:"1",loc:{first_line:1,last_line:1,first_column:1,last_column:1},expected:['"checkout '+t+'"']},n}Tl[t]=null!=kl?kl.id:null,wl[t]={name:t,order:e?parseInt(e,10):null},Nl(t),o.debug("in createBranch");},merge:function(t,e,n,r){t=ue.sanitizeText(t,Xt()),e=ue.sanitizeText(e,Xt());var i=xl[Tl[El]],a=xl[Tl[t]];if(El===t){var s=new Error('Incorrect usage of "merge". Cannot merge a branch to itself');throw s.hash={text:"merge "+t,token:"merge "+t,line:"1",loc:{first_line:1,last_line:1,first_column:1,last_column:1},expected:["branch abc"]},s}if(void 0===i||!i){var c=new Error('Incorrect usage of "merge". Current branch ('+El+")has no commits");throw c.hash={text:"merge "+t,token:"merge "+t,line:"1",loc:{first_line:1,last_line:1,first_column:1,last_column:1},expected:["commit"]},c}if(void 0===Tl[t]){var l=new Error('Incorrect usage of "merge". Branch to be merged ('+t+") does not exist");throw l.hash={text:"merge "+t,token:"merge "+t,line:"1",loc:{first_line:1,last_line:1,first_column:1,last_column:1},expected:["branch "+t]},l}if(void 0===a||!a){var u=new Error('Incorrect usage of "merge". Branch to be merged ('+t+") has no commits");throw u.hash={text:"merge "+t,token:"merge "+t,line:"1",loc:{first_line:1,last_line:1,first_column:1,last_column:1},expected:['"commit"']},u}if(i===a){var h=new Error('Incorrect usage of "merge". Both branches have same head');throw h.hash={text:"merge "+t,token:"merge "+t,line:"1",loc:{first_line:1,last_line:1,first_column:1,last_column:1},expected:["branch abc"]},h}if(e&&void 0!==xl[e]){var f=new Error('Incorrect usage of "merge". Commit with id:'+e+" already exists, use different custom Id");throw f.hash={text:"merge "+t+e+n+r,token:"merge "+t+e+n+r,line:"1",loc:{first_line:1,last_line:1,first_column:1,last_column:1},expected:["merge "+t+" "+e+"_UNIQUE "+n+" "+r]},f}var d={id:e||Sl+"-"+Al(),message:"merged branch "+t+" into "+El,seq:Sl++,parents:[null==kl?null:kl.id,Tl[t]],branch:El,type:Ll.MERGE,customType:n,customId:!!e,tag:r||""};kl=d,xl[d.id]=d,Tl[El]=d.id,o.debug(Tl),o.debug("in mergeBranch");},cherryPick:function(t,e){if(t=ue.sanitizeText(t,Xt()),e=ue.sanitizeText(e,Xt()),!t||void 0===xl[t]){var n=new Error('Incorrect usage of "cherryPick". Source commit id should exist and provided');throw n.hash={text:"cherryPick "+t+" "+e,token:"cherryPick "+t+" "+e,line:"1",loc:{first_line:1,last_line:1,first_column:1,last_column:1},expected:["cherry-pick abc"]},n}var r=xl[t],i=r.branch;if(r.type===Ll.MERGE){var a=new Error('Incorrect usage of "cherryPick". Source commit should not be a merge commit');throw a.hash={text:"cherryPick "+t+" "+e,token:"cherryPick "+t+" "+e,line:"1",loc:{first_line:1,last_line:1,first_column:1,last_column:1},expected:["cherry-pick abc"]},a}if(!e||void 0===xl[e]){if(i===El){var s=new Error('Incorrect usage of "cherryPick". Source commit is already on current branch');throw s.hash={text:"cherryPick "+t+" "+e,token:"cherryPick "+t+" "+e,line:"1",loc:{first_line:1,last_line:1,first_column:1,last_column:1},expected:["cherry-pick abc"]},s}var c=xl[Tl[El]];if(void 0===c||!c){var l=new Error('Incorrect usage of "cherry-pick". Current branch ('+El+")has no commits");throw l.hash={text:"cherryPick "+t+" "+e,token:"cherryPick "+t+" "+e,line:"1",loc:{first_line:1,last_line:1,first_column:1,last_column:1},expected:["cherry-pick abc"]},l}var u={id:Sl+"-"+Al(),message:"cherry-picked "+r+" into "+El,seq:Sl++,parents:[null==kl?null:kl.id,r.id],branch:El,type:Ll.CHERRY_PICK,tag:"cherry-pick:"+r.id};kl=u,xl[u.id]=u,Tl[El]=u.id,o.debug(Tl),o.debug("in cheeryPick");}},checkout:Nl,prettyPrint:function(){o.debug(xl),Dl([Bl()[0]]);},clear:function(){xl={},kl=null;var t=Xt().gitGraph.mainBranchName,e=Xt().gitGraph.mainBranchOrder;(Tl={})[t]=null,(wl={})[t]={name:t,order:e},El=t,Sl=0,ge();},getBranchesAsObjArray:function(){return Object.values(wl).map((function(t,e){return null!==t.order?t:ml(ml({},t),{},{order:parseFloat("0.".concat(e),10)})})).sort((function(t,e){return t.order-e.order})).map((function(t){return {name:t.name}}))},getBranches:function(){return Tl},getCommits:function(){return xl},getCommitsArray:Bl,getCurrentBranch:function(){return El},getDirection:function(){return Cl},getHead:function(){return kl},setAccTitle:ye,getAccTitle:me,getAccDescription:ve,setAccDescription:be,commitType:Ll};var Fl={},Rl={},Pl={},jl=[],zl=0,Yl=function(t,e,n){var r=Xt().gitGraph,i=t.append("g").attr("class","commit-bullets"),a=t.append("g").attr("class","commit-labels"),o=0;Object.keys(e).sort((function(t,n){return e[t].seq-e[n].seq})).forEach((function(t,s){var c=e[t],l=Rl[c.branch].pos,u=o+10;if(n){var h,f=void 0!==c.customType&&""!==c.customType?c.customType:c.type;switch(f){case 0:default:h="commit-normal";break;case 1:h="commit-reverse";break;case 2:h="commit-highlight";break;case 3:h="commit-merge";break;case 4:h="commit-cherry-pick";}if(2===f){var d=i.append("rect");d.attr("x",u-10),d.attr("y",l-10),d.attr("height",20),d.attr("width",20),d.attr("class","commit ".concat(c.id," commit-highlight").concat(Rl[c.branch].index%8," ").concat(h,"-outer")),i.append("rect").attr("x",u-6).attr("y",l-6).attr("height",12).attr("width",12).attr("class","commit ".concat(c.id," commit").concat(Rl[c.branch].index%8," ").concat(h,"-inner"));}else if(4===f)i.append("circle").attr("cx",u).attr("cy",l).attr("r",10).attr("class","commit ".concat(c.id," ").concat(h)),i.append("circle").attr("cx",u-3).attr("cy",l+2).attr("r",2.75).attr("fill","#fff").attr("class","commit ".concat(c.id," ").concat(h)),i.append("circle").attr("cx",u+3).attr("cy",l+2).attr("r",2.75).attr("fill","#fff").attr("class","commit ".concat(c.id," ").concat(h)),i.append("line").attr("x1",u+3).attr("y1",l+1).attr("x2",u).attr("y2",l-5).attr("stroke","#fff").attr("class","commit ".concat(c.id," ").concat(h)),i.append("line").attr("x1",u-3).attr("y1",l+1).attr("x2",u).attr("y2",l-5).attr("stroke","#fff").attr("class","commit ".concat(c.id," ").concat(h));else {var p=i.append("circle");if(p.attr("cx",u),p.attr("cy",l),p.attr("r",3===c.type?9:10),p.attr("class","commit ".concat(c.id," commit").concat(Rl[c.branch].index%8)),3===f){var g=i.append("circle");g.attr("cx",u),g.attr("cy",l),g.attr("r",6),g.attr("class","commit ".concat(h," ").concat(c.id," commit").concat(Rl[c.branch].index%8));}1===f&&i.append("path").attr("d","M ".concat(u-5,",").concat(l-5,"L").concat(u+5,",").concat(l+5,"M").concat(u-5,",").concat(l+5,"L").concat(u+5,",").concat(l-5)).attr("class","commit ".concat(h," ").concat(c.id," commit").concat(Rl[c.branch].index%8));}}if(Pl[c.id]={x:o+10,y:l},n){if(4!==c.type&&(c.customId&&3===c.type||3!==c.type)&&r.showCommitLabel){var y=a.append("g"),m=y.insert("rect").attr("class","commit-label-bkg"),b=y.append("text").attr("x",o).attr("y",l+25).attr("class","commit-label").text(c.id),v=b.node().getBBox();if(m.attr("x",o+10-v.width/2-2).attr("y",l+13.5).attr("width",v.width+4).attr("height",v.height+4),b.attr("x",o+10-v.width/2),r.rotateCommitLabel){var _=-7.5-(v.width+10)/25*9.5,x=10+v.width/25*8.5;y.attr("transform","translate("+_+", "+x+") rotate(-45, "+o+", "+l+")");}}if(c.tag){var k=a.insert("polygon"),w=a.append("circle"),T=a.append("text").attr("y",l-16).attr("class","tag-label").text(c.tag),E=T.node().getBBox();T.attr("x",o+10-E.width/2);var C=E.height/2,S=l-19.2;k.attr("class","tag-label-bkg").attr("points","\n ".concat(o-E.width/2-2,",").concat(S+2,"\n ").concat(o-E.width/2-2,",").concat(S-2,"\n ").concat(o+10-E.width/2-4,",").concat(S-C-2,"\n ").concat(o+10+E.width/2+4,",").concat(S-C-2,"\n ").concat(o+10+E.width/2+4,",").concat(S+C+2,"\n ").concat(o+10-E.width/2-4,",").concat(S+C+2)),w.attr("cx",o-E.width/2+2).attr("cy",S).attr("r",1.5).attr("class","tag-hole");}}(o+=50)>zl&&(zl=o);}));},Ul=function t(e,n,r){var i=r||0,a=e+Math.abs(e-n)/2;if(i>5)return a;for(var o=!0,s=0;s<jl.length;s++)Math.abs(jl[s]-a)<10&&(o=!1);return o?(jl.push(a),a):t(e,n-Math.abs(e-n)/5,i+1)};const $l={draw:function(t,e,n,r){Rl={},Pl={},Fl={},zl=0,jl=[];var i=Xt(),a=Xt().gitGraph;o.debug("in gitgraph renderer",t+"\n","id:",e,n),Fl=r.db.getCommits();var s=r.db.getBranchesAsObjArray(),c=0;s.forEach((function(t,e){Rl[t.name]={pos:c,index:e},c+=50+(a.rotateCommitLabel?40:0);}));var u=(0, l.select)('[id="'.concat(e,'"]'));Mn(r.db,u,e),Yl(u,Fl,!1),a.showBranches&&function(t,e){var n=Xt().gitGraph,r=t.append("g");e.forEach((function(t,e){var i=e%8,a=Rl[t.name].pos,o=r.append("line");o.attr("x1",0),o.attr("y1",a),o.attr("x2",zl),o.attr("y2",a),o.attr("class","branch branch"+i),jl.push(a);var s=function(t){var e=document.createElementNS("http://www.w3.org/2000/svg","text"),n=[];n="string"==typeof t?t.split(/\\n|\n|<br\s*\/?>/gi):Array.isArray(t)?t:[];for(var r=0;r<n.length;r++){var i=document.createElementNS("http://www.w3.org/2000/svg","tspan");i.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve"),i.setAttribute("dy","1em"),i.setAttribute("x","0"),i.setAttribute("class","row"),i.textContent=n[r].trim(),e.appendChild(i);}return e}(t.name),c=r.insert("rect"),l=r.insert("g").attr("class","branchLabel").insert("g").attr("class","label branch-label"+i);l.node().appendChild(s);var u=s.getBBox();c.attr("class","branchLabelBkg label"+i).attr("rx",4).attr("ry",4).attr("x",-u.width-4-(!0===n.rotateCommitLabel?30:0)).attr("y",-u.height/2+8).attr("width",u.width+18).attr("height",u.height+4),l.attr("transform","translate("+(-u.width-14-(!0===n.rotateCommitLabel?30:0))+", "+(a-u.height/2-1)+")"),c.attr("transform","translate(-19, "+(a-u.height/2)+")");}));}(u,s),function(t,e){var n=t.append("g").attr("class","commit-arrows");Object.keys(e).forEach((function(t,r){var i=e[t];i.parents&&i.parents.length>0&&i.parents.forEach((function(t){!function(t,e,n,r){var i=Xt(),a=Pl[e.id],o=Pl[n.id],s=function(t,e,n){return Pl[e.id],Pl[t.id],Object.keys(n).filter((function(r){return n[r].branch===e.branch&&n[r].seq>t.seq&&n[r].seq<e.seq})).length>0}(e,n,r);i.arrowMarkerAbsolute&&(window.location.protocol+"//"+window.location.host+window.location.pathname+window.location.search).replace(/\(/g,"\\(").replace(/\)/g,"\\)");var c,l="",u="",h=0,f=0,d=Rl[n.branch].index;if(s){l="A 10 10, 0, 0, 0,",u="A 10 10, 0, 0, 1,",h=10,f=10,d=Rl[n.branch].index;var p=a.y<o.y?Ul(a.y,o.y):Ul(o.y,a.y);c=a.y<o.y?"M ".concat(a.x," ").concat(a.y," L ").concat(a.x," ").concat(p-h," ").concat(l," ").concat(a.x+f," ").concat(p," L ").concat(o.x-h," ").concat(p," ").concat(u," ").concat(o.x," ").concat(p+f," L ").concat(o.x," ").concat(o.y):"M ".concat(a.x," ").concat(a.y," L ").concat(a.x," ").concat(p+h," ").concat(u," ").concat(a.x+f," ").concat(p," L ").concat(o.x-h," ").concat(p," ").concat(l," ").concat(o.x," ").concat(p-f," L ").concat(o.x," ").concat(o.y);}else a.y<o.y&&(l="A 20 20, 0, 0, 0,",h=20,f=20,d=Rl[n.branch].index,c="M ".concat(a.x," ").concat(a.y," L ").concat(a.x," ").concat(o.y-h," ").concat(l," ").concat(a.x+f," ").concat(o.y," L ").concat(o.x," ").concat(o.y)),a.y>o.y&&(l="A 20 20, 0, 0, 0,",h=20,f=20,d=Rl[e.branch].index,c="M ".concat(a.x," ").concat(a.y," L ").concat(o.x-h," ").concat(a.y," ").concat(l," ").concat(o.x," ").concat(a.y-f," L ").concat(o.x," ").concat(o.y)),a.y===o.y&&(d=Rl[e.branch].index,c="M ".concat(a.x," ").concat(a.y," L ").concat(a.x," ").concat(o.y-h," ").concat(l," ").concat(a.x+f," ").concat(o.y," L ").concat(o.x," ").concat(o.y));t.append("path").attr("d",c).attr("class","arrow arrow"+d%8);}(n,e[t],i,e);}));}));}(u,Fl),Yl(u,Fl,!0);var h=a.diagramPadding,f=u.node().getBBox(),d=f.width+2*h,p=f.height+2*h;Tn(u,0,d,i.useMaxWidth);var g="".concat(f.x-h-(a.showBranches&&!0===a.rotateCommitLabel?30:0)," ").concat(f.y-h," ").concat(d," ").concat(p);u.attr("viewBox",g);}};var Wl=n(2553),ql=n.n(Wl);const Hl=function(t){return t.match(/^\s*gitGraph/)?"gitGraph":null},Vl=function(){var t,e,n,r,i,a;t="gitGraph",e=ql(),n=Il,r=$l,i=void 0,a=Hl,pl[t]={parser:e,db:n,renderer:r,init:i},function(t,e){Xe[t]={detector:e};}(t,a);};function Gl(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r);}}function Xl(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var Zl=function(){function t(e){var n,r;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),Xl(this,"type","graph"),Xl(this,"parser",void 0),Xl(this,"renderer",void 0),Xl(this,"db",void 0);var i=gl(),a=Xt();this.txt=e,this.type=Ze(e,a),o.debug("Type "+this.type),this.db=i[this.type].db,null===(n=(r=this.db).clear)||void 0===n||n.call(r),this.renderer=i[this.type].renderer,this.parser=i[this.type].parser,this.parser.parser.yy=this.db,"function"==typeof i[this.type].init&&(i[this.type].init(a),o.debug("Initialized diagram "+this.type,a)),this.txt=this.txt+"\n",this.parser.parser.yy.graphType=this.type,this.parser.parser.yy.parseError=function(t,e){throw {str:t,hash:e}},this.parser.parse(this.txt);}var e,r;return e=t,(r=[{key:"parse",value:function(t){var e=!1;try{t+="\n",this.db.clear(),this.parser.parse(t);}catch(t){if(e=!0,!n.g.mermaid.parseError)throw t;null!=t.str?n.g.mermaid.parseError(t.str,t.hash):n.g.mermaid.parseError(t);}return !e}},{key:"getParser",value:function(){return this.parser}},{key:"getType",value:function(){return this.type}}])&&Gl(e.prototype,r),Object.defineProperty(e,"prototype",{writable:!1}),t}();const Ql=Zl,Kl=function(t){return "g.classGroup text {\n fill: ".concat(t.nodeBorder,";\n fill: ").concat(t.classText,";\n stroke: none;\n font-family: ").concat(t.fontFamily,";\n font-size: 10px;\n\n .title {\n font-weight: bolder;\n }\n\n}\n\n.nodeLabel, .edgeLabel {\n color: ").concat(t.classText,";\n}\n.edgeLabel .label rect {\n fill: ").concat(t.mainBkg,";\n}\n.label text {\n fill: ").concat(t.classText,";\n}\n.edgeLabel .label span {\n background: ").concat(t.mainBkg,";\n}\n\n.classTitle {\n font-weight: bolder;\n}\n.node rect,\n .node circle,\n .node ellipse,\n .node polygon,\n .node path {\n fill: ").concat(t.mainBkg,";\n stroke: ").concat(t.nodeBorder,";\n stroke-width: 1px;\n }\n\n\n.divider {\n stroke: ").concat(t.nodeBorder,";\n stroke: 1;\n}\n\ng.clickable {\n cursor: pointer;\n}\n\ng.classGroup rect {\n fill: ").concat(t.mainBkg,";\n stroke: ").concat(t.nodeBorder,";\n}\n\ng.classGroup line {\n stroke: ").concat(t.nodeBorder,";\n stroke-width: 1;\n}\n\n.classLabel .box {\n stroke: none;\n stroke-width: 0;\n fill: ").concat(t.mainBkg,";\n opacity: 0.5;\n}\n\n.classLabel .label {\n fill: ").concat(t.nodeBorder,";\n font-size: 10px;\n}\n\n.relation {\n stroke: ").concat(t.lineColor,";\n stroke-width: 1;\n fill: none;\n}\n\n.dashed-line{\n stroke-dasharray: 3;\n}\n\n#compositionStart, .composition {\n fill: ").concat(t.lineColor," !important;\n stroke: ").concat(t.lineColor," !important;\n stroke-width: 1;\n}\n\n#compositionEnd, .composition {\n fill: ").concat(t.lineColor," !important;\n stroke: ").concat(t.lineColor," !important;\n stroke-width: 1;\n}\n\n#dependencyStart, .dependency {\n fill: ").concat(t.lineColor," !important;\n stroke: ").concat(t.lineColor," !important;\n stroke-width: 1;\n}\n\n#dependencyStart, .dependency {\n fill: ").concat(t.lineColor," !important;\n stroke: ").concat(t.lineColor," !important;\n stroke-width: 1;\n}\n\n#extensionStart, .extension {\n fill: ").concat(t.lineColor," !important;\n stroke: ").concat(t.lineColor," !important;\n stroke-width: 1;\n}\n\n#extensionEnd, .extension {\n fill: ").concat(t.lineColor," !important;\n stroke: ").concat(t.lineColor," !important;\n stroke-width: 1;\n}\n\n#aggregationStart, .aggregation {\n fill: ").concat(t.mainBkg," !important;\n stroke: ").concat(t.lineColor," !important;\n stroke-width: 1;\n}\n\n#aggregationEnd, .aggregation {\n fill: ").concat(t.mainBkg," !important;\n stroke: ").concat(t.lineColor," !important;\n stroke-width: 1;\n}\n\n#lollipopStart, .lollipop {\n fill: ").concat(t.mainBkg," !important;\n stroke: ").concat(t.lineColor," !important;\n stroke-width: 1;\n}\n\n#lollipopEnd, .lollipop {\n fill: ").concat(t.mainBkg," !important;\n stroke: ").concat(t.lineColor," !important;\n stroke-width: 1;\n}\n\n.edgeTerminals {\n font-size: 11px;\n}\n\n")},Jl=function(t){return ".label {\n font-family: ".concat(t.fontFamily,";\n color: ").concat(t.nodeTextColor||t.textColor,";\n }\n .cluster-label text {\n fill: ").concat(t.titleColor,";\n }\n .cluster-label span {\n color: ").concat(t.titleColor,";\n }\n\n .label text,span {\n fill: ").concat(t.nodeTextColor||t.textColor,";\n color: ").concat(t.nodeTextColor||t.textColor,";\n }\n\n .node rect,\n .node circle,\n .node ellipse,\n .node polygon,\n .node path {\n fill: ").concat(t.mainBkg,";\n stroke: ").concat(t.nodeBorder,";\n stroke-width: 1px;\n }\n\n .node .label {\n text-align: center;\n }\n .node.clickable {\n cursor: pointer;\n }\n\n .arrowheadPath {\n fill: ").concat(t.arrowheadColor,";\n }\n\n .edgePath .path {\n stroke: ").concat(t.lineColor,";\n stroke-width: 2.0px;\n }\n\n .flowchart-link {\n stroke: ").concat(t.lineColor,";\n fill: none;\n }\n\n .edgeLabel {\n background-color: ").concat(t.edgeLabelBackground,";\n rect {\n opacity: 0.5;\n background-color: ").concat(t.edgeLabelBackground,";\n fill: ").concat(t.edgeLabelBackground,";\n }\n text-align: center;\n }\n\n .cluster rect {\n fill: ").concat(t.clusterBkg,";\n stroke: ").concat(t.clusterBorder,";\n stroke-width: 1px;\n }\n\n .cluster text {\n fill: ").concat(t.titleColor,";\n }\n\n .cluster span {\n color: ").concat(t.titleColor,";\n }\n /* .cluster div {\n color: ").concat(t.titleColor,";\n } */\n\n div.mermaidTooltip {\n position: absolute;\n text-align: center;\n max-width: 200px;\n padding: 2px;\n font-family: ").concat(t.fontFamily,";\n font-size: 12px;\n background: ").concat(t.tertiaryColor,";\n border: 1px solid ").concat(t.border2,";\n border-radius: 2px;\n pointer-events: none;\n z-index: 100;\n }\n")},tu=function(t){return "\ndefs #statediagram-barbEnd {\n fill: ".concat(t.transitionColor,";\n stroke: ").concat(t.transitionColor,";\n }\ng.stateGroup text {\n fill: ").concat(t.nodeBorder,";\n stroke: none;\n font-size: 10px;\n}\ng.stateGroup text {\n fill: ").concat(t.textColor,";\n stroke: none;\n font-size: 10px;\n\n}\ng.stateGroup .state-title {\n font-weight: bolder;\n fill: ").concat(t.stateLabelColor,";\n}\n\ng.stateGroup rect {\n fill: ").concat(t.mainBkg,";\n stroke: ").concat(t.nodeBorder,";\n}\n\ng.stateGroup line {\n stroke: ").concat(t.lineColor,";\n stroke-width: 1;\n}\n\n.transition {\n stroke: ").concat(t.transitionColor,";\n stroke-width: 1;\n fill: none;\n}\n\n.stateGroup .composit {\n fill: ").concat(t.background,";\n border-bottom: 1px\n}\n\n.stateGroup .alt-composit {\n fill: #e0e0e0;\n border-bottom: 1px\n}\n\n.state-note {\n stroke: ").concat(t.noteBorderColor,";\n fill: ").concat(t.noteBkgColor,";\n\n text {\n fill: ").concat(t.noteTextColor,";\n stroke: none;\n font-size: 10px;\n }\n}\n\n.stateLabel .box {\n stroke: none;\n stroke-width: 0;\n fill: ").concat(t.mainBkg,";\n opacity: 0.5;\n}\n\n.edgeLabel .label rect {\n fill: ").concat(t.labelBackgroundColor,";\n opacity: 0.5;\n}\n.edgeLabel .label text {\n fill: ").concat(t.transitionLabelColor||t.tertiaryTextColor,";\n}\n.label div .edgeLabel {\n color: ").concat(t.transitionLabelColor||t.tertiaryTextColor,";\n}\n\n.stateLabel text {\n fill: ").concat(t.stateLabelColor,";\n font-size: 10px;\n font-weight: bold;\n}\n\n.node circle.state-start {\n fill: ").concat(t.specialStateColor,";\n stroke: ").concat(t.specialStateColor,";\n}\n\n.node .fork-join {\n fill: ").concat(t.specialStateColor,";\n stroke: ").concat(t.specialStateColor,";\n}\n\n.node circle.state-end {\n fill: ").concat(t.innerEndBackground,";\n stroke: ").concat(t.background,";\n stroke-width: 1.5\n}\n.end-state-inner {\n fill: ").concat(t.compositeBackground||t.background,";\n // stroke: ").concat(t.background,";\n stroke-width: 1.5\n}\n\n.node rect {\n fill: ").concat(t.stateBkg||t.mainBkg,";\n stroke: ").concat(t.stateBorder||t.nodeBorder,";\n stroke-width: 1px;\n}\n.node polygon {\n fill: ").concat(t.mainBkg,";\n stroke: ").concat(t.stateBorder||t.nodeBorder,";;\n stroke-width: 1px;\n}\n#statediagram-barbEnd {\n fill: ").concat(t.lineColor,";\n}\n\n.statediagram-cluster rect {\n fill: ").concat(t.compositeTitleBackground,";\n stroke: ").concat(t.stateBorder||t.nodeBorder,";\n stroke-width: 1px;\n}\n\n.cluster-label, .nodeLabel {\n color: ").concat(t.stateLabelColor,";\n}\n\n.statediagram-cluster rect.outer {\n rx: 5px;\n ry: 5px;\n}\n.statediagram-state .divider {\n stroke: ").concat(t.stateBorder||t.nodeBorder,";\n}\n\n.statediagram-state .title-state {\n rx: 5px;\n ry: 5px;\n}\n.statediagram-cluster.statediagram-cluster .inner {\n fill: ").concat(t.compositeBackground||t.background,";\n}\n.statediagram-cluster.statediagram-cluster-alt .inner {\n fill: ").concat(t.altBackground?t.altBackground:"#efefef",";\n}\n\n.statediagram-cluster .inner {\n rx:0;\n ry:0;\n}\n\n.statediagram-state rect.basic {\n rx: 5px;\n ry: 5px;\n}\n.statediagram-state rect.divider {\n stroke-dasharray: 10,10;\n fill: ").concat(t.altBackground?t.altBackground:"#efefef",";\n}\n\n.note-edge {\n stroke-dasharray: 5;\n}\n\n.statediagram-note rect {\n fill: ").concat(t.noteBkgColor,";\n stroke: ").concat(t.noteBorderColor,";\n stroke-width: 1px;\n rx: 0;\n ry: 0;\n}\n.statediagram-note rect {\n fill: ").concat(t.noteBkgColor,";\n stroke: ").concat(t.noteBorderColor,";\n stroke-width: 1px;\n rx: 0;\n ry: 0;\n}\n\n.statediagram-note text {\n fill: ").concat(t.noteTextColor,";\n}\n\n.statediagram-note .nodeLabel {\n color: ").concat(t.noteTextColor,";\n}\n.statediagram .edgeLabel {\n color: red; // ").concat(t.noteTextColor,";\n}\n\n#dependencyStart, #dependencyEnd {\n fill: ").concat(t.lineColor,";\n stroke: ").concat(t.lineColor,";\n stroke-width: 1;\n}\n")};var eu={flowchart:Jl,"flowchart-v2":Jl,sequence:function(t){return ".actor {\n stroke: ".concat(t.actorBorder,";\n fill: ").concat(t.actorBkg,";\n }\n\n text.actor > tspan {\n fill: ").concat(t.actorTextColor,";\n stroke: none;\n }\n\n .actor-line {\n stroke: ").concat(t.actorLineColor,";\n }\n\n .messageLine0 {\n stroke-width: 1.5;\n stroke-dasharray: none;\n stroke: ").concat(t.signalColor,";\n }\n\n .messageLine1 {\n stroke-width: 1.5;\n stroke-dasharray: 2, 2;\n stroke: ").concat(t.signalColor,";\n }\n\n #arrowhead path {\n fill: ").concat(t.signalColor,";\n stroke: ").concat(t.signalColor,";\n }\n\n .sequenceNumber {\n fill: ").concat(t.sequenceNumberColor,";\n }\n\n #sequencenumber {\n fill: ").concat(t.signalColor,";\n }\n\n #crosshead path {\n fill: ").concat(t.signalColor,";\n stroke: ").concat(t.signalColor,";\n }\n\n .messageText {\n fill: ").concat(t.signalTextColor,";\n stroke: none;\n }\n\n .labelBox {\n stroke: ").concat(t.labelBoxBorderColor,";\n fill: ").concat(t.labelBoxBkgColor,";\n }\n\n .labelText, .labelText > tspan {\n fill: ").concat(t.labelTextColor,";\n stroke: none;\n }\n\n .loopText, .loopText > tspan {\n fill: ").concat(t.loopTextColor,";\n stroke: none;\n }\n\n .loopLine {\n stroke-width: 2px;\n stroke-dasharray: 2, 2;\n stroke: ").concat(t.labelBoxBorderColor,";\n fill: ").concat(t.labelBoxBorderColor,";\n }\n\n .note {\n //stroke: #decc93;\n stroke: ").concat(t.noteBorderColor,";\n fill: ").concat(t.noteBkgColor,";\n }\n\n .noteText, .noteText > tspan {\n fill: ").concat(t.noteTextColor,";\n stroke: none;\n }\n\n .activation0 {\n fill: ").concat(t.activationBkgColor,";\n stroke: ").concat(t.activationBorderColor,";\n }\n\n .activation1 {\n fill: ").concat(t.activationBkgColor,";\n stroke: ").concat(t.activationBorderColor,";\n }\n\n .activation2 {\n fill: ").concat(t.activationBkgColor,";\n stroke: ").concat(t.activationBorderColor,";\n }\n\n .actorPopupMenu {\n position: absolute;\n }\n\n .actorPopupMenuPanel {\n position: absolute;\n fill: ").concat(t.actorBkg,";\n box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);\n filter: drop-shadow(3px 5px 2px rgb(0 0 0 / 0.4));\n}\n .actor-man line {\n stroke: ").concat(t.actorBorder,";\n fill: ").concat(t.actorBkg,";\n }\n .actor-man circle, line {\n stroke: ").concat(t.actorBorder,";\n fill: ").concat(t.actorBkg,";\n stroke-width: 2px;\n }\n")},gantt:function(t){return '\n .mermaid-main-font {\n font-family: "trebuchet ms", verdana, arial, sans-serif;\n font-family: var(--mermaid-font-family);\n }\n .exclude-range {\n fill: '.concat(t.excludeBkgColor,";\n }\n\n .section {\n stroke: none;\n opacity: 0.2;\n }\n\n .section0 {\n fill: ").concat(t.sectionBkgColor,";\n }\n\n .section2 {\n fill: ").concat(t.sectionBkgColor2,";\n }\n\n .section1,\n .section3 {\n fill: ").concat(t.altSectionBkgColor,";\n opacity: 0.2;\n }\n\n .sectionTitle0 {\n fill: ").concat(t.titleColor,";\n }\n\n .sectionTitle1 {\n fill: ").concat(t.titleColor,";\n }\n\n .sectionTitle2 {\n fill: ").concat(t.titleColor,";\n }\n\n .sectionTitle3 {\n fill: ").concat(t.titleColor,";\n }\n\n .sectionTitle {\n text-anchor: start;\n // font-size: ").concat(t.ganttFontSize,";\n // text-height: 14px;\n font-family: 'trebuchet ms', verdana, arial, sans-serif;\n font-family: var(--mermaid-font-family);\n\n }\n\n\n /* Grid and axis */\n\n .grid .tick {\n stroke: ").concat(t.gridColor,";\n opacity: 0.8;\n shape-rendering: crispEdges;\n text {\n font-family: ").concat(t.fontFamily,";\n fill: ").concat(t.textColor,";\n }\n }\n\n .grid path {\n stroke-width: 0;\n }\n\n\n /* Today line */\n\n .today {\n fill: none;\n stroke: ").concat(t.todayLineColor,";\n stroke-width: 2px;\n }\n\n\n /* Task styling */\n\n /* Default task */\n\n .task {\n stroke-width: 2;\n }\n\n .taskText {\n text-anchor: middle;\n font-family: 'trebuchet ms', verdana, arial, sans-serif;\n font-family: var(--mermaid-font-family);\n }\n\n // .taskText:not([font-size]) {\n // font-size: ").concat(t.ganttFontSize,";\n // }\n\n .taskTextOutsideRight {\n fill: ").concat(t.taskTextDarkColor,";\n text-anchor: start;\n // font-size: ").concat(t.ganttFontSize,";\n font-family: 'trebuchet ms', verdana, arial, sans-serif;\n font-family: var(--mermaid-font-family);\n\n }\n\n .taskTextOutsideLeft {\n fill: ").concat(t.taskTextDarkColor,";\n text-anchor: end;\n // font-size: ").concat(t.ganttFontSize,";\n }\n\n /* Special case clickable */\n .task.clickable {\n cursor: pointer;\n }\n .taskText.clickable {\n cursor: pointer;\n fill: ").concat(t.taskTextClickableColor," !important;\n font-weight: bold;\n }\n\n .taskTextOutsideLeft.clickable {\n cursor: pointer;\n fill: ").concat(t.taskTextClickableColor," !important;\n font-weight: bold;\n }\n\n .taskTextOutsideRight.clickable {\n cursor: pointer;\n fill: ").concat(t.taskTextClickableColor," !important;\n font-weight: bold;\n }\n\n /* Specific task settings for the sections*/\n\n .taskText0,\n .taskText1,\n .taskText2,\n .taskText3 {\n fill: ").concat(t.taskTextColor,";\n }\n\n .task0,\n .task1,\n .task2,\n .task3 {\n fill: ").concat(t.taskBkgColor,";\n stroke: ").concat(t.taskBorderColor,";\n }\n\n .taskTextOutside0,\n .taskTextOutside2\n {\n fill: ").concat(t.taskTextOutsideColor,";\n }\n\n .taskTextOutside1,\n .taskTextOutside3 {\n fill: ").concat(t.taskTextOutsideColor,";\n }\n\n\n /* Active task */\n\n .active0,\n .active1,\n .active2,\n .active3 {\n fill: ").concat(t.activeTaskBkgColor,";\n stroke: ").concat(t.activeTaskBorderColor,";\n }\n\n .activeText0,\n .activeText1,\n .activeText2,\n .activeText3 {\n fill: ").concat(t.taskTextDarkColor," !important;\n }\n\n\n /* Completed task */\n\n .done0,\n .done1,\n .done2,\n .done3 {\n stroke: ").concat(t.doneTaskBorderColor,";\n fill: ").concat(t.doneTaskBkgColor,";\n stroke-width: 2;\n }\n\n .doneText0,\n .doneText1,\n .doneText2,\n .doneText3 {\n fill: ").concat(t.taskTextDarkColor," !important;\n }\n\n\n /* Tasks on the critical line */\n\n .crit0,\n .crit1,\n .crit2,\n .crit3 {\n stroke: ").concat(t.critBorderColor,";\n fill: ").concat(t.critBkgColor,";\n stroke-width: 2;\n }\n\n .activeCrit0,\n .activeCrit1,\n .activeCrit2,\n .activeCrit3 {\n stroke: ").concat(t.critBorderColor,";\n fill: ").concat(t.activeTaskBkgColor,";\n stroke-width: 2;\n }\n\n .doneCrit0,\n .doneCrit1,\n .doneCrit2,\n .doneCrit3 {\n stroke: ").concat(t.critBorderColor,";\n fill: ").concat(t.doneTaskBkgColor,";\n stroke-width: 2;\n cursor: pointer;\n shape-rendering: crispEdges;\n }\n\n .milestone {\n transform: rotate(45deg) scale(0.8,0.8);\n }\n\n .milestoneText {\n font-style: italic;\n }\n .doneCritText0,\n .doneCritText1,\n .doneCritText2,\n .doneCritText3 {\n fill: ").concat(t.taskTextDarkColor," !important;\n }\n\n .activeCritText0,\n .activeCritText1,\n .activeCritText2,\n .activeCritText3 {\n fill: ").concat(t.taskTextDarkColor," !important;\n }\n\n .titleText {\n text-anchor: middle;\n font-size: 18px;\n fill: ").concat(t.textColor," ;\n font-family: 'trebuchet ms', verdana, arial, sans-serif;\n font-family: var(--mermaid-font-family);\n }\n")},classDiagram:Kl,"classDiagram-v2":Kl,class:Kl,stateDiagram:tu,state:tu,gitGraph:function(t){return "\n .commit-id,\n .commit-msg,\n .branch-label {\n fill: lightgrey;\n color: lightgrey;\n font-family: 'trebuchet ms', verdana, arial, sans-serif;\n font-family: var(--mermaid-font-family);\n }\n ".concat([0,1,2,3,4,5,6,7].map((function(e){return "\n .branch-label".concat(e," { fill: ").concat(t["gitBranchLabel"+e],"; }\n .commit").concat(e," { stroke: ").concat(t["git"+e],"; fill: ").concat(t["git"+e],"; }\n .commit-highlight").concat(e," { stroke: ").concat(t["gitInv"+e],"; fill: ").concat(t["gitInv"+e],"; }\n .label").concat(e," { fill: ").concat(t["git"+e],"; }\n .arrow").concat(e," { stroke: ").concat(t["git"+e],"; }\n ")})).join("\n"),"\n\n .branch {\n stroke-width: 1;\n stroke: ").concat(t.lineColor,";\n stroke-dasharray: 2;\n }\n .commit-label { font-size: ").concat(t.commitLabelFontSize,"; fill: ").concat(t.commitLabelColor,";}\n .commit-label-bkg { font-size: ").concat(t.commitLabelFontSize,"; fill: ").concat(t.commitLabelBackground,"; opacity: 0.5; }\n .tag-label { font-size: ").concat(t.tagLabelFontSize,"; fill: ").concat(t.tagLabelColor,";}\n .tag-label-bkg { fill: ").concat(t.tagLabelBackground,"; stroke: ").concat(t.tagLabelBorder,"; }\n .tag-hole { fill: ").concat(t.textColor,"; }\n\n .commit-merge {\n stroke: ").concat(t.primaryColor,";\n fill: ").concat(t.primaryColor,";\n }\n .commit-reverse {\n stroke: ").concat(t.primaryColor,";\n fill: ").concat(t.primaryColor,";\n stroke-width: 3;\n }\n .commit-highlight-outer {\n }\n .commit-highlight-inner {\n stroke: ").concat(t.primaryColor,";\n fill: ").concat(t.primaryColor,";\n }\n\n .arrow { stroke-width: 8; stroke-linecap: round; fill: none}\n }\n")},info:function(){return ""},pie:function(t){return "\n .pieCircle{\n stroke: ".concat(t.pieStrokeColor,";\n stroke-width : ").concat(t.pieStrokeWidth,";\n opacity : ").concat(t.pieOpacity,";\n }\n .pieTitleText {\n text-anchor: middle;\n font-size: ").concat(t.pieTitleTextSize,";\n fill: ").concat(t.pieTitleTextColor,";\n font-family: ").concat(t.fontFamily,";\n }\n .slice {\n font-family: ").concat(t.fontFamily,";\n fill: ").concat(t.pieSectionTextColor,";\n font-size:").concat(t.pieSectionTextSize,";\n // fill: white;\n }\n .legend text {\n fill: ").concat(t.pieLegendTextColor,";\n font-family: ").concat(t.fontFamily,";\n font-size: ").concat(t.pieLegendTextSize,";\n }\n")},er:function(t){return "\n .entityBox {\n fill: ".concat(t.mainBkg,";\n stroke: ").concat(t.nodeBorder,";\n }\n\n .attributeBoxOdd {\n fill: #ffffff;\n stroke: ").concat(t.nodeBorder,";\n }\n\n .attributeBoxEven {\n fill: #f2f2f2;\n stroke: ").concat(t.nodeBorder,";\n }\n\n .relationshipLabelBox {\n fill: ").concat(t.tertiaryColor,";\n opacity: 0.7;\n background-color: ").concat(t.tertiaryColor,";\n rect {\n opacity: 0.5;\n }\n }\n\n .relationshipLine {\n stroke: ").concat(t.lineColor,";\n }\n")},error:function(){return ""},journey:function(t){return ".label {\n font-family: 'trebuchet ms', verdana, arial, sans-serif;\n font-family: var(--mermaid-font-family);\n color: ".concat(t.textColor,";\n }\n .mouth {\n stroke: #666;\n }\n\n line {\n stroke: ").concat(t.textColor,"\n }\n\n .legend {\n fill: ").concat(t.textColor,";\n }\n\n .label text {\n fill: #333;\n }\n .label {\n color: ").concat(t.textColor,"\n }\n\n .face {\n ").concat(t.faceColor?"fill: ".concat(t.faceColor):"fill: #FFF8DC",";\n stroke: #999;\n }\n\n .node rect,\n .node circle,\n .node ellipse,\n .node polygon,\n .node path {\n fill: ").concat(t.mainBkg,";\n stroke: ").concat(t.nodeBorder,";\n stroke-width: 1px;\n }\n\n .node .label {\n text-align: center;\n }\n .node.clickable {\n cursor: pointer;\n }\n\n .arrowheadPath {\n fill: ").concat(t.arrowheadColor,";\n }\n\n .edgePath .path {\n stroke: ").concat(t.lineColor,";\n stroke-width: 1.5px;\n }\n\n .flowchart-link {\n stroke: ").concat(t.lineColor,";\n fill: none;\n }\n\n .edgeLabel {\n background-color: ").concat(t.edgeLabelBackground,";\n rect {\n opacity: 0.5;\n }\n text-align: center;\n }\n\n .cluster rect {\n }\n\n .cluster text {\n fill: ").concat(t.titleColor,";\n }\n\n div.mermaidTooltip {\n position: absolute;\n text-align: center;\n max-width: 200px;\n padding: 2px;\n font-family: 'trebuchet ms', verdana, arial, sans-serif;\n font-family: var(--mermaid-font-family);\n font-size: 12px;\n background: ").concat(t.tertiaryColor,";\n border: 1px solid ").concat(t.border2,";\n border-radius: 2px;\n pointer-events: none;\n z-index: 100;\n }\n\n .task-type-0, .section-type-0 {\n ").concat(t.fillType0?"fill: ".concat(t.fillType0):"",";\n }\n .task-type-1, .section-type-1 {\n ").concat(t.fillType0?"fill: ".concat(t.fillType1):"",";\n }\n .task-type-2, .section-type-2 {\n ").concat(t.fillType0?"fill: ".concat(t.fillType2):"",";\n }\n .task-type-3, .section-type-3 {\n ").concat(t.fillType0?"fill: ".concat(t.fillType3):"",";\n }\n .task-type-4, .section-type-4 {\n ").concat(t.fillType0?"fill: ".concat(t.fillType4):"",";\n }\n .task-type-5, .section-type-5 {\n ").concat(t.fillType0?"fill: ".concat(t.fillType5):"",";\n }\n .task-type-6, .section-type-6 {\n ").concat(t.fillType0?"fill: ".concat(t.fillType6):"",";\n }\n .task-type-7, .section-type-7 {\n ").concat(t.fillType0?"fill: ".concat(t.fillType7):"",";\n }\n\n .actor-0 {\n ").concat(t.actor0?"fill: ".concat(t.actor0):"",";\n }\n .actor-1 {\n ").concat(t.actor1?"fill: ".concat(t.actor1):"",";\n }\n .actor-2 {\n ").concat(t.actor2?"fill: ".concat(t.actor2):"",";\n }\n .actor-3 {\n ").concat(t.actor3?"fill: ".concat(t.actor3):"",";\n }\n .actor-4 {\n ").concat(t.actor4?"fill: ".concat(t.actor4):"",";\n }\n .actor-5 {\n ").concat(t.actor5?"fill: ".concat(t.actor5):"",";\n }\n\n }\n")},requirement:function(t){return "\n\n marker {\n fill: ".concat(t.relationColor,";\n stroke: ").concat(t.relationColor,";\n }\n\n marker.cross {\n stroke: ").concat(t.lineColor,";\n }\n\n svg {\n font-family: ").concat(t.fontFamily,";\n font-size: ").concat(t.fontSize,";\n }\n\n .reqBox {\n fill: ").concat(t.requirementBackground,";\n fill-opacity: 100%;\n stroke: ").concat(t.requirementBorderColor,";\n stroke-width: ").concat(t.requirementBorderSize,";\n }\n \n .reqTitle, .reqLabel{\n fill: ").concat(t.requirementTextColor,";\n }\n .reqLabelBox {\n fill: ").concat(t.relationLabelBackground,";\n fill-opacity: 100%;\n }\n\n .req-title-line {\n stroke: ").concat(t.requirementBorderColor,";\n stroke-width: ").concat(t.requirementBorderSize,";\n }\n .relationshipLine {\n stroke: ").concat(t.relationColor,";\n stroke-width: 1;\n }\n .relationshipLabel {\n fill: ").concat(t.relationLabelColor,";\n }\n\n")},c4:function(t){return ".person {\n stroke: ".concat(t.personBorder,";\n fill: ").concat(t.personBkg,";\n }\n")}};function nu(t){return nu="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},nu(t)}var ru=!1,iu=function(t){var e=t;return (e=(e=e.replace(/fl°°/g,(function(){return "&#"}))).replace(/fl°/g,(function(){return "&"}))).replace(/¶ß/g,(function(){return ";"}))},au={};function ou(t){Na.setConf(t.flowchart),La.setConf(t.flowchart),void 0!==t.sequenceDiagram&&cc.setConf(Q(t.sequence,t.sequenceDiagram)),cc.setConf(t.sequence),bo.setConf(t.gantt),Ic.setConf(t.state),Uc.setConf(t.state),hl.setConf(t.journey),Bi.setConf(t.class);}var su=Object.freeze({render:function(t,e,n,r){ru||(Vl(),ru=!0),Kt();var i=e.replace(/\r\n?/g,"\n"),a=An.detectInit(i);a&&(Cn(a),Qt(a));var s=Xt();o.debug(s),e.length>s.maxTextSize&&(i="graph TB;a[Maximum text size in diagram exceeded];style a fill:#faa");var c,u,h=(0, l.select)("body");if(void 0!==r){if("sandbox"===s.securityLevel){var f=(0, l.select)("body").append("iframe").attr("id","i"+t).attr("style","width: 100%; height: 100%;").attr("sandbox","");(h=(0, l.select)(f.nodes()[0].contentDocument.body)).node().style.margin=0;}if(r.innerHTML="","sandbox"===s.securityLevel){var d=(0, l.select)(r).append("iframe").attr("id","i"+t).attr("style","width: 100%; height: 100%;").attr("sandbox","");(h=(0, l.select)(d.nodes()[0].contentDocument.body)).node().style.margin=0;}else h=(0, l.select)(r);h.append("div").attr("id","d"+t).attr("style","font-family: "+s.fontFamily).append("svg").attr("id",t).attr("width","100%").attr("xmlns","http://www.w3.org/2000/svg").attr("xmlns:xlink","http://www.w3.org/1999/xlink").append("g");}else {var p,g=document.getElementById(t);if(g&&g.remove(),(p="sandbox"!==s.securityLevel?document.querySelector("#d"+t):document.querySelector("#i"+t))&&p.remove(),"sandbox"===s.securityLevel){var y=(0, l.select)("body").append("iframe").attr("id","i"+t).attr("style","width: 100%; height: 100%;").attr("sandbox","");(h=(0, l.select)(y.nodes()[0].contentDocument.body)).node().style.margin=0;}else h=(0, l.select)("body");h.append("div").attr("id","d"+t).append("svg").attr("id",t).attr("width","100%").attr("xmlns","http://www.w3.org/2000/svg").append("g");}i=i.replace(/style.*:\S*#.*;/g,(function(t){return t.substring(0,t.length-1)})).replace(/classDef.*:\S*#.*;/g,(function(t){return t.substring(0,t.length-1)})).replace(/#\w+;/g,(function(t){var e=t.substring(1,t.length-1);return /^\+?\d+$/.test(e)?"fl°°"+e+"¶ß":"fl°"+e+"¶ß"}));try{c=new Ql(i);}catch(t){c=new Ql("error"),u=t;}var m=h.select("#d"+t).node(),b=c.type,v=m.firstChild,_=v.firstChild,x="";if(void 0!==s.themeCSS&&(x+="\n".concat(s.themeCSS)),void 0!==s.fontFamily&&(x+="\n:root { --mermaid-font-family: ".concat(s.fontFamily,"}")),void 0!==s.altFontFamily&&(x+="\n:root { --mermaid-alt-font-family: ".concat(s.altFontFamily,"}")),"flowchart"===b||"flowchart-v2"===b||"graph"===b){var k=Na.getClasses(i,c),E=s.htmlLabels||s.flowchart.htmlLabels;for(var C in k)E?(x+="\n.".concat(C," > * { ").concat(k[C].styles.join(" !important; ")," !important; }"),x+="\n.".concat(C," span { ").concat(k[C].styles.join(" !important; ")," !important; }")):(x+="\n.".concat(C," path { ").concat(k[C].styles.join(" !important; ")," !important; }"),x+="\n.".concat(C," rect { ").concat(k[C].styles.join(" !important; ")," !important; }"),x+="\n.".concat(C," polygon { ").concat(k[C].styles.join(" !important; ")," !important; }"),x+="\n.".concat(C," ellipse { ").concat(k[C].styles.join(" !important; ")," !important; }"),x+="\n.".concat(C," circle { ").concat(k[C].styles.join(" !important; ")," !important; }"),k[C].textStyles&&(x+="\n.".concat(C," tspan { ").concat(k[C].textStyles.join(" !important; ")," !important; }")));}var S=function(t,e){return w(W("".concat(t,"{").concat(e,"}")),T)}("#".concat(t),function(t,e,n){return " {\n font-family: ".concat(n.fontFamily,";\n font-size: ").concat(n.fontSize,";\n fill: ").concat(n.textColor,"\n }\n\n /* Classes common for multiple diagrams */\n\n .error-icon {\n fill: ").concat(n.errorBkgColor,";\n }\n .error-text {\n fill: ").concat(n.errorTextColor,";\n stroke: ").concat(n.errorTextColor,";\n }\n\n .edge-thickness-normal {\n stroke-width: 2px;\n }\n .edge-thickness-thick {\n stroke-width: 3.5px\n }\n .edge-pattern-solid {\n stroke-dasharray: 0;\n }\n\n .edge-pattern-dashed{\n stroke-dasharray: 3;\n }\n .edge-pattern-dotted {\n stroke-dasharray: 2;\n }\n\n .marker {\n fill: ").concat(n.lineColor,";\n stroke: ").concat(n.lineColor,";\n }\n .marker.cross {\n stroke: ").concat(n.lineColor,";\n }\n\n svg {\n font-family: ").concat(n.fontFamily,";\n font-size: ").concat(n.fontSize,";\n }\n\n ").concat(eu[t](n),"\n\n ").concat(e,"\n")}(b,x,s.themeVariables)),A=document.createElement("style");A.innerHTML="#".concat(t," ")+S,v.insertBefore(A,_);try{c.renderer.draw(i,t,X,c);}catch(e){throw Bi.draw(t,X),e}h.select('[id="'.concat(t,'"]')).selectAll("foreignobject > *").attr("xmlns","http://www.w3.org/1999/xhtml");var M=h.select("#d"+t).node().innerHTML;if(o.debug("cnf.arrowMarkerAbsolute",s.arrowMarkerAbsolute),s.arrowMarkerAbsolute&&"false"!==s.arrowMarkerAbsolute||"sandbox"===s.arrowMarkerAbsolute||(M=M.replace(/marker-end="url\(.*?#/g,'marker-end="url(#',"g")),M=(M=iu(M)).replace(/<br>/g,"<br/>"),"sandbox"===s.securityLevel){var N=h.select("#d"+t+" svg").node(),O="100%";N&&(O=N.viewBox.baseVal.height+"px"),M='<iframe style="width:'.concat("100%",";height:").concat(O,';border:0;margin:0;" src="data:text/html;base64,').concat(btoa('<body style="margin:0">'+M+"</body>"),'" sandbox="allow-top-navigation-by-user-activation allow-popups">\n The “iframe” tag is not supported by your browser.\n</iframe>');}else "loose"!==s.securityLevel&&(M=te().sanitize(M,{ADD_TAGS:["foreignobject"],ADD_ATTR:["dominant-baseline"]}));if(void 0!==n)switch(b){case"flowchart":case"flowchart-v2":n(M,la.bindFunctions);break;case"gantt":n(M,go.bindFunctions);break;case"class":case"classDiagram":n(M,fr.bindFunctions);break;default:n(M);}else o.debug("CB = undefined!");vs.forEach((function(t){t();})),vs=[];var D="sandbox"===s.securityLevel?"#i"+t:"#d"+t,B=(0, l.select)(D).node();if(null!==B&&"function"==typeof B.remove&&(0, l.select)(D).node().remove(),u)throw u;return M},parse:function(t,e){ru||(Vl(),ru=!0);var n=!1;try{var r=e||new Ql(t);return r.db.clear(),r.parse(t)}catch(t){if(n=!0,!fu.parseError)throw t;null!=t.str?fu.parseError(t.str,t.hash):fu.parseError(t);}return !n},parseDirective:function(t,e,n,r){try{if(void 0!==e)switch(e=e.trim(),n){case"open_directive":au={};break;case"type_directive":au.type=e.toLowerCase();break;case"arg_directive":au.args=JSON.parse(e);break;case"close_directive":(function(t,e,n){switch(o.debug("Directive type=".concat(e.type," with args:"),e.args),e.type){case"init":case"initialize":["config"].forEach((function(t){void 0!==e.args[t]&&("flowchart-v2"===n&&(n="flowchart"),e.args[n]=e.args[t],delete e.args[t]);})),o.debug("sanitize in handleDirective",e.args),Cn(e.args),o.debug("sanitize in handleDirective (done)",e.args),Qt(e.args);break;case"wrap":case"nowrap":t&&t.setWrap&&t.setWrap("wrap"===e.type);break;case"themeCss":o.warn("themeCss encountered");break;default:o.warn("Unhandled directive: source: '%%{".concat(e.type,": ").concat(JSON.stringify(e.args?e.args:{}),"}%%"),e);}})(t,au,r),au=null;}}catch(t){o.error("Error while rendering sequenceDiagram directive: ".concat(e," jison context: ").concat(n)),o.error(t.message);}},initialize:function(t){var e;null!=t&&t.fontFamily&&(null!==(e=t.themeVariables)&&void 0!==e&&e.fontFamily||(t.themeVariables={fontFamily:t.fontFamily})),function(t){Ut=Q({},t);}(t),null!=t&&t.theme&&Lt[t.theme]?t.themeVariables=Lt[t.theme].getThemeVariables(t.themeVariables):t&&(t.themeVariables=Lt.default.getThemeVariables(t.themeVariables));var n="object"===nu(t)?function(t){return Wt=Q({},$t),Wt=Q(Wt,t),t.theme&&Lt[t.theme]&&(Wt.themeVariables=Lt[t.theme].getThemeVariables(t.themeVariables)),Ht=Vt(Wt,qt),Wt}(t):Gt();ou(n),s(n.logLevel),ru||(Vl(),ru=!0);},getConfig:Xt,setConfig:function(t){return Q(Ht,t),Xt()},getSiteConfig:Gt,updateSiteConfig:function(t){return Wt=Q(Wt,t),Vt(Wt,qt),Wt},reset:function(){Kt();},globalReset:function(){Kt(),ou(Xt());},defaultConfig:$t});s(Xt().logLevel),Kt(Xt());const cu=su;var lu=function(){var t,e,n=cu.getConfig();arguments.length>=2?(void 0!==arguments[0]&&(hu.sequenceConfig=arguments[0]),t=arguments[1]):t=arguments[0],"function"==typeof arguments[arguments.length-1]?(e=arguments[arguments.length-1],o.debug("Callback function found")):void 0!==n.mermaid&&("function"==typeof n.mermaid.callback?(e=n.mermaid.callback,o.debug("Callback function found")):o.debug("No Callback function found")),t=void 0===t?document.querySelectorAll(".mermaid"):"string"==typeof t?document.querySelectorAll(t):t instanceof window.Node?[t]:t,o.debug("Start On Load before: "+hu.startOnLoad),void 0!==hu.startOnLoad&&(o.debug("Start On Load inner: "+hu.startOnLoad),cu.updateSiteConfig({startOnLoad:hu.startOnLoad})),void 0!==hu.ganttConfig&&cu.updateSiteConfig({gantt:hu.ganttConfig});for(var r,i=new An.initIdGenerator(n.deterministicIds,n.deterministicIDSeed),a=[],s=function(n){o.info("Rendering diagram: "+t[n].id,n);var s=t[n];if(s.getAttribute("data-processed"))return "continue";s.setAttribute("data-processed",!0);var c="mermaid-".concat(i.next());r=s.innerHTML,r=An.entityDecode(r).trim().replace(/<br\s*\/?>/gi,"<br/>");var l=An.detectInit(r);l&&o.debug("Detected early reinit: ",l);try{cu.render(c,r,(function(t,n){s.innerHTML=t,void 0!==e&&e(c),n&&n(s);}),s);}catch(t){o.warn("Catching Error (bootstrap)",t),"function"==typeof hu.parseError&&hu.parseError({error:t,str:t.str,hash:t.hash,message:t.str}),a.push({error:t,str:t.str,hash:t.hash,message:t.str});}},c=0;c<t.length;c++)s(c);if(a.length>0)throw a[0]},uu=function(){hu.startOnLoad?cu.getConfig().startOnLoad&&hu.init():void 0===hu.startOnLoad&&(o.debug("In start, no config"),cu.getConfig().startOnLoad&&hu.init());};"undefined"!=typeof document&&window.addEventListener("load",(function(){uu();}),!1);var hu={startOnLoad:!0,htmlLabels:!0,diagrams:{},mermaidAPI:cu,parse:null!=cu?cu.parse:null,render:null!=cu?cu.render:null,init:function(){try{lu.apply(void 0,arguments);}catch(t){o.warn("Syntax Error rendering"),o.warn(t.str);}},initThrowsErrors:lu,initialize:function(t){void 0!==t.mermaid&&(void 0!==t.mermaid.startOnLoad&&(hu.startOnLoad=t.mermaid.startOnLoad),void 0!==t.mermaid.htmlLabels&&(hu.htmlLabels="false"!==t.mermaid.htmlLabels&&!1!==t.mermaid.htmlLabels)),cu.initialize(t);},contentLoaded:uu,setParseErrorHandler:function(t){hu.parseError=t;}};const fu=hu;},4949:(t,e,n)=>{t.exports={graphlib:n(6614),dagre:n(6478),intersect:n(8114),render:n(5787),util:n(8355),version:n(5689)};},9144:(t,e,n)=>{var r=n(8355);function i(t,e,n,i){var a=t.append("marker").attr("id",e).attr("viewBox","0 0 10 10").attr("refX",9).attr("refY",5).attr("markerUnits","strokeWidth").attr("markerWidth",8).attr("markerHeight",6).attr("orient","auto").append("path").attr("d","M 0 0 L 10 5 L 0 10 z").style("stroke-width",1).style("stroke-dasharray","1,0");r.applyStyle(a,n[i+"Style"]),n[i+"Class"]&&a.attr("class",n[i+"Class"]);}t.exports={default:i,normal:i,vee:function(t,e,n,i){var a=t.append("marker").attr("id",e).attr("viewBox","0 0 10 10").attr("refX",9).attr("refY",5).attr("markerUnits","strokeWidth").attr("markerWidth",8).attr("markerHeight",6).attr("orient","auto").append("path").attr("d","M 0 0 L 10 5 L 0 10 L 4 5 z").style("stroke-width",1).style("stroke-dasharray","1,0");r.applyStyle(a,n[i+"Style"]),n[i+"Class"]&&a.attr("class",n[i+"Class"]);},undirected:function(t,e,n,i){var a=t.append("marker").attr("id",e).attr("viewBox","0 0 10 10").attr("refX",9).attr("refY",5).attr("markerUnits","strokeWidth").attr("markerWidth",8).attr("markerHeight",6).attr("orient","auto").append("path").attr("d","M 0 5 L 10 5").style("stroke-width",1).style("stroke-dasharray","1,0");r.applyStyle(a,n[i+"Style"]),n[i+"Class"]&&a.attr("class",n[i+"Class"]);}};},5632:(t,e,n)=>{var r=n(8355),i=n(4322),a=n(1322);t.exports=function(t,e){var n,o=e.nodes().filter((function(t){return r.isSubgraph(e,t)})),s=t.selectAll("g.cluster").data(o,(function(t){return t}));return s.selectAll("*").remove(),s.enter().append("g").attr("class","cluster").attr("id",(function(t){return e.node(t).id})).style("opacity",0),s=t.selectAll("g.cluster"),r.applyTransition(s,e).style("opacity",1),s.each((function(t){var n=e.node(t),r=i.select(this);i.select(this).append("rect");var o=r.append("g").attr("class","label");a(o,n,n.clusterLabelPos);})),s.selectAll("rect").each((function(t){var n=e.node(t),a=i.select(this);r.applyStyle(a,n.style);})),n=s.exit?s.exit():s.selectAll(null),r.applyTransition(n,e).style("opacity",0).remove(),s};},6315:(t,e,n)=>{var r=n(1034),i=n(1322),a=n(8355),o=n(4322);t.exports=function(t,e){var n,s=t.selectAll("g.edgeLabel").data(e.edges(),(function(t){return a.edgeToId(t)})).classed("update",!0);return s.exit().remove(),s.enter().append("g").classed("edgeLabel",!0).style("opacity",0),(s=t.selectAll("g.edgeLabel")).each((function(t){var n=o.select(this);n.select(".label").remove();var a=e.edge(t),s=i(n,e.edge(t),0,0).classed("label",!0),c=s.node().getBBox();a.labelId&&s.attr("id",a.labelId),r.has(a,"width")||(a.width=c.width),r.has(a,"height")||(a.height=c.height);})),n=s.exit?s.exit():s.selectAll(null),a.applyTransition(n,e).style("opacity",0).remove(),s};},940:(t,e,n)=>{var r=n(1034),i=n(3042),a=n(8355),o=n(4322);function s(t,e){var n=(o.line||o.svg.line)().x((function(t){return t.x})).y((function(t){return t.y}));return (n.curve||n.interpolate)(t.curve),n(e)}t.exports=function(t,e,n){var c=t.selectAll("g.edgePath").data(e.edges(),(function(t){return a.edgeToId(t)})).classed("update",!0),l=function(t,e){var n=t.enter().append("g").attr("class","edgePath").style("opacity",0);return n.append("path").attr("class","path").attr("d",(function(t){var n=e.edge(t),i=e.node(t.v).elem;return s(n,r.range(n.points.length).map((function(){return e=(t=i).getBBox(),{x:(n=t.ownerSVGElement.getScreenCTM().inverse().multiply(t.getScreenCTM()).translate(e.width/2,e.height/2)).e,y:n.f};var t,e,n;})))})),n.append("defs"),n}(c,e);!function(t,e){var n=t.exit();a.applyTransition(n,e).style("opacity",0).remove();}(c,e);var u=void 0!==c.merge?c.merge(l):c;return a.applyTransition(u,e).style("opacity",1),u.each((function(t){var n=o.select(this),r=e.edge(t);r.elem=this,r.id&&n.attr("id",r.id),a.applyClass(n,r.class,(n.classed("update")?"update ":"")+"edgePath");})),u.selectAll("path.path").each((function(t){var n=e.edge(t);n.arrowheadId=r.uniqueId("arrowhead");var c=o.select(this).attr("marker-end",(function(){return "url("+(t=location.href,e=n.arrowheadId,t.split("#")[0]+"#"+e+")");var t,e;})).style("fill","none");a.applyTransition(c,e).attr("d",(function(t){return function(t,e){var n=t.edge(e),r=t.node(e.v),a=t.node(e.w),o=n.points.slice(1,n.points.length-1);return o.unshift(i(r,o[0])),o.push(i(a,o[o.length-1])),s(n,o)}(e,t)})),a.applyStyle(c,n.style);})),u.selectAll("defs *").remove(),u.selectAll("defs").each((function(t){var r=e.edge(t);(0, n[r.arrowhead])(o.select(this),r.arrowheadId,r,"arrowhead");})),u};},607:(t,e,n)=>{var r=n(1034),i=n(1322),a=n(8355),o=n(4322);t.exports=function(t,e,n){var s,c=e.nodes().filter((function(t){return !a.isSubgraph(e,t)})),l=t.selectAll("g.node").data(c,(function(t){return t})).classed("update",!0);return l.exit().remove(),l.enter().append("g").attr("class","node").style("opacity",0),(l=t.selectAll("g.node")).each((function(t){var s=e.node(t),c=o.select(this);a.applyClass(c,s.class,(c.classed("update")?"update ":"")+"node"),c.select("g.label").remove();var l=c.append("g").attr("class","label"),u=i(l,s),h=n[s.shape],f=r.pick(u.node().getBBox(),"width","height");s.elem=this,s.id&&c.attr("id",s.id),s.labelId&&l.attr("id",s.labelId),r.has(s,"width")&&(f.width=s.width),r.has(s,"height")&&(f.height=s.height),f.width+=s.paddingLeft+s.paddingRight,f.height+=s.paddingTop+s.paddingBottom,l.attr("transform","translate("+(s.paddingLeft-s.paddingRight)/2+","+(s.paddingTop-s.paddingBottom)/2+")");var d=o.select(this);d.select(".label-container").remove();var p=h(d,f,s).classed("label-container",!0);a.applyStyle(p,s.style);var g=p.node().getBBox();s.width=g.width,s.height=g.height;})),s=l.exit?l.exit():l.selectAll(null),a.applyTransition(s,e).style("opacity",0).remove(),l};},4322:(t,e,n)=>{var r;if(!r)try{r=n(7543);}catch(t){}r||(r=window.d3),t.exports=r;},6478:(t,e,n)=>{var r;try{r=n(681);}catch(t){}r||(r=window.dagre),t.exports=r;},6614:(t,e,n)=>{var r;try{r=n(8282);}catch(t){}r||(r=window.graphlib),t.exports=r;},8114:(t,e,n)=>{t.exports={node:n(3042),circle:n(6587),ellipse:n(3260),polygon:n(5337),rect:n(8049)};},6587:(t,e,n)=>{var r=n(3260);t.exports=function(t,e,n){return r(t,e,e,n)};},3260:t=>{t.exports=function(t,e,n,r){var i=t.x,a=t.y,o=i-r.x,s=a-r.y,c=Math.sqrt(e*e*s*s+n*n*o*o),l=Math.abs(e*n*o/c);r.x<i&&(l=-l);var u=Math.abs(e*n*s/c);return r.y<a&&(u=-u),{x:i+l,y:a+u}};},6808:t=>{function e(t,e){return t*e>0}t.exports=function(t,n,r,i){var a,o,s,c,l,u,h,f,d,p,g,y,m;if(!(a=n.y-t.y,s=t.x-n.x,l=n.x*t.y-t.x*n.y,d=a*r.x+s*r.y+l,p=a*i.x+s*i.y+l,0!==d&&0!==p&&e(d,p)||(o=i.y-r.y,c=r.x-i.x,u=i.x*r.y-r.x*i.y,h=o*t.x+c*t.y+u,f=o*n.x+c*n.y+u,0!==h&&0!==f&&e(h,f)||0==(g=a*c-o*s))))return y=Math.abs(g/2),{x:(m=s*u-c*l)<0?(m-y)/g:(m+y)/g,y:(m=o*l-a*u)<0?(m-y)/g:(m+y)/g}};},3042:t=>{t.exports=function(t,e){return t.intersect(e)};},5337:(t,e,n)=>{var r=n(6808);t.exports=function(t,e,n){var i=t.x,a=t.y,o=[],s=Number.POSITIVE_INFINITY,c=Number.POSITIVE_INFINITY;e.forEach((function(t){s=Math.min(s,t.x),c=Math.min(c,t.y);}));for(var l=i-t.width/2-s,u=a-t.height/2-c,h=0;h<e.length;h++){var f=e[h],d=e[h<e.length-1?h+1:0],p=r(t,n,{x:l+f.x,y:u+f.y},{x:l+d.x,y:u+d.y});p&&o.push(p);}return o.length?(o.length>1&&o.sort((function(t,e){var r=t.x-n.x,i=t.y-n.y,a=Math.sqrt(r*r+i*i),o=e.x-n.x,s=e.y-n.y,c=Math.sqrt(o*o+s*s);return a<c?-1:a===c?0:1})),o[0]):(console.log("NO INTERSECTION FOUND, RETURN NODE CENTER",t),t)};},8049:t=>{t.exports=function(t,e){var n,r,i=t.x,a=t.y,o=e.x-i,s=e.y-a,c=t.width/2,l=t.height/2;return Math.abs(s)*c>Math.abs(o)*l?(s<0&&(l=-l),n=0===s?0:l*o/s,r=l):(o<0&&(c=-c),n=c,r=0===o?0:c*s/o),{x:i+n,y:a+r}};},8284:(t,e,n)=>{var r=n(8355);t.exports=function(t,e){var n=t.append("foreignObject").attr("width","100000"),i=n.append("xhtml:div");i.attr("xmlns","http://www.w3.org/1999/xhtml");var a=e.label;switch(typeof a){case"function":i.insert(a);break;case"object":i.insert((function(){return a}));break;default:i.html(a);}r.applyStyle(i,e.labelStyle),i.style("display","inline-block"),i.style("white-space","nowrap");var o=i.node().getBoundingClientRect();return n.attr("width",o.width).attr("height",o.height),n};},1322:(t,e,n)=>{var r=n(7318),i=n(8284),a=n(8287);t.exports=function(t,e,n){var o=e.label,s=t.append("g");"svg"===e.labelType?a(s,e):"string"!=typeof o||"html"===e.labelType?i(s,e):r(s,e);var c,l=s.node().getBBox();switch(n){case"top":c=-e.height/2;break;case"bottom":c=e.height/2-l.height;break;default:c=-l.height/2;}return s.attr("transform","translate("+-l.width/2+","+c+")"),s};},8287:(t,e,n)=>{var r=n(8355);t.exports=function(t,e){var n=t;return n.node().appendChild(e.label),r.applyStyle(n,e.labelStyle),n};},7318:(t,e,n)=>{var r=n(8355);t.exports=function(t,e){for(var n=t.append("text"),i=function(t){for(var e,n="",r=!1,i=0;i<t.length;++i)e=t[i],r?(n+="n"===e?"\n":e,r=!1):"\\"===e?r=!0:n+=e;return n}(e.label).split("\n"),a=0;a<i.length;a++)n.append("tspan").attr("xml:space","preserve").attr("dy","1em").attr("x","1").text(i[a]);return r.applyStyle(n,e.labelStyle),n};},1034:(t,e,n)=>{var r;try{r={defaults:n(1747),each:n(6073),isFunction:n(3560),isPlainObject:n(8630),pick:n(9722),has:n(8721),range:n(6026),uniqueId:n(3955)};}catch(t){}r||(r=window._),t.exports=r;},6381:(t,e,n)=>{var r=n(8355),i=n(4322);t.exports=function(t,e){var n=t.filter((function(){return !i.select(this).classed("update")}));function a(t){var n=e.node(t);return "translate("+n.x+","+n.y+")"}n.attr("transform",a),r.applyTransition(t,e).style("opacity",1).attr("transform",a),r.applyTransition(n.selectAll("rect"),e).attr("width",(function(t){return e.node(t).width})).attr("height",(function(t){return e.node(t).height})).attr("x",(function(t){return -e.node(t).width/2})).attr("y",(function(t){return -e.node(t).height/2}));};},4577:(t,e,n)=>{var r=n(8355),i=n(4322),a=n(1034);t.exports=function(t,e){function n(t){var n=e.edge(t);return a.has(n,"x")?"translate("+n.x+","+n.y+")":""}t.filter((function(){return !i.select(this).classed("update")})).attr("transform",n),r.applyTransition(t,e).style("opacity",1).attr("transform",n);};},4849:(t,e,n)=>{var r=n(8355),i=n(4322);t.exports=function(t,e){function n(t){var n=e.node(t);return "translate("+n.x+","+n.y+")"}t.filter((function(){return !i.select(this).classed("update")})).attr("transform",n),r.applyTransition(t,e).style("opacity",1).attr("transform",n);};},5787:(t,e,n)=>{var r=n(1034),i=n(4322),a=n(6478).layout;t.exports=function(){var t=n(607),e=n(5632),i=n(6315),l=n(940),u=n(4849),h=n(4577),f=n(6381),d=n(4418),p=n(9144),g=function(n,g){!function(t){t.nodes().forEach((function(e){var n=t.node(e);r.has(n,"label")||t.children(e).length||(n.label=e),r.has(n,"paddingX")&&r.defaults(n,{paddingLeft:n.paddingX,paddingRight:n.paddingX}),r.has(n,"paddingY")&&r.defaults(n,{paddingTop:n.paddingY,paddingBottom:n.paddingY}),r.has(n,"padding")&&r.defaults(n,{paddingLeft:n.padding,paddingRight:n.padding,paddingTop:n.padding,paddingBottom:n.padding}),r.defaults(n,o),r.each(["paddingLeft","paddingRight","paddingTop","paddingBottom"],(function(t){n[t]=Number(n[t]);})),r.has(n,"width")&&(n._prevWidth=n.width),r.has(n,"height")&&(n._prevHeight=n.height);})),t.edges().forEach((function(e){var n=t.edge(e);r.has(n,"label")||(n.label=""),r.defaults(n,s);}));}(g);var y=c(n,"output"),m=c(y,"clusters"),b=c(y,"edgePaths"),v=i(c(y,"edgeLabels"),g),_=t(c(y,"nodes"),g,d);a(g),u(_,g),h(v,g),l(b,g,p);var x=e(m,g);f(x,g),function(t){r.each(t.nodes(),(function(e){var n=t.node(e);r.has(n,"_prevWidth")?n.width=n._prevWidth:delete n.width,r.has(n,"_prevHeight")?n.height=n._prevHeight:delete n.height,delete n._prevWidth,delete n._prevHeight;}));}(g);};return g.createNodes=function(e){return arguments.length?(t=e,g):t},g.createClusters=function(t){return arguments.length?(e=t,g):e},g.createEdgeLabels=function(t){return arguments.length?(i=t,g):i},g.createEdgePaths=function(t){return arguments.length?(l=t,g):l},g.shapes=function(t){return arguments.length?(d=t,g):d},g.arrows=function(t){return arguments.length?(p=t,g):p},g};var o={paddingLeft:10,paddingRight:10,paddingTop:10,paddingBottom:10,rx:0,ry:0,shape:"rect"},s={arrowhead:"normal",curve:i.curveLinear};function c(t,e){var n=t.select("g."+e);return n.empty()&&(n=t.append("g").attr("class",e)),n}},4418:(t,e,n)=>{var r=n(8049),i=n(3260),a=n(6587),o=n(5337);t.exports={rect:function(t,e,n){var i=t.insert("rect",":first-child").attr("rx",n.rx).attr("ry",n.ry).attr("x",-e.width/2).attr("y",-e.height/2).attr("width",e.width).attr("height",e.height);return n.intersect=function(t){return r(n,t)},i},ellipse:function(t,e,n){var r=e.width/2,a=e.height/2,o=t.insert("ellipse",":first-child").attr("x",-e.width/2).attr("y",-e.height/2).attr("rx",r).attr("ry",a);return n.intersect=function(t){return i(n,r,a,t)},o},circle:function(t,e,n){var r=Math.max(e.width,e.height)/2,i=t.insert("circle",":first-child").attr("x",-e.width/2).attr("y",-e.height/2).attr("r",r);return n.intersect=function(t){return a(n,r,t)},i},diamond:function(t,e,n){var r=e.width*Math.SQRT2/2,i=e.height*Math.SQRT2/2,a=[{x:0,y:-i},{x:-r,y:0},{x:0,y:i},{x:r,y:0}],s=t.insert("polygon",":first-child").attr("points",a.map((function(t){return t.x+","+t.y})).join(" "));return n.intersect=function(t){return o(n,a,t)},s}};},8355:(t,e,n)=>{var r=n(1034);t.exports={isSubgraph:function(t,e){return !!t.children(e).length},edgeToId:function(t){return a(t.v)+":"+a(t.w)+":"+a(t.name)},applyStyle:function(t,e){e&&t.attr("style",e);},applyClass:function(t,e,n){e&&t.attr("class",e).attr("class",n+" "+t.attr("class"));},applyTransition:function(t,e){var n=e.graph();if(r.isPlainObject(n)){var i=n.transition;if(r.isFunction(i))return i(t)}return t}};var i=/:/g;function a(t){return t?String(t).replace(i,"\\:"):""}},5689:t=>{t.exports="0.6.4";},681:(t,e,n)=>{t.exports={graphlib:n(574),layout:n(8123),debug:n(7570),util:{time:n(1138).time,notime:n(1138).notime},version:n(8177)};},2188:(t,e,n)=>{var r=n(8436),i=n(4079);t.exports={run:function(t){var e="greedy"===t.graph().acyclicer?i(t,function(t){return function(e){return t.edge(e).weight}}(t)):function(t){var e=[],n={},i={};return r.forEach(t.nodes(),(function a(o){r.has(i,o)||(i[o]=!0,n[o]=!0,r.forEach(t.outEdges(o),(function(t){r.has(n,t.w)?e.push(t):a(t.w);})),delete n[o]);})),e}(t);r.forEach(e,(function(e){var n=t.edge(e);t.removeEdge(e),n.forwardName=e.name,n.reversed=!0,t.setEdge(e.w,e.v,n,r.uniqueId("rev"));}));},undo:function(t){r.forEach(t.edges(),(function(e){var n=t.edge(e);if(n.reversed){t.removeEdge(e);var r=n.forwardName;delete n.reversed,delete n.forwardName,t.setEdge(e.w,e.v,n,r);}}));}};},1133:(t,e,n)=>{var r=n(8436),i=n(1138);function a(t,e,n,r,a,o){var s={width:0,height:0,rank:o,borderType:e},c=a[e][o-1],l=i.addDummyNode(t,"border",s,n);a[e][o]=l,t.setParent(l,r),c&&t.setEdge(c,l,{weight:1});}t.exports=function(t){r.forEach(t.children(),(function e(n){var i=t.children(n),o=t.node(n);if(i.length&&r.forEach(i,e),r.has(o,"minRank")){o.borderLeft=[],o.borderRight=[];for(var s=o.minRank,c=o.maxRank+1;s<c;++s)a(t,"borderLeft","_bl",n,o,s),a(t,"borderRight","_br",n,o,s);}}));};},3258:(t,e,n)=>{var r=n(8436);function i(t){r.forEach(t.nodes(),(function(e){a(t.node(e));})),r.forEach(t.edges(),(function(e){a(t.edge(e));}));}function a(t){var e=t.width;t.width=t.height,t.height=e;}function o(t){t.y=-t.y;}function s(t){var e=t.x;t.x=t.y,t.y=e;}t.exports={adjust:function(t){var e=t.graph().rankdir.toLowerCase();"lr"!==e&&"rl"!==e||i(t);},undo:function(t){var e=t.graph().rankdir.toLowerCase();"bt"!==e&&"rl"!==e||function(t){r.forEach(t.nodes(),(function(e){o(t.node(e));})),r.forEach(t.edges(),(function(e){var n=t.edge(e);r.forEach(n.points,o),r.has(n,"y")&&o(n);}));}(t),"lr"!==e&&"rl"!==e||(function(t){r.forEach(t.nodes(),(function(e){s(t.node(e));})),r.forEach(t.edges(),(function(e){var n=t.edge(e);r.forEach(n.points,s),r.has(n,"x")&&s(n);}));}(t),i(t));}};},7822:t=>{function e(){var t={};t._next=t._prev=t,this._sentinel=t;}function n(t){t._prev._next=t._next,t._next._prev=t._prev,delete t._next,delete t._prev;}function r(t,e){if("_next"!==t&&"_prev"!==t)return e}t.exports=e,e.prototype.dequeue=function(){var t=this._sentinel,e=t._prev;if(e!==t)return n(e),e},e.prototype.enqueue=function(t){var e=this._sentinel;t._prev&&t._next&&n(t),t._next=e._next,e._next._prev=t,e._next=t,t._prev=e;},e.prototype.toString=function(){for(var t=[],e=this._sentinel,n=e._prev;n!==e;)t.push(JSON.stringify(n,r)),n=n._prev;return "["+t.join(", ")+"]"};},7570:(t,e,n)=>{var r=n(8436),i=n(1138),a=n(574).Graph;t.exports={debugOrdering:function(t){var e=i.buildLayerMatrix(t),n=new a({compound:!0,multigraph:!0}).setGraph({});return r.forEach(t.nodes(),(function(e){n.setNode(e,{label:e}),n.setParent(e,"layer"+t.node(e).rank);})),r.forEach(t.edges(),(function(t){n.setEdge(t.v,t.w,{},t.name);})),r.forEach(e,(function(t,e){var i="layer"+e;n.setNode(i,{rank:"same"}),r.reduce(t,(function(t,e){return n.setEdge(t,e,{style:"invis"}),e}));})),n}};},574:(t,e,n)=>{var r;try{r=n(8282);}catch(t){}r||(r=window.graphlib),t.exports=r;},4079:(t,e,n)=>{var r=n(8436),i=n(574).Graph,a=n(7822);t.exports=function(t,e){if(t.nodeCount()<=1)return [];var n=function(t,e){var n=new i,o=0,s=0;r.forEach(t.nodes(),(function(t){n.setNode(t,{v:t,in:0,out:0});})),r.forEach(t.edges(),(function(t){var r=n.edge(t.v,t.w)||0,i=e(t),a=r+i;n.setEdge(t.v,t.w,a),s=Math.max(s,n.node(t.v).out+=i),o=Math.max(o,n.node(t.w).in+=i);}));var l=r.range(s+o+3).map((function(){return new a})),u=o+1;return r.forEach(n.nodes(),(function(t){c(l,u,n.node(t));})),{graph:n,buckets:l,zeroIdx:u}}(t,e||o),l=function(t,e,n){for(var r,i=[],a=e[e.length-1],o=e[0];t.nodeCount();){for(;r=o.dequeue();)s(t,e,n,r);for(;r=a.dequeue();)s(t,e,n,r);if(t.nodeCount())for(var c=e.length-2;c>0;--c)if(r=e[c].dequeue()){i=i.concat(s(t,e,n,r,!0));break}}return i}(n.graph,n.buckets,n.zeroIdx);return r.flatten(r.map(l,(function(e){return t.outEdges(e.v,e.w)})),!0)};var o=r.constant(1);function s(t,e,n,i,a){var o=a?[]:void 0;return r.forEach(t.inEdges(i.v),(function(r){var i=t.edge(r),s=t.node(r.v);a&&o.push({v:r.v,w:r.w}),s.out-=i,c(e,n,s);})),r.forEach(t.outEdges(i.v),(function(r){var i=t.edge(r),a=r.w,o=t.node(a);o.in-=i,c(e,n,o);})),t.removeNode(i.v),o}function c(t,e,n){n.out?n.in?t[n.out-n.in+e].enqueue(n):t[t.length-1].enqueue(n):t[0].enqueue(n);}},8123:(t,e,n)=>{var r=n(8436),i=n(2188),a=n(5995),o=n(8093),s=n(1138).normalizeRanks,c=n(4219),l=n(1138).removeEmptyRanks,u=n(2981),h=n(1133),f=n(3258),d=n(3408),p=n(7873),g=n(1138),y=n(574).Graph;t.exports=function(t,e){var n=e&&e.debugTiming?g.time:g.notime;n("layout",(function(){var e=n(" buildLayoutGraph",(function(){return function(t){var e=new y({multigraph:!0,compound:!0}),n=C(t.graph());return e.setGraph(r.merge({},b,E(n,m),r.pick(n,v))),r.forEach(t.nodes(),(function(n){var i=C(t.node(n));e.setNode(n,r.defaults(E(i,_),x)),e.setParent(n,t.parent(n));})),r.forEach(t.edges(),(function(n){var i=C(t.edge(n));e.setEdge(n,r.merge({},w,E(i,k),r.pick(i,T)));})),e}(t)}));n(" runLayout",(function(){!function(t,e){e(" makeSpaceForEdgeLabels",(function(){!function(t){var e=t.graph();e.ranksep/=2,r.forEach(t.edges(),(function(n){var r=t.edge(n);r.minlen*=2,"c"!==r.labelpos.toLowerCase()&&("TB"===e.rankdir||"BT"===e.rankdir?r.width+=r.labeloffset:r.height+=r.labeloffset);}));}(t);})),e(" removeSelfEdges",(function(){!function(t){r.forEach(t.edges(),(function(e){if(e.v===e.w){var n=t.node(e.v);n.selfEdges||(n.selfEdges=[]),n.selfEdges.push({e,label:t.edge(e)}),t.removeEdge(e);}}));}(t);})),e(" acyclic",(function(){i.run(t);})),e(" nestingGraph.run",(function(){u.run(t);})),e(" rank",(function(){o(g.asNonCompoundGraph(t));})),e(" injectEdgeLabelProxies",(function(){!function(t){r.forEach(t.edges(),(function(e){var n=t.edge(e);if(n.width&&n.height){var r=t.node(e.v),i={rank:(t.node(e.w).rank-r.rank)/2+r.rank,e};g.addDummyNode(t,"edge-proxy",i,"_ep");}}));}(t);})),e(" removeEmptyRanks",(function(){l(t);})),e(" nestingGraph.cleanup",(function(){u.cleanup(t);})),e(" normalizeRanks",(function(){s(t);})),e(" assignRankMinMax",(function(){!function(t){var e=0;r.forEach(t.nodes(),(function(n){var i=t.node(n);i.borderTop&&(i.minRank=t.node(i.borderTop).rank,i.maxRank=t.node(i.borderBottom).rank,e=r.max(e,i.maxRank));})),t.graph().maxRank=e;}(t);})),e(" removeEdgeLabelProxies",(function(){!function(t){r.forEach(t.nodes(),(function(e){var n=t.node(e);"edge-proxy"===n.dummy&&(t.edge(n.e).labelRank=n.rank,t.removeNode(e));}));}(t);})),e(" normalize.run",(function(){a.run(t);})),e(" parentDummyChains",(function(){c(t);})),e(" addBorderSegments",(function(){h(t);})),e(" order",(function(){d(t);})),e(" insertSelfEdges",(function(){!function(t){var e=g.buildLayerMatrix(t);r.forEach(e,(function(e){var n=0;r.forEach(e,(function(e,i){var a=t.node(e);a.order=i+n,r.forEach(a.selfEdges,(function(e){g.addDummyNode(t,"selfedge",{width:e.label.width,height:e.label.height,rank:a.rank,order:i+ ++n,e:e.e,label:e.label},"_se");})),delete a.selfEdges;}));}));}(t);})),e(" adjustCoordinateSystem",(function(){f.adjust(t);})),e(" position",(function(){p(t);})),e(" positionSelfEdges",(function(){!function(t){r.forEach(t.nodes(),(function(e){var n=t.node(e);if("selfedge"===n.dummy){var r=t.node(n.e.v),i=r.x+r.width/2,a=r.y,o=n.x-i,s=r.height/2;t.setEdge(n.e,n.label),t.removeNode(e),n.label.points=[{x:i+2*o/3,y:a-s},{x:i+5*o/6,y:a-s},{x:i+o,y:a},{x:i+5*o/6,y:a+s},{x:i+2*o/3,y:a+s}],n.label.x=n.x,n.label.y=n.y;}}));}(t);})),e(" removeBorderNodes",(function(){!function(t){r.forEach(t.nodes(),(function(e){if(t.children(e).length){var n=t.node(e),i=t.node(n.borderTop),a=t.node(n.borderBottom),o=t.node(r.last(n.borderLeft)),s=t.node(r.last(n.borderRight));n.width=Math.abs(s.x-o.x),n.height=Math.abs(a.y-i.y),n.x=o.x+n.width/2,n.y=i.y+n.height/2;}})),r.forEach(t.nodes(),(function(e){"border"===t.node(e).dummy&&t.removeNode(e);}));}(t);})),e(" normalize.undo",(function(){a.undo(t);})),e(" fixupEdgeLabelCoords",(function(){!function(t){r.forEach(t.edges(),(function(e){var n=t.edge(e);if(r.has(n,"x"))switch("l"!==n.labelpos&&"r"!==n.labelpos||(n.width-=n.labeloffset),n.labelpos){case"l":n.x-=n.width/2+n.labeloffset;break;case"r":n.x+=n.width/2+n.labeloffset;}}));}(t);})),e(" undoCoordinateSystem",(function(){f.undo(t);})),e(" translateGraph",(function(){!function(t){var e=Number.POSITIVE_INFINITY,n=0,i=Number.POSITIVE_INFINITY,a=0,o=t.graph(),s=o.marginx||0,c=o.marginy||0;function l(t){var r=t.x,o=t.y,s=t.width,c=t.height;e=Math.min(e,r-s/2),n=Math.max(n,r+s/2),i=Math.min(i,o-c/2),a=Math.max(a,o+c/2);}r.forEach(t.nodes(),(function(e){l(t.node(e));})),r.forEach(t.edges(),(function(e){var n=t.edge(e);r.has(n,"x")&&l(n);})),e-=s,i-=c,r.forEach(t.nodes(),(function(n){var r=t.node(n);r.x-=e,r.y-=i;})),r.forEach(t.edges(),(function(n){var a=t.edge(n);r.forEach(a.points,(function(t){t.x-=e,t.y-=i;})),r.has(a,"x")&&(a.x-=e),r.has(a,"y")&&(a.y-=i);})),o.width=n-e+s,o.height=a-i+c;}(t);})),e(" assignNodeIntersects",(function(){!function(t){r.forEach(t.edges(),(function(e){var n,r,i=t.edge(e),a=t.node(e.v),o=t.node(e.w);i.points?(n=i.points[0],r=i.points[i.points.length-1]):(i.points=[],n=o,r=a),i.points.unshift(g.intersectRect(a,n)),i.points.push(g.intersectRect(o,r));}));}(t);})),e(" reversePoints",(function(){!function(t){r.forEach(t.edges(),(function(e){var n=t.edge(e);n.reversed&&n.points.reverse();}));}(t);})),e(" acyclic.undo",(function(){i.undo(t);}));}(e,n);})),n(" updateInputGraph",(function(){!function(t,e){r.forEach(t.nodes(),(function(n){var r=t.node(n),i=e.node(n);r&&(r.x=i.x,r.y=i.y,e.children(n).length&&(r.width=i.width,r.height=i.height));})),r.forEach(t.edges(),(function(n){var i=t.edge(n),a=e.edge(n);i.points=a.points,r.has(a,"x")&&(i.x=a.x,i.y=a.y);})),t.graph().width=e.graph().width,t.graph().height=e.graph().height;}(t,e);}));}));};var m=["nodesep","edgesep","ranksep","marginx","marginy"],b={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},v=["acyclicer","ranker","rankdir","align"],_=["width","height"],x={width:0,height:0},k=["minlen","weight","width","height","labeloffset"],w={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},T=["labelpos"];function E(t,e){return r.mapValues(r.pick(t,e),Number)}function C(t){var e={};return r.forEach(t,(function(t,n){e[n.toLowerCase()]=t;})),e}},8436:(t,e,n)=>{var r;try{r={cloneDeep:n(361),constant:n(5703),defaults:n(1747),each:n(6073),filter:n(3105),find:n(3311),flatten:n(5564),forEach:n(4486),forIn:n(2620),has:n(8721),isUndefined:n(2353),last:n(928),map:n(5161),mapValues:n(6604),max:n(6162),merge:n(3857),min:n(3632),minBy:n(2762),now:n(7771),pick:n(9722),range:n(6026),reduce:n(4061),sortBy:n(9734),uniqueId:n(3955),values:n(2628),zipObject:n(7287)};}catch(t){}r||(r=window._),t.exports=r;},2981:(t,e,n)=>{var r=n(8436),i=n(1138);function a(t,e,n,o,s,c,l){var u=t.children(l);if(u.length){var h=i.addBorderNode(t,"_bt"),f=i.addBorderNode(t,"_bb"),d=t.node(l);t.setParent(h,l),d.borderTop=h,t.setParent(f,l),d.borderBottom=f,r.forEach(u,(function(r){a(t,e,n,o,s,c,r);var i=t.node(r),u=i.borderTop?i.borderTop:r,d=i.borderBottom?i.borderBottom:r,p=i.borderTop?o:2*o,g=u!==d?1:s-c[l]+1;t.setEdge(h,u,{weight:p,minlen:g,nestingEdge:!0}),t.setEdge(d,f,{weight:p,minlen:g,nestingEdge:!0});})),t.parent(l)||t.setEdge(e,h,{weight:0,minlen:s+c[l]});}else l!==e&&t.setEdge(e,l,{weight:0,minlen:n});}t.exports={run:function(t){var e=i.addDummyNode(t,"root",{},"_root"),n=function(t){var e={};function n(i,a){var o=t.children(i);o&&o.length&&r.forEach(o,(function(t){n(t,a+1);})),e[i]=a;}return r.forEach(t.children(),(function(t){n(t,1);})),e}(t),o=r.max(r.values(n))-1,s=2*o+1;t.graph().nestingRoot=e,r.forEach(t.edges(),(function(e){t.edge(e).minlen*=s;}));var c=function(t){return r.reduce(t.edges(),(function(e,n){return e+t.edge(n).weight}),0)}(t)+1;r.forEach(t.children(),(function(r){a(t,e,s,c,o,n,r);})),t.graph().nodeRankFactor=s;},cleanup:function(t){var e=t.graph();t.removeNode(e.nestingRoot),delete e.nestingRoot,r.forEach(t.edges(),(function(e){t.edge(e).nestingEdge&&t.removeEdge(e);}));}};},5995:(t,e,n)=>{var r=n(8436),i=n(1138);t.exports={run:function(t){t.graph().dummyChains=[],r.forEach(t.edges(),(function(e){!function(t,e){var n,r,a,o=e.v,s=t.node(o).rank,c=e.w,l=t.node(c).rank,u=e.name,h=t.edge(e),f=h.labelRank;if(l!==s+1){for(t.removeEdge(e),a=0,++s;s<l;++a,++s)h.points=[],r={width:0,height:0,edgeLabel:h,edgeObj:e,rank:s},n=i.addDummyNode(t,"edge",r,"_d"),s===f&&(r.width=h.width,r.height=h.height,r.dummy="edge-label",r.labelpos=h.labelpos),t.setEdge(o,n,{weight:h.weight},u),0===a&&t.graph().dummyChains.push(n),o=n;t.setEdge(o,c,{weight:h.weight},u);}}(t,e);}));},undo:function(t){r.forEach(t.graph().dummyChains,(function(e){var n,r=t.node(e),i=r.edgeLabel;for(t.setEdge(r.edgeObj,i);r.dummy;)n=t.successors(e)[0],t.removeNode(e),i.points.push({x:r.x,y:r.y}),"edge-label"===r.dummy&&(i.x=r.x,i.y=r.y,i.width=r.width,i.height=r.height),e=n,r=t.node(e);}));}};},5093:(t,e,n)=>{var r=n(8436);t.exports=function(t,e,n){var i,a={};r.forEach(n,(function(n){for(var r,o,s=t.parent(n);s;){if((r=t.parent(s))?(o=a[r],a[r]=s):(o=i,i=s),o&&o!==s)return void e.setEdge(o,s);s=r;}}));};},5439:(t,e,n)=>{var r=n(8436);t.exports=function(t,e){return r.map(e,(function(e){var n=t.inEdges(e);if(n.length){var i=r.reduce(n,(function(e,n){var r=t.edge(n),i=t.node(n.v);return {sum:e.sum+r.weight*i.order,weight:e.weight+r.weight}}),{sum:0,weight:0});return {v:e,barycenter:i.sum/i.weight,weight:i.weight}}return {v:e}}))};},3128:(t,e,n)=>{var r=n(8436),i=n(574).Graph;t.exports=function(t,e,n){var a=function(t){for(var e;t.hasNode(e=r.uniqueId("_root")););return e}(t),o=new i({compound:!0}).setGraph({root:a}).setDefaultNodeLabel((function(e){return t.node(e)}));return r.forEach(t.nodes(),(function(i){var s=t.node(i),c=t.parent(i);(s.rank===e||s.minRank<=e&&e<=s.maxRank)&&(o.setNode(i),o.setParent(i,c||a),r.forEach(t[n](i),(function(e){var n=e.v===i?e.w:e.v,a=o.edge(n,i),s=r.isUndefined(a)?0:a.weight;o.setEdge(n,i,{weight:t.edge(e).weight+s});})),r.has(s,"minRank")&&o.setNode(i,{borderLeft:s.borderLeft[e],borderRight:s.borderRight[e]}));})),o};},6630:(t,e,n)=>{var r=n(8436);function i(t,e,n){for(var i=r.zipObject(n,r.map(n,(function(t,e){return e}))),a=r.flatten(r.map(e,(function(e){return r.sortBy(r.map(t.outEdges(e),(function(e){return {pos:i[e.w],weight:t.edge(e).weight}})),"pos")})),!0),o=1;o<n.length;)o<<=1;var s=2*o-1;o-=1;var c=r.map(new Array(s),(function(){return 0})),l=0;return r.forEach(a.forEach((function(t){var e=t.pos+o;c[e]+=t.weight;for(var n=0;e>0;)e%2&&(n+=c[e+1]),c[e=e-1>>1]+=t.weight;l+=t.weight*n;}))),l}t.exports=function(t,e){for(var n=0,r=1;r<e.length;++r)n+=i(t,e[r-1],e[r]);return n};},3408:(t,e,n)=>{var r=n(8436),i=n(2588),a=n(6630),o=n(1026),s=n(3128),c=n(5093),l=n(574).Graph,u=n(1138);function h(t,e,n){return r.map(e,(function(e){return s(t,e,n)}))}function f(t,e){var n=new l;r.forEach(t,(function(t){var i=t.graph().root,a=o(t,i,n,e);r.forEach(a.vs,(function(e,n){t.node(e).order=n;})),c(t,n,a.vs);}));}function d(t,e){r.forEach(e,(function(e){r.forEach(e,(function(e,n){t.node(e).order=n;}));}));}t.exports=function(t){var e=u.maxRank(t),n=h(t,r.range(1,e+1),"inEdges"),o=h(t,r.range(e-1,-1,-1),"outEdges"),s=i(t);d(t,s);for(var c,l=Number.POSITIVE_INFINITY,p=0,g=0;g<4;++p,++g){f(p%2?n:o,p%4>=2),s=u.buildLayerMatrix(t);var y=a(t,s);y<l&&(g=0,c=r.cloneDeep(s),l=y);}d(t,c);};},2588:(t,e,n)=>{var r=n(8436);t.exports=function(t){var e={},n=r.filter(t.nodes(),(function(e){return !t.children(e).length})),i=r.max(r.map(n,(function(e){return t.node(e).rank}))),a=r.map(r.range(i+1),(function(){return []})),o=r.sortBy(n,(function(e){return t.node(e).rank}));return r.forEach(o,(function n(i){if(!r.has(e,i)){e[i]=!0;var o=t.node(i);a[o.rank].push(i),r.forEach(t.successors(i),n);}})),a};},9567:(t,e,n)=>{var r=n(8436);t.exports=function(t,e){var n={};return r.forEach(t,(function(t,e){var i=n[t.v]={indegree:0,in:[],out:[],vs:[t.v],i:e};r.isUndefined(t.barycenter)||(i.barycenter=t.barycenter,i.weight=t.weight);})),r.forEach(e.edges(),(function(t){var e=n[t.v],i=n[t.w];r.isUndefined(e)||r.isUndefined(i)||(i.indegree++,e.out.push(n[t.w]));})),function(t){var e=[];function n(t){return function(e){var n,i,a,o;e.merged||(r.isUndefined(e.barycenter)||r.isUndefined(t.barycenter)||e.barycenter>=t.barycenter)&&(i=e,a=0,o=0,(n=t).weight&&(a+=n.barycenter*n.weight,o+=n.weight),i.weight&&(a+=i.barycenter*i.weight,o+=i.weight),n.vs=i.vs.concat(n.vs),n.barycenter=a/o,n.weight=o,n.i=Math.min(i.i,n.i),i.merged=!0);}}function i(e){return function(n){n.in.push(e),0==--n.indegree&&t.push(n);}}for(;t.length;){var a=t.pop();e.push(a),r.forEach(a.in.reverse(),n(a)),r.forEach(a.out,i(a));}return r.map(r.filter(e,(function(t){return !t.merged})),(function(t){return r.pick(t,["vs","i","barycenter","weight"])}))}(r.filter(n,(function(t){return !t.indegree})))};},1026:(t,e,n)=>{var r=n(8436),i=n(5439),a=n(9567),o=n(7304);t.exports=function t(e,n,s,c){var l=e.children(n),u=e.node(n),h=u?u.borderLeft:void 0,f=u?u.borderRight:void 0,d={};h&&(l=r.filter(l,(function(t){return t!==h&&t!==f})));var p=i(e,l);r.forEach(p,(function(n){if(e.children(n.v).length){var i=t(e,n.v,s,c);d[n.v]=i,r.has(i,"barycenter")&&(a=n,o=i,r.isUndefined(a.barycenter)?(a.barycenter=o.barycenter,a.weight=o.weight):(a.barycenter=(a.barycenter*a.weight+o.barycenter*o.weight)/(a.weight+o.weight),a.weight+=o.weight));}var a,o;}));var g=a(p,s);!function(t,e){r.forEach(t,(function(t){t.vs=r.flatten(t.vs.map((function(t){return e[t]?e[t].vs:t})),!0);}));}(g,d);var y=o(g,c);if(h&&(y.vs=r.flatten([h,y.vs,f],!0),e.predecessors(h).length)){var m=e.node(e.predecessors(h)[0]),b=e.node(e.predecessors(f)[0]);r.has(y,"barycenter")||(y.barycenter=0,y.weight=0),y.barycenter=(y.barycenter*y.weight+m.order+b.order)/(y.weight+2),y.weight+=2;}return y};},7304:(t,e,n)=>{var r=n(8436),i=n(1138);function a(t,e,n){for(var i;e.length&&(i=r.last(e)).i<=n;)e.pop(),t.push(i.vs),n++;return n}t.exports=function(t,e){var n,o=i.partition(t,(function(t){return r.has(t,"barycenter")})),s=o.lhs,c=r.sortBy(o.rhs,(function(t){return -t.i})),l=[],u=0,h=0,f=0;s.sort((n=!!e,function(t,e){return t.barycenter<e.barycenter?-1:t.barycenter>e.barycenter?1:n?e.i-t.i:t.i-e.i})),f=a(l,c,f),r.forEach(s,(function(t){f+=t.vs.length,l.push(t.vs),u+=t.barycenter*t.weight,h+=t.weight,f=a(l,c,f);}));var d={vs:r.flatten(l,!0)};return h&&(d.barycenter=u/h,d.weight=h),d};},4219:(t,e,n)=>{var r=n(8436);t.exports=function(t){var e=function(t){var e={},n=0;return r.forEach(t.children(),(function i(a){var o=n;r.forEach(t.children(a),i),e[a]={low:o,lim:n++};})),e}(t);r.forEach(t.graph().dummyChains,(function(n){for(var r=t.node(n),i=r.edgeObj,a=function(t,e,n,r){var i,a,o=[],s=[],c=Math.min(e[n].low,e[r].low),l=Math.max(e[n].lim,e[r].lim);i=n;do{i=t.parent(i),o.push(i);}while(i&&(e[i].low>c||l>e[i].lim));for(a=i,i=r;(i=t.parent(i))!==a;)s.push(i);return {path:o.concat(s.reverse()),lca:a}}(t,e,i.v,i.w),o=a.path,s=a.lca,c=0,l=o[c],u=!0;n!==i.w;){if(r=t.node(n),u){for(;(l=o[c])!==s&&t.node(l).maxRank<r.rank;)c++;l===s&&(u=!1);}if(!u){for(;c<o.length-1&&t.node(l=o[c+1]).minRank<=r.rank;)c++;l=o[c];}t.setParent(n,l),n=t.successors(n)[0];}}));};},3573:(t,e,n)=>{var r=n(8436),i=n(574).Graph,a=n(1138);function o(t,e){var n={};return r.reduce(e,(function(e,i){var a=0,o=0,s=e.length,l=r.last(i);return r.forEach(i,(function(e,u){var h=function(t,e){if(t.node(e).dummy)return r.find(t.predecessors(e),(function(e){return t.node(e).dummy}))}(t,e),f=h?t.node(h).order:s;(h||e===l)&&(r.forEach(i.slice(o,u+1),(function(e){r.forEach(t.predecessors(e),(function(r){var i=t.node(r),o=i.order;!(o<a||f<o)||i.dummy&&t.node(e).dummy||c(n,r,e);}));})),o=u+1,a=f);})),i})),n}function s(t,e){var n={};function i(e,i,a,o,s){var l;r.forEach(r.range(i,a),(function(i){l=e[i],t.node(l).dummy&&r.forEach(t.predecessors(l),(function(e){var r=t.node(e);r.dummy&&(r.order<o||r.order>s)&&c(n,e,l);}));}));}return r.reduce(e,(function(e,n){var a,o=-1,s=0;return r.forEach(n,(function(r,c){if("border"===t.node(r).dummy){var l=t.predecessors(r);l.length&&(a=t.node(l[0]).order,i(n,s,c,o,a),s=c,o=a);}i(n,s,n.length,a,e.length);})),n})),n}function c(t,e,n){if(e>n){var r=e;e=n,n=r;}var i=t[e];i||(t[e]=i={}),i[n]=!0;}function l(t,e,n){if(e>n){var i=e;e=n,n=i;}return r.has(t[e],n)}function u(t,e,n,i){var a={},o={},s={};return r.forEach(e,(function(t){r.forEach(t,(function(t,e){a[t]=t,o[t]=t,s[t]=e;}));})),r.forEach(e,(function(t){var e=-1;r.forEach(t,(function(t){var c=i(t);if(c.length){c=r.sortBy(c,(function(t){return s[t]}));for(var u=(c.length-1)/2,h=Math.floor(u),f=Math.ceil(u);h<=f;++h){var d=c[h];o[t]===t&&e<s[d]&&!l(n,t,d)&&(o[d]=t,o[t]=a[t]=a[d],e=s[d]);}}}));})),{root:a,align:o}}function h(t,e,n,a,o){var s={},c=function(t,e,n,a){var o=new i,s=t.graph(),c=function(t,e,n){return function(i,a,o){var s,c=i.node(a),l=i.node(o),u=0;if(u+=c.width/2,r.has(c,"labelpos"))switch(c.labelpos.toLowerCase()){case"l":s=-c.width/2;break;case"r":s=c.width/2;}if(s&&(u+=n?s:-s),s=0,u+=(c.dummy?e:t)/2,u+=(l.dummy?e:t)/2,u+=l.width/2,r.has(l,"labelpos"))switch(l.labelpos.toLowerCase()){case"l":s=l.width/2;break;case"r":s=-l.width/2;}return s&&(u+=n?s:-s),s=0,u}}(s.nodesep,s.edgesep,a);return r.forEach(e,(function(e){var i;r.forEach(e,(function(e){var r=n[e];if(o.setNode(r),i){var a=n[i],s=o.edge(a,r);o.setEdge(a,r,Math.max(c(t,e,i),s||0));}i=e;}));})),o}(t,e,n,o),l=o?"borderLeft":"borderRight";function u(t,e){for(var n=c.nodes(),r=n.pop(),i={};r;)i[r]?t(r):(i[r]=!0,n.push(r),n=n.concat(e(r))),r=n.pop();}return u((function(t){s[t]=c.inEdges(t).reduce((function(t,e){return Math.max(t,s[e.v]+c.edge(e))}),0);}),c.predecessors.bind(c)),u((function(e){var n=c.outEdges(e).reduce((function(t,e){return Math.min(t,s[e.w]-c.edge(e))}),Number.POSITIVE_INFINITY),r=t.node(e);n!==Number.POSITIVE_INFINITY&&r.borderType!==l&&(s[e]=Math.max(s[e],n));}),c.successors.bind(c)),r.forEach(a,(function(t){s[t]=s[n[t]];})),s}function f(t,e){return r.minBy(r.values(e),(function(e){var n=Number.NEGATIVE_INFINITY,i=Number.POSITIVE_INFINITY;return r.forIn(e,(function(e,r){var a=function(t,e){return t.node(e).width}(t,r)/2;n=Math.max(e+a,n),i=Math.min(e-a,i);})),n-i}))}function d(t,e){var n=r.values(e),i=r.min(n),a=r.max(n);r.forEach(["u","d"],(function(n){r.forEach(["l","r"],(function(o){var s,c=n+o,l=t[c];if(l!==e){var u=r.values(l);(s="l"===o?i-r.min(u):a-r.max(u))&&(t[c]=r.mapValues(l,(function(t){return t+s})));}}));}));}function p(t,e){return r.mapValues(t.ul,(function(n,i){if(e)return t[e.toLowerCase()][i];var a=r.sortBy(r.map(t,i));return (a[1]+a[2])/2}))}t.exports={positionX:function(t){var e,n=a.buildLayerMatrix(t),i=r.merge(o(t,n),s(t,n)),c={};r.forEach(["u","d"],(function(a){e="u"===a?n:r.values(n).reverse(),r.forEach(["l","r"],(function(n){"r"===n&&(e=r.map(e,(function(t){return r.values(t).reverse()})));var o=("u"===a?t.predecessors:t.successors).bind(t),s=u(0,e,i,o),l=h(t,e,s.root,s.align,"r"===n);"r"===n&&(l=r.mapValues(l,(function(t){return -t}))),c[a+n]=l;}));}));var l=f(t,c);return d(c,l),p(c,t.graph().align)},findType1Conflicts:o,findType2Conflicts:s,addConflict:c,hasConflict:l,verticalAlignment:u,horizontalCompaction:h,alignCoordinates:d,findSmallestWidthAlignment:f,balance:p};},7873:(t,e,n)=>{var r=n(8436),i=n(1138),a=n(3573).positionX;t.exports=function(t){(function(t){var e=i.buildLayerMatrix(t),n=t.graph().ranksep,a=0;r.forEach(e,(function(e){var i=r.max(r.map(e,(function(e){return t.node(e).height})));r.forEach(e,(function(e){t.node(e).y=a+i/2;})),a+=i+n;}));})(t=i.asNonCompoundGraph(t)),r.forEach(a(t),(function(e,n){t.node(n).x=e;}));};},300:(t,e,n)=>{var r=n(8436),i=n(574).Graph,a=n(6681).slack;function o(t,e){return r.forEach(t.nodes(),(function n(i){r.forEach(e.nodeEdges(i),(function(r){var o=r.v,s=i===o?r.w:o;t.hasNode(s)||a(e,r)||(t.setNode(s,{}),t.setEdge(i,s,{}),n(s));}));})),t.nodeCount()}function s(t,e){return r.minBy(e.edges(),(function(n){if(t.hasNode(n.v)!==t.hasNode(n.w))return a(e,n)}))}function c(t,e,n){r.forEach(t.nodes(),(function(t){e.node(t).rank+=n;}));}t.exports=function(t){var e,n,r=new i({directed:!1}),l=t.nodes()[0],u=t.nodeCount();for(r.setNode(l,{});o(r,t)<u;)e=s(r,t),n=r.hasNode(e.v)?a(t,e):-a(t,e),c(r,t,n);return r};},8093:(t,e,n)=>{var r=n(6681).longestPath,i=n(300),a=n(2472);t.exports=function(t){switch(t.graph().ranker){case"network-simplex":default:!function(t){a(t);}(t);break;case"tight-tree":!function(t){r(t),i(t);}(t);break;case"longest-path":o(t);}};var o=r;},2472:(t,e,n)=>{var r=n(8436),i=n(300),a=n(6681).slack,o=n(6681).longestPath,s=n(574).alg.preorder,c=n(574).alg.postorder,l=n(1138).simplify;function u(t){t=l(t),o(t);var e,n=i(t);for(d(n),h(n,t);e=g(n);)m(n,t,e,y(n,t,e));}function h(t,e){var n=c(t,t.nodes());n=n.slice(0,n.length-1),r.forEach(n,(function(n){!function(t,e,n){var r=t.node(n).parent;t.edge(n,r).cutvalue=f(t,e,n);}(t,e,n);}));}function f(t,e,n){var i=t.node(n).parent,a=!0,o=e.edge(n,i),s=0;return o||(a=!1,o=e.edge(i,n)),s=o.weight,r.forEach(e.nodeEdges(n),(function(r){var o,c,l=r.v===n,u=l?r.w:r.v;if(u!==i){var h=l===a,f=e.edge(r).weight;if(s+=h?f:-f,o=n,c=u,t.hasEdge(o,c)){var d=t.edge(n,u).cutvalue;s+=h?-d:d;}}})),s}function d(t,e){arguments.length<2&&(e=t.nodes()[0]),p(t,{},1,e);}function p(t,e,n,i,a){var o=n,s=t.node(i);return e[i]=!0,r.forEach(t.neighbors(i),(function(a){r.has(e,a)||(n=p(t,e,n,a,i));})),s.low=o,s.lim=n++,a?s.parent=a:delete s.parent,n}function g(t){return r.find(t.edges(),(function(e){return t.edge(e).cutvalue<0}))}function y(t,e,n){var i=n.v,o=n.w;e.hasEdge(i,o)||(i=n.w,o=n.v);var s=t.node(i),c=t.node(o),l=s,u=!1;s.lim>c.lim&&(l=c,u=!0);var h=r.filter(e.edges(),(function(e){return u===b(0,t.node(e.v),l)&&u!==b(0,t.node(e.w),l)}));return r.minBy(h,(function(t){return a(e,t)}))}function m(t,e,n,i){var a=n.v,o=n.w;t.removeEdge(a,o),t.setEdge(i.v,i.w,{}),d(t),h(t,e),function(t,e){var n=r.find(t.nodes(),(function(t){return !e.node(t).parent})),i=s(t,n);i=i.slice(1),r.forEach(i,(function(n){var r=t.node(n).parent,i=e.edge(n,r),a=!1;i||(i=e.edge(r,n),a=!0),e.node(n).rank=e.node(r).rank+(a?i.minlen:-i.minlen);}));}(t,e);}function b(t,e,n){return n.low<=e.lim&&e.lim<=n.lim}t.exports=u,u.initLowLimValues=d,u.initCutValues=h,u.calcCutValue=f,u.leaveEdge=g,u.enterEdge=y,u.exchangeEdges=m;},6681:(t,e,n)=>{var r=n(8436);t.exports={longestPath:function(t){var e={};r.forEach(t.sources(),(function n(i){var a=t.node(i);if(r.has(e,i))return a.rank;e[i]=!0;var o=r.min(r.map(t.outEdges(i),(function(e){return n(e.w)-t.edge(e).minlen})));return o!==Number.POSITIVE_INFINITY&&null!=o||(o=0),a.rank=o}));},slack:function(t,e){return t.node(e.w).rank-t.node(e.v).rank-t.edge(e).minlen}};},1138:(t,e,n)=>{var r=n(8436),i=n(574).Graph;function a(t,e,n,i){var a;do{a=r.uniqueId(i);}while(t.hasNode(a));return n.dummy=e,t.setNode(a,n),a}function o(t){return r.max(r.map(t.nodes(),(function(e){var n=t.node(e).rank;if(!r.isUndefined(n))return n})))}t.exports={addDummyNode:a,simplify:function(t){var e=(new i).setGraph(t.graph());return r.forEach(t.nodes(),(function(n){e.setNode(n,t.node(n));})),r.forEach(t.edges(),(function(n){var r=e.edge(n.v,n.w)||{weight:0,minlen:1},i=t.edge(n);e.setEdge(n.v,n.w,{weight:r.weight+i.weight,minlen:Math.max(r.minlen,i.minlen)});})),e},asNonCompoundGraph:function(t){var e=new i({multigraph:t.isMultigraph()}).setGraph(t.graph());return r.forEach(t.nodes(),(function(n){t.children(n).length||e.setNode(n,t.node(n));})),r.forEach(t.edges(),(function(n){e.setEdge(n,t.edge(n));})),e},successorWeights:function(t){var e=r.map(t.nodes(),(function(e){var n={};return r.forEach(t.outEdges(e),(function(e){n[e.w]=(n[e.w]||0)+t.edge(e).weight;})),n}));return r.zipObject(t.nodes(),e)},predecessorWeights:function(t){var e=r.map(t.nodes(),(function(e){var n={};return r.forEach(t.inEdges(e),(function(e){n[e.v]=(n[e.v]||0)+t.edge(e).weight;})),n}));return r.zipObject(t.nodes(),e)},intersectRect:function(t,e){var n,r,i=t.x,a=t.y,o=e.x-i,s=e.y-a,c=t.width/2,l=t.height/2;if(!o&&!s)throw new Error("Not possible to find intersection inside of the rectangle");return Math.abs(s)*c>Math.abs(o)*l?(s<0&&(l=-l),n=l*o/s,r=l):(o<0&&(c=-c),n=c,r=c*s/o),{x:i+n,y:a+r}},buildLayerMatrix:function(t){var e=r.map(r.range(o(t)+1),(function(){return []}));return r.forEach(t.nodes(),(function(n){var i=t.node(n),a=i.rank;r.isUndefined(a)||(e[a][i.order]=n);})),e},normalizeRanks:function(t){var e=r.min(r.map(t.nodes(),(function(e){return t.node(e).rank})));r.forEach(t.nodes(),(function(n){var i=t.node(n);r.has(i,"rank")&&(i.rank-=e);}));},removeEmptyRanks:function(t){var e=r.min(r.map(t.nodes(),(function(e){return t.node(e).rank}))),n=[];r.forEach(t.nodes(),(function(r){var i=t.node(r).rank-e;n[i]||(n[i]=[]),n[i].push(r);}));var i=0,a=t.graph().nodeRankFactor;r.forEach(n,(function(e,n){r.isUndefined(e)&&n%a!=0?--i:i&&r.forEach(e,(function(e){t.node(e).rank+=i;}));}));},addBorderNode:function(t,e,n,r){var i={width:0,height:0};return arguments.length>=4&&(i.rank=n,i.order=r),a(t,"border",i,e)},maxRank:o,partition:function(t,e){var n={lhs:[],rhs:[]};return r.forEach(t,(function(t){e(t)?n.lhs.push(t):n.rhs.push(t);})),n},time:function(t,e){var n=r.now();try{return e()}finally{console.log(t+" time: "+(r.now()-n)+"ms");}},notime:function(t,e){return e()}};},8177:t=>{t.exports="0.8.5";},7856:function(t){t.exports=function(){function t(e){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t(e)}function e(t,n){return e=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t},e(t,n)}function n(){if("undefined"==typeof Reflect||!Reflect.construct)return !1;if(Reflect.construct.sham)return !1;if("function"==typeof Proxy)return !0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return !1}}function r(t,i,a){return r=n()?Reflect.construct:function(t,n,r){var i=[null];i.push.apply(i,n);var a=new(Function.bind.apply(t,i));return r&&e(a,r.prototype),a},r.apply(null,arguments)}function i(t){return function(t){if(Array.isArray(t))return a(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return a(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return "Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?a(t,e):void 0}}(t)||function(){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 a(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}var o=Object.hasOwnProperty,s=Object.setPrototypeOf,c=Object.isFrozen,l=Object.getPrototypeOf,u=Object.getOwnPropertyDescriptor,h=Object.freeze,f=Object.seal,d=Object.create,p="undefined"!=typeof Reflect&&Reflect,g=p.apply,y=p.construct;g||(g=function(t,e,n){return t.apply(e,n)}),h||(h=function(t){return t}),f||(f=function(t){return t}),y||(y=function(t,e){return r(t,i(e))});var m,b=A(Array.prototype.forEach),v=A(Array.prototype.pop),_=A(Array.prototype.push),x=A(String.prototype.toLowerCase),k=A(String.prototype.match),w=A(String.prototype.replace),T=A(String.prototype.indexOf),E=A(String.prototype.trim),C=A(RegExp.prototype.test),S=(m=TypeError,function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return y(m,e)});function A(t){return function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return g(t,e,r)}}function M(t,e,n){n=n||x,s&&s(t,null);for(var r=e.length;r--;){var i=e[r];if("string"==typeof i){var a=n(i);a!==i&&(c(e)||(e[r]=a),i=a);}t[i]=!0;}return t}function N(t){var e,n=d(null);for(e in t)g(o,t,[e])&&(n[e]=t[e]);return n}function O(t,e){for(;null!==t;){var n=u(t,e);if(n){if(n.get)return A(n.get);if("function"==typeof n.value)return A(n.value)}t=l(t);}return function(t){return console.warn("fallback value for",t),null}}var D=h(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),B=h(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),L=h(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),I=h(["animate","color-profile","cursor","discard","fedropshadow","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),F=h(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover"]),R=h(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),P=h(["#text"]),j=h(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","xmlns","slot"]),z=h(["accent-height","accumulate","additive","alignment-baseline","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Y=h(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),U=h(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),$=f(/\{\{[\w\W]*|[\w\W]*\}\}/gm),W=f(/<%[\w\W]*|[\w\W]*%>/gm),q=f(/^data-[\-\w.\u00B7-\uFFFF]/),H=f(/^aria-[\-\w]+$/),V=f(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),G=f(/^(?:\w+script|data):/i),X=f(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Z=f(/^html$/i),Q=function(){return "undefined"==typeof window?null:window},K=function(e,n){if("object"!==t(e)||"function"!=typeof e.createPolicy)return null;var r=null,i="data-tt-policy-suffix";n.currentScript&&n.currentScript.hasAttribute(i)&&(r=n.currentScript.getAttribute(i));var a="dompurify"+(r?"#"+r:"");try{return e.createPolicy(a,{createHTML:function(t){return t},createScriptURL:function(t){return t}})}catch(t){return console.warn("TrustedTypes policy "+a+" could not be created."),null}};return function e(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Q(),r=function(t){return e(t)};if(r.version="2.4.0",r.removed=[],!n||!n.document||9!==n.document.nodeType)return r.isSupported=!1,r;var a=n.document,o=n.document,s=n.DocumentFragment,c=n.HTMLTemplateElement,l=n.Node,u=n.Element,f=n.NodeFilter,d=n.NamedNodeMap,p=void 0===d?n.NamedNodeMap||n.MozNamedAttrMap:d,g=n.HTMLFormElement,y=n.DOMParser,m=n.trustedTypes,A=u.prototype,J=O(A,"cloneNode"),tt=O(A,"nextSibling"),et=O(A,"childNodes"),nt=O(A,"parentNode");if("function"==typeof c){var rt=o.createElement("template");rt.content&&rt.content.ownerDocument&&(o=rt.content.ownerDocument);}var it=K(m,a),at=it?it.createHTML(""):"",ot=o,st=ot.implementation,ct=ot.createNodeIterator,lt=ot.createDocumentFragment,ut=ot.getElementsByTagName,ht=a.importNode,ft={};try{ft=N(o).documentMode?o.documentMode:{};}catch(t){}var dt={};r.isSupported="function"==typeof nt&&st&&void 0!==st.createHTMLDocument&&9!==ft;var pt,gt,yt=$,mt=W,bt=q,vt=H,_t=G,xt=X,kt=V,wt=null,Tt=M({},[].concat(i(D),i(B),i(L),i(F),i(P))),Et=null,Ct=M({},[].concat(i(j),i(z),i(Y),i(U))),St=Object.seal(Object.create(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),At=null,Mt=null,Nt=!0,Ot=!0,Dt=!1,Bt=!1,Lt=!1,It=!1,Ft=!1,Rt=!1,Pt=!1,jt=!1,zt=!0,Yt=!1,Ut="user-content-",$t=!0,Wt=!1,qt={},Ht=null,Vt=M({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),Gt=null,Xt=M({},["audio","video","img","source","image","track"]),Zt=null,Qt=M({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Kt="http://www.w3.org/1998/Math/MathML",Jt="http://www.w3.org/2000/svg",te="http://www.w3.org/1999/xhtml",ee=te,ne=!1,re=["application/xhtml+xml","text/html"],ie="text/html",ae=null,oe=o.createElement("form"),se=function(t){return t instanceof RegExp||t instanceof Function},ce=function(e){ae&&ae===e||(e&&"object"===t(e)||(e={}),e=N(e),pt=pt=-1===re.indexOf(e.PARSER_MEDIA_TYPE)?ie:e.PARSER_MEDIA_TYPE,gt="application/xhtml+xml"===pt?function(t){return t}:x,wt="ALLOWED_TAGS"in e?M({},e.ALLOWED_TAGS,gt):Tt,Et="ALLOWED_ATTR"in e?M({},e.ALLOWED_ATTR,gt):Ct,Zt="ADD_URI_SAFE_ATTR"in e?M(N(Qt),e.ADD_URI_SAFE_ATTR,gt):Qt,Gt="ADD_DATA_URI_TAGS"in e?M(N(Xt),e.ADD_DATA_URI_TAGS,gt):Xt,Ht="FORBID_CONTENTS"in e?M({},e.FORBID_CONTENTS,gt):Vt,At="FORBID_TAGS"in e?M({},e.FORBID_TAGS,gt):{},Mt="FORBID_ATTR"in e?M({},e.FORBID_ATTR,gt):{},qt="USE_PROFILES"in e&&e.USE_PROFILES,Nt=!1!==e.ALLOW_ARIA_ATTR,Ot=!1!==e.ALLOW_DATA_ATTR,Dt=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Bt=e.SAFE_FOR_TEMPLATES||!1,Lt=e.WHOLE_DOCUMENT||!1,Rt=e.RETURN_DOM||!1,Pt=e.RETURN_DOM_FRAGMENT||!1,jt=e.RETURN_TRUSTED_TYPE||!1,Ft=e.FORCE_BODY||!1,zt=!1!==e.SANITIZE_DOM,Yt=e.SANITIZE_NAMED_PROPS||!1,$t=!1!==e.KEEP_CONTENT,Wt=e.IN_PLACE||!1,kt=e.ALLOWED_URI_REGEXP||kt,ee=e.NAMESPACE||te,e.CUSTOM_ELEMENT_HANDLING&&se(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(St.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&se(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(St.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(St.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Bt&&(Ot=!1),Pt&&(Rt=!0),qt&&(wt=M({},i(P)),Et=[],!0===qt.html&&(M(wt,D),M(Et,j)),!0===qt.svg&&(M(wt,B),M(Et,z),M(Et,U)),!0===qt.svgFilters&&(M(wt,L),M(Et,z),M(Et,U)),!0===qt.mathMl&&(M(wt,F),M(Et,Y),M(Et,U))),e.ADD_TAGS&&(wt===Tt&&(wt=N(wt)),M(wt,e.ADD_TAGS,gt)),e.ADD_ATTR&&(Et===Ct&&(Et=N(Et)),M(Et,e.ADD_ATTR,gt)),e.ADD_URI_SAFE_ATTR&&M(Zt,e.ADD_URI_SAFE_ATTR,gt),e.FORBID_CONTENTS&&(Ht===Vt&&(Ht=N(Ht)),M(Ht,e.FORBID_CONTENTS,gt)),$t&&(wt["#text"]=!0),Lt&&M(wt,["html","head","body"]),wt.table&&(M(wt,["tbody"]),delete At.tbody),h&&h(e),ae=e);},le=M({},["mi","mo","mn","ms","mtext"]),ue=M({},["foreignobject","desc","title","annotation-xml"]),he=M({},["title","style","font","a","script"]),fe=M({},B);M(fe,L),M(fe,I);var de=M({},F);M(de,R);var pe=function(t){var e=nt(t);e&&e.tagName||(e={namespaceURI:te,tagName:"template"});var n=x(t.tagName),r=x(e.tagName);return t.namespaceURI===Jt?e.namespaceURI===te?"svg"===n:e.namespaceURI===Kt?"svg"===n&&("annotation-xml"===r||le[r]):Boolean(fe[n]):t.namespaceURI===Kt?e.namespaceURI===te?"math"===n:e.namespaceURI===Jt?"math"===n&&ue[r]:Boolean(de[n]):t.namespaceURI===te&&!(e.namespaceURI===Jt&&!ue[r])&&!(e.namespaceURI===Kt&&!le[r])&&!de[n]&&(he[n]||!fe[n])},ge=function(t){_(r.removed,{element:t});try{t.parentNode.removeChild(t);}catch(e){try{t.outerHTML=at;}catch(e){t.remove();}}},ye=function(t,e){try{_(r.removed,{attribute:e.getAttributeNode(t),from:e});}catch(t){_(r.removed,{attribute:null,from:e});}if(e.removeAttribute(t),"is"===t&&!Et[t])if(Rt||Pt)try{ge(e);}catch(t){}else try{e.setAttribute(t,"");}catch(t){}},me=function(t){var e,n;if(Ft)t="<remove></remove>"+t;else {var r=k(t,/^[\r\n\t ]+/);n=r&&r[0];}"application/xhtml+xml"===pt&&(t='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+t+"</body></html>");var i=it?it.createHTML(t):t;if(ee===te)try{e=(new y).parseFromString(i,pt);}catch(t){}if(!e||!e.documentElement){e=st.createDocument(ee,"template",null);try{e.documentElement.innerHTML=ne?"":i;}catch(t){}}var a=e.body||e.documentElement;return t&&n&&a.insertBefore(o.createTextNode(n),a.childNodes[0]||null),ee===te?ut.call(e,Lt?"html":"body")[0]:Lt?e.documentElement:a},be=function(t){return ct.call(t.ownerDocument||t,t,f.SHOW_ELEMENT|f.SHOW_COMMENT|f.SHOW_TEXT,null,!1)},ve=function(t){return t instanceof g&&("string"!=typeof t.nodeName||"string"!=typeof t.textContent||"function"!=typeof t.removeChild||!(t.attributes instanceof p)||"function"!=typeof t.removeAttribute||"function"!=typeof t.setAttribute||"string"!=typeof t.namespaceURI||"function"!=typeof t.insertBefore)},_e=function(e){return "object"===t(l)?e instanceof l:e&&"object"===t(e)&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName},xe=function(t,e,n){dt[t]&&b(dt[t],(function(t){t.call(r,e,n,ae);}));},ke=function(t){var e;if(xe("beforeSanitizeElements",t,null),ve(t))return ge(t),!0;if(C(/[\u0080-\uFFFF]/,t.nodeName))return ge(t),!0;var n=gt(t.nodeName);if(xe("uponSanitizeElement",t,{tagName:n,allowedTags:wt}),t.hasChildNodes()&&!_e(t.firstElementChild)&&(!_e(t.content)||!_e(t.content.firstElementChild))&&C(/<[/\w]/g,t.innerHTML)&&C(/<[/\w]/g,t.textContent))return ge(t),!0;if("select"===n&&C(/<template/i,t.innerHTML))return ge(t),!0;if(!wt[n]||At[n]){if(!At[n]&&Te(n)){if(St.tagNameCheck instanceof RegExp&&C(St.tagNameCheck,n))return !1;if(St.tagNameCheck instanceof Function&&St.tagNameCheck(n))return !1}if($t&&!Ht[n]){var i=nt(t)||t.parentNode,a=et(t)||t.childNodes;if(a&&i)for(var o=a.length-1;o>=0;--o)i.insertBefore(J(a[o],!0),tt(t));}return ge(t),!0}return t instanceof u&&!pe(t)?(ge(t),!0):"noscript"!==n&&"noembed"!==n||!C(/<\/no(script|embed)/i,t.innerHTML)?(Bt&&3===t.nodeType&&(e=t.textContent,e=w(e,yt," "),e=w(e,mt," "),t.textContent!==e&&(_(r.removed,{element:t.cloneNode()}),t.textContent=e)),xe("afterSanitizeElements",t,null),!1):(ge(t),!0)},we=function(t,e,n){if(zt&&("id"===e||"name"===e)&&(n in o||n in oe))return !1;if(Ot&&!Mt[e]&&C(bt,e));else if(Nt&&C(vt,e));else if(!Et[e]||Mt[e]){if(!(Te(t)&&(St.tagNameCheck instanceof RegExp&&C(St.tagNameCheck,t)||St.tagNameCheck instanceof Function&&St.tagNameCheck(t))&&(St.attributeNameCheck instanceof RegExp&&C(St.attributeNameCheck,e)||St.attributeNameCheck instanceof Function&&St.attributeNameCheck(e))||"is"===e&&St.allowCustomizedBuiltInElements&&(St.tagNameCheck instanceof RegExp&&C(St.tagNameCheck,n)||St.tagNameCheck instanceof Function&&St.tagNameCheck(n))))return !1}else if(Zt[e]);else if(C(kt,w(n,xt,"")));else if("src"!==e&&"xlink:href"!==e&&"href"!==e||"script"===t||0!==T(n,"data:")||!Gt[t])if(Dt&&!C(_t,w(n,xt,"")));else if(n)return !1;return !0},Te=function(t){return t.indexOf("-")>0},Ee=function(e){var n,i,a,o;xe("beforeSanitizeAttributes",e,null);var s=e.attributes;if(s){var c={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Et};for(o=s.length;o--;){var l=n=s[o],u=l.name,h=l.namespaceURI;if(i="value"===u?n.value:E(n.value),a=gt(u),c.attrName=a,c.attrValue=i,c.keepAttr=!0,c.forceKeepAttr=void 0,xe("uponSanitizeAttribute",e,c),i=c.attrValue,!c.forceKeepAttr&&(ye(u,e),c.keepAttr))if(C(/\/>/i,i))ye(u,e);else {Bt&&(i=w(i,yt," "),i=w(i,mt," "));var f=gt(e.nodeName);if(we(f,a,i)){if(!Yt||"id"!==a&&"name"!==a||(ye(u,e),i=Ut+i),it&&"object"===t(m)&&"function"==typeof m.getAttributeType)if(h);else switch(m.getAttributeType(f,a)){case"TrustedHTML":i=it.createHTML(i);break;case"TrustedScriptURL":i=it.createScriptURL(i);}try{h?e.setAttributeNS(h,u,i):e.setAttribute(u,i),v(r.removed);}catch(t){}}}}xe("afterSanitizeAttributes",e,null);}},Ce=function t(e){var n,r=be(e);for(xe("beforeSanitizeShadowDOM",e,null);n=r.nextNode();)xe("uponSanitizeShadowNode",n,null),ke(n)||(n.content instanceof s&&t(n.content),Ee(n));xe("afterSanitizeShadowDOM",e,null);};return r.sanitize=function(e){var i,o,c,u,h,f=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if((ne=!e)&&(e="\x3c!--\x3e"),"string"!=typeof e&&!_e(e)){if("function"!=typeof e.toString)throw S("toString is not a function");if("string"!=typeof(e=e.toString()))throw S("dirty is not a string, aborting")}if(!r.isSupported){if("object"===t(n.toStaticHTML)||"function"==typeof n.toStaticHTML){if("string"==typeof e)return n.toStaticHTML(e);if(_e(e))return n.toStaticHTML(e.outerHTML)}return e}if(It||ce(f),r.removed=[],"string"==typeof e&&(Wt=!1),Wt){if(e.nodeName){var d=gt(e.nodeName);if(!wt[d]||At[d])throw S("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof l)1===(o=(i=me("\x3c!----\x3e")).ownerDocument.importNode(e,!0)).nodeType&&"BODY"===o.nodeName||"HTML"===o.nodeName?i=o:i.appendChild(o);else {if(!Rt&&!Bt&&!Lt&&-1===e.indexOf("<"))return it&&jt?it.createHTML(e):e;if(!(i=me(e)))return Rt?null:jt?at:""}i&&Ft&&ge(i.firstChild);for(var p=be(Wt?e:i);c=p.nextNode();)3===c.nodeType&&c===u||ke(c)||(c.content instanceof s&&Ce(c.content),Ee(c),u=c);if(u=null,Wt)return e;if(Rt){if(Pt)for(h=lt.call(i.ownerDocument);i.firstChild;)h.appendChild(i.firstChild);else h=i;return Et.shadowroot&&(h=ht.call(a,h,!0)),h}var g=Lt?i.outerHTML:i.innerHTML;return Lt&&wt["!doctype"]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&C(Z,i.ownerDocument.doctype.name)&&(g="<!DOCTYPE "+i.ownerDocument.doctype.name+">\n"+g),Bt&&(g=w(g,yt," "),g=w(g,mt," ")),it&&jt?it.createHTML(g):g},r.setConfig=function(t){ce(t),It=!0;},r.clearConfig=function(){ae=null,It=!1;},r.isValidAttribute=function(t,e,n){ae||ce({});var r=gt(t),i=gt(e);return we(r,i,n)},r.addHook=function(t,e){"function"==typeof e&&(dt[t]=dt[t]||[],_(dt[t],e));},r.removeHook=function(t){if(dt[t])return v(dt[t])},r.removeHooks=function(t){dt[t]&&(dt[t]=[]);},r.removeAllHooks=function(){dt={};},r}()}();},8282:(t,e,n)=>{var r=n(2354);t.exports={Graph:r.Graph,json:n(8974),alg:n(2440),version:r.version};},2842:(t,e,n)=>{var r=n(9126);t.exports=function(t){var e,n={},i=[];function a(i){r.has(n,i)||(n[i]=!0,e.push(i),r.each(t.successors(i),a),r.each(t.predecessors(i),a));}return r.each(t.nodes(),(function(t){e=[],a(t),e.length&&i.push(e);})),i};},3984:(t,e,n)=>{var r=n(9126);function i(t,e,n,a,o,s){r.has(a,e)||(a[e]=!0,n||s.push(e),r.each(o(e),(function(e){i(t,e,n,a,o,s);})),n&&s.push(e));}t.exports=function(t,e,n){r.isArray(e)||(e=[e]);var a=(t.isDirected()?t.successors:t.neighbors).bind(t),o=[],s={};return r.each(e,(function(e){if(!t.hasNode(e))throw new Error("Graph does not have node: "+e);i(t,e,"post"===n,s,a,o);})),o};},4847:(t,e,n)=>{var r=n(3763),i=n(9126);t.exports=function(t,e,n){return i.transform(t.nodes(),(function(i,a){i[a]=r(t,a,e,n);}),{})};},3763:(t,e,n)=>{var r=n(9126),i=n(9675);t.exports=function(t,e,n,r){return function(t,e,n,r){var a,o,s={},c=new i,l=function(t){var e=t.v!==a?t.v:t.w,r=s[e],i=n(t),l=o.distance+i;if(i<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+t+" Weight: "+i);l<r.distance&&(r.distance=l,r.predecessor=a,c.decrease(e,l));};for(t.nodes().forEach((function(t){var n=t===e?0:Number.POSITIVE_INFINITY;s[t]={distance:n},c.add(t,n);}));c.size()>0&&(a=c.removeMin(),(o=s[a]).distance!==Number.POSITIVE_INFINITY);)r(a).forEach(l);return s}(t,String(e),n||a,r||function(e){return t.outEdges(e)})};var a=r.constant(1);},9096:(t,e,n)=>{var r=n(9126),i=n(5023);t.exports=function(t){return r.filter(i(t),(function(e){return e.length>1||1===e.length&&t.hasEdge(e[0],e[0])}))};},8924:(t,e,n)=>{var r=n(9126);t.exports=function(t,e,n){return function(t,e,n){var r={},i=t.nodes();return i.forEach((function(t){r[t]={},r[t][t]={distance:0},i.forEach((function(e){t!==e&&(r[t][e]={distance:Number.POSITIVE_INFINITY});})),n(t).forEach((function(n){var i=n.v===t?n.w:n.v,a=e(n);r[t][i]={distance:a,predecessor:t};}));})),i.forEach((function(t){var e=r[t];i.forEach((function(n){var a=r[n];i.forEach((function(n){var r=a[t],i=e[n],o=a[n],s=r.distance+i.distance;s<o.distance&&(o.distance=s,o.predecessor=i.predecessor);}));}));})),r}(t,e||i,n||function(e){return t.outEdges(e)})};var i=r.constant(1);},2440:(t,e,n)=>{t.exports={components:n(2842),dijkstra:n(3763),dijkstraAll:n(4847),findCycles:n(9096),floydWarshall:n(8924),isAcyclic:n(2707),postorder:n(8828),preorder:n(2648),prim:n(514),tarjan:n(5023),topsort:n(2166)};},2707:(t,e,n)=>{var r=n(2166);t.exports=function(t){try{r(t);}catch(t){if(t instanceof r.CycleException)return !1;throw t}return !0};},8828:(t,e,n)=>{var r=n(3984);t.exports=function(t,e){return r(t,e,"post")};},2648:(t,e,n)=>{var r=n(3984);t.exports=function(t,e){return r(t,e,"pre")};},514:(t,e,n)=>{var r=n(9126),i=n(771),a=n(9675);t.exports=function(t,e){var n,o=new i,s={},c=new a;function l(t){var r=t.v===n?t.w:t.v,i=c.priority(r);if(void 0!==i){var a=e(t);a<i&&(s[r]=n,c.decrease(r,a));}}if(0===t.nodeCount())return o;r.each(t.nodes(),(function(t){c.add(t,Number.POSITIVE_INFINITY),o.setNode(t);})),c.decrease(t.nodes()[0],0);for(var u=!1;c.size()>0;){if(n=c.removeMin(),r.has(s,n))o.setEdge(n,s[n]);else {if(u)throw new Error("Input graph is not connected: "+t);u=!0;}t.nodeEdges(n).forEach(l);}return o};},5023:(t,e,n)=>{var r=n(9126);t.exports=function(t){var e=0,n=[],i={},a=[];function o(s){var c=i[s]={onStack:!0,lowlink:e,index:e++};if(n.push(s),t.successors(s).forEach((function(t){r.has(i,t)?i[t].onStack&&(c.lowlink=Math.min(c.lowlink,i[t].index)):(o(t),c.lowlink=Math.min(c.lowlink,i[t].lowlink));})),c.lowlink===c.index){var l,u=[];do{l=n.pop(),i[l].onStack=!1,u.push(l);}while(s!==l);a.push(u);}}return t.nodes().forEach((function(t){r.has(i,t)||o(t);})),a};},2166:(t,e,n)=>{var r=n(9126);function i(t){var e={},n={},i=[];if(r.each(t.sinks(),(function o(s){if(r.has(n,s))throw new a;r.has(e,s)||(n[s]=!0,e[s]=!0,r.each(t.predecessors(s),o),delete n[s],i.push(s));})),r.size(e)!==t.nodeCount())throw new a;return i}function a(){}t.exports=i,i.CycleException=a,a.prototype=new Error;},9675:(t,e,n)=>{var r=n(9126);function i(){this._arr=[],this._keyIndices={};}t.exports=i,i.prototype.size=function(){return this._arr.length},i.prototype.keys=function(){return this._arr.map((function(t){return t.key}))},i.prototype.has=function(t){return r.has(this._keyIndices,t)},i.prototype.priority=function(t){var e=this._keyIndices[t];if(void 0!==e)return this._arr[e].priority},i.prototype.min=function(){if(0===this.size())throw new Error("Queue underflow");return this._arr[0].key},i.prototype.add=function(t,e){var n=this._keyIndices;if(t=String(t),!r.has(n,t)){var i=this._arr,a=i.length;return n[t]=a,i.push({key:t,priority:e}),this._decrease(a),!0}return !1},i.prototype.removeMin=function(){this._swap(0,this._arr.length-1);var t=this._arr.pop();return delete this._keyIndices[t.key],this._heapify(0),t.key},i.prototype.decrease=function(t,e){var n=this._keyIndices[t];if(e>this._arr[n].priority)throw new Error("New priority is greater than current priority. Key: "+t+" Old: "+this._arr[n].priority+" New: "+e);this._arr[n].priority=e,this._decrease(n);},i.prototype._heapify=function(t){var e=this._arr,n=2*t,r=n+1,i=t;n<e.length&&(i=e[n].priority<e[i].priority?n:i,r<e.length&&(i=e[r].priority<e[i].priority?r:i),i!==t&&(this._swap(t,i),this._heapify(i)));},i.prototype._decrease=function(t){for(var e,n=this._arr,r=n[t].priority;0!==t&&!(n[e=t>>1].priority<r);)this._swap(t,e),t=e;},i.prototype._swap=function(t,e){var n=this._arr,r=this._keyIndices,i=n[t],a=n[e];n[t]=a,n[e]=i,r[a.key]=t,r[i.key]=e;};},771:(t,e,n)=>{var r=n(9126);t.exports=a;var i="\0";function a(t){this._isDirected=!r.has(t,"directed")||t.directed,this._isMultigraph=!!r.has(t,"multigraph")&&t.multigraph,this._isCompound=!!r.has(t,"compound")&&t.compound,this._label=void 0,this._defaultNodeLabelFn=r.constant(void 0),this._defaultEdgeLabelFn=r.constant(void 0),this._nodes={},this._isCompound&&(this._parent={},this._children={},this._children["\0"]={}),this._in={},this._preds={},this._out={},this._sucs={},this._edgeObjs={},this._edgeLabels={};}function o(t,e){t[e]?t[e]++:t[e]=1;}function s(t,e){--t[e]||delete t[e];}function c(t,e,n,i){var a=""+e,o=""+n;if(!t&&a>o){var s=a;a=o,o=s;}return a+""+o+""+(r.isUndefined(i)?"\0":i)}function l(t,e,n,r){var i=""+e,a=""+n;if(!t&&i>a){var o=i;i=a,a=o;}var s={v:i,w:a};return r&&(s.name=r),s}function u(t,e){return c(t,e.v,e.w,e.name)}a.prototype._nodeCount=0,a.prototype._edgeCount=0,a.prototype.isDirected=function(){return this._isDirected},a.prototype.isMultigraph=function(){return this._isMultigraph},a.prototype.isCompound=function(){return this._isCompound},a.prototype.setGraph=function(t){return this._label=t,this},a.prototype.graph=function(){return this._label},a.prototype.setDefaultNodeLabel=function(t){return r.isFunction(t)||(t=r.constant(t)),this._defaultNodeLabelFn=t,this},a.prototype.nodeCount=function(){return this._nodeCount},a.prototype.nodes=function(){return r.keys(this._nodes)},a.prototype.sources=function(){var t=this;return r.filter(this.nodes(),(function(e){return r.isEmpty(t._in[e])}))},a.prototype.sinks=function(){var t=this;return r.filter(this.nodes(),(function(e){return r.isEmpty(t._out[e])}))},a.prototype.setNodes=function(t,e){var n=arguments,i=this;return r.each(t,(function(t){n.length>1?i.setNode(t,e):i.setNode(t);})),this},a.prototype.setNode=function(t,e){return r.has(this._nodes,t)?(arguments.length>1&&(this._nodes[t]=e),this):(this._nodes[t]=arguments.length>1?e:this._defaultNodeLabelFn(t),this._isCompound&&(this._parent[t]=i,this._children[t]={},this._children["\0"][t]=!0),this._in[t]={},this._preds[t]={},this._out[t]={},this._sucs[t]={},++this._nodeCount,this)},a.prototype.node=function(t){return this._nodes[t]},a.prototype.hasNode=function(t){return r.has(this._nodes,t)},a.prototype.removeNode=function(t){var e=this;if(r.has(this._nodes,t)){var n=function(t){e.removeEdge(e._edgeObjs[t]);};delete this._nodes[t],this._isCompound&&(this._removeFromParentsChildList(t),delete this._parent[t],r.each(this.children(t),(function(t){e.setParent(t);})),delete this._children[t]),r.each(r.keys(this._in[t]),n),delete this._in[t],delete this._preds[t],r.each(r.keys(this._out[t]),n),delete this._out[t],delete this._sucs[t],--this._nodeCount;}return this},a.prototype.setParent=function(t,e){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(r.isUndefined(e))e=i;else {for(var n=e+="";!r.isUndefined(n);n=this.parent(n))if(n===t)throw new Error("Setting "+e+" as parent of "+t+" would create a cycle");this.setNode(e);}return this.setNode(t),this._removeFromParentsChildList(t),this._parent[t]=e,this._children[e][t]=!0,this},a.prototype._removeFromParentsChildList=function(t){delete this._children[this._parent[t]][t];},a.prototype.parent=function(t){if(this._isCompound){var e=this._parent[t];if(e!==i)return e}},a.prototype.children=function(t){if(r.isUndefined(t)&&(t=i),this._isCompound){var e=this._children[t];if(e)return r.keys(e)}else {if(t===i)return this.nodes();if(this.hasNode(t))return []}},a.prototype.predecessors=function(t){var e=this._preds[t];if(e)return r.keys(e)},a.prototype.successors=function(t){var e=this._sucs[t];if(e)return r.keys(e)},a.prototype.neighbors=function(t){var e=this.predecessors(t);if(e)return r.union(e,this.successors(t))},a.prototype.isLeaf=function(t){return 0===(this.isDirected()?this.successors(t):this.neighbors(t)).length},a.prototype.filterNodes=function(t){var e=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});e.setGraph(this.graph());var n=this;r.each(this._nodes,(function(n,r){t(r)&&e.setNode(r,n);})),r.each(this._edgeObjs,(function(t){e.hasNode(t.v)&&e.hasNode(t.w)&&e.setEdge(t,n.edge(t));}));var i={};function a(t){var r=n.parent(t);return void 0===r||e.hasNode(r)?(i[t]=r,r):r in i?i[r]:a(r)}return this._isCompound&&r.each(e.nodes(),(function(t){e.setParent(t,a(t));})),e},a.prototype.setDefaultEdgeLabel=function(t){return r.isFunction(t)||(t=r.constant(t)),this._defaultEdgeLabelFn=t,this},a.prototype.edgeCount=function(){return this._edgeCount},a.prototype.edges=function(){return r.values(this._edgeObjs)},a.prototype.setPath=function(t,e){var n=this,i=arguments;return r.reduce(t,(function(t,r){return i.length>1?n.setEdge(t,r,e):n.setEdge(t,r),r})),this},a.prototype.setEdge=function(){var t,e,n,i,a=!1,s=arguments[0];"object"==typeof s&&null!==s&&"v"in s?(t=s.v,e=s.w,n=s.name,2===arguments.length&&(i=arguments[1],a=!0)):(t=s,e=arguments[1],n=arguments[3],arguments.length>2&&(i=arguments[2],a=!0)),t=""+t,e=""+e,r.isUndefined(n)||(n=""+n);var u=c(this._isDirected,t,e,n);if(r.has(this._edgeLabels,u))return a&&(this._edgeLabels[u]=i),this;if(!r.isUndefined(n)&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(t),this.setNode(e),this._edgeLabels[u]=a?i:this._defaultEdgeLabelFn(t,e,n);var h=l(this._isDirected,t,e,n);return t=h.v,e=h.w,Object.freeze(h),this._edgeObjs[u]=h,o(this._preds[e],t),o(this._sucs[t],e),this._in[e][u]=h,this._out[t][u]=h,this._edgeCount++,this},a.prototype.edge=function(t,e,n){var r=1===arguments.length?u(this._isDirected,arguments[0]):c(this._isDirected,t,e,n);return this._edgeLabels[r]},a.prototype.hasEdge=function(t,e,n){var i=1===arguments.length?u(this._isDirected,arguments[0]):c(this._isDirected,t,e,n);return r.has(this._edgeLabels,i)},a.prototype.removeEdge=function(t,e,n){var r=1===arguments.length?u(this._isDirected,arguments[0]):c(this._isDirected,t,e,n),i=this._edgeObjs[r];return i&&(t=i.v,e=i.w,delete this._edgeLabels[r],delete this._edgeObjs[r],s(this._preds[e],t),s(this._sucs[t],e),delete this._in[e][r],delete this._out[t][r],this._edgeCount--),this},a.prototype.inEdges=function(t,e){var n=this._in[t];if(n){var i=r.values(n);return e?r.filter(i,(function(t){return t.v===e})):i}},a.prototype.outEdges=function(t,e){var n=this._out[t];if(n){var i=r.values(n);return e?r.filter(i,(function(t){return t.w===e})):i}},a.prototype.nodeEdges=function(t,e){var n=this.inEdges(t,e);if(n)return n.concat(this.outEdges(t,e))};},2354:(t,e,n)=>{t.exports={Graph:n(771),version:n(9631)};},8974:(t,e,n)=>{var r=n(9126),i=n(771);function a(t){return r.map(t.nodes(),(function(e){var n=t.node(e),i=t.parent(e),a={v:e};return r.isUndefined(n)||(a.value=n),r.isUndefined(i)||(a.parent=i),a}))}function o(t){return r.map(t.edges(),(function(e){var n=t.edge(e),i={v:e.v,w:e.w};return r.isUndefined(e.name)||(i.name=e.name),r.isUndefined(n)||(i.value=n),i}))}t.exports={write:function(t){var e={options:{directed:t.isDirected(),multigraph:t.isMultigraph(),compound:t.isCompound()},nodes:a(t),edges:o(t)};return r.isUndefined(t.graph())||(e.value=r.clone(t.graph())),e},read:function(t){var e=new i(t.options).setGraph(t.value);return r.each(t.nodes,(function(t){e.setNode(t.v,t.value),t.parent&&e.setParent(t.v,t.parent);})),r.each(t.edges,(function(t){e.setEdge({v:t.v,w:t.w,name:t.name},t.value);})),e}};},9126:(t,e,n)=>{var r;try{r={clone:n(6678),constant:n(5703),each:n(6073),filter:n(3105),has:n(8721),isArray:n(1469),isEmpty:n(1609),isFunction:n(3560),isUndefined:n(2353),keys:n(3674),map:n(5161),reduce:n(4061),size:n(4238),transform:n(8718),union:n(3386),values:n(2628)};}catch(t){}r||(r=window._),t.exports=r;},9631:t=>{t.exports="2.1.8";},8552:(t,e,n)=>{var r=n(852)(n(5639),"DataView");t.exports=r;},1989:(t,e,n)=>{var r=n(1789),i=n(401),a=n(7667),o=n(1327),s=n(1866);function c(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1]);}}c.prototype.clear=r,c.prototype.delete=i,c.prototype.get=a,c.prototype.has=o,c.prototype.set=s,t.exports=c;},8407:(t,e,n)=>{var r=n(7040),i=n(4125),a=n(2117),o=n(7518),s=n(4705);function c(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1]);}}c.prototype.clear=r,c.prototype.delete=i,c.prototype.get=a,c.prototype.has=o,c.prototype.set=s,t.exports=c;},7071:(t,e,n)=>{var r=n(852)(n(5639),"Map");t.exports=r;},3369:(t,e,n)=>{var r=n(4785),i=n(1285),a=n(6e3),o=n(9916),s=n(5265);function c(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1]);}}c.prototype.clear=r,c.prototype.delete=i,c.prototype.get=a,c.prototype.has=o,c.prototype.set=s,t.exports=c;},3818:(t,e,n)=>{var r=n(852)(n(5639),"Promise");t.exports=r;},8525:(t,e,n)=>{var r=n(852)(n(5639),"Set");t.exports=r;},8668:(t,e,n)=>{var r=n(3369),i=n(619),a=n(2385);function o(t){var e=-1,n=null==t?0:t.length;for(this.__data__=new r;++e<n;)this.add(t[e]);}o.prototype.add=o.prototype.push=i,o.prototype.has=a,t.exports=o;},6384:(t,e,n)=>{var r=n(8407),i=n(7465),a=n(3779),o=n(7599),s=n(4758),c=n(4309);function l(t){var e=this.__data__=new r(t);this.size=e.size;}l.prototype.clear=i,l.prototype.delete=a,l.prototype.get=o,l.prototype.has=s,l.prototype.set=c,t.exports=l;},2705:(t,e,n)=>{var r=n(5639).Symbol;t.exports=r;},1149:(t,e,n)=>{var r=n(5639).Uint8Array;t.exports=r;},577:(t,e,n)=>{var r=n(852)(n(5639),"WeakMap");t.exports=r;},6874:t=>{t.exports=function(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)};},7412:t=>{t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length;++n<r&&!1!==e(t[n],n,t););return t};},4963:t=>{t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length,i=0,a=[];++n<r;){var o=t[n];e(o,n,t)&&(a[i++]=o);}return a};},7443:(t,e,n)=>{var r=n(2118);t.exports=function(t,e){return !(null==t||!t.length)&&r(t,e,0)>-1};},1196:t=>{t.exports=function(t,e,n){for(var r=-1,i=null==t?0:t.length;++r<i;)if(n(e,t[r]))return !0;return !1};},4636:(t,e,n)=>{var r=n(2545),i=n(5694),a=n(1469),o=n(4144),s=n(5776),c=n(6719),l=Object.prototype.hasOwnProperty;t.exports=function(t,e){var n=a(t),u=!n&&i(t),h=!n&&!u&&o(t),f=!n&&!u&&!h&&c(t),d=n||u||h||f,p=d?r(t.length,String):[],g=p.length;for(var y in t)!e&&!l.call(t,y)||d&&("length"==y||h&&("offset"==y||"parent"==y)||f&&("buffer"==y||"byteLength"==y||"byteOffset"==y)||s(y,g))||p.push(y);return p};},9932:t=>{t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length,i=Array(r);++n<r;)i[n]=e(t[n],n,t);return i};},2488:t=>{t.exports=function(t,e){for(var n=-1,r=e.length,i=t.length;++n<r;)t[i+n]=e[n];return t};},2663:t=>{t.exports=function(t,e,n,r){var i=-1,a=null==t?0:t.length;for(r&&a&&(n=t[++i]);++i<a;)n=e(n,t[i],i,t);return n};},2908:t=>{t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length;++n<r;)if(e(t[n],n,t))return !0;return !1};},8983:(t,e,n)=>{var r=n(371)("length");t.exports=r;},6556:(t,e,n)=>{var r=n(9465),i=n(7813);t.exports=function(t,e,n){(void 0!==n&&!i(t[e],n)||void 0===n&&!(e in t))&&r(t,e,n);};},4865:(t,e,n)=>{var r=n(9465),i=n(7813),a=Object.prototype.hasOwnProperty;t.exports=function(t,e,n){var o=t[e];a.call(t,e)&&i(o,n)&&(void 0!==n||e in t)||r(t,e,n);};},8470:(t,e,n)=>{var r=n(7813);t.exports=function(t,e){for(var n=t.length;n--;)if(r(t[n][0],e))return n;return -1};},4037:(t,e,n)=>{var r=n(8363),i=n(3674);t.exports=function(t,e){return t&&r(e,i(e),t)};},3886:(t,e,n)=>{var r=n(8363),i=n(1704);t.exports=function(t,e){return t&&r(e,i(e),t)};},9465:(t,e,n)=>{var r=n(8777);t.exports=function(t,e,n){"__proto__"==e&&r?r(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n;};},5990:(t,e,n)=>{var r=n(6384),i=n(7412),a=n(4865),o=n(4037),s=n(3886),c=n(4626),l=n(278),u=n(8805),h=n(1911),f=n(8234),d=n(6904),p=n(4160),g=n(3824),y=n(9148),m=n(8517),b=n(1469),v=n(4144),_=n(6688),x=n(3218),k=n(2928),w=n(3674),T=n(1704),E="[object Arguments]",C="[object Function]",S="[object Object]",A={};A[E]=A["[object Array]"]=A["[object ArrayBuffer]"]=A["[object DataView]"]=A["[object Boolean]"]=A["[object Date]"]=A["[object Float32Array]"]=A["[object Float64Array]"]=A["[object Int8Array]"]=A["[object Int16Array]"]=A["[object Int32Array]"]=A["[object Map]"]=A["[object Number]"]=A[S]=A["[object RegExp]"]=A["[object Set]"]=A["[object String]"]=A["[object Symbol]"]=A["[object Uint8Array]"]=A["[object Uint8ClampedArray]"]=A["[object Uint16Array]"]=A["[object Uint32Array]"]=!0,A["[object Error]"]=A[C]=A["[object WeakMap]"]=!1,t.exports=function t(e,n,M,N,O,D){var B,L=1&n,I=2&n,F=4&n;if(M&&(B=O?M(e,N,O,D):M(e)),void 0!==B)return B;if(!x(e))return e;var R=b(e);if(R){if(B=g(e),!L)return l(e,B)}else {var P=p(e),j=P==C||"[object GeneratorFunction]"==P;if(v(e))return c(e,L);if(P==S||P==E||j&&!O){if(B=I||j?{}:m(e),!L)return I?h(e,s(B,e)):u(e,o(B,e))}else {if(!A[P])return O?e:{};B=y(e,P,L);}}D||(D=new r);var z=D.get(e);if(z)return z;D.set(e,B),k(e)?e.forEach((function(r){B.add(t(r,n,M,r,e,D));})):_(e)&&e.forEach((function(r,i){B.set(i,t(r,n,M,i,e,D));}));var Y=R?void 0:(F?I?d:f:I?T:w)(e);return i(Y||e,(function(r,i){Y&&(r=e[i=r]),a(B,i,t(r,n,M,i,e,D));})),B};},3118:(t,e,n)=>{var r=n(3218),i=Object.create,a=function(){function t(){}return function(e){if(!r(e))return {};if(i)return i(e);t.prototype=e;var n=new t;return t.prototype=void 0,n}}();t.exports=a;},9881:(t,e,n)=>{var r=n(7816),i=n(9291)(r);t.exports=i;},6029:(t,e,n)=>{var r=n(3448);t.exports=function(t,e,n){for(var i=-1,a=t.length;++i<a;){var o=t[i],s=e(o);if(null!=s&&(void 0===c?s==s&&!r(s):n(s,c)))var c=s,l=o;}return l};},760:(t,e,n)=>{var r=n(9881);t.exports=function(t,e){var n=[];return r(t,(function(t,r,i){e(t,r,i)&&n.push(t);})),n};},1848:t=>{t.exports=function(t,e,n,r){for(var i=t.length,a=n+(r?1:-1);r?a--:++a<i;)if(e(t[a],a,t))return a;return -1};},1078:(t,e,n)=>{var r=n(2488),i=n(7285);t.exports=function t(e,n,a,o,s){var c=-1,l=e.length;for(a||(a=i),s||(s=[]);++c<l;){var u=e[c];n>0&&a(u)?n>1?t(u,n-1,a,o,s):r(s,u):o||(s[s.length]=u);}return s};},8483:(t,e,n)=>{var r=n(5063)();t.exports=r;},7816:(t,e,n)=>{var r=n(8483),i=n(3674);t.exports=function(t,e){return t&&r(t,e,i)};},7786:(t,e,n)=>{var r=n(1811),i=n(327);t.exports=function(t,e){for(var n=0,a=(e=r(e,t)).length;null!=t&&n<a;)t=t[i(e[n++])];return n&&n==a?t:void 0};},8866:(t,e,n)=>{var r=n(2488),i=n(1469);t.exports=function(t,e,n){var a=e(t);return i(t)?a:r(a,n(t))};},4239:(t,e,n)=>{var r=n(2705),i=n(9607),a=n(2333),o=r?r.toStringTag:void 0;t.exports=function(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":o&&o in Object(t)?i(t):a(t)};},3325:t=>{t.exports=function(t,e){return t>e};},8565:t=>{var e=Object.prototype.hasOwnProperty;t.exports=function(t,n){return null!=t&&e.call(t,n)};},13:t=>{t.exports=function(t,e){return null!=t&&e in Object(t)};},2118:(t,e,n)=>{var r=n(1848),i=n(2722),a=n(2351);t.exports=function(t,e,n){return e==e?a(t,e,n):r(t,i,n)};},9454:(t,e,n)=>{var r=n(4239),i=n(7005);t.exports=function(t){return i(t)&&"[object Arguments]"==r(t)};},939:(t,e,n)=>{var r=n(2492),i=n(7005);t.exports=function t(e,n,a,o,s){return e===n||(null==e||null==n||!i(e)&&!i(n)?e!=e&&n!=n:r(e,n,a,o,t,s))};},2492:(t,e,n)=>{var r=n(6384),i=n(7114),a=n(8351),o=n(6096),s=n(4160),c=n(1469),l=n(4144),u=n(6719),h="[object Arguments]",f="[object Array]",d="[object Object]",p=Object.prototype.hasOwnProperty;t.exports=function(t,e,n,g,y,m){var b=c(t),v=c(e),_=b?f:s(t),x=v?f:s(e),k=(_=_==h?d:_)==d,w=(x=x==h?d:x)==d,T=_==x;if(T&&l(t)){if(!l(e))return !1;b=!0,k=!1;}if(T&&!k)return m||(m=new r),b||u(t)?i(t,e,n,g,y,m):a(t,e,_,n,g,y,m);if(!(1&n)){var E=k&&p.call(t,"__wrapped__"),C=w&&p.call(e,"__wrapped__");if(E||C){var S=E?t.value():t,A=C?e.value():e;return m||(m=new r),y(S,A,n,g,m)}}return !!T&&(m||(m=new r),o(t,e,n,g,y,m))};},5588:(t,e,n)=>{var r=n(4160),i=n(7005);t.exports=function(t){return i(t)&&"[object Map]"==r(t)};},2958:(t,e,n)=>{var r=n(6384),i=n(939);t.exports=function(t,e,n,a){var o=n.length,s=o,c=!a;if(null==t)return !s;for(t=Object(t);o--;){var l=n[o];if(c&&l[2]?l[1]!==t[l[0]]:!(l[0]in t))return !1}for(;++o<s;){var u=(l=n[o])[0],h=t[u],f=l[1];if(c&&l[2]){if(void 0===h&&!(u in t))return !1}else {var d=new r;if(a)var p=a(h,f,u,t,e,d);if(!(void 0===p?i(f,h,3,a,d):p))return !1}}return !0};},2722:t=>{t.exports=function(t){return t!=t};},8458:(t,e,n)=>{var r=n(3560),i=n(5346),a=n(3218),o=n(346),s=/^\[object .+?Constructor\]$/,c=Function.prototype,l=Object.prototype,u=c.toString,h=l.hasOwnProperty,f=RegExp("^"+u.call(h).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=function(t){return !(!a(t)||i(t))&&(r(t)?f:s).test(o(t))};},9221:(t,e,n)=>{var r=n(4160),i=n(7005);t.exports=function(t){return i(t)&&"[object Set]"==r(t)};},8749:(t,e,n)=>{var r=n(4239),i=n(1780),a=n(7005),o={};o["[object Float32Array]"]=o["[object Float64Array]"]=o["[object Int8Array]"]=o["[object Int16Array]"]=o["[object Int32Array]"]=o["[object Uint8Array]"]=o["[object Uint8ClampedArray]"]=o["[object Uint16Array]"]=o["[object Uint32Array]"]=!0,o["[object Arguments]"]=o["[object Array]"]=o["[object ArrayBuffer]"]=o["[object Boolean]"]=o["[object DataView]"]=o["[object Date]"]=o["[object Error]"]=o["[object Function]"]=o["[object Map]"]=o["[object Number]"]=o["[object Object]"]=o["[object RegExp]"]=o["[object Set]"]=o["[object String]"]=o["[object WeakMap]"]=!1,t.exports=function(t){return a(t)&&i(t.length)&&!!o[r(t)]};},7206:(t,e,n)=>{var r=n(1573),i=n(6432),a=n(6557),o=n(1469),s=n(9601);t.exports=function(t){return "function"==typeof t?t:null==t?a:"object"==typeof t?o(t)?i(t[0],t[1]):r(t):s(t)};},280:(t,e,n)=>{var r=n(5726),i=n(6916),a=Object.prototype.hasOwnProperty;t.exports=function(t){if(!r(t))return i(t);var e=[];for(var n in Object(t))a.call(t,n)&&"constructor"!=n&&e.push(n);return e};},313:(t,e,n)=>{var r=n(3218),i=n(5726),a=n(3498),o=Object.prototype.hasOwnProperty;t.exports=function(t){if(!r(t))return a(t);var e=i(t),n=[];for(var s in t)("constructor"!=s||!e&&o.call(t,s))&&n.push(s);return n};},433:t=>{t.exports=function(t,e){return t<e};},9199:(t,e,n)=>{var r=n(9881),i=n(8612);t.exports=function(t,e){var n=-1,a=i(t)?Array(t.length):[];return r(t,(function(t,r,i){a[++n]=e(t,r,i);})),a};},1573:(t,e,n)=>{var r=n(2958),i=n(1499),a=n(2634);t.exports=function(t){var e=i(t);return 1==e.length&&e[0][2]?a(e[0][0],e[0][1]):function(n){return n===t||r(n,t,e)}};},6432:(t,e,n)=>{var r=n(939),i=n(7361),a=n(9095),o=n(5403),s=n(9162),c=n(2634),l=n(327);t.exports=function(t,e){return o(t)&&s(e)?c(l(t),e):function(n){var o=i(n,t);return void 0===o&&o===e?a(n,t):r(e,o,3)}};},2980:(t,e,n)=>{var r=n(6384),i=n(6556),a=n(8483),o=n(9783),s=n(3218),c=n(1704),l=n(6390);t.exports=function t(e,n,u,h,f){e!==n&&a(n,(function(a,c){if(f||(f=new r),s(a))o(e,n,c,u,t,h,f);else {var d=h?h(l(e,c),a,c+"",e,n,f):void 0;void 0===d&&(d=a),i(e,c,d);}}),c);};},9783:(t,e,n)=>{var r=n(6556),i=n(4626),a=n(7133),o=n(278),s=n(8517),c=n(5694),l=n(1469),u=n(9246),h=n(4144),f=n(3560),d=n(3218),p=n(8630),g=n(6719),y=n(6390),m=n(3678);t.exports=function(t,e,n,b,v,_,x){var k=y(t,n),w=y(e,n),T=x.get(w);if(T)r(t,n,T);else {var E=_?_(k,w,n+"",t,e,x):void 0,C=void 0===E;if(C){var S=l(w),A=!S&&h(w),M=!S&&!A&&g(w);E=w,S||A||M?l(k)?E=k:u(k)?E=o(k):A?(C=!1,E=i(w,!0)):M?(C=!1,E=a(w,!0)):E=[]:p(w)||c(w)?(E=k,c(k)?E=m(k):d(k)&&!f(k)||(E=s(w))):C=!1;}C&&(x.set(w,E),v(E,w,b,_,x),x.delete(w)),r(t,n,E);}};},9556:(t,e,n)=>{var r=n(9932),i=n(7786),a=n(7206),o=n(9199),s=n(1131),c=n(1717),l=n(5022),u=n(6557),h=n(1469);t.exports=function(t,e,n){e=e.length?r(e,(function(t){return h(t)?function(e){return i(e,1===t.length?t[0]:t)}:t})):[u];var f=-1;e=r(e,c(a));var d=o(t,(function(t,n,i){return {criteria:r(e,(function(e){return e(t)})),index:++f,value:t}}));return s(d,(function(t,e){return l(t,e,n)}))};},5970:(t,e,n)=>{var r=n(3012),i=n(9095);t.exports=function(t,e){return r(t,e,(function(e,n){return i(t,n)}))};},3012:(t,e,n)=>{var r=n(7786),i=n(611),a=n(1811);t.exports=function(t,e,n){for(var o=-1,s=e.length,c={};++o<s;){var l=e[o],u=r(t,l);n(u,l)&&i(c,a(l,t),u);}return c};},371:t=>{t.exports=function(t){return function(e){return null==e?void 0:e[t]}};},9152:(t,e,n)=>{var r=n(7786);t.exports=function(t){return function(e){return r(e,t)}};},98:t=>{var e=Math.ceil,n=Math.max;t.exports=function(t,r,i,a){for(var o=-1,s=n(e((r-t)/(i||1)),0),c=Array(s);s--;)c[a?s:++o]=t,t+=i;return c};},107:t=>{t.exports=function(t,e,n,r,i){return i(t,(function(t,i,a){n=r?(r=!1,t):e(n,t,i,a);})),n};},5976:(t,e,n)=>{var r=n(6557),i=n(5357),a=n(61);t.exports=function(t,e){return a(i(t,e,r),t+"")};},611:(t,e,n)=>{var r=n(4865),i=n(1811),a=n(5776),o=n(3218),s=n(327);t.exports=function(t,e,n,c){if(!o(t))return t;for(var l=-1,u=(e=i(e,t)).length,h=u-1,f=t;null!=f&&++l<u;){var d=s(e[l]),p=n;if("__proto__"===d||"constructor"===d||"prototype"===d)return t;if(l!=h){var g=f[d];void 0===(p=c?c(g,d,f):void 0)&&(p=o(g)?g:a(e[l+1])?[]:{});}r(f,d,p),f=f[d];}return t};},6560:(t,e,n)=>{var r=n(5703),i=n(8777),a=n(6557),o=i?function(t,e){return i(t,"toString",{configurable:!0,enumerable:!1,value:r(e),writable:!0})}:a;t.exports=o;},1131:t=>{t.exports=function(t,e){var n=t.length;for(t.sort(e);n--;)t[n]=t[n].value;return t};},2545:t=>{t.exports=function(t,e){for(var n=-1,r=Array(t);++n<t;)r[n]=e(n);return r};},531:(t,e,n)=>{var r=n(2705),i=n(9932),a=n(1469),o=n(3448),s=r?r.prototype:void 0,c=s?s.toString:void 0;t.exports=function t(e){if("string"==typeof e)return e;if(a(e))return i(e,t)+"";if(o(e))return c?c.call(e):"";var n=e+"";return "0"==n&&1/e==-1/0?"-0":n};},7561:(t,e,n)=>{var r=n(7990),i=/^\s+/;t.exports=function(t){return t?t.slice(0,r(t)+1).replace(i,""):t};},1717:t=>{t.exports=function(t){return function(e){return t(e)}};},5652:(t,e,n)=>{var r=n(8668),i=n(7443),a=n(1196),o=n(4757),s=n(3593),c=n(1814);t.exports=function(t,e,n){var l=-1,u=i,h=t.length,f=!0,d=[],p=d;if(n)f=!1,u=a;else if(h>=200){var g=e?null:s(t);if(g)return c(g);f=!1,u=o,p=new r;}else p=e?[]:d;t:for(;++l<h;){var y=t[l],m=e?e(y):y;if(y=n||0!==y?y:0,f&&m==m){for(var b=p.length;b--;)if(p[b]===m)continue t;e&&p.push(m),d.push(y);}else u(p,m,n)||(p!==d&&p.push(m),d.push(y));}return d};},7415:(t,e,n)=>{var r=n(9932);t.exports=function(t,e){return r(e,(function(e){return t[e]}))};},1757:t=>{t.exports=function(t,e,n){for(var r=-1,i=t.length,a=e.length,o={};++r<i;){var s=r<a?e[r]:void 0;n(o,t[r],s);}return o};},4757:t=>{t.exports=function(t,e){return t.has(e)};},4290:(t,e,n)=>{var r=n(6557);t.exports=function(t){return "function"==typeof t?t:r};},1811:(t,e,n)=>{var r=n(1469),i=n(5403),a=n(5514),o=n(9833);t.exports=function(t,e){return r(t)?t:i(t,e)?[t]:a(o(t))};},4318:(t,e,n)=>{var r=n(1149);t.exports=function(t){var e=new t.constructor(t.byteLength);return new r(e).set(new r(t)),e};},4626:(t,e,n)=>{t=n.nmd(t);var r=n(5639),i=e&&!e.nodeType&&e,a=i&&t&&!t.nodeType&&t,o=a&&a.exports===i?r.Buffer:void 0,s=o?o.allocUnsafe:void 0;t.exports=function(t,e){if(e)return t.slice();var n=t.length,r=s?s(n):new t.constructor(n);return t.copy(r),r};},7157:(t,e,n)=>{var r=n(4318);t.exports=function(t,e){var n=e?r(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)};},3147:t=>{var e=/\w*$/;t.exports=function(t){var n=new t.constructor(t.source,e.exec(t));return n.lastIndex=t.lastIndex,n};},419:(t,e,n)=>{var r=n(2705),i=r?r.prototype:void 0,a=i?i.valueOf:void 0;t.exports=function(t){return a?Object(a.call(t)):{}};},7133:(t,e,n)=>{var r=n(4318);t.exports=function(t,e){var n=e?r(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)};},6393:(t,e,n)=>{var r=n(3448);t.exports=function(t,e){if(t!==e){var n=void 0!==t,i=null===t,a=t==t,o=r(t),s=void 0!==e,c=null===e,l=e==e,u=r(e);if(!c&&!u&&!o&&t>e||o&&s&&l&&!c&&!u||i&&s&&l||!n&&l||!a)return 1;if(!i&&!o&&!u&&t<e||u&&n&&a&&!i&&!o||c&&n&&a||!s&&a||!l)return -1}return 0};},5022:(t,e,n)=>{var r=n(6393);t.exports=function(t,e,n){for(var i=-1,a=t.criteria,o=e.criteria,s=a.length,c=n.length;++i<s;){var l=r(a[i],o[i]);if(l)return i>=c?l:l*("desc"==n[i]?-1:1)}return t.index-e.index};},278:t=>{t.exports=function(t,e){var n=-1,r=t.length;for(e||(e=Array(r));++n<r;)e[n]=t[n];return e};},8363:(t,e,n)=>{var r=n(4865),i=n(9465);t.exports=function(t,e,n,a){var o=!n;n||(n={});for(var s=-1,c=e.length;++s<c;){var l=e[s],u=a?a(n[l],t[l],l,n,t):void 0;void 0===u&&(u=t[l]),o?i(n,l,u):r(n,l,u);}return n};},8805:(t,e,n)=>{var r=n(8363),i=n(9551);t.exports=function(t,e){return r(t,i(t),e)};},1911:(t,e,n)=>{var r=n(8363),i=n(1442);t.exports=function(t,e){return r(t,i(t),e)};},4429:(t,e,n)=>{var r=n(5639)["__core-js_shared__"];t.exports=r;},1463:(t,e,n)=>{var r=n(5976),i=n(6612);t.exports=function(t){return r((function(e,n){var r=-1,a=n.length,o=a>1?n[a-1]:void 0,s=a>2?n[2]:void 0;for(o=t.length>3&&"function"==typeof o?(a--,o):void 0,s&&i(n[0],n[1],s)&&(o=a<3?void 0:o,a=1),e=Object(e);++r<a;){var c=n[r];c&&t(e,c,r,o);}return e}))};},9291:(t,e,n)=>{var r=n(8612);t.exports=function(t,e){return function(n,i){if(null==n)return n;if(!r(n))return t(n,i);for(var a=n.length,o=e?a:-1,s=Object(n);(e?o--:++o<a)&&!1!==i(s[o],o,s););return n}};},5063:t=>{t.exports=function(t){return function(e,n,r){for(var i=-1,a=Object(e),o=r(e),s=o.length;s--;){var c=o[t?s:++i];if(!1===n(a[c],c,a))break}return e}};},7740:(t,e,n)=>{var r=n(7206),i=n(8612),a=n(3674);t.exports=function(t){return function(e,n,o){var s=Object(e);if(!i(e)){var c=r(n,3);e=a(e),n=function(t){return c(s[t],t,s)};}var l=t(e,n,o);return l>-1?s[c?e[l]:l]:void 0}};},7445:(t,e,n)=>{var r=n(98),i=n(6612),a=n(8601);t.exports=function(t){return function(e,n,o){return o&&"number"!=typeof o&&i(e,n,o)&&(n=o=void 0),e=a(e),void 0===n?(n=e,e=0):n=a(n),o=void 0===o?e<n?1:-1:a(o),r(e,n,o,t)}};},3593:(t,e,n)=>{var r=n(8525),i=n(308),a=n(1814),o=r&&1/a(new r([,-0]))[1]==1/0?function(t){return new r(t)}:i;t.exports=o;},8777:(t,e,n)=>{var r=n(852),i=function(){try{var t=r(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();t.exports=i;},7114:(t,e,n)=>{var r=n(8668),i=n(2908),a=n(4757);t.exports=function(t,e,n,o,s,c){var l=1&n,u=t.length,h=e.length;if(u!=h&&!(l&&h>u))return !1;var f=c.get(t),d=c.get(e);if(f&&d)return f==e&&d==t;var p=-1,g=!0,y=2&n?new r:void 0;for(c.set(t,e),c.set(e,t);++p<u;){var m=t[p],b=e[p];if(o)var v=l?o(b,m,p,e,t,c):o(m,b,p,t,e,c);if(void 0!==v){if(v)continue;g=!1;break}if(y){if(!i(e,(function(t,e){if(!a(y,e)&&(m===t||s(m,t,n,o,c)))return y.push(e)}))){g=!1;break}}else if(m!==b&&!s(m,b,n,o,c)){g=!1;break}}return c.delete(t),c.delete(e),g};},8351:(t,e,n)=>{var r=n(2705),i=n(1149),a=n(7813),o=n(7114),s=n(8776),c=n(1814),l=r?r.prototype:void 0,u=l?l.valueOf:void 0;t.exports=function(t,e,n,r,l,h,f){switch(n){case"[object DataView]":if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return !1;t=t.buffer,e=e.buffer;case"[object ArrayBuffer]":return !(t.byteLength!=e.byteLength||!h(new i(t),new i(e)));case"[object Boolean]":case"[object Date]":case"[object Number]":return a(+t,+e);case"[object Error]":return t.name==e.name&&t.message==e.message;case"[object RegExp]":case"[object String]":return t==e+"";case"[object Map]":var d=s;case"[object Set]":var p=1&r;if(d||(d=c),t.size!=e.size&&!p)return !1;var g=f.get(t);if(g)return g==e;r|=2,f.set(t,e);var y=o(d(t),d(e),r,l,h,f);return f.delete(t),y;case"[object Symbol]":if(u)return u.call(t)==u.call(e)}return !1};},6096:(t,e,n)=>{var r=n(8234),i=Object.prototype.hasOwnProperty;t.exports=function(t,e,n,a,o,s){var c=1&n,l=r(t),u=l.length;if(u!=r(e).length&&!c)return !1;for(var h=u;h--;){var f=l[h];if(!(c?f in e:i.call(e,f)))return !1}var d=s.get(t),p=s.get(e);if(d&&p)return d==e&&p==t;var g=!0;s.set(t,e),s.set(e,t);for(var y=c;++h<u;){var m=t[f=l[h]],b=e[f];if(a)var v=c?a(b,m,f,e,t,s):a(m,b,f,t,e,s);if(!(void 0===v?m===b||o(m,b,n,a,s):v)){g=!1;break}y||(y="constructor"==f);}if(g&&!y){var _=t.constructor,x=e.constructor;_==x||!("constructor"in t)||!("constructor"in e)||"function"==typeof _&&_ instanceof _&&"function"==typeof x&&x instanceof x||(g=!1);}return s.delete(t),s.delete(e),g};},9021:(t,e,n)=>{var r=n(5564),i=n(5357),a=n(61);t.exports=function(t){return a(i(t,void 0,r),t+"")};},1957:(t,e,n)=>{var r="object"==typeof n.g&&n.g&&n.g.Object===Object&&n.g;t.exports=r;},8234:(t,e,n)=>{var r=n(8866),i=n(9551),a=n(3674);t.exports=function(t){return r(t,a,i)};},6904:(t,e,n)=>{var r=n(8866),i=n(1442),a=n(1704);t.exports=function(t){return r(t,a,i)};},5050:(t,e,n)=>{var r=n(7019);t.exports=function(t,e){var n=t.__data__;return r(e)?n["string"==typeof e?"string":"hash"]:n.map};},1499:(t,e,n)=>{var r=n(9162),i=n(3674);t.exports=function(t){for(var e=i(t),n=e.length;n--;){var a=e[n],o=t[a];e[n]=[a,o,r(o)];}return e};},852:(t,e,n)=>{var r=n(8458),i=n(7801);t.exports=function(t,e){var n=i(t,e);return r(n)?n:void 0};},5924:(t,e,n)=>{var r=n(5569)(Object.getPrototypeOf,Object);t.exports=r;},9607:(t,e,n)=>{var r=n(2705),i=Object.prototype,a=i.hasOwnProperty,o=i.toString,s=r?r.toStringTag:void 0;t.exports=function(t){var e=a.call(t,s),n=t[s];try{t[s]=void 0;var r=!0;}catch(t){}var i=o.call(t);return r&&(e?t[s]=n:delete t[s]),i};},9551:(t,e,n)=>{var r=n(4963),i=n(479),a=Object.prototype.propertyIsEnumerable,o=Object.getOwnPropertySymbols,s=o?function(t){return null==t?[]:(t=Object(t),r(o(t),(function(e){return a.call(t,e)})))}:i;t.exports=s;},1442:(t,e,n)=>{var r=n(2488),i=n(5924),a=n(9551),o=n(479),s=Object.getOwnPropertySymbols?function(t){for(var e=[];t;)r(e,a(t)),t=i(t);return e}:o;t.exports=s;},4160:(t,e,n)=>{var r=n(8552),i=n(7071),a=n(3818),o=n(8525),s=n(577),c=n(4239),l=n(346),u="[object Map]",h="[object Promise]",f="[object Set]",d="[object WeakMap]",p="[object DataView]",g=l(r),y=l(i),m=l(a),b=l(o),v=l(s),_=c;(r&&_(new r(new ArrayBuffer(1)))!=p||i&&_(new i)!=u||a&&_(a.resolve())!=h||o&&_(new o)!=f||s&&_(new s)!=d)&&(_=function(t){var e=c(t),n="[object Object]"==e?t.constructor:void 0,r=n?l(n):"";if(r)switch(r){case g:return p;case y:return u;case m:return h;case b:return f;case v:return d}return e}),t.exports=_;},7801:t=>{t.exports=function(t,e){return null==t?void 0:t[e]};},222:(t,e,n)=>{var r=n(1811),i=n(5694),a=n(1469),o=n(5776),s=n(1780),c=n(327);t.exports=function(t,e,n){for(var l=-1,u=(e=r(e,t)).length,h=!1;++l<u;){var f=c(e[l]);if(!(h=null!=t&&n(t,f)))break;t=t[f];}return h||++l!=u?h:!!(u=null==t?0:t.length)&&s(u)&&o(f,u)&&(a(t)||i(t))};},2689:t=>{var e=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]");t.exports=function(t){return e.test(t)};},1789:(t,e,n)=>{var r=n(4536);t.exports=function(){this.__data__=r?r(null):{},this.size=0;};},401:t=>{t.exports=function(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e};},7667:(t,e,n)=>{var r=n(4536),i=Object.prototype.hasOwnProperty;t.exports=function(t){var e=this.__data__;if(r){var n=e[t];return "__lodash_hash_undefined__"===n?void 0:n}return i.call(e,t)?e[t]:void 0};},1327:(t,e,n)=>{var r=n(4536),i=Object.prototype.hasOwnProperty;t.exports=function(t){var e=this.__data__;return r?void 0!==e[t]:i.call(e,t)};},1866:(t,e,n)=>{var r=n(4536);t.exports=function(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=r&&void 0===e?"__lodash_hash_undefined__":e,this};},3824:t=>{var e=Object.prototype.hasOwnProperty;t.exports=function(t){var n=t.length,r=new t.constructor(n);return n&&"string"==typeof t[0]&&e.call(t,"index")&&(r.index=t.index,r.input=t.input),r};},9148:(t,e,n)=>{var r=n(4318),i=n(7157),a=n(3147),o=n(419),s=n(7133);t.exports=function(t,e,n){var c=t.constructor;switch(e){case"[object ArrayBuffer]":return r(t);case"[object Boolean]":case"[object Date]":return new c(+t);case"[object DataView]":return i(t,n);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return s(t,n);case"[object Map]":case"[object Set]":return new c;case"[object Number]":case"[object String]":return new c(t);case"[object RegExp]":return a(t);case"[object Symbol]":return o(t)}};},8517:(t,e,n)=>{var r=n(3118),i=n(5924),a=n(5726);t.exports=function(t){return "function"!=typeof t.constructor||a(t)?{}:r(i(t))};},7285:(t,e,n)=>{var r=n(2705),i=n(5694),a=n(1469),o=r?r.isConcatSpreadable:void 0;t.exports=function(t){return a(t)||i(t)||!!(o&&t&&t[o])};},5776:t=>{var e=/^(?:0|[1-9]\d*)$/;t.exports=function(t,n){var r=typeof t;return !!(n=null==n?9007199254740991:n)&&("number"==r||"symbol"!=r&&e.test(t))&&t>-1&&t%1==0&&t<n};},6612:(t,e,n)=>{var r=n(7813),i=n(8612),a=n(5776),o=n(3218);t.exports=function(t,e,n){if(!o(n))return !1;var s=typeof e;return !!("number"==s?i(n)&&a(e,n.length):"string"==s&&e in n)&&r(n[e],t)};},5403:(t,e,n)=>{var r=n(1469),i=n(3448),a=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,o=/^\w*$/;t.exports=function(t,e){if(r(t))return !1;var n=typeof t;return !("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=t&&!i(t))||o.test(t)||!a.test(t)||null!=e&&t in Object(e)};},7019:t=>{t.exports=function(t){var e=typeof t;return "string"==e||"number"==e||"symbol"==e||"boolean"==e?"__proto__"!==t:null===t};},5346:(t,e,n)=>{var r,i=n(4429),a=(r=/[^.]+$/.exec(i&&i.keys&&i.keys.IE_PROTO||""))?"Symbol(src)_1."+r:"";t.exports=function(t){return !!a&&a in t};},5726:t=>{var e=Object.prototype;t.exports=function(t){var n=t&&t.constructor;return t===("function"==typeof n&&n.prototype||e)};},9162:(t,e,n)=>{var r=n(3218);t.exports=function(t){return t==t&&!r(t)};},7040:t=>{t.exports=function(){this.__data__=[],this.size=0;};},4125:(t,e,n)=>{var r=n(8470),i=Array.prototype.splice;t.exports=function(t){var e=this.__data__,n=r(e,t);return !(n<0||(n==e.length-1?e.pop():i.call(e,n,1),--this.size,0))};},2117:(t,e,n)=>{var r=n(8470);t.exports=function(t){var e=this.__data__,n=r(e,t);return n<0?void 0:e[n][1]};},7518:(t,e,n)=>{var r=n(8470);t.exports=function(t){return r(this.__data__,t)>-1};},4705:(t,e,n)=>{var r=n(8470);t.exports=function(t,e){var n=this.__data__,i=r(n,t);return i<0?(++this.size,n.push([t,e])):n[i][1]=e,this};},4785:(t,e,n)=>{var r=n(1989),i=n(8407),a=n(7071);t.exports=function(){this.size=0,this.__data__={hash:new r,map:new(a||i),string:new r};};},1285:(t,e,n)=>{var r=n(5050);t.exports=function(t){var e=r(this,t).delete(t);return this.size-=e?1:0,e};},6e3:(t,e,n)=>{var r=n(5050);t.exports=function(t){return r(this,t).get(t)};},9916:(t,e,n)=>{var r=n(5050);t.exports=function(t){return r(this,t).has(t)};},5265:(t,e,n)=>{var r=n(5050);t.exports=function(t,e){var n=r(this,t),i=n.size;return n.set(t,e),this.size+=n.size==i?0:1,this};},8776:t=>{t.exports=function(t){var e=-1,n=Array(t.size);return t.forEach((function(t,r){n[++e]=[r,t];})),n};},2634:t=>{t.exports=function(t,e){return function(n){return null!=n&&n[t]===e&&(void 0!==e||t in Object(n))}};},4523:(t,e,n)=>{var r=n(8306);t.exports=function(t){var e=r(t,(function(t){return 500===n.size&&n.clear(),t})),n=e.cache;return e};},4536:(t,e,n)=>{var r=n(852)(Object,"create");t.exports=r;},6916:(t,e,n)=>{var r=n(5569)(Object.keys,Object);t.exports=r;},3498:t=>{t.exports=function(t){var e=[];if(null!=t)for(var n in Object(t))e.push(n);return e};},1167:(t,e,n)=>{t=n.nmd(t);var r=n(1957),i=e&&!e.nodeType&&e,a=i&&t&&!t.nodeType&&t,o=a&&a.exports===i&&r.process,s=function(){try{return a&&a.require&&a.require("util").types||o&&o.binding&&o.binding("util")}catch(t){}}();t.exports=s;},2333:t=>{var e=Object.prototype.toString;t.exports=function(t){return e.call(t)};},5569:t=>{t.exports=function(t,e){return function(n){return t(e(n))}};},5357:(t,e,n)=>{var r=n(6874),i=Math.max;t.exports=function(t,e,n){return e=i(void 0===e?t.length-1:e,0),function(){for(var a=arguments,o=-1,s=i(a.length-e,0),c=Array(s);++o<s;)c[o]=a[e+o];o=-1;for(var l=Array(e+1);++o<e;)l[o]=a[o];return l[e]=n(c),r(t,this,l)}};},5639:(t,e,n)=>{var r=n(1957),i="object"==typeof self&&self&&self.Object===Object&&self,a=r||i||Function("return this")();t.exports=a;},6390:t=>{t.exports=function(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]};},619:t=>{t.exports=function(t){return this.__data__.set(t,"__lodash_hash_undefined__"),this};},2385:t=>{t.exports=function(t){return this.__data__.has(t)};},1814:t=>{t.exports=function(t){var e=-1,n=Array(t.size);return t.forEach((function(t){n[++e]=t;})),n};},61:(t,e,n)=>{var r=n(6560),i=n(1275)(r);t.exports=i;},1275:t=>{var e=Date.now;t.exports=function(t){var n=0,r=0;return function(){var i=e(),a=16-(i-r);if(r=i,a>0){if(++n>=800)return arguments[0]}else n=0;return t.apply(void 0,arguments)}};},7465:(t,e,n)=>{var r=n(8407);t.exports=function(){this.__data__=new r,this.size=0;};},3779:t=>{t.exports=function(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n};},7599:t=>{t.exports=function(t){return this.__data__.get(t)};},4758:t=>{t.exports=function(t){return this.__data__.has(t)};},4309:(t,e,n)=>{var r=n(8407),i=n(7071),a=n(3369);t.exports=function(t,e){var n=this.__data__;if(n instanceof r){var o=n.__data__;if(!i||o.length<199)return o.push([t,e]),this.size=++n.size,this;n=this.__data__=new a(o);}return n.set(t,e),this.size=n.size,this};},2351:t=>{t.exports=function(t,e,n){for(var r=n-1,i=t.length;++r<i;)if(t[r]===e)return r;return -1};},8016:(t,e,n)=>{var r=n(8983),i=n(2689),a=n(1903);t.exports=function(t){return i(t)?a(t):r(t)};},5514:(t,e,n)=>{var r=n(4523),i=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,a=/\\(\\)?/g,o=r((function(t){var e=[];return 46===t.charCodeAt(0)&&e.push(""),t.replace(i,(function(t,n,r,i){e.push(r?i.replace(a,"$1"):n||t);})),e}));t.exports=o;},327:(t,e,n)=>{var r=n(3448);t.exports=function(t){if("string"==typeof t||r(t))return t;var e=t+"";return "0"==e&&1/t==-1/0?"-0":e};},346:t=>{var e=Function.prototype.toString;t.exports=function(t){if(null!=t){try{return e.call(t)}catch(t){}try{return t+""}catch(t){}}return ""};},7990:t=>{var e=/\s/;t.exports=function(t){for(var n=t.length;n--&&e.test(t.charAt(n)););return n};},1903:t=>{var e="[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]",n="\\ud83c[\\udffb-\\udfff]",r="[^\\ud800-\\udfff]",i="(?:\\ud83c[\\udde6-\\uddff]){2}",a="[\\ud800-\\udbff][\\udc00-\\udfff]",o="(?:"+e+"|"+n+")?",s="[\\ufe0e\\ufe0f]?",c=s+o+"(?:\\u200d(?:"+[r,i,a].join("|")+")"+s+o+")*",l="(?:"+[r+e+"?",e,i,a,"[\\ud800-\\udfff]"].join("|")+")",u=RegExp(n+"(?="+n+")|"+l+c,"g");t.exports=function(t){for(var e=u.lastIndex=0;u.test(t);)++e;return e};},6678:(t,e,n)=>{var r=n(5990);t.exports=function(t){return r(t,4)};},361:(t,e,n)=>{var r=n(5990);t.exports=function(t){return r(t,5)};},5703:t=>{t.exports=function(t){return function(){return t}};},1747:(t,e,n)=>{var r=n(5976),i=n(7813),a=n(6612),o=n(1704),s=Object.prototype,c=s.hasOwnProperty,l=r((function(t,e){t=Object(t);var n=-1,r=e.length,l=r>2?e[2]:void 0;for(l&&a(e[0],e[1],l)&&(r=1);++n<r;)for(var u=e[n],h=o(u),f=-1,d=h.length;++f<d;){var p=h[f],g=t[p];(void 0===g||i(g,s[p])&&!c.call(t,p))&&(t[p]=u[p]);}return t}));t.exports=l;},6073:(t,e,n)=>{t.exports=n(4486);},7813:t=>{t.exports=function(t,e){return t===e||t!=t&&e!=e};},3105:(t,e,n)=>{var r=n(4963),i=n(760),a=n(7206),o=n(1469);t.exports=function(t,e){return (o(t)?r:i)(t,a(e,3))};},3311:(t,e,n)=>{var r=n(7740)(n(998));t.exports=r;},998:(t,e,n)=>{var r=n(1848),i=n(7206),a=n(554),o=Math.max;t.exports=function(t,e,n){var s=null==t?0:t.length;if(!s)return -1;var c=null==n?0:a(n);return c<0&&(c=o(s+c,0)),r(t,i(e,3),c)};},5564:(t,e,n)=>{var r=n(1078);t.exports=function(t){return null!=t&&t.length?r(t,1):[]};},4486:(t,e,n)=>{var r=n(7412),i=n(9881),a=n(4290),o=n(1469);t.exports=function(t,e){return (o(t)?r:i)(t,a(e))};},2620:(t,e,n)=>{var r=n(8483),i=n(4290),a=n(1704);t.exports=function(t,e){return null==t?t:r(t,i(e),a)};},7361:(t,e,n)=>{var r=n(7786);t.exports=function(t,e,n){var i=null==t?void 0:r(t,e);return void 0===i?n:i};},8721:(t,e,n)=>{var r=n(8565),i=n(222);t.exports=function(t,e){return null!=t&&i(t,e,r)};},9095:(t,e,n)=>{var r=n(13),i=n(222);t.exports=function(t,e){return null!=t&&i(t,e,r)};},6557:t=>{t.exports=function(t){return t};},5694:(t,e,n)=>{var r=n(9454),i=n(7005),a=Object.prototype,o=a.hasOwnProperty,s=a.propertyIsEnumerable,c=r(function(){return arguments}())?r:function(t){return i(t)&&o.call(t,"callee")&&!s.call(t,"callee")};t.exports=c;},1469:t=>{var e=Array.isArray;t.exports=e;},8612:(t,e,n)=>{var r=n(3560),i=n(1780);t.exports=function(t){return null!=t&&i(t.length)&&!r(t)};},9246:(t,e,n)=>{var r=n(8612),i=n(7005);t.exports=function(t){return i(t)&&r(t)};},4144:(t,e,n)=>{t=n.nmd(t);var r=n(5639),i=n(5062),a=e&&!e.nodeType&&e,o=a&&t&&!t.nodeType&&t,s=o&&o.exports===a?r.Buffer:void 0,c=(s?s.isBuffer:void 0)||i;t.exports=c;},1609:(t,e,n)=>{var r=n(280),i=n(4160),a=n(5694),o=n(1469),s=n(8612),c=n(4144),l=n(5726),u=n(6719),h=Object.prototype.hasOwnProperty;t.exports=function(t){if(null==t)return !0;if(s(t)&&(o(t)||"string"==typeof t||"function"==typeof t.splice||c(t)||u(t)||a(t)))return !t.length;var e=i(t);if("[object Map]"==e||"[object Set]"==e)return !t.size;if(l(t))return !r(t).length;for(var n in t)if(h.call(t,n))return !1;return !0};},3560:(t,e,n)=>{var r=n(4239),i=n(3218);t.exports=function(t){if(!i(t))return !1;var e=r(t);return "[object Function]"==e||"[object GeneratorFunction]"==e||"[object AsyncFunction]"==e||"[object Proxy]"==e};},1780:t=>{t.exports=function(t){return "number"==typeof t&&t>-1&&t%1==0&&t<=9007199254740991};},6688:(t,e,n)=>{var r=n(5588),i=n(1717),a=n(1167),o=a&&a.isMap,s=o?i(o):r;t.exports=s;},3218:t=>{t.exports=function(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)};},7005:t=>{t.exports=function(t){return null!=t&&"object"==typeof t};},8630:(t,e,n)=>{var r=n(4239),i=n(5924),a=n(7005),o=Function.prototype,s=Object.prototype,c=o.toString,l=s.hasOwnProperty,u=c.call(Object);t.exports=function(t){if(!a(t)||"[object Object]"!=r(t))return !1;var e=i(t);if(null===e)return !0;var n=l.call(e,"constructor")&&e.constructor;return "function"==typeof n&&n instanceof n&&c.call(n)==u};},2928:(t,e,n)=>{var r=n(9221),i=n(1717),a=n(1167),o=a&&a.isSet,s=o?i(o):r;t.exports=s;},7037:(t,e,n)=>{var r=n(4239),i=n(1469),a=n(7005);t.exports=function(t){return "string"==typeof t||!i(t)&&a(t)&&"[object String]"==r(t)};},3448:(t,e,n)=>{var r=n(4239),i=n(7005);t.exports=function(t){return "symbol"==typeof t||i(t)&&"[object Symbol]"==r(t)};},6719:(t,e,n)=>{var r=n(8749),i=n(1717),a=n(1167),o=a&&a.isTypedArray,s=o?i(o):r;t.exports=s;},2353:t=>{t.exports=function(t){return void 0===t};},3674:(t,e,n)=>{var r=n(4636),i=n(280),a=n(8612);t.exports=function(t){return a(t)?r(t):i(t)};},1704:(t,e,n)=>{var r=n(4636),i=n(313),a=n(8612);t.exports=function(t){return a(t)?r(t,!0):i(t)};},928:t=>{t.exports=function(t){var e=null==t?0:t.length;return e?t[e-1]:void 0};},5161:(t,e,n)=>{var r=n(9932),i=n(7206),a=n(9199),o=n(1469);t.exports=function(t,e){return (o(t)?r:a)(t,i(e,3))};},6604:(t,e,n)=>{var r=n(9465),i=n(7816),a=n(7206);t.exports=function(t,e){var n={};return e=a(e,3),i(t,(function(t,i,a){r(n,i,e(t,i,a));})),n};},6162:(t,e,n)=>{var r=n(6029),i=n(3325),a=n(6557);t.exports=function(t){return t&&t.length?r(t,a,i):void 0};},8306:(t,e,n)=>{var r=n(3369);function i(t,e){if("function"!=typeof t||null!=e&&"function"!=typeof e)throw new TypeError("Expected a function");var n=function(){var r=arguments,i=e?e.apply(this,r):r[0],a=n.cache;if(a.has(i))return a.get(i);var o=t.apply(this,r);return n.cache=a.set(i,o)||a,o};return n.cache=new(i.Cache||r),n}i.Cache=r,t.exports=i;},3857:(t,e,n)=>{var r=n(2980),i=n(1463)((function(t,e,n){r(t,e,n);}));t.exports=i;},3632:(t,e,n)=>{var r=n(6029),i=n(433),a=n(6557);t.exports=function(t){return t&&t.length?r(t,a,i):void 0};},2762:(t,e,n)=>{var r=n(6029),i=n(7206),a=n(433);t.exports=function(t,e){return t&&t.length?r(t,i(e,2),a):void 0};},308:t=>{t.exports=function(){};},7771:(t,e,n)=>{var r=n(5639);t.exports=function(){return r.Date.now()};},9722:(t,e,n)=>{var r=n(5970),i=n(9021)((function(t,e){return null==t?{}:r(t,e)}));t.exports=i;},9601:(t,e,n)=>{var r=n(371),i=n(9152),a=n(5403),o=n(327);t.exports=function(t){return a(t)?r(o(t)):i(t)};},6026:(t,e,n)=>{var r=n(7445)();t.exports=r;},4061:(t,e,n)=>{var r=n(2663),i=n(9881),a=n(7206),o=n(107),s=n(1469);t.exports=function(t,e,n){var c=s(t)?r:o,l=arguments.length<3;return c(t,a(e,4),n,l,i)};},4238:(t,e,n)=>{var r=n(280),i=n(4160),a=n(8612),o=n(7037),s=n(8016);t.exports=function(t){if(null==t)return 0;if(a(t))return o(t)?s(t):t.length;var e=i(t);return "[object Map]"==e||"[object Set]"==e?t.size:r(t).length};},9734:(t,e,n)=>{var r=n(1078),i=n(9556),a=n(5976),o=n(6612),s=a((function(t,e){if(null==t)return [];var n=e.length;return n>1&&o(t,e[0],e[1])?e=[]:n>2&&o(e[0],e[1],e[2])&&(e=[e[0]]),i(t,r(e,1),[])}));t.exports=s;},479:t=>{t.exports=function(){return []};},5062:t=>{t.exports=function(){return !1};},8601:(t,e,n)=>{var r=n(4841);t.exports=function(t){return t?Infinity===(t=r(t))||t===-1/0?17976931348623157e292*(t<0?-1:1):t==t?t:0:0===t?t:0};},554:(t,e,n)=>{var r=n(8601);t.exports=function(t){var e=r(t),n=e%1;return e==e?n?e-n:e:0};},4841:(t,e,n)=>{var r=n(7561),i=n(3218),a=n(3448),o=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,c=/^0o[0-7]+$/i,l=parseInt;t.exports=function(t){if("number"==typeof t)return t;if(a(t))return NaN;if(i(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=i(e)?e+"":e;}if("string"!=typeof t)return 0===t?t:+t;t=r(t);var n=s.test(t);return n||c.test(t)?l(t.slice(2),n?2:8):o.test(t)?NaN:+t};},3678:(t,e,n)=>{var r=n(8363),i=n(1704);t.exports=function(t){return r(t,i(t))};},9833:(t,e,n)=>{var r=n(531);t.exports=function(t){return null==t?"":r(t)};},8718:(t,e,n)=>{var r=n(7412),i=n(3118),a=n(7816),o=n(7206),s=n(5924),c=n(1469),l=n(4144),u=n(3560),h=n(3218),f=n(6719);t.exports=function(t,e,n){var d=c(t),p=d||l(t)||f(t);if(e=o(e,4),null==n){var g=t&&t.constructor;n=p?d?new g:[]:h(t)&&u(g)?i(s(t)):{};}return (p?r:a)(t,(function(t,r,i){return e(n,t,r,i)})),n};},3386:(t,e,n)=>{var r=n(1078),i=n(5976),a=n(5652),o=n(9246),s=i((function(t){return a(r(t,1,o,!0))}));t.exports=s;},3955:(t,e,n)=>{var r=n(9833),i=0;t.exports=function(t){var e=++i;return r(t)+e};},2628:(t,e,n)=>{var r=n(7415),i=n(3674);t.exports=function(t){return null==t?[]:r(t,i(t))};},7287:(t,e,n)=>{var r=n(4865),i=n(1757);t.exports=function(t,e){return i(t||[],e||[],r)};},9234:()=>{},1748:(t,e,n)=>{var r={"./locale":9234,"./locale.js":9234};function i(t){var e=a(t);return n(e)}function a(t){if(!n.o(r,t)){var e=new Error("Cannot find module '"+t+"'");throw e.code="MODULE_NOT_FOUND",e}return r[t]}i.keys=function(){return Object.keys(r)},i.resolve=a,t.exports=i,i.id=1748;},1941:function(t,e,n){(t=n.nmd(t)).exports=function(){var e,r;function i(){return e.apply(null,arguments)}function a(t){return t instanceof Array||"[object Array]"===Object.prototype.toString.call(t)}function o(t){return null!=t&&"[object Object]"===Object.prototype.toString.call(t)}function s(t){return void 0===t}function c(t){return "number"==typeof t||"[object Number]"===Object.prototype.toString.call(t)}function l(t){return t instanceof Date||"[object Date]"===Object.prototype.toString.call(t)}function u(t,e){var n,r=[];for(n=0;n<t.length;++n)r.push(e(t[n],n));return r}function h(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function f(t,e){for(var n in e)h(e,n)&&(t[n]=e[n]);return h(e,"toString")&&(t.toString=e.toString),h(e,"valueOf")&&(t.valueOf=e.valueOf),t}function d(t,e,n,r){return ve(t,e,n,r,!0).utc()}function p(t){return null==t._pf&&(t._pf={empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],meridiem:null,rfc2822:!1,weekdayMismatch:!1}),t._pf}function g(t){if(null==t._isValid){var e=p(t),n=r.call(e.parsedDateParts,(function(t){return null!=t})),i=!isNaN(t._d.getTime())&&e.overflow<0&&!e.empty&&!e.invalidMonth&&!e.invalidWeekday&&!e.weekdayMismatch&&!e.nullInput&&!e.invalidFormat&&!e.userInvalidated&&(!e.meridiem||e.meridiem&&n);if(t._strict&&(i=i&&0===e.charsLeftOver&&0===e.unusedTokens.length&&void 0===e.bigHour),null!=Object.isFrozen&&Object.isFrozen(t))return i;t._isValid=i;}return t._isValid}function y(t){var e=d(NaN);return null!=t?f(p(e),t):p(e).userInvalidated=!0,e}r=Array.prototype.some?Array.prototype.some:function(t){for(var e=Object(this),n=e.length>>>0,r=0;r<n;r++)if(r in e&&t.call(this,e[r],r,e))return !0;return !1};var m=i.momentProperties=[];function b(t,e){var n,r,i;if(s(e._isAMomentObject)||(t._isAMomentObject=e._isAMomentObject),s(e._i)||(t._i=e._i),s(e._f)||(t._f=e._f),s(e._l)||(t._l=e._l),s(e._strict)||(t._strict=e._strict),s(e._tzm)||(t._tzm=e._tzm),s(e._isUTC)||(t._isUTC=e._isUTC),s(e._offset)||(t._offset=e._offset),s(e._pf)||(t._pf=p(e)),s(e._locale)||(t._locale=e._locale),0<m.length)for(n=0;n<m.length;n++)s(i=e[r=m[n]])||(t[r]=i);return t}var v=!1;function _(t){b(this,t),this._d=new Date(null!=t._d?t._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),!1===v&&(v=!0,i.updateOffset(this),v=!1);}function x(t){return t instanceof _||null!=t&&null!=t._isAMomentObject}function k(t){return t<0?Math.ceil(t)||0:Math.floor(t)}function w(t){var e=+t,n=0;return 0!==e&&isFinite(e)&&(n=k(e)),n}function T(t,e,n){var r,i=Math.min(t.length,e.length),a=Math.abs(t.length-e.length),o=0;for(r=0;r<i;r++)(n&&t[r]!==e[r]||!n&&w(t[r])!==w(e[r]))&&o++;return o+a}function E(t){!1===i.suppressDeprecationWarnings&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+t);}function C(t,e){var n=!0;return f((function(){if(null!=i.deprecationHandler&&i.deprecationHandler(null,t),n){for(var r,a=[],o=0;o<arguments.length;o++){if(r="","object"==typeof arguments[o]){for(var s in r+="\n["+o+"] ",arguments[0])r+=s+": "+arguments[0][s]+", ";r=r.slice(0,-2);}else r=arguments[o];a.push(r);}E(t+"\nArguments: "+Array.prototype.slice.call(a).join("")+"\n"+(new Error).stack),n=!1;}return e.apply(this,arguments)}),e)}var S,A={};function M(t,e){null!=i.deprecationHandler&&i.deprecationHandler(t,e),A[t]||(E(e),A[t]=!0);}function N(t){return t instanceof Function||"[object Function]"===Object.prototype.toString.call(t)}function O(t,e){var n,r=f({},t);for(n in e)h(e,n)&&(o(t[n])&&o(e[n])?(r[n]={},f(r[n],t[n]),f(r[n],e[n])):null!=e[n]?r[n]=e[n]:delete r[n]);for(n in t)h(t,n)&&!h(e,n)&&o(t[n])&&(r[n]=f({},r[n]));return r}function D(t){null!=t&&this.set(t);}i.suppressDeprecationWarnings=!1,i.deprecationHandler=null,S=Object.keys?Object.keys:function(t){var e,n=[];for(e in t)h(t,e)&&n.push(e);return n};var B={};function L(t,e){var n=t.toLowerCase();B[n]=B[n+"s"]=B[e]=t;}function I(t){return "string"==typeof t?B[t]||B[t.toLowerCase()]:void 0}function F(t){var e,n,r={};for(n in t)h(t,n)&&(e=I(n))&&(r[e]=t[n]);return r}var R={};function P(t,e){R[t]=e;}function j(t,e,n){var r=""+Math.abs(t),i=e-r.length;return (0<=t?n?"+":"":"-")+Math.pow(10,Math.max(0,i)).toString().substr(1)+r}var z=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,Y=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,U={},$={};function W(t,e,n,r){var i=r;"string"==typeof r&&(i=function(){return this[r]()}),t&&($[t]=i),e&&($[e[0]]=function(){return j(i.apply(this,arguments),e[1],e[2])}),n&&($[n]=function(){return this.localeData().ordinal(i.apply(this,arguments),t)});}function q(t,e){return t.isValid()?(e=H(e,t.localeData()),U[e]=U[e]||function(t){var e,n,r,i=t.match(z);for(e=0,n=i.length;e<n;e++)$[i[e]]?i[e]=$[i[e]]:i[e]=(r=i[e]).match(/\[[\s\S]/)?r.replace(/^\[|\]$/g,""):r.replace(/\\/g,"");return function(e){var r,a="";for(r=0;r<n;r++)a+=N(i[r])?i[r].call(e,t):i[r];return a}}(e),U[e](t)):t.localeData().invalidDate()}function H(t,e){var n=5;function r(t){return e.longDateFormat(t)||t}for(Y.lastIndex=0;0<=n&&Y.test(t);)t=t.replace(Y,r),Y.lastIndex=0,n-=1;return t}var V=/\d/,G=/\d\d/,X=/\d{3}/,Z=/\d{4}/,Q=/[+-]?\d{6}/,K=/\d\d?/,J=/\d\d\d\d?/,tt=/\d\d\d\d\d\d?/,et=/\d{1,3}/,nt=/\d{1,4}/,rt=/[+-]?\d{1,6}/,it=/\d+/,at=/[+-]?\d+/,ot=/Z|[+-]\d\d:?\d\d/gi,st=/Z|[+-]\d\d(?::?\d\d)?/gi,ct=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,lt={};function ut(t,e,n){lt[t]=N(e)?e:function(t,r){return t&&n?n:e};}function ht(t,e){return h(lt,t)?lt[t](e._strict,e._locale):new RegExp(ft(t.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,(function(t,e,n,r,i){return e||n||r||i}))))}function ft(t){return t.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}var dt={};function pt(t,e){var n,r=e;for("string"==typeof t&&(t=[t]),c(e)&&(r=function(t,n){n[e]=w(t);}),n=0;n<t.length;n++)dt[t[n]]=r;}function gt(t,e){pt(t,(function(t,n,r,i){r._w=r._w||{},e(t,r._w,r,i);}));}function yt(t){return mt(t)?366:365}function mt(t){return t%4==0&&t%100!=0||t%400==0}W("Y",0,0,(function(){var t=this.year();return t<=9999?""+t:"+"+t})),W(0,["YY",2],0,(function(){return this.year()%100})),W(0,["YYYY",4],0,"year"),W(0,["YYYYY",5],0,"year"),W(0,["YYYYYY",6,!0],0,"year"),L("year","y"),P("year",1),ut("Y",at),ut("YY",K,G),ut("YYYY",nt,Z),ut("YYYYY",rt,Q),ut("YYYYYY",rt,Q),pt(["YYYYY","YYYYYY"],0),pt("YYYY",(function(t,e){e[0]=2===t.length?i.parseTwoDigitYear(t):w(t);})),pt("YY",(function(t,e){e[0]=i.parseTwoDigitYear(t);})),pt("Y",(function(t,e){e[0]=parseInt(t,10);})),i.parseTwoDigitYear=function(t){return w(t)+(68<w(t)?1900:2e3)};var bt,vt=_t("FullYear",!0);function _t(t,e){return function(n){return null!=n?(kt(this,t,n),i.updateOffset(this,e),this):xt(this,t)}}function xt(t,e){return t.isValid()?t._d["get"+(t._isUTC?"UTC":"")+e]():NaN}function kt(t,e,n){t.isValid()&&!isNaN(n)&&("FullYear"===e&&mt(t.year())&&1===t.month()&&29===t.date()?t._d["set"+(t._isUTC?"UTC":"")+e](n,t.month(),wt(n,t.month())):t._d["set"+(t._isUTC?"UTC":"")+e](n));}function wt(t,e){if(isNaN(t)||isNaN(e))return NaN;var n=(e%12+12)%12;return t+=(e-n)/12,1===n?mt(t)?29:28:31-n%7%2}bt=Array.prototype.indexOf?Array.prototype.indexOf:function(t){var e;for(e=0;e<this.length;++e)if(this[e]===t)return e;return -1},W("M",["MM",2],"Mo",(function(){return this.month()+1})),W("MMM",0,0,(function(t){return this.localeData().monthsShort(this,t)})),W("MMMM",0,0,(function(t){return this.localeData().months(this,t)})),L("month","M"),P("month",8),ut("M",K),ut("MM",K,G),ut("MMM",(function(t,e){return e.monthsShortRegex(t)})),ut("MMMM",(function(t,e){return e.monthsRegex(t)})),pt(["M","MM"],(function(t,e){e[1]=w(t)-1;})),pt(["MMM","MMMM"],(function(t,e,n,r){var i=n._locale.monthsParse(t,r,n._strict);null!=i?e[1]=i:p(n).invalidMonth=t;}));var Tt=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,Et="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),Ct="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_");function St(t,e){var n;if(!t.isValid())return t;if("string"==typeof e)if(/^\d+$/.test(e))e=w(e);else if(!c(e=t.localeData().monthsParse(e)))return t;return n=Math.min(t.date(),wt(t.year(),e)),t._d["set"+(t._isUTC?"UTC":"")+"Month"](e,n),t}function At(t){return null!=t?(St(this,t),i.updateOffset(this,!0),this):xt(this,"Month")}var Mt=ct,Nt=ct;function Ot(){function t(t,e){return e.length-t.length}var e,n,r=[],i=[],a=[];for(e=0;e<12;e++)n=d([2e3,e]),r.push(this.monthsShort(n,"")),i.push(this.months(n,"")),a.push(this.months(n,"")),a.push(this.monthsShort(n,""));for(r.sort(t),i.sort(t),a.sort(t),e=0;e<12;e++)r[e]=ft(r[e]),i[e]=ft(i[e]);for(e=0;e<24;e++)a[e]=ft(a[e]);this._monthsRegex=new RegExp("^("+a.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+i.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+r.join("|")+")","i");}function Dt(t){var e;if(t<100&&0<=t){var n=Array.prototype.slice.call(arguments);n[0]=t+400,e=new Date(Date.UTC.apply(null,n)),isFinite(e.getUTCFullYear())&&e.setUTCFullYear(t);}else e=new Date(Date.UTC.apply(null,arguments));return e}function Bt(t,e,n){var r=7+e-n;return -(7+Dt(t,0,r).getUTCDay()-e)%7+r-1}function Lt(t,e,n,r,i){var a,o,s=1+7*(e-1)+(7+n-r)%7+Bt(t,r,i);return o=s<=0?yt(a=t-1)+s:s>yt(t)?(a=t+1,s-yt(t)):(a=t,s),{year:a,dayOfYear:o}}function It(t,e,n){var r,i,a=Bt(t.year(),e,n),o=Math.floor((t.dayOfYear()-a-1)/7)+1;return o<1?r=o+Ft(i=t.year()-1,e,n):o>Ft(t.year(),e,n)?(r=o-Ft(t.year(),e,n),i=t.year()+1):(i=t.year(),r=o),{week:r,year:i}}function Ft(t,e,n){var r=Bt(t,e,n),i=Bt(t+1,e,n);return (yt(t)-r+i)/7}function Rt(t,e){return t.slice(e,7).concat(t.slice(0,e))}W("w",["ww",2],"wo","week"),W("W",["WW",2],"Wo","isoWeek"),L("week","w"),L("isoWeek","W"),P("week",5),P("isoWeek",5),ut("w",K),ut("ww",K,G),ut("W",K),ut("WW",K,G),gt(["w","ww","W","WW"],(function(t,e,n,r){e[r.substr(0,1)]=w(t);})),W("d",0,"do","day"),W("dd",0,0,(function(t){return this.localeData().weekdaysMin(this,t)})),W("ddd",0,0,(function(t){return this.localeData().weekdaysShort(this,t)})),W("dddd",0,0,(function(t){return this.localeData().weekdays(this,t)})),W("e",0,0,"weekday"),W("E",0,0,"isoWeekday"),L("day","d"),L("weekday","e"),L("isoWeekday","E"),P("day",11),P("weekday",11),P("isoWeekday",11),ut("d",K),ut("e",K),ut("E",K),ut("dd",(function(t,e){return e.weekdaysMinRegex(t)})),ut("ddd",(function(t,e){return e.weekdaysShortRegex(t)})),ut("dddd",(function(t,e){return e.weekdaysRegex(t)})),gt(["dd","ddd","dddd"],(function(t,e,n,r){var i=n._locale.weekdaysParse(t,r,n._strict);null!=i?e.d=i:p(n).invalidWeekday=t;})),gt(["d","e","E"],(function(t,e,n,r){e[r]=w(t);}));var Pt="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),jt="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),zt="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),Yt=ct,Ut=ct,$t=ct;function Wt(){function t(t,e){return e.length-t.length}var e,n,r,i,a,o=[],s=[],c=[],l=[];for(e=0;e<7;e++)n=d([2e3,1]).day(e),r=this.weekdaysMin(n,""),i=this.weekdaysShort(n,""),a=this.weekdays(n,""),o.push(r),s.push(i),c.push(a),l.push(r),l.push(i),l.push(a);for(o.sort(t),s.sort(t),c.sort(t),l.sort(t),e=0;e<7;e++)s[e]=ft(s[e]),c[e]=ft(c[e]),l[e]=ft(l[e]);this._weekdaysRegex=new RegExp("^("+l.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+c.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+s.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+o.join("|")+")","i");}function qt(){return this.hours()%12||12}function Ht(t,e){W(t,0,0,(function(){return this.localeData().meridiem(this.hours(),this.minutes(),e)}));}function Vt(t,e){return e._meridiemParse}W("H",["HH",2],0,"hour"),W("h",["hh",2],0,qt),W("k",["kk",2],0,(function(){return this.hours()||24})),W("hmm",0,0,(function(){return ""+qt.apply(this)+j(this.minutes(),2)})),W("hmmss",0,0,(function(){return ""+qt.apply(this)+j(this.minutes(),2)+j(this.seconds(),2)})),W("Hmm",0,0,(function(){return ""+this.hours()+j(this.minutes(),2)})),W("Hmmss",0,0,(function(){return ""+this.hours()+j(this.minutes(),2)+j(this.seconds(),2)})),Ht("a",!0),Ht("A",!1),L("hour","h"),P("hour",13),ut("a",Vt),ut("A",Vt),ut("H",K),ut("h",K),ut("k",K),ut("HH",K,G),ut("hh",K,G),ut("kk",K,G),ut("hmm",J),ut("hmmss",tt),ut("Hmm",J),ut("Hmmss",tt),pt(["H","HH"],3),pt(["k","kk"],(function(t,e,n){var r=w(t);e[3]=24===r?0:r;})),pt(["a","A"],(function(t,e,n){n._isPm=n._locale.isPM(t),n._meridiem=t;})),pt(["h","hh"],(function(t,e,n){e[3]=w(t),p(n).bigHour=!0;})),pt("hmm",(function(t,e,n){var r=t.length-2;e[3]=w(t.substr(0,r)),e[4]=w(t.substr(r)),p(n).bigHour=!0;})),pt("hmmss",(function(t,e,n){var r=t.length-4,i=t.length-2;e[3]=w(t.substr(0,r)),e[4]=w(t.substr(r,2)),e[5]=w(t.substr(i)),p(n).bigHour=!0;})),pt("Hmm",(function(t,e,n){var r=t.length-2;e[3]=w(t.substr(0,r)),e[4]=w(t.substr(r));})),pt("Hmmss",(function(t,e,n){var r=t.length-4,i=t.length-2;e[3]=w(t.substr(0,r)),e[4]=w(t.substr(r,2)),e[5]=w(t.substr(i));}));var Gt,Xt=_t("Hours",!0),Zt={calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},longDateFormat:{LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},invalidDate:"Invalid date",ordinal:"%d",dayOfMonthOrdinalParse:/\d{1,2}/,relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},months:Et,monthsShort:Ct,week:{dow:0,doy:6},weekdays:Pt,weekdaysMin:zt,weekdaysShort:jt,meridiemParse:/[ap]\.?m?\.?/i},Qt={},Kt={};function Jt(t){return t?t.toLowerCase().replace("_","-"):t}function te(e){var r=null;if(!Qt[e]&&t&&t.exports)try{r=Gt._abbr,n(1748)("./"+e),ee(r);}catch(e){}return Qt[e]}function ee(t,e){var n;return t&&((n=s(e)?re(t):ne(t,e))?Gt=n:"undefined"!=typeof console&&console.warn&&console.warn("Locale "+t+" not found. Did you forget to load it?")),Gt._abbr}function ne(t,e){if(null===e)return delete Qt[t],null;var n,r=Zt;if(e.abbr=t,null!=Qt[t])M("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),r=Qt[t]._config;else if(null!=e.parentLocale)if(null!=Qt[e.parentLocale])r=Qt[e.parentLocale]._config;else {if(null==(n=te(e.parentLocale)))return Kt[e.parentLocale]||(Kt[e.parentLocale]=[]),Kt[e.parentLocale].push({name:t,config:e}),null;r=n._config;}return Qt[t]=new D(O(r,e)),Kt[t]&&Kt[t].forEach((function(t){ne(t.name,t.config);})),ee(t),Qt[t]}function re(t){var e;if(t&&t._locale&&t._locale._abbr&&(t=t._locale._abbr),!t)return Gt;if(!a(t)){if(e=te(t))return e;t=[t];}return function(t){for(var e,n,r,i,a=0;a<t.length;){for(e=(i=Jt(t[a]).split("-")).length,n=(n=Jt(t[a+1]))?n.split("-"):null;0<e;){if(r=te(i.slice(0,e).join("-")))return r;if(n&&n.length>=e&&T(i,n,!0)>=e-1)break;e--;}a++;}return Gt}(t)}function ie(t){var e,n=t._a;return n&&-2===p(t).overflow&&(e=n[1]<0||11<n[1]?1:n[2]<1||n[2]>wt(n[0],n[1])?2:n[3]<0||24<n[3]||24===n[3]&&(0!==n[4]||0!==n[5]||0!==n[6])?3:n[4]<0||59<n[4]?4:n[5]<0||59<n[5]?5:n[6]<0||999<n[6]?6:-1,p(t)._overflowDayOfYear&&(e<0||2<e)&&(e=2),p(t)._overflowWeeks&&-1===e&&(e=7),p(t)._overflowWeekday&&-1===e&&(e=8),p(t).overflow=e),t}function ae(t,e,n){return null!=t?t:null!=e?e:n}function oe(t){var e,n,r,a,o,s=[];if(!t._d){var c,l;for(c=t,l=new Date(i.now()),r=c._useUTC?[l.getUTCFullYear(),l.getUTCMonth(),l.getUTCDate()]:[l.getFullYear(),l.getMonth(),l.getDate()],t._w&&null==t._a[2]&&null==t._a[1]&&function(t){var e,n,r,i,a,o,s,c;if(null!=(e=t._w).GG||null!=e.W||null!=e.E)a=1,o=4,n=ae(e.GG,t._a[0],It(_e(),1,4).year),r=ae(e.W,1),((i=ae(e.E,1))<1||7<i)&&(c=!0);else {a=t._locale._week.dow,o=t._locale._week.doy;var l=It(_e(),a,o);n=ae(e.gg,t._a[0],l.year),r=ae(e.w,l.week),null!=e.d?((i=e.d)<0||6<i)&&(c=!0):null!=e.e?(i=e.e+a,(e.e<0||6<e.e)&&(c=!0)):i=a;}r<1||r>Ft(n,a,o)?p(t)._overflowWeeks=!0:null!=c?p(t)._overflowWeekday=!0:(s=Lt(n,r,i,a,o),t._a[0]=s.year,t._dayOfYear=s.dayOfYear);}(t),null!=t._dayOfYear&&(o=ae(t._a[0],r[0]),(t._dayOfYear>yt(o)||0===t._dayOfYear)&&(p(t)._overflowDayOfYear=!0),n=Dt(o,0,t._dayOfYear),t._a[1]=n.getUTCMonth(),t._a[2]=n.getUTCDate()),e=0;e<3&&null==t._a[e];++e)t._a[e]=s[e]=r[e];for(;e<7;e++)t._a[e]=s[e]=null==t._a[e]?2===e?1:0:t._a[e];24===t._a[3]&&0===t._a[4]&&0===t._a[5]&&0===t._a[6]&&(t._nextDay=!0,t._a[3]=0),t._d=(t._useUTC?Dt:function(t,e,n,r,i,a,o){var s;return t<100&&0<=t?(s=new Date(t+400,e,n,r,i,a,o),isFinite(s.getFullYear())&&s.setFullYear(t)):s=new Date(t,e,n,r,i,a,o),s}).apply(null,s),a=t._useUTC?t._d.getUTCDay():t._d.getDay(),null!=t._tzm&&t._d.setUTCMinutes(t._d.getUTCMinutes()-t._tzm),t._nextDay&&(t._a[3]=24),t._w&&void 0!==t._w.d&&t._w.d!==a&&(p(t).weekdayMismatch=!0);}}var se=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,ce=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,le=/Z|[+-]\d\d(?::?\d\d)?/,ue=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/]],he=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],fe=/^\/?Date\((\-?\d+)/i;function de(t){var e,n,r,i,a,o,s=t._i,c=se.exec(s)||ce.exec(s);if(c){for(p(t).iso=!0,e=0,n=ue.length;e<n;e++)if(ue[e][1].exec(c[1])){i=ue[e][0],r=!1!==ue[e][2];break}if(null==i)return void(t._isValid=!1);if(c[3]){for(e=0,n=he.length;e<n;e++)if(he[e][1].exec(c[3])){a=(c[2]||" ")+he[e][0];break}if(null==a)return void(t._isValid=!1)}if(!r&&null!=a)return void(t._isValid=!1);if(c[4]){if(!le.exec(c[4]))return void(t._isValid=!1);o="Z";}t._f=i+(a||"")+(o||""),me(t);}else t._isValid=!1;}var pe=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;var ge={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function ye(t){var e,n,r,i=pe.exec(t._i.replace(/\([^)]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").replace(/^\s\s*/,"").replace(/\s\s*$/,""));if(i){var a=function(t,e,n,r,i,a){var o=[function(t){var e=parseInt(t,10);return e<=49?2e3+e:e<=999?1900+e:e}(t),Ct.indexOf(e),parseInt(n,10),parseInt(r,10),parseInt(i,10)];return a&&o.push(parseInt(a,10)),o}(i[4],i[3],i[2],i[5],i[6],i[7]);if(n=a,r=t,(e=i[1])&&jt.indexOf(e)!==new Date(n[0],n[1],n[2]).getDay()&&(p(r).weekdayMismatch=!0,!(r._isValid=!1)))return;t._a=a,t._tzm=function(t,e,n){if(t)return ge[t];if(e)return 0;var r=parseInt(n,10),i=r%100;return (r-i)/100*60+i}(i[8],i[9],i[10]),t._d=Dt.apply(null,t._a),t._d.setUTCMinutes(t._d.getUTCMinutes()-t._tzm),p(t).rfc2822=!0;}else t._isValid=!1;}function me(t){if(t._f!==i.ISO_8601)if(t._f!==i.RFC_2822){t._a=[],p(t).empty=!0;var e,n,r,a,o,s,c,l,u=""+t._i,f=u.length,d=0;for(r=H(t._f,t._locale).match(z)||[],e=0;e<r.length;e++)a=r[e],(n=(u.match(ht(a,t))||[])[0])&&(0<(o=u.substr(0,u.indexOf(n))).length&&p(t).unusedInput.push(o),u=u.slice(u.indexOf(n)+n.length),d+=n.length),$[a]?(n?p(t).empty=!1:p(t).unusedTokens.push(a),s=a,l=t,null!=(c=n)&&h(dt,s)&&dt[s](c,l._a,l,s)):t._strict&&!n&&p(t).unusedTokens.push(a);p(t).charsLeftOver=f-d,0<u.length&&p(t).unusedInput.push(u),t._a[3]<=12&&!0===p(t).bigHour&&0<t._a[3]&&(p(t).bigHour=void 0),p(t).parsedDateParts=t._a.slice(0),p(t).meridiem=t._meridiem,t._a[3]=function(t,e,n){var r;return null==n?e:null!=t.meridiemHour?t.meridiemHour(e,n):(null!=t.isPM&&((r=t.isPM(n))&&e<12&&(e+=12),r||12!==e||(e=0)),e)}(t._locale,t._a[3],t._meridiem),oe(t),ie(t);}else ye(t);else de(t);}function be(t){var e,n,r,h,d=t._i,m=t._f;return t._locale=t._locale||re(t._l),null===d||void 0===m&&""===d?y({nullInput:!0}):("string"==typeof d&&(t._i=d=t._locale.preparse(d)),x(d)?new _(ie(d)):(l(d)?t._d=d:a(m)?function(t){var e,n,r,i,a;if(0===t._f.length)return p(t).invalidFormat=!0,t._d=new Date(NaN);for(i=0;i<t._f.length;i++)a=0,e=b({},t),null!=t._useUTC&&(e._useUTC=t._useUTC),e._f=t._f[i],me(e),g(e)&&(a+=p(e).charsLeftOver,a+=10*p(e).unusedTokens.length,p(e).score=a,(null==r||a<r)&&(r=a,n=e));f(t,n||e);}(t):m?me(t):s(n=(e=t)._i)?e._d=new Date(i.now()):l(n)?e._d=new Date(n.valueOf()):"string"==typeof n?(r=e,null===(h=fe.exec(r._i))?(de(r),!1===r._isValid&&(delete r._isValid,ye(r),!1===r._isValid&&(delete r._isValid,i.createFromInputFallback(r)))):r._d=new Date(+h[1])):a(n)?(e._a=u(n.slice(0),(function(t){return parseInt(t,10)})),oe(e)):o(n)?function(t){if(!t._d){var e=F(t._i);t._a=u([e.year,e.month,e.day||e.date,e.hour,e.minute,e.second,e.millisecond],(function(t){return t&&parseInt(t,10)})),oe(t);}}(e):c(n)?e._d=new Date(n):i.createFromInputFallback(e),g(t)||(t._d=null),t))}function ve(t,e,n,r,i){var s,c={};return !0!==n&&!1!==n||(r=n,n=void 0),(o(t)&&function(t){if(Object.getOwnPropertyNames)return 0===Object.getOwnPropertyNames(t).length;var e;for(e in t)if(t.hasOwnProperty(e))return !1;return !0}(t)||a(t)&&0===t.length)&&(t=void 0),c._isAMomentObject=!0,c._useUTC=c._isUTC=i,c._l=n,c._i=t,c._f=e,c._strict=r,(s=new _(ie(be(c))))._nextDay&&(s.add(1,"d"),s._nextDay=void 0),s}function _e(t,e,n,r){return ve(t,e,n,r,!1)}i.createFromInputFallback=C("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",(function(t){t._d=new Date(t._i+(t._useUTC?" UTC":""));})),i.ISO_8601=function(){},i.RFC_2822=function(){};var xe=C("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",(function(){var t=_e.apply(null,arguments);return this.isValid()&&t.isValid()?t<this?this:t:y()})),ke=C("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",(function(){var t=_e.apply(null,arguments);return this.isValid()&&t.isValid()?this<t?this:t:y()}));function we(t,e){var n,r;if(1===e.length&&a(e[0])&&(e=e[0]),!e.length)return _e();for(n=e[0],r=1;r<e.length;++r)e[r].isValid()&&!e[r][t](n)||(n=e[r]);return n}var Te=["year","quarter","month","week","day","hour","minute","second","millisecond"];function Ee(t){var e=F(t),n=e.year||0,r=e.quarter||0,i=e.month||0,a=e.week||e.isoWeek||0,o=e.day||0,s=e.hour||0,c=e.minute||0,l=e.second||0,u=e.millisecond||0;this._isValid=function(t){for(var e in t)if(-1===bt.call(Te,e)||null!=t[e]&&isNaN(t[e]))return !1;for(var n=!1,r=0;r<Te.length;++r)if(t[Te[r]]){if(n)return !1;parseFloat(t[Te[r]])!==w(t[Te[r]])&&(n=!0);}return !0}(e),this._milliseconds=+u+1e3*l+6e4*c+1e3*s*60*60,this._days=+o+7*a,this._months=+i+3*r+12*n,this._data={},this._locale=re(),this._bubble();}function Ce(t){return t instanceof Ee}function Se(t){return t<0?-1*Math.round(-1*t):Math.round(t)}function Ae(t,e){W(t,0,0,(function(){var t=this.utcOffset(),n="+";return t<0&&(t=-t,n="-"),n+j(~~(t/60),2)+e+j(~~t%60,2)}));}Ae("Z",":"),Ae("ZZ",""),ut("Z",st),ut("ZZ",st),pt(["Z","ZZ"],(function(t,e,n){n._useUTC=!0,n._tzm=Ne(st,t);}));var Me=/([\+\-]|\d\d)/gi;function Ne(t,e){var n=(e||"").match(t);if(null===n)return null;var r=((n[n.length-1]||[])+"").match(Me)||["-",0,0],i=60*r[1]+w(r[2]);return 0===i?0:"+"===r[0]?i:-i}function Oe(t,e){var n,r;return e._isUTC?(n=e.clone(),r=(x(t)||l(t)?t.valueOf():_e(t).valueOf())-n.valueOf(),n._d.setTime(n._d.valueOf()+r),i.updateOffset(n,!1),n):_e(t).local()}function De(t){return 15*-Math.round(t._d.getTimezoneOffset()/15)}function Be(){return !!this.isValid()&&this._isUTC&&0===this._offset}i.updateOffset=function(){};var Le=/^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/,Ie=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function Fe(t,e){var n,r,i,a=t,o=null;return Ce(t)?a={ms:t._milliseconds,d:t._days,M:t._months}:c(t)?(a={},e?a[e]=t:a.milliseconds=t):(o=Le.exec(t))?(n="-"===o[1]?-1:1,a={y:0,d:w(o[2])*n,h:w(o[3])*n,m:w(o[4])*n,s:w(o[5])*n,ms:w(Se(1e3*o[6]))*n}):(o=Ie.exec(t))?(n="-"===o[1]?-1:1,a={y:Re(o[2],n),M:Re(o[3],n),w:Re(o[4],n),d:Re(o[5],n),h:Re(o[6],n),m:Re(o[7],n),s:Re(o[8],n)}):null==a?a={}:"object"==typeof a&&("from"in a||"to"in a)&&(i=function(t,e){var n;return t.isValid()&&e.isValid()?(e=Oe(e,t),t.isBefore(e)?n=Pe(t,e):((n=Pe(e,t)).milliseconds=-n.milliseconds,n.months=-n.months),n):{milliseconds:0,months:0}}(_e(a.from),_e(a.to)),(a={}).ms=i.milliseconds,a.M=i.months),r=new Ee(a),Ce(t)&&h(t,"_locale")&&(r._locale=t._locale),r}function Re(t,e){var n=t&&parseFloat(t.replace(",","."));return (isNaN(n)?0:n)*e}function Pe(t,e){var n={};return n.months=e.month()-t.month()+12*(e.year()-t.year()),t.clone().add(n.months,"M").isAfter(e)&&--n.months,n.milliseconds=+e-+t.clone().add(n.months,"M"),n}function je(t,e){return function(n,r){var i;return null===r||isNaN(+r)||(M(e,"moment()."+e+"(period, number) is deprecated. Please use moment()."+e+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),i=n,n=r,r=i),ze(this,Fe(n="string"==typeof n?+n:n,r),t),this}}function ze(t,e,n,r){var a=e._milliseconds,o=Se(e._days),s=Se(e._months);t.isValid()&&(r=null==r||r,s&&St(t,xt(t,"Month")+s*n),o&&kt(t,"Date",xt(t,"Date")+o*n),a&&t._d.setTime(t._d.valueOf()+a*n),r&&i.updateOffset(t,o||s));}Fe.fn=Ee.prototype,Fe.invalid=function(){return Fe(NaN)};var Ye=je(1,"add"),Ue=je(-1,"subtract");function $e(t,e){var n=12*(e.year()-t.year())+(e.month()-t.month()),r=t.clone().add(n,"months");return -(n+(e-r<0?(e-r)/(r-t.clone().add(n-1,"months")):(e-r)/(t.clone().add(n+1,"months")-r)))||0}function We(t){var e;return void 0===t?this._locale._abbr:(null!=(e=re(t))&&(this._locale=e),this)}i.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",i.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";var qe=C("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",(function(t){return void 0===t?this.localeData():this.locale(t)}));function He(){return this._locale}var Ve=126227808e5;function Ge(t,e){return (t%e+e)%e}function Xe(t,e,n){return t<100&&0<=t?new Date(t+400,e,n)-Ve:new Date(t,e,n).valueOf()}function Ze(t,e,n){return t<100&&0<=t?Date.UTC(t+400,e,n)-Ve:Date.UTC(t,e,n)}function Qe(t,e){W(0,[t,t.length],0,e);}function Ke(t,e,n,r,i){var a;return null==t?It(this,r,i).year:((a=Ft(t,r,i))<e&&(e=a),function(t,e,n,r,i){var a=Lt(t,e,n,r,i),o=Dt(a.year,0,a.dayOfYear);return this.year(o.getUTCFullYear()),this.month(o.getUTCMonth()),this.date(o.getUTCDate()),this}.call(this,t,e,n,r,i))}W(0,["gg",2],0,(function(){return this.weekYear()%100})),W(0,["GG",2],0,(function(){return this.isoWeekYear()%100})),Qe("gggg","weekYear"),Qe("ggggg","weekYear"),Qe("GGGG","isoWeekYear"),Qe("GGGGG","isoWeekYear"),L("weekYear","gg"),L("isoWeekYear","GG"),P("weekYear",1),P("isoWeekYear",1),ut("G",at),ut("g",at),ut("GG",K,G),ut("gg",K,G),ut("GGGG",nt,Z),ut("gggg",nt,Z),ut("GGGGG",rt,Q),ut("ggggg",rt,Q),gt(["gggg","ggggg","GGGG","GGGGG"],(function(t,e,n,r){e[r.substr(0,2)]=w(t);})),gt(["gg","GG"],(function(t,e,n,r){e[r]=i.parseTwoDigitYear(t);})),W("Q",0,"Qo","quarter"),L("quarter","Q"),P("quarter",7),ut("Q",V),pt("Q",(function(t,e){e[1]=3*(w(t)-1);})),W("D",["DD",2],"Do","date"),L("date","D"),P("date",9),ut("D",K),ut("DD",K,G),ut("Do",(function(t,e){return t?e._dayOfMonthOrdinalParse||e._ordinalParse:e._dayOfMonthOrdinalParseLenient})),pt(["D","DD"],2),pt("Do",(function(t,e){e[2]=w(t.match(K)[0]);}));var Je=_t("Date",!0);W("DDD",["DDDD",3],"DDDo","dayOfYear"),L("dayOfYear","DDD"),P("dayOfYear",4),ut("DDD",et),ut("DDDD",X),pt(["DDD","DDDD"],(function(t,e,n){n._dayOfYear=w(t);})),W("m",["mm",2],0,"minute"),L("minute","m"),P("minute",14),ut("m",K),ut("mm",K,G),pt(["m","mm"],4);var tn=_t("Minutes",!1);W("s",["ss",2],0,"second"),L("second","s"),P("second",15),ut("s",K),ut("ss",K,G),pt(["s","ss"],5);var en,nn=_t("Seconds",!1);for(W("S",0,0,(function(){return ~~(this.millisecond()/100)})),W(0,["SS",2],0,(function(){return ~~(this.millisecond()/10)})),W(0,["SSS",3],0,"millisecond"),W(0,["SSSS",4],0,(function(){return 10*this.millisecond()})),W(0,["SSSSS",5],0,(function(){return 100*this.millisecond()})),W(0,["SSSSSS",6],0,(function(){return 1e3*this.millisecond()})),W(0,["SSSSSSS",7],0,(function(){return 1e4*this.millisecond()})),W(0,["SSSSSSSS",8],0,(function(){return 1e5*this.millisecond()})),W(0,["SSSSSSSSS",9],0,(function(){return 1e6*this.millisecond()})),L("millisecond","ms"),P("millisecond",16),ut("S",et,V),ut("SS",et,G),ut("SSS",et,X),en="SSSS";en.length<=9;en+="S")ut(en,it);function rn(t,e){e[6]=w(1e3*("0."+t));}for(en="S";en.length<=9;en+="S")pt(en,rn);var an=_t("Milliseconds",!1);W("z",0,0,"zoneAbbr"),W("zz",0,0,"zoneName");var on=_.prototype;function sn(t){return t}on.add=Ye,on.calendar=function(t,e){var n=t||_e(),r=Oe(n,this).startOf("day"),a=i.calendarFormat(this,r)||"sameElse",o=e&&(N(e[a])?e[a].call(this,n):e[a]);return this.format(o||this.localeData().calendar(a,this,_e(n)))},on.clone=function(){return new _(this)},on.diff=function(t,e,n){var r,i,a;if(!this.isValid())return NaN;if(!(r=Oe(t,this)).isValid())return NaN;switch(i=6e4*(r.utcOffset()-this.utcOffset()),e=I(e)){case"year":a=$e(this,r)/12;break;case"month":a=$e(this,r);break;case"quarter":a=$e(this,r)/3;break;case"second":a=(this-r)/1e3;break;case"minute":a=(this-r)/6e4;break;case"hour":a=(this-r)/36e5;break;case"day":a=(this-r-i)/864e5;break;case"week":a=(this-r-i)/6048e5;break;default:a=this-r;}return n?a:k(a)},on.endOf=function(t){var e;if(void 0===(t=I(t))||"millisecond"===t||!this.isValid())return this;var n=this._isUTC?Ze:Xe;switch(t){case"year":e=n(this.year()+1,0,1)-1;break;case"quarter":e=n(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":e=n(this.year(),this.month()+1,1)-1;break;case"week":e=n(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":e=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":e=n(this.year(),this.month(),this.date()+1)-1;break;case"hour":e=this._d.valueOf(),e+=36e5-Ge(e+(this._isUTC?0:6e4*this.utcOffset()),36e5)-1;break;case"minute":e=this._d.valueOf(),e+=6e4-Ge(e,6e4)-1;break;case"second":e=this._d.valueOf(),e+=1e3-Ge(e,1e3)-1;}return this._d.setTime(e),i.updateOffset(this,!0),this},on.format=function(t){t||(t=this.isUtc()?i.defaultFormatUtc:i.defaultFormat);var e=q(this,t);return this.localeData().postformat(e)},on.from=function(t,e){return this.isValid()&&(x(t)&&t.isValid()||_e(t).isValid())?Fe({to:this,from:t}).locale(this.locale()).humanize(!e):this.localeData().invalidDate()},on.fromNow=function(t){return this.from(_e(),t)},on.to=function(t,e){return this.isValid()&&(x(t)&&t.isValid()||_e(t).isValid())?Fe({from:this,to:t}).locale(this.locale()).humanize(!e):this.localeData().invalidDate()},on.toNow=function(t){return this.to(_e(),t)},on.get=function(t){return N(this[t=I(t)])?this[t]():this},on.invalidAt=function(){return p(this).overflow},on.isAfter=function(t,e){var n=x(t)?t:_e(t);return !(!this.isValid()||!n.isValid())&&("millisecond"===(e=I(e)||"millisecond")?this.valueOf()>n.valueOf():n.valueOf()<this.clone().startOf(e).valueOf())},on.isBefore=function(t,e){var n=x(t)?t:_e(t);return !(!this.isValid()||!n.isValid())&&("millisecond"===(e=I(e)||"millisecond")?this.valueOf()<n.valueOf():this.clone().endOf(e).valueOf()<n.valueOf())},on.isBetween=function(t,e,n,r){var i=x(t)?t:_e(t),a=x(e)?e:_e(e);return !!(this.isValid()&&i.isValid()&&a.isValid())&&("("===(r=r||"()")[0]?this.isAfter(i,n):!this.isBefore(i,n))&&(")"===r[1]?this.isBefore(a,n):!this.isAfter(a,n))},on.isSame=function(t,e){var n,r=x(t)?t:_e(t);return !(!this.isValid()||!r.isValid())&&("millisecond"===(e=I(e)||"millisecond")?this.valueOf()===r.valueOf():(n=r.valueOf(),this.clone().startOf(e).valueOf()<=n&&n<=this.clone().endOf(e).valueOf()))},on.isSameOrAfter=function(t,e){return this.isSame(t,e)||this.isAfter(t,e)},on.isSameOrBefore=function(t,e){return this.isSame(t,e)||this.isBefore(t,e)},on.isValid=function(){return g(this)},on.lang=qe,on.locale=We,on.localeData=He,on.max=ke,on.min=xe,on.parsingFlags=function(){return f({},p(this))},on.set=function(t,e){if("object"==typeof t)for(var n=function(t){var e=[];for(var n in t)e.push({unit:n,priority:R[n]});return e.sort((function(t,e){return t.priority-e.priority})),e}(t=F(t)),r=0;r<n.length;r++)this[n[r].unit](t[n[r].unit]);else if(N(this[t=I(t)]))return this[t](e);return this},on.startOf=function(t){var e;if(void 0===(t=I(t))||"millisecond"===t||!this.isValid())return this;var n=this._isUTC?Ze:Xe;switch(t){case"year":e=n(this.year(),0,1);break;case"quarter":e=n(this.year(),this.month()-this.month()%3,1);break;case"month":e=n(this.year(),this.month(),1);break;case"week":e=n(this.year(),this.month(),this.date()-this.weekday());break;case"isoWeek":e=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case"day":case"date":e=n(this.year(),this.month(),this.date());break;case"hour":e=this._d.valueOf(),e-=Ge(e+(this._isUTC?0:6e4*this.utcOffset()),36e5);break;case"minute":e=this._d.valueOf(),e-=Ge(e,6e4);break;case"second":e=this._d.valueOf(),e-=Ge(e,1e3);}return this._d.setTime(e),i.updateOffset(this,!0),this},on.subtract=Ue,on.toArray=function(){var t=this;return [t.year(),t.month(),t.date(),t.hour(),t.minute(),t.second(),t.millisecond()]},on.toObject=function(){var t=this;return {years:t.year(),months:t.month(),date:t.date(),hours:t.hours(),minutes:t.minutes(),seconds:t.seconds(),milliseconds:t.milliseconds()}},on.toDate=function(){return new Date(this.valueOf())},on.toISOString=function(t){if(!this.isValid())return null;var e=!0!==t,n=e?this.clone().utc():this;return n.year()<0||9999<n.year()?q(n,e?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):N(Date.prototype.toISOString)?e?this.toDate().toISOString():new Date(this.valueOf()+60*this.utcOffset()*1e3).toISOString().replace("Z",q(n,"Z")):q(n,e?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")},on.inspect=function(){if(!this.isValid())return "moment.invalid(/* "+this._i+" */)";var t="moment",e="";this.isLocal()||(t=0===this.utcOffset()?"moment.utc":"moment.parseZone",e="Z");var n="["+t+'("]',r=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",i=e+'[")]';return this.format(n+r+"-MM-DD[T]HH:mm:ss.SSS"+i)},on.toJSON=function(){return this.isValid()?this.toISOString():null},on.toString=function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},on.unix=function(){return Math.floor(this.valueOf()/1e3)},on.valueOf=function(){return this._d.valueOf()-6e4*(this._offset||0)},on.creationData=function(){return {input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}},on.year=vt,on.isLeapYear=function(){return mt(this.year())},on.weekYear=function(t){return Ke.call(this,t,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy)},on.isoWeekYear=function(t){return Ke.call(this,t,this.isoWeek(),this.isoWeekday(),1,4)},on.quarter=on.quarters=function(t){return null==t?Math.ceil((this.month()+1)/3):this.month(3*(t-1)+this.month()%3)},on.month=At,on.daysInMonth=function(){return wt(this.year(),this.month())},on.week=on.weeks=function(t){var e=this.localeData().week(this);return null==t?e:this.add(7*(t-e),"d")},on.isoWeek=on.isoWeeks=function(t){var e=It(this,1,4).week;return null==t?e:this.add(7*(t-e),"d")},on.weeksInYear=function(){var t=this.localeData()._week;return Ft(this.year(),t.dow,t.doy)},on.isoWeeksInYear=function(){return Ft(this.year(),1,4)},on.date=Je,on.day=on.days=function(t){if(!this.isValid())return null!=t?this:NaN;var e,n,r=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=t?(e=t,n=this.localeData(),t="string"!=typeof e?e:isNaN(e)?"number"==typeof(e=n.weekdaysParse(e))?e:null:parseInt(e,10),this.add(t-r,"d")):r},on.weekday=function(t){if(!this.isValid())return null!=t?this:NaN;var e=(this.day()+7-this.localeData()._week.dow)%7;return null==t?e:this.add(t-e,"d")},on.isoWeekday=function(t){if(!this.isValid())return null!=t?this:NaN;if(null==t)return this.day()||7;var e,n,r=(e=t,n=this.localeData(),"string"==typeof e?n.weekdaysParse(e)%7||7:isNaN(e)?null:e);return this.day(this.day()%7?r:r-7)},on.dayOfYear=function(t){var e=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==t?e:this.add(t-e,"d")},on.hour=on.hours=Xt,on.minute=on.minutes=tn,on.second=on.seconds=nn,on.millisecond=on.milliseconds=an,on.utcOffset=function(t,e,n){var r,a=this._offset||0;if(!this.isValid())return null!=t?this:NaN;if(null==t)return this._isUTC?a:De(this);if("string"==typeof t){if(null===(t=Ne(st,t)))return this}else Math.abs(t)<16&&!n&&(t*=60);return !this._isUTC&&e&&(r=De(this)),this._offset=t,this._isUTC=!0,null!=r&&this.add(r,"m"),a!==t&&(!e||this._changeInProgress?ze(this,Fe(t-a,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,i.updateOffset(this,!0),this._changeInProgress=null)),this},on.utc=function(t){return this.utcOffset(0,t)},on.local=function(t){return this._isUTC&&(this.utcOffset(0,t),this._isUTC=!1,t&&this.subtract(De(this),"m")),this},on.parseZone=function(){if(null!=this._tzm)this.utcOffset(this._tzm,!1,!0);else if("string"==typeof this._i){var t=Ne(ot,this._i);null!=t?this.utcOffset(t):this.utcOffset(0,!0);}return this},on.hasAlignedHourOffset=function(t){return !!this.isValid()&&(t=t?_e(t).utcOffset():0,(this.utcOffset()-t)%60==0)},on.isDST=function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},on.isLocal=function(){return !!this.isValid()&&!this._isUTC},on.isUtcOffset=function(){return !!this.isValid()&&this._isUTC},on.isUtc=Be,on.isUTC=Be,on.zoneAbbr=function(){return this._isUTC?"UTC":""},on.zoneName=function(){return this._isUTC?"Coordinated Universal Time":""},on.dates=C("dates accessor is deprecated. Use date instead.",Je),on.months=C("months accessor is deprecated. Use month instead",At),on.years=C("years accessor is deprecated. Use year instead",vt),on.zone=C("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",(function(t,e){return null!=t?("string"!=typeof t&&(t=-t),this.utcOffset(t,e),this):-this.utcOffset()})),on.isDSTShifted=C("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",(function(){if(!s(this._isDSTShifted))return this._isDSTShifted;var t={};if(b(t,this),(t=be(t))._a){var e=t._isUTC?d(t._a):_e(t._a);this._isDSTShifted=this.isValid()&&0<T(t._a,e.toArray());}else this._isDSTShifted=!1;return this._isDSTShifted}));var cn=D.prototype;function ln(t,e,n,r){var i=re(),a=d().set(r,e);return i[n](a,t)}function un(t,e,n){if(c(t)&&(e=t,t=void 0),t=t||"",null!=e)return ln(t,e,n,"month");var r,i=[];for(r=0;r<12;r++)i[r]=ln(t,r,n,"month");return i}function hn(t,e,n,r){"boolean"==typeof t?c(e)&&(n=e,e=void 0):(e=t,t=!1,c(n=e)&&(n=e,e=void 0)),e=e||"";var i,a=re(),o=t?a._week.dow:0;if(null!=n)return ln(e,(n+o)%7,r,"day");var s=[];for(i=0;i<7;i++)s[i]=ln(e,(i+o)%7,r,"day");return s}cn.calendar=function(t,e,n){var r=this._calendar[t]||this._calendar.sameElse;return N(r)?r.call(e,n):r},cn.longDateFormat=function(t){var e=this._longDateFormat[t],n=this._longDateFormat[t.toUpperCase()];return e||!n?e:(this._longDateFormat[t]=n.replace(/MMMM|MM|DD|dddd/g,(function(t){return t.slice(1)})),this._longDateFormat[t])},cn.invalidDate=function(){return this._invalidDate},cn.ordinal=function(t){return this._ordinal.replace("%d",t)},cn.preparse=sn,cn.postformat=sn,cn.relativeTime=function(t,e,n,r){var i=this._relativeTime[n];return N(i)?i(t,e,n,r):i.replace(/%d/i,t)},cn.pastFuture=function(t,e){var n=this._relativeTime[0<t?"future":"past"];return N(n)?n(e):n.replace(/%s/i,e)},cn.set=function(t){var e,n;for(n in t)N(e=t[n])?this[n]=e:this["_"+n]=e;this._config=t,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source);},cn.months=function(t,e){return t?a(this._months)?this._months[t.month()]:this._months[(this._months.isFormat||Tt).test(e)?"format":"standalone"][t.month()]:a(this._months)?this._months:this._months.standalone},cn.monthsShort=function(t,e){return t?a(this._monthsShort)?this._monthsShort[t.month()]:this._monthsShort[Tt.test(e)?"format":"standalone"][t.month()]:a(this._monthsShort)?this._monthsShort:this._monthsShort.standalone},cn.monthsParse=function(t,e,n){var r,i,a;if(this._monthsParseExact)return function(t,e,n){var r,i,a,o=t.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],r=0;r<12;++r)a=d([2e3,r]),this._shortMonthsParse[r]=this.monthsShort(a,"").toLocaleLowerCase(),this._longMonthsParse[r]=this.months(a,"").toLocaleLowerCase();return n?"MMM"===e?-1!==(i=bt.call(this._shortMonthsParse,o))?i:null:-1!==(i=bt.call(this._longMonthsParse,o))?i:null:"MMM"===e?-1!==(i=bt.call(this._shortMonthsParse,o))||-1!==(i=bt.call(this._longMonthsParse,o))?i:null:-1!==(i=bt.call(this._longMonthsParse,o))||-1!==(i=bt.call(this._shortMonthsParse,o))?i:null}.call(this,t,e,n);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),r=0;r<12;r++){if(i=d([2e3,r]),n&&!this._longMonthsParse[r]&&(this._longMonthsParse[r]=new RegExp("^"+this.months(i,"").replace(".","")+"$","i"),this._shortMonthsParse[r]=new RegExp("^"+this.monthsShort(i,"").replace(".","")+"$","i")),n||this._monthsParse[r]||(a="^"+this.months(i,"")+"|^"+this.monthsShort(i,""),this._monthsParse[r]=new RegExp(a.replace(".",""),"i")),n&&"MMMM"===e&&this._longMonthsParse[r].test(t))return r;if(n&&"MMM"===e&&this._shortMonthsParse[r].test(t))return r;if(!n&&this._monthsParse[r].test(t))return r}},cn.monthsRegex=function(t){return this._monthsParseExact?(h(this,"_monthsRegex")||Ot.call(this),t?this._monthsStrictRegex:this._monthsRegex):(h(this,"_monthsRegex")||(this._monthsRegex=Nt),this._monthsStrictRegex&&t?this._monthsStrictRegex:this._monthsRegex)},cn.monthsShortRegex=function(t){return this._monthsParseExact?(h(this,"_monthsRegex")||Ot.call(this),t?this._monthsShortStrictRegex:this._monthsShortRegex):(h(this,"_monthsShortRegex")||(this._monthsShortRegex=Mt),this._monthsShortStrictRegex&&t?this._monthsShortStrictRegex:this._monthsShortRegex)},cn.week=function(t){return It(t,this._week.dow,this._week.doy).week},cn.firstDayOfYear=function(){return this._week.doy},cn.firstDayOfWeek=function(){return this._week.dow},cn.weekdays=function(t,e){var n=a(this._weekdays)?this._weekdays:this._weekdays[t&&!0!==t&&this._weekdays.isFormat.test(e)?"format":"standalone"];return !0===t?Rt(n,this._week.dow):t?n[t.day()]:n},cn.weekdaysMin=function(t){return !0===t?Rt(this._weekdaysMin,this._week.dow):t?this._weekdaysMin[t.day()]:this._weekdaysMin},cn.weekdaysShort=function(t){return !0===t?Rt(this._weekdaysShort,this._week.dow):t?this._weekdaysShort[t.day()]:this._weekdaysShort},cn.weekdaysParse=function(t,e,n){var r,i,a;if(this._weekdaysParseExact)return function(t,e,n){var r,i,a,o=t.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],r=0;r<7;++r)a=d([2e3,1]).day(r),this._minWeekdaysParse[r]=this.weekdaysMin(a,"").toLocaleLowerCase(),this._shortWeekdaysParse[r]=this.weekdaysShort(a,"").toLocaleLowerCase(),this._weekdaysParse[r]=this.weekdays(a,"").toLocaleLowerCase();return n?"dddd"===e?-1!==(i=bt.call(this._weekdaysParse,o))?i:null:"ddd"===e?-1!==(i=bt.call(this._shortWeekdaysParse,o))?i:null:-1!==(i=bt.call(this._minWeekdaysParse,o))?i:null:"dddd"===e?-1!==(i=bt.call(this._weekdaysParse,o))||-1!==(i=bt.call(this._shortWeekdaysParse,o))||-1!==(i=bt.call(this._minWeekdaysParse,o))?i:null:"ddd"===e?-1!==(i=bt.call(this._shortWeekdaysParse,o))||-1!==(i=bt.call(this._weekdaysParse,o))||-1!==(i=bt.call(this._minWeekdaysParse,o))?i:null:-1!==(i=bt.call(this._minWeekdaysParse,o))||-1!==(i=bt.call(this._weekdaysParse,o))||-1!==(i=bt.call(this._shortWeekdaysParse,o))?i:null}.call(this,t,e,n);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),r=0;r<7;r++){if(i=d([2e3,1]).day(r),n&&!this._fullWeekdaysParse[r]&&(this._fullWeekdaysParse[r]=new RegExp("^"+this.weekdays(i,"").replace(".","\\.?")+"$","i"),this._shortWeekdaysParse[r]=new RegExp("^"+this.weekdaysShort(i,"").replace(".","\\.?")+"$","i"),this._minWeekdaysParse[r]=new RegExp("^"+this.weekdaysMin(i,"").replace(".","\\.?")+"$","i")),this._weekdaysParse[r]||(a="^"+this.weekdays(i,"")+"|^"+this.weekdaysShort(i,"")+"|^"+this.weekdaysMin(i,""),this._weekdaysParse[r]=new RegExp(a.replace(".",""),"i")),n&&"dddd"===e&&this._fullWeekdaysParse[r].test(t))return r;if(n&&"ddd"===e&&this._shortWeekdaysParse[r].test(t))return r;if(n&&"dd"===e&&this._minWeekdaysParse[r].test(t))return r;if(!n&&this._weekdaysParse[r].test(t))return r}},cn.weekdaysRegex=function(t){return this._weekdaysParseExact?(h(this,"_weekdaysRegex")||Wt.call(this),t?this._weekdaysStrictRegex:this._weekdaysRegex):(h(this,"_weekdaysRegex")||(this._weekdaysRegex=Yt),this._weekdaysStrictRegex&&t?this._weekdaysStrictRegex:this._weekdaysRegex)},cn.weekdaysShortRegex=function(t){return this._weekdaysParseExact?(h(this,"_weekdaysRegex")||Wt.call(this),t?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(h(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=Ut),this._weekdaysShortStrictRegex&&t?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)},cn.weekdaysMinRegex=function(t){return this._weekdaysParseExact?(h(this,"_weekdaysRegex")||Wt.call(this),t?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(h(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=$t),this._weekdaysMinStrictRegex&&t?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)},cn.isPM=function(t){return "p"===(t+"").toLowerCase().charAt(0)},cn.meridiem=function(t,e,n){return 11<t?n?"pm":"PM":n?"am":"AM"},ee("en",{dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(t){var e=t%10;return t+(1===w(t%100/10)?"th":1===e?"st":2===e?"nd":3===e?"rd":"th")}}),i.lang=C("moment.lang is deprecated. Use moment.locale instead.",ee),i.langData=C("moment.langData is deprecated. Use moment.localeData instead.",re);var fn=Math.abs;function dn(t,e,n,r){var i=Fe(e,n);return t._milliseconds+=r*i._milliseconds,t._days+=r*i._days,t._months+=r*i._months,t._bubble()}function pn(t){return t<0?Math.floor(t):Math.ceil(t)}function gn(t){return 4800*t/146097}function yn(t){return 146097*t/4800}function mn(t){return function(){return this.as(t)}}var bn=mn("ms"),vn=mn("s"),_n=mn("m"),xn=mn("h"),kn=mn("d"),wn=mn("w"),Tn=mn("M"),En=mn("Q"),Cn=mn("y");function Sn(t){return function(){return this.isValid()?this._data[t]:NaN}}var An=Sn("milliseconds"),Mn=Sn("seconds"),Nn=Sn("minutes"),On=Sn("hours"),Dn=Sn("days"),Bn=Sn("months"),Ln=Sn("years"),In=Math.round,Fn={ss:44,s:45,m:45,h:22,d:26,M:11},Rn=Math.abs;function Pn(t){return (0<t)-(t<0)||+t}function jn(){if(!this.isValid())return this.localeData().invalidDate();var t,e,n=Rn(this._milliseconds)/1e3,r=Rn(this._days),i=Rn(this._months);e=k((t=k(n/60))/60),n%=60,t%=60;var a=k(i/12),o=i%=12,s=r,c=e,l=t,u=n?n.toFixed(3).replace(/\.?0+$/,""):"",h=this.asSeconds();if(!h)return "P0D";var f=h<0?"-":"",d=Pn(this._months)!==Pn(h)?"-":"",p=Pn(this._days)!==Pn(h)?"-":"",g=Pn(this._milliseconds)!==Pn(h)?"-":"";return f+"P"+(a?d+a+"Y":"")+(o?d+o+"M":"")+(s?p+s+"D":"")+(c||l||u?"T":"")+(c?g+c+"H":"")+(l?g+l+"M":"")+(u?g+u+"S":"")}var zn=Ee.prototype;return zn.isValid=function(){return this._isValid},zn.abs=function(){var t=this._data;return this._milliseconds=fn(this._milliseconds),this._days=fn(this._days),this._months=fn(this._months),t.milliseconds=fn(t.milliseconds),t.seconds=fn(t.seconds),t.minutes=fn(t.minutes),t.hours=fn(t.hours),t.months=fn(t.months),t.years=fn(t.years),this},zn.add=function(t,e){return dn(this,t,e,1)},zn.subtract=function(t,e){return dn(this,t,e,-1)},zn.as=function(t){if(!this.isValid())return NaN;var e,n,r=this._milliseconds;if("month"===(t=I(t))||"quarter"===t||"year"===t)switch(e=this._days+r/864e5,n=this._months+gn(e),t){case"month":return n;case"quarter":return n/3;case"year":return n/12}else switch(e=this._days+Math.round(yn(this._months)),t){case"week":return e/7+r/6048e5;case"day":return e+r/864e5;case"hour":return 24*e+r/36e5;case"minute":return 1440*e+r/6e4;case"second":return 86400*e+r/1e3;case"millisecond":return Math.floor(864e5*e)+r;default:throw new Error("Unknown unit "+t)}},zn.asMilliseconds=bn,zn.asSeconds=vn,zn.asMinutes=_n,zn.asHours=xn,zn.asDays=kn,zn.asWeeks=wn,zn.asMonths=Tn,zn.asQuarters=En,zn.asYears=Cn,zn.valueOf=function(){return this.isValid()?this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*w(this._months/12):NaN},zn._bubble=function(){var t,e,n,r,i,a=this._milliseconds,o=this._days,s=this._months,c=this._data;return 0<=a&&0<=o&&0<=s||a<=0&&o<=0&&s<=0||(a+=864e5*pn(yn(s)+o),s=o=0),c.milliseconds=a%1e3,t=k(a/1e3),c.seconds=t%60,e=k(t/60),c.minutes=e%60,n=k(e/60),c.hours=n%24,s+=i=k(gn(o+=k(n/24))),o-=pn(yn(i)),r=k(s/12),s%=12,c.days=o,c.months=s,c.years=r,this},zn.clone=function(){return Fe(this)},zn.get=function(t){return t=I(t),this.isValid()?this[t+"s"]():NaN},zn.milliseconds=An,zn.seconds=Mn,zn.minutes=Nn,zn.hours=On,zn.days=Dn,zn.weeks=function(){return k(this.days()/7)},zn.months=Bn,zn.years=Ln,zn.humanize=function(t){if(!this.isValid())return this.localeData().invalidDate();var e,n,r,i,a,o,s,c,l,u,h=this.localeData(),f=(e=!t,n=h,r=Fe(this).abs(),i=In(r.as("s")),a=In(r.as("m")),o=In(r.as("h")),s=In(r.as("d")),c=In(r.as("M")),l=In(r.as("y")),(u=i<=Fn.ss&&["s",i]||i<Fn.s&&["ss",i]||a<=1&&["m"]||a<Fn.m&&["mm",a]||o<=1&&["h"]||o<Fn.h&&["hh",o]||s<=1&&["d"]||s<Fn.d&&["dd",s]||c<=1&&["M"]||c<Fn.M&&["MM",c]||l<=1&&["y"]||["yy",l])[2]=e,u[3]=0<+this,u[4]=n,function(t,e,n,r,i){return i.relativeTime(e||1,!!n,t,r)}.apply(null,u));return t&&(f=h.pastFuture(+this,f)),h.postformat(f)},zn.toISOString=jn,zn.toString=jn,zn.toJSON=jn,zn.locale=We,zn.localeData=He,zn.toIsoString=C("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",jn),zn.lang=qe,W("X",0,0,"unix"),W("x",0,0,"valueOf"),ut("x",at),ut("X",/[+-]?\d+(\.\d{1,3})?/),pt("X",(function(t,e,n){n._d=new Date(1e3*parseFloat(t,10));})),pt("x",(function(t,e,n){n._d=new Date(w(t));})),i.version="2.24.0",e=_e,i.fn=on,i.min=function(){return we("isBefore",[].slice.call(arguments,0))},i.max=function(){return we("isAfter",[].slice.call(arguments,0))},i.now=function(){return Date.now?Date.now():+new Date},i.utc=d,i.unix=function(t){return _e(1e3*t)},i.months=function(t,e){return un(t,e,"months")},i.isDate=l,i.locale=ee,i.invalid=y,i.duration=Fe,i.isMoment=x,i.weekdays=function(t,e,n){return hn(t,e,n,"weekdays")},i.parseZone=function(){return _e.apply(null,arguments).parseZone()},i.localeData=re,i.isDuration=Ce,i.monthsShort=function(t,e){return un(t,e,"monthsShort")},i.weekdaysMin=function(t,e,n){return hn(t,e,n,"weekdaysMin")},i.defineLocale=ne,i.updateLocale=function(t,e){if(null!=e){var n,r,i=Zt;null!=(r=te(t))&&(i=r._config),(n=new D(e=O(i,e))).parentLocale=Qt[t],Qt[t]=n,ee(t);}else null!=Qt[t]&&(null!=Qt[t].parentLocale?Qt[t]=Qt[t].parentLocale:null!=Qt[t]&&delete Qt[t]);return Qt[t]},i.locales=function(){return S(Qt)},i.weekdaysShort=function(t,e,n){return hn(t,e,n,"weekdaysShort")},i.normalizeUnits=I,i.relativeTimeRounding=function(t){return void 0===t?In:"function"==typeof t&&(In=t,!0)},i.relativeTimeThreshold=function(t,e){return void 0!==Fn[t]&&(void 0===e?Fn[t]:(Fn[t]=e,"s"===t&&(Fn.ss=e-1),!0))},i.calendarFormat=function(t,e){var n=t.diff(e,"days",!0);return n<-6?"sameElse":n<-1?"lastWeek":n<0?"lastDay":n<1?"sameDay":n<2?"nextDay":n<7?"nextWeek":"sameElse"},i.prototype=on,i.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"},i}();},6470:t=>{function e(t){if("string"!=typeof t)throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}function n(t,e){for(var n,r="",i=0,a=-1,o=0,s=0;s<=t.length;++s){if(s<t.length)n=t.charCodeAt(s);else {if(47===n)break;n=47;}if(47===n){if(a===s-1||1===o);else if(a!==s-1&&2===o){if(r.length<2||2!==i||46!==r.charCodeAt(r.length-1)||46!==r.charCodeAt(r.length-2))if(r.length>2){var c=r.lastIndexOf("/");if(c!==r.length-1){-1===c?(r="",i=0):i=(r=r.slice(0,c)).length-1-r.lastIndexOf("/"),a=s,o=0;continue}}else if(2===r.length||1===r.length){r="",i=0,a=s,o=0;continue}e&&(r.length>0?r+="/..":r="..",i=2);}else r.length>0?r+="/"+t.slice(a+1,s):r=t.slice(a+1,s),i=s-a-1;a=s,o=0;}else 46===n&&-1!==o?++o:o=-1;}return r}var r={resolve:function(){for(var t,r="",i=!1,a=arguments.length-1;a>=-1&&!i;a--){var o;a>=0?o=arguments[a]:(void 0===t&&(t=process.cwd()),o=t),e(o),0!==o.length&&(r=o+"/"+r,i=47===o.charCodeAt(0));}return r=n(r,!i),i?r.length>0?"/"+r:"/":r.length>0?r:"."},normalize:function(t){if(e(t),0===t.length)return ".";var r=47===t.charCodeAt(0),i=47===t.charCodeAt(t.length-1);return 0!==(t=n(t,!r)).length||r||(t="."),t.length>0&&i&&(t+="/"),r?"/"+t:t},isAbsolute:function(t){return e(t),t.length>0&&47===t.charCodeAt(0)},join:function(){if(0===arguments.length)return ".";for(var t,n=0;n<arguments.length;++n){var i=arguments[n];e(i),i.length>0&&(void 0===t?t=i:t+="/"+i);}return void 0===t?".":r.normalize(t)},relative:function(t,n){if(e(t),e(n),t===n)return "";if((t=r.resolve(t))===(n=r.resolve(n)))return "";for(var i=1;i<t.length&&47===t.charCodeAt(i);++i);for(var a=t.length,o=a-i,s=1;s<n.length&&47===n.charCodeAt(s);++s);for(var c=n.length-s,l=o<c?o:c,u=-1,h=0;h<=l;++h){if(h===l){if(c>l){if(47===n.charCodeAt(s+h))return n.slice(s+h+1);if(0===h)return n.slice(s+h)}else o>l&&(47===t.charCodeAt(i+h)?u=h:0===h&&(u=0));break}var f=t.charCodeAt(i+h);if(f!==n.charCodeAt(s+h))break;47===f&&(u=h);}var d="";for(h=i+u+1;h<=a;++h)h!==a&&47!==t.charCodeAt(h)||(0===d.length?d+="..":d+="/..");return d.length>0?d+n.slice(s+u):(s+=u,47===n.charCodeAt(s)&&++s,n.slice(s))},_makeLong:function(t){return t},dirname:function(t){if(e(t),0===t.length)return ".";for(var n=t.charCodeAt(0),r=47===n,i=-1,a=!0,o=t.length-1;o>=1;--o)if(47===(n=t.charCodeAt(o))){if(!a){i=o;break}}else a=!1;return -1===i?r?"/":".":r&&1===i?"//":t.slice(0,i)},basename:function(t,n){if(void 0!==n&&"string"!=typeof n)throw new TypeError('"ext" argument must be a string');e(t);var r,i=0,a=-1,o=!0;if(void 0!==n&&n.length>0&&n.length<=t.length){if(n.length===t.length&&n===t)return "";var s=n.length-1,c=-1;for(r=t.length-1;r>=0;--r){var l=t.charCodeAt(r);if(47===l){if(!o){i=r+1;break}}else -1===c&&(o=!1,c=r+1),s>=0&&(l===n.charCodeAt(s)?-1==--s&&(a=r):(s=-1,a=c));}return i===a?a=c:-1===a&&(a=t.length),t.slice(i,a)}for(r=t.length-1;r>=0;--r)if(47===t.charCodeAt(r)){if(!o){i=r+1;break}}else -1===a&&(o=!1,a=r+1);return -1===a?"":t.slice(i,a)},extname:function(t){e(t);for(var n=-1,r=0,i=-1,a=!0,o=0,s=t.length-1;s>=0;--s){var c=t.charCodeAt(s);if(47!==c)-1===i&&(a=!1,i=s+1),46===c?-1===n?n=s:1!==o&&(o=1):-1!==n&&(o=-1);else if(!a){r=s+1;break}}return -1===n||-1===i||0===o||1===o&&n===i-1&&n===r+1?"":t.slice(n,i)},format:function(t){if(null===t||"object"!=typeof t)throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof t);return function(t,e){var n=e.dir||e.root,r=e.base||(e.name||"")+(e.ext||"");return n?n===e.root?n+r:n+"/"+r:r}(0,t)},parse:function(t){e(t);var n={root:"",dir:"",base:"",ext:"",name:""};if(0===t.length)return n;var r,i=t.charCodeAt(0),a=47===i;a?(n.root="/",r=1):r=0;for(var o=-1,s=0,c=-1,l=!0,u=t.length-1,h=0;u>=r;--u)if(47!==(i=t.charCodeAt(u)))-1===c&&(l=!1,c=u+1),46===i?-1===o?o=u:1!==h&&(h=1):-1!==o&&(h=-1);else if(!l){s=u+1;break}return -1===o||-1===c||0===h||1===h&&o===c-1&&o===s+1?-1!==c&&(n.base=n.name=0===s&&a?t.slice(1,c):t.slice(s,c)):(0===s&&a?(n.name=t.slice(1,o),n.base=t.slice(1,c)):(n.name=t.slice(s,o),n.base=t.slice(s,c)),n.ext=t.slice(o,c)),s>0?n.dir=t.slice(0,s-1):a&&(n.dir="/"),n},sep:"/",delimiter:":",win32:null,posix:null};r.posix=r,t.exports=r;},555:()=>{},8218:()=>{},8009:()=>{},5354:()=>{},6878:()=>{},8183:()=>{},1428:()=>{},4551:()=>{},8800:()=>{},1993:()=>{},3069:()=>{},9143:()=>{},7543:(t,e,n)=>{function r(t,e){return null==t||null==e?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function i(t){let e=t,n=t,i=t;function a(t,e,r=0,a=t.length){if(r<a){if(0!==n(e,e))return a;do{const n=r+a>>>1;i(t[n],e)<0?r=n+1:a=n;}while(r<a)}return r}return 2!==t.length&&(e=(e,n)=>t(e)-n,n=r,i=(e,n)=>r(t(e),n)),{left:a,center:function(t,n,r=0,i=t.length){const o=a(t,n,r,i-1);return o>r&&e(t[o-1],n)>-e(t[o],n)?o-1:o},right:function(t,e,r=0,a=t.length){if(r<a){if(0!==n(e,e))return a;do{const n=r+a>>>1;i(t[n],e)<=0?r=n+1:a=n;}while(r<a)}return r}}}function a(t){return null===t?NaN:+t}n.r(e),n.d(e,{Adder:()=>x,Delaunay:()=>Bs,FormatSpecifier:()=>Fl,InternMap:()=>T,InternSet:()=>E,Node:()=>ng,Voronoi:()=>Ss,ZoomTransform:()=>sE,active:()=>ta,arc:()=>Jk,area:()=>sw,areaRadial:()=>yw,ascending:()=>r,autoType:()=>lc,axisBottom:()=>ie,axisLeft:()=>ae,axisRight:()=>re,axisTop:()=>ne,bin:()=>it,bisect:()=>u,bisectCenter:()=>l,bisectLeft:()=>c,bisectRight:()=>s,bisector:()=>i,blob:()=>$c,brush:()=>Oa,brushSelection:()=>Aa,brushX:()=>Ma,brushY:()=>Na,buffer:()=>qc,chord:()=>$a,chordDirected:()=>qa,chordTranspose:()=>Wa,cluster:()=>Xp,color:()=>tr,contourDensity:()=>is,contours:()=>Ko,count:()=>h,create:()=>Ck,creator:()=>pn,cross:()=>g,csv:()=>Zc,csvFormat:()=>Zs,csvFormatBody:()=>Qs,csvFormatRow:()=>Js,csvFormatRows:()=>Ks,csvFormatValue:()=>tc,csvParse:()=>Gs,csvParseRows:()=>Xs,cubehelix:()=>Uo,cumsum:()=>y,curveBasis:()=>Xw,curveBasisClosed:()=>Qw,curveBasisOpen:()=>Jw,curveBumpX:()=>eT,curveBumpY:()=>nT,curveBundle:()=>iT,curveCardinal:()=>sT,curveCardinalClosed:()=>lT,curveCardinalOpen:()=>hT,curveCatmullRom:()=>pT,curveCatmullRomClosed:()=>yT,curveCatmullRomOpen:()=>bT,curveLinear:()=>rw,curveLinearClosed:()=>_T,curveMonotoneX:()=>AT,curveMonotoneY:()=>MT,curveNatural:()=>DT,curveStep:()=>LT,curveStepAfter:()=>FT,curveStepBefore:()=>IT,descending:()=>m,deviation:()=>v,difference:()=>zt,disjoint:()=>Yt,dispatch:()=>fe,drag:()=>zs,dragDisable:()=>Ln,dragEnable:()=>In,dsv:()=>Xc,dsvFormat:()=>Hs,easeBack:()=>Rc,easeBackIn:()=>Ic,easeBackInOut:()=>Rc,easeBackOut:()=>Fc,easeBounce:()=>Dc,easeBounceIn:()=>Oc,easeBounceInOut:()=>Bc,easeBounceOut:()=>Dc,easeCircle:()=>Mc,easeCircleIn:()=>Sc,easeCircleInOut:()=>Mc,easeCircleOut:()=>Ac,easeCubic:()=>Zi,easeCubicIn:()=>Gi,easeCubicInOut:()=>Zi,easeCubicOut:()=>Xi,easeElastic:()=>zc,easeElasticIn:()=>jc,easeElasticInOut:()=>Yc,easeElasticOut:()=>zc,easeExp:()=>Cc,easeExpIn:()=>Tc,easeExpInOut:()=>Cc,easeExpOut:()=>Ec,easeLinear:()=>hc,easePoly:()=>mc,easePolyIn:()=>gc,easePolyInOut:()=>mc,easePolyOut:()=>yc,easeQuad:()=>pc,easeQuadIn:()=>fc,easeQuadInOut:()=>pc,easeQuadOut:()=>dc,easeSin:()=>kc,easeSinIn:()=>_c,easeSinInOut:()=>kc,easeSinOut:()=>xc,every:()=>Lt,extent:()=>_,fcumsum:()=>w,filter:()=>Ft,flatGroup:()=>L,flatRollup:()=>I,forceCenter:()=>al,forceCollide:()=>bl,forceLink:()=>xl,forceManyBody:()=>Sl,forceRadial:()=>Al,forceSimulation:()=>Cl,forceX:()=>Ml,forceY:()=>Nl,format:()=>Yl,formatDefaultLocale:()=>Hl,formatLocale:()=>ql,formatPrefix:()=>Ul,formatSpecifier:()=>Il,fsum:()=>k,geoAlbers:()=>up,geoAlbersUsa:()=>hp,geoArea:()=>Zu,geoAzimuthalEqualArea:()=>gp,geoAzimuthalEqualAreaRaw:()=>pp,geoAzimuthalEquidistant:()=>mp,geoAzimuthalEquidistantRaw:()=>yp,geoBounds:()=>Oh,geoCentroid:()=>$h,geoCircle:()=>tf,geoClipAntimeridian:()=>ff,geoClipCircle:()=>df,geoClipExtent:()=>xf,geoClipRectangle:()=>_f,geoConicConformal:()=>wp,geoConicConformalRaw:()=>kp,geoConicEqualArea:()=>lp,geoConicEqualAreaRaw:()=>cp,geoConicEquidistant:()=>Sp,geoConicEquidistantRaw:()=>Cp,geoContains:()=>Pf,geoDistance:()=>Mf,geoEqualEarth:()=>Lp,geoEqualEarthRaw:()=>Bp,geoEquirectangular:()=>Ep,geoEquirectangularRaw:()=>Tp,geoGnomonic:()=>Fp,geoGnomonicRaw:()=>Ip,geoGraticule:()=>Yf,geoGraticule10:()=>Uf,geoIdentity:()=>Rp,geoInterpolate:()=>$f,geoLength:()=>Cf,geoMercator:()=>vp,geoMercatorRaw:()=>bp,geoNaturalEarth1:()=>jp,geoNaturalEarth1Raw:()=>Pp,geoOrthographic:()=>Yp,geoOrthographicRaw:()=>zp,geoPath:()=>Hd,geoProjection:()=>ap,geoProjectionMutator:()=>op,geoRotation:()=>Qh,geoStereographic:()=>$p,geoStereographicRaw:()=>Up,geoStream:()=>Cu,geoTransform:()=>Vd,geoTransverseMercator:()=>qp,geoTransverseMercatorRaw:()=>Wp,gray:()=>xo,greatest:()=>Et,greatestIndex:()=>Ct,group:()=>O,groupSort:()=>H,groups:()=>D,hcl:()=>No,hierarchy:()=>Qp,histogram:()=>it,hsl:()=>hr,html:()=>rl,image:()=>Kc,index:()=>P,indexes:()=>j,interpolate:()=>Ir,interpolateArray:()=>Sr,interpolateBasis:()=>gr,interpolateBasisClosed:()=>yr,interpolateBlues:()=>Jx,interpolateBrBG:()=>hx,interpolateBuGn:()=>Mx,interpolateBuPu:()=>Ox,interpolateCividis:()=>uk,interpolateCool:()=>dk,interpolateCubehelix:()=>hy,interpolateCubehelixDefault:()=>hk,interpolateCubehelixLong:()=>fy,interpolateDate:()=>Mr,interpolateDiscrete:()=>Kg,interpolateGnBu:()=>Bx,interpolateGreens:()=>ek,interpolateGreys:()=>rk,interpolateHcl:()=>cy,interpolateHclLong:()=>ly,interpolateHsl:()=>iy,interpolateHslLong:()=>ay,interpolateHue:()=>Jg,interpolateInferno:()=>Tk,interpolateLab:()=>oy,interpolateMagma:()=>wk,interpolateNumber:()=>Nr,interpolateNumberArray:()=>Er,interpolateObject:()=>Or,interpolateOrRd:()=>Ix,interpolateOranges:()=>lk,interpolatePRGn:()=>dx,interpolatePiYG:()=>gx,interpolatePlasma:()=>Ek,interpolatePuBu:()=>jx,interpolatePuBuGn:()=>Rx,interpolatePuOr:()=>mx,interpolatePuRd:()=>Yx,interpolatePurples:()=>ak,interpolateRainbow:()=>gk,interpolateRdBu:()=>vx,interpolateRdGy:()=>xx,interpolateRdPu:()=>$x,interpolateRdYlBu:()=>wx,interpolateRdYlGn:()=>Ex,interpolateReds:()=>sk,interpolateRgb:()=>xr,interpolateRgbBasis:()=>wr,interpolateRgbBasisClosed:()=>Tr,interpolateRound:()=>ty,interpolateSinebow:()=>vk,interpolateSpectral:()=>Sx,interpolateString:()=>Lr,interpolateTransformCss:()=>gi,interpolateTransformSvg:()=>yi,interpolateTurbo:()=>_k,interpolateViridis:()=>kk,interpolateWarm:()=>fk,interpolateYlGn:()=>Vx,interpolateYlGnBu:()=>qx,interpolateYlOrBr:()=>Xx,interpolateYlOrRd:()=>Qx,interpolateZoom:()=>ny,interrupt:()=>li,intersection:()=>Ut,interval:()=>iE,isoFormat:()=>eE,isoParse:()=>rE,json:()=>tl,lab:()=>ko,lch:()=>Mo,least:()=>wt,leastIndex:()=>Tt,line:()=>ow,lineRadial:()=>gw,linkHorizontal:()=>Tw,linkRadial:()=>Cw,linkVertical:()=>Ew,local:()=>Ak,map:()=>Rt,matcher:()=>be,max:()=>at,maxIndex:()=>dt,mean:()=>pt,median:()=>gt,merge:()=>yt,min:()=>ot,minIndex:()=>mt,mode:()=>bt,namespace:()=>Le,namespaces:()=>Be,nice:()=>nt,now:()=>Gr,pack:()=>kg,packEnclose:()=>rg,packSiblings:()=>yg,pairs:()=>vt,partition:()=>Ag,path:()=>Ja,permute:()=>U,pie:()=>uw,piecewise:()=>dy,pointRadial:()=>mw,pointer:()=>Rr,pointers:()=>Nk,polygonArea:()=>gy,polygonCentroid:()=>yy,polygonContains:()=>xy,polygonHull:()=>_y,polygonLength:()=>ky,precisionFixed:()=>Vl,precisionPrefix:()=>Gl,precisionRound:()=>Xl,quadtree:()=>ul,quantile:()=>lt,quantileSorted:()=>ut,quantize:()=>py,quickselect:()=>st,radialArea:()=>yw,radialLine:()=>gw,randomBates:()=>My,randomBernoulli:()=>Dy,randomBeta:()=>Iy,randomBinomial:()=>Fy,randomCauchy:()=>Py,randomExponential:()=>Ny,randomGamma:()=>Ly,randomGeometric:()=>By,randomInt:()=>Ey,randomIrwinHall:()=>Ay,randomLcg:()=>Uy,randomLogNormal:()=>Sy,randomLogistic:()=>jy,randomNormal:()=>Cy,randomPareto:()=>Oy,randomPoisson:()=>zy,randomUniform:()=>Ty,randomWeibull:()=>Ry,range:()=>xt,rank:()=>kt,reduce:()=>Pt,reverse:()=>jt,rgb:()=>ir,ribbon:()=>uo,ribbonArrow:()=>ho,rollup:()=>F,rollups:()=>R,scaleBand:()=>Vy,scaleDiverging:()=>V_,scaleDivergingLog:()=>G_,scaleDivergingPow:()=>Z_,scaleDivergingSqrt:()=>Q_,scaleDivergingSymlog:()=>X_,scaleIdentity:()=>cm,scaleImplicit:()=>qy,scaleLinear:()=>sm,scaleLog:()=>mm,scaleOrdinal:()=>Hy,scalePoint:()=>Xy,scalePow:()=>Cm,scaleQuantile:()=>Om,scaleQuantize:()=>Dm,scaleRadial:()=>Nm,scaleSequential:()=>z_,scaleSequentialLog:()=>Y_,scaleSequentialPow:()=>$_,scaleSequentialQuantile:()=>q_,scaleSequentialSqrt:()=>W_,scaleSequentialSymlog:()=>U_,scaleSqrt:()=>Sm,scaleSymlog:()=>xm,scaleThreshold:()=>Bm,scaleTime:()=>F_,scaleUtc:()=>R_,scan:()=>St,schemeAccent:()=>tx,schemeBlues:()=>Kx,schemeBrBG:()=>ux,schemeBuGn:()=>Ax,schemeBuPu:()=>Nx,schemeCategory10:()=>J_,schemeDark2:()=>ex,schemeGnBu:()=>Dx,schemeGreens:()=>tk,schemeGreys:()=>nk,schemeOrRd:()=>Lx,schemeOranges:()=>ck,schemePRGn:()=>fx,schemePaired:()=>nx,schemePastel1:()=>rx,schemePastel2:()=>ix,schemePiYG:()=>px,schemePuBu:()=>Px,schemePuBuGn:()=>Fx,schemePuOr:()=>yx,schemePuRd:()=>zx,schemePurples:()=>ik,schemeRdBu:()=>bx,schemeRdGy:()=>_x,schemeRdPu:()=>Ux,schemeRdYlBu:()=>kx,schemeRdYlGn:()=>Tx,schemeReds:()=>ok,schemeSet1:()=>ax,schemeSet2:()=>ox,schemeSet3:()=>sx,schemeSpectral:()=>Cx,schemeTableau10:()=>cx,schemeYlGn:()=>Hx,schemeYlGnBu:()=>Wx,schemeYlOrBr:()=>Gx,schemeYlOrRd:()=>Zx,select:()=>Mn,selectAll:()=>Ok,selection:()=>An,selector:()=>pe,selectorAll:()=>me,shuffle:()=>At,shuffler:()=>Mt,some:()=>It,sort:()=>$,stack:()=>YT,stackOffsetDiverging:()=>$T,stackOffsetExpand:()=>UT,stackOffsetNone:()=>RT,stackOffsetSilhouette:()=>WT,stackOffsetWiggle:()=>qT,stackOrderAppearance:()=>HT,stackOrderAscending:()=>GT,stackOrderDescending:()=>ZT,stackOrderInsideOut:()=>QT,stackOrderNone:()=>PT,stackOrderReverse:()=>KT,stratify:()=>Lg,style:()=>qe,subset:()=>Ht,sum:()=>Nt,superset:()=>Wt,svg:()=>il,symbol:()=>qw,symbolCircle:()=>Sw,symbolCross:()=>Aw,symbolDiamond:()=>Ow,symbolSquare:()=>Fw,symbolStar:()=>Iw,symbolTriangle:()=>Pw,symbolWye:()=>$w,symbols:()=>Ww,text:()=>Vc,thresholdFreedmanDiaconis:()=>ht,thresholdScott:()=>ft,thresholdSturges:()=>rt,tickFormat:()=>am,tickIncrement:()=>tt,tickStep:()=>et,ticks:()=>J,timeDay:()=>nb,timeDays:()=>rb,timeFormat:()=>hv,timeFormatDefaultLocale:()=>D_,timeFormatLocale:()=>lv,timeFriday:()=>ub,timeFridays:()=>mb,timeHour:()=>Jm,timeHours:()=>tb,timeInterval:()=>Um,timeMillisecond:()=>Wm,timeMilliseconds:()=>qm,timeMinute:()=>Zm,timeMinutes:()=>Qm,timeMonday:()=>ob,timeMondays:()=>db,timeMonth:()=>_b,timeMonths:()=>xb,timeParse:()=>fv,timeSaturday:()=>hb,timeSaturdays:()=>bb,timeSecond:()=>Vm,timeSeconds:()=>Gm,timeSunday:()=>ab,timeSundays:()=>fb,timeThursday:()=>lb,timeThursdays:()=>yb,timeTickInterval:()=>av,timeTicks:()=>iv,timeTuesday:()=>sb,timeTuesdays:()=>pb,timeWednesday:()=>cb,timeWednesdays:()=>gb,timeWeek:()=>ab,timeWeeks:()=>fb,timeYear:()=>wb,timeYears:()=>Tb,timeout:()=>ni,timer:()=>Qr,timerFlush:()=>Kr,transition:()=>qi,transpose:()=>Ot,tree:()=>$g,treemap:()=>Gg,treemapBinary:()=>Xg,treemapDice:()=>Sg,treemapResquarify:()=>Qg,treemapSlice:()=>Wg,treemapSliceDice:()=>Zg,treemapSquarify:()=>Vg,tsv:()=>Qc,tsvFormat:()=>ic,tsvFormatBody:()=>ac,tsvFormatRow:()=>sc,tsvFormatRows:()=>oc,tsvFormatValue:()=>cc,tsvParse:()=>nc,tsvParseRows:()=>rc,union:()=>Vt,utcDay:()=>Db,utcDays:()=>Bb,utcFormat:()=>dv,utcFriday:()=>zb,utcFridays:()=>Vb,utcHour:()=>Mb,utcHours:()=>Nb,utcMillisecond:()=>Wm,utcMilliseconds:()=>qm,utcMinute:()=>Cb,utcMinutes:()=>Sb,utcMonday:()=>Fb,utcMondays:()=>$b,utcMonth:()=>Zb,utcMonths:()=>Qb,utcParse:()=>pv,utcSaturday:()=>Yb,utcSaturdays:()=>Gb,utcSecond:()=>Vm,utcSeconds:()=>Gm,utcSunday:()=>Ib,utcSundays:()=>Ub,utcThursday:()=>jb,utcThursdays:()=>Hb,utcTickInterval:()=>rv,utcTicks:()=>nv,utcTuesday:()=>Rb,utcTuesdays:()=>Wb,utcWednesday:()=>Pb,utcWednesdays:()=>qb,utcWeek:()=>Ib,utcWeeks:()=>Ub,utcYear:()=>Jb,utcYears:()=>tv,variance:()=>b,window:()=>Ye,xml:()=>nl,zip:()=>Bt,zoom:()=>bE,zoomIdentity:()=>cE,zoomTransform:()=>lE});const o=i(r),s=o.right,c=o.left,l=i(a).center,u=s;function h(t,e){let n=0;if(void 0===e)for(let e of t)null!=e&&(e=+e)>=e&&++n;else {let r=-1;for(let i of t)null!=(i=e(i,++r,t))&&(i=+i)>=i&&++n;}return n}function f(t){return 0|t.length}function d(t){return !(t>0)}function p(t){return "object"!=typeof t||"length"in t?t:Array.from(t)}function g(...t){const e="function"==typeof t[t.length-1]&&function(t){return e=>t(...e)}(t.pop()),n=(t=t.map(p)).map(f),r=t.length-1,i=new Array(r+1).fill(0),a=[];if(r<0||n.some(d))return a;for(;;){a.push(i.map(((e,n)=>t[n][e])));let o=r;for(;++i[o]===n[o];){if(0===o)return e?a.map(e):a;i[o--]=0;}}}function y(t,e){var n=0,r=0;return Float64Array.from(t,void 0===e?t=>n+=+t||0:i=>n+=+e(i,r++,t)||0)}function m(t,e){return null==t||null==e?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function b(t,e){let n,r=0,i=0,a=0;if(void 0===e)for(let e of t)null!=e&&(e=+e)>=e&&(n=e-i,i+=n/++r,a+=n*(e-i));else {let o=-1;for(let s of t)null!=(s=e(s,++o,t))&&(s=+s)>=s&&(n=s-i,i+=n/++r,a+=n*(s-i));}if(r>1)return a/(r-1)}function v(t,e){const n=b(t,e);return n?Math.sqrt(n):n}function _(t,e){let n,r;if(void 0===e)for(const e of t)null!=e&&(void 0===n?e>=e&&(n=r=e):(n>e&&(n=e),r<e&&(r=e)));else {let i=-1;for(let a of t)null!=(a=e(a,++i,t))&&(void 0===n?a>=a&&(n=r=a):(n>a&&(n=a),r<a&&(r=a)));}return [n,r]}class x{constructor(){this._partials=new Float64Array(32),this._n=0;}add(t){const e=this._partials;let n=0;for(let r=0;r<this._n&&r<32;r++){const i=e[r],a=t+i,o=Math.abs(t)<Math.abs(i)?t-(a-i):i-(a-t);o&&(e[n++]=o),t=a;}return e[n]=t,this._n=n+1,this}valueOf(){const t=this._partials;let e,n,r,i=this._n,a=0;if(i>0){for(a=t[--i];i>0&&(e=a,n=t[--i],a=e+n,r=n-(a-e),!r););i>0&&(r<0&&t[i-1]<0||r>0&&t[i-1]>0)&&(n=2*r,e=a+n,n==e-a&&(a=e));}return a}}function k(t,e){const n=new x;if(void 0===e)for(let e of t)(e=+e)&&n.add(e);else {let r=-1;for(let i of t)(i=+e(i,++r,t))&&n.add(i);}return +n}function w(t,e){const n=new x;let r=-1;return Float64Array.from(t,void 0===e?t=>n.add(+t||0):i=>n.add(+e(i,++r,t)||0))}class T extends Map{constructor(t,e=M){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:e}}),null!=t)for(const[e,n]of t)this.set(e,n);}get(t){return super.get(C(this,t))}has(t){return super.has(C(this,t))}set(t,e){return super.set(S(this,t),e)}delete(t){return super.delete(A(this,t))}}class E extends Set{constructor(t,e=M){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:e}}),null!=t)for(const e of t)this.add(e);}has(t){return super.has(C(this,t))}add(t){return super.add(S(this,t))}delete(t){return super.delete(A(this,t))}}function C({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):n}function S({_intern:t,_key:e},n){const r=e(n);return t.has(r)?t.get(r):(t.set(r,n),n)}function A({_intern:t,_key:e},n){const r=e(n);return t.has(r)&&(n=t.get(r),t.delete(r)),n}function M(t){return null!==t&&"object"==typeof t?t.valueOf():t}function N(t){return t}function O(t,...e){return Y(t,N,N,e)}function D(t,...e){return Y(t,Array.from,N,e)}function B(t,e){for(let n=1,r=e.length;n<r;++n)t=t.flatMap((t=>t.pop().map((([e,n])=>[...t,e,n]))));return t}function L(t,...e){return B(D(t,...e),e)}function I(t,e,...n){return B(R(t,e,...n),n)}function F(t,e,...n){return Y(t,N,e,n)}function R(t,e,...n){return Y(t,Array.from,e,n)}function P(t,...e){return Y(t,N,z,e)}function j(t,...e){return Y(t,Array.from,z,e)}function z(t){if(1!==t.length)throw new Error("duplicate key");return t[0]}function Y(t,e,n,r){return function t(i,a){if(a>=r.length)return n(i);const o=new T,s=r[a++];let c=-1;for(const t of i){const e=s(t,++c,i),n=o.get(e);n?n.push(t):o.set(e,[t]);}for(const[e,n]of o)o.set(e,t(n,a));return e(o)}(t,0)}function U(t,e){return Array.from(e,(e=>t[e]))}function $(t,...e){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");t=Array.from(t);let[n]=e;if(n&&2!==n.length||e.length>1){const r=Uint32Array.from(t,((t,e)=>e));return e.length>1?(e=e.map((e=>t.map(e))),r.sort(((t,n)=>{for(const r of e){const e=q(r[t],r[n]);if(e)return e}}))):(n=t.map(n),r.sort(((t,e)=>q(n[t],n[e])))),U(t,r)}return t.sort(W(n))}function W(t=r){if(t===r)return q;if("function"!=typeof t)throw new TypeError("compare is not a function");return (e,n)=>{const r=t(e,n);return r||0===r?r:(0===t(n,n))-(0===t(e,e))}}function q(t,e){return (null==t||!(t>=t))-(null==e||!(e>=e))||(t<e?-1:t>e?1:0)}function H(t,e,n){return (2!==e.length?$(F(t,e,n),(([t,e],[n,i])=>r(e,i)||r(t,n))):$(O(t,n),(([t,n],[i,a])=>e(n,a)||r(t,i)))).map((([t])=>t))}var V=Array.prototype,G=V.slice;function X(t){return ()=>t}var Z=Math.sqrt(50),Q=Math.sqrt(10),K=Math.sqrt(2);function J(t,e,n){var r,i,a,o,s=-1;if(n=+n,(t=+t)==(e=+e)&&n>0)return [t];if((r=e<t)&&(i=t,t=e,e=i),0===(o=tt(t,e,n))||!isFinite(o))return [];if(o>0){let n=Math.round(t/o),r=Math.round(e/o);for(n*o<t&&++n,r*o>e&&--r,a=new Array(i=r-n+1);++s<i;)a[s]=(n+s)*o;}else {o=-o;let n=Math.round(t*o),r=Math.round(e*o);for(n/o<t&&++n,r/o>e&&--r,a=new Array(i=r-n+1);++s<i;)a[s]=(n+s)/o;}return r&&a.reverse(),a}function tt(t,e,n){var r=(e-t)/Math.max(0,n),i=Math.floor(Math.log(r)/Math.LN10),a=r/Math.pow(10,i);return i>=0?(a>=Z?10:a>=Q?5:a>=K?2:1)*Math.pow(10,i):-Math.pow(10,-i)/(a>=Z?10:a>=Q?5:a>=K?2:1)}function et(t,e,n){var r=Math.abs(e-t)/Math.max(0,n),i=Math.pow(10,Math.floor(Math.log(r)/Math.LN10)),a=r/i;return a>=Z?i*=10:a>=Q?i*=5:a>=K&&(i*=2),e<t?-i:i}function nt(t,e,n){let r;for(;;){const i=tt(t,e,n);if(i===r||0===i||!isFinite(i))return [t,e];i>0?(t=Math.floor(t/i)*i,e=Math.ceil(e/i)*i):i<0&&(t=Math.ceil(t*i)/i,e=Math.floor(e*i)/i),r=i;}}function rt(t){return Math.ceil(Math.log(h(t))/Math.LN2)+1}function it(){var t=N,e=_,n=rt;function r(r){Array.isArray(r)||(r=Array.from(r));var i,a,o=r.length,s=new Array(o);for(i=0;i<o;++i)s[i]=t(r[i],i,r);var c=e(s),l=c[0],h=c[1],f=n(s,l,h);if(!Array.isArray(f)){const t=h,n=+f;if(e===_&&([l,h]=nt(l,h,n)),(f=J(l,h,n))[f.length-1]>=h)if(t>=h&&e===_){const t=tt(l,h,n);isFinite(t)&&(t>0?h=(Math.floor(h/t)+1)*t:t<0&&(h=(Math.ceil(h*-t)+1)/-t));}else f.pop();}for(var d=f.length;f[0]<=l;)f.shift(),--d;for(;f[d-1]>h;)f.pop(),--d;var p,g=new Array(d+1);for(i=0;i<=d;++i)(p=g[i]=[]).x0=i>0?f[i-1]:l,p.x1=i<d?f[i]:h;for(i=0;i<o;++i)null!=(a=s[i])&&l<=a&&a<=h&&g[u(f,a,0,d)].push(r[i]);return g}return r.value=function(e){return arguments.length?(t="function"==typeof e?e:X(e),r):t},r.domain=function(t){return arguments.length?(e="function"==typeof t?t:X([t[0],t[1]]),r):e},r.thresholds=function(t){return arguments.length?(n="function"==typeof t?t:Array.isArray(t)?X(G.call(t)):X(t),r):n},r}function at(t,e){let n;if(void 0===e)for(const e of t)null!=e&&(n<e||void 0===n&&e>=e)&&(n=e);else {let r=-1;for(let i of t)null!=(i=e(i,++r,t))&&(n<i||void 0===n&&i>=i)&&(n=i);}return n}function ot(t,e){let n;if(void 0===e)for(const e of t)null!=e&&(n>e||void 0===n&&e>=e)&&(n=e);else {let r=-1;for(let i of t)null!=(i=e(i,++r,t))&&(n>i||void 0===n&&i>=i)&&(n=i);}return n}function st(t,e,n=0,r=t.length-1,i){for(i=void 0===i?q:W(i);r>n;){if(r-n>600){const a=r-n+1,o=e-n+1,s=Math.log(a),c=.5*Math.exp(2*s/3),l=.5*Math.sqrt(s*c*(a-c)/a)*(o-a/2<0?-1:1);st(t,e,Math.max(n,Math.floor(e-o*c/a+l)),Math.min(r,Math.floor(e+(a-o)*c/a+l)),i);}const a=t[e];let o=n,s=r;for(ct(t,n,e),i(t[r],a)>0&&ct(t,n,r);o<s;){for(ct(t,o,s),++o,--s;i(t[o],a)<0;)++o;for(;i(t[s],a)>0;)--s;}0===i(t[n],a)?ct(t,n,s):(++s,ct(t,s,r)),s<=e&&(n=s+1),e<=s&&(r=s-1);}return t}function ct(t,e,n){const r=t[e];t[e]=t[n],t[n]=r;}function lt(t,e,n){if(t=Float64Array.from(function*(t,e){if(void 0===e)for(let e of t)null!=e&&(e=+e)>=e&&(yield e);else {let n=-1;for(let r of t)null!=(r=e(r,++n,t))&&(r=+r)>=r&&(yield r);}}(t,n)),r=t.length){if((e=+e)<=0||r<2)return ot(t);if(e>=1)return at(t);var r,i=(r-1)*e,a=Math.floor(i),o=at(st(t,a).subarray(0,a+1));return o+(ot(t.subarray(a+1))-o)*(i-a)}}function ut(t,e,n=a){if(r=t.length){if((e=+e)<=0||r<2)return +n(t[0],0,t);if(e>=1)return +n(t[r-1],r-1,t);var r,i=(r-1)*e,o=Math.floor(i),s=+n(t[o],o,t);return s+(+n(t[o+1],o+1,t)-s)*(i-o)}}function ht(t,e,n){return Math.ceil((n-e)/(2*(lt(t,.75)-lt(t,.25))*Math.pow(h(t),-1/3)))}function ft(t,e,n){return Math.ceil((n-e)/(3.5*v(t)*Math.pow(h(t),-1/3)))}function dt(t,e){let n,r=-1,i=-1;if(void 0===e)for(const e of t)++i,null!=e&&(n<e||void 0===n&&e>=e)&&(n=e,r=i);else for(let a of t)null!=(a=e(a,++i,t))&&(n<a||void 0===n&&a>=a)&&(n=a,r=i);return r}function pt(t,e){let n=0,r=0;if(void 0===e)for(let e of t)null!=e&&(e=+e)>=e&&(++n,r+=e);else {let i=-1;for(let a of t)null!=(a=e(a,++i,t))&&(a=+a)>=a&&(++n,r+=a);}if(n)return r/n}function gt(t,e){return lt(t,.5,e)}function yt(t){return Array.from(function*(t){for(const e of t)yield*e;}(t))}function mt(t,e){let n,r=-1,i=-1;if(void 0===e)for(const e of t)++i,null!=e&&(n>e||void 0===n&&e>=e)&&(n=e,r=i);else for(let a of t)null!=(a=e(a,++i,t))&&(n>a||void 0===n&&a>=a)&&(n=a,r=i);return r}function bt(t,e){const n=new T;if(void 0===e)for(let e of t)null!=e&&e>=e&&n.set(e,(n.get(e)||0)+1);else {let r=-1;for(let i of t)null!=(i=e(i,++r,t))&&i>=i&&n.set(i,(n.get(i)||0)+1);}let r,i=0;for(const[t,e]of n)e>i&&(i=e,r=t);return r}function vt(t,e=_t){const n=[];let r,i=!1;for(const a of t)i&&n.push(e(r,a)),r=a,i=!0;return n}function _t(t,e){return [t,e]}function xt(t,e,n){t=+t,e=+e,n=(i=arguments.length)<2?(e=t,t=0,1):i<3?1:+n;for(var r=-1,i=0|Math.max(0,Math.ceil((e-t)/n)),a=new Array(i);++r<i;)a[r]=t+r*n;return a}function kt(t,e=r){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");let n=Array.from(t);const i=new Float64Array(n.length);2!==e.length&&(n=n.map(e),e=r);const a=(t,r)=>e(n[t],n[r]);let o,s;return Uint32Array.from(n,((t,e)=>e)).sort(e===r?(t,e)=>q(n[t],n[e]):W(a)).forEach(((t,e)=>{const n=a(t,void 0===o?t:o);n>=0?((void 0===o||n>0)&&(o=t,s=e),i[t]=s):i[t]=NaN;})),i}function wt(t,e=r){let n,i=!1;if(1===e.length){let a;for(const o of t){const t=e(o);(i?r(t,a)<0:0===r(t,t))&&(n=o,a=t,i=!0);}}else for(const r of t)(i?e(r,n)<0:0===e(r,r))&&(n=r,i=!0);return n}function Tt(t,e=r){if(1===e.length)return mt(t,e);let n,i=-1,a=-1;for(const r of t)++a,(i<0?0===e(r,r):e(r,n)<0)&&(n=r,i=a);return i}function Et(t,e=r){let n,i=!1;if(1===e.length){let a;for(const o of t){const t=e(o);(i?r(t,a)>0:0===r(t,t))&&(n=o,a=t,i=!0);}}else for(const r of t)(i?e(r,n)>0:0===e(r,r))&&(n=r,i=!0);return n}function Ct(t,e=r){if(1===e.length)return dt(t,e);let n,i=-1,a=-1;for(const r of t)++a,(i<0?0===e(r,r):e(r,n)>0)&&(n=r,i=a);return i}function St(t,e){const n=Tt(t,e);return n<0?void 0:n}const At=Mt(Math.random);function Mt(t){return function(e,n=0,r=e.length){let i=r-(n=+n);for(;i;){const r=t()*i--|0,a=e[i+n];e[i+n]=e[r+n],e[r+n]=a;}return e}}function Nt(t,e){let n=0;if(void 0===e)for(let e of t)(e=+e)&&(n+=e);else {let r=-1;for(let i of t)(i=+e(i,++r,t))&&(n+=i);}return n}function Ot(t){if(!(i=t.length))return [];for(var e=-1,n=ot(t,Dt),r=new Array(n);++e<n;)for(var i,a=-1,o=r[e]=new Array(i);++a<i;)o[a]=t[a][e];return r}function Dt(t){return t.length}function Bt(){return Ot(arguments)}function Lt(t,e){if("function"!=typeof e)throw new TypeError("test is not a function");let n=-1;for(const r of t)if(!e(r,++n,t))return !1;return !0}function It(t,e){if("function"!=typeof e)throw new TypeError("test is not a function");let n=-1;for(const r of t)if(e(r,++n,t))return !0;return !1}function Ft(t,e){if("function"!=typeof e)throw new TypeError("test is not a function");const n=[];let r=-1;for(const i of t)e(i,++r,t)&&n.push(i);return n}function Rt(t,e){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");if("function"!=typeof e)throw new TypeError("mapper is not a function");return Array.from(t,((n,r)=>e(n,r,t)))}function Pt(t,e,n){if("function"!=typeof e)throw new TypeError("reducer is not a function");const r=t[Symbol.iterator]();let i,a,o=-1;if(arguments.length<3){if(({done:i,value:n}=r.next()),i)return;++o;}for(;({done:i,value:a}=r.next()),!i;)n=e(n,a,++o,t);return n}function jt(t){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");return Array.from(t).reverse()}function zt(t,...e){t=new E(t);for(const n of e)for(const e of n)t.delete(e);return t}function Yt(t,e){const n=e[Symbol.iterator](),r=new E;for(const e of t){if(r.has(e))return !1;let t,i;for(;({value:t,done:i}=n.next())&&!i;){if(Object.is(e,t))return !1;r.add(t);}}return !0}function Ut(t,...e){t=new E(t),e=e.map($t);t:for(const n of t)for(const r of e)if(!r.has(n)){t.delete(n);continue t}return t}function $t(t){return t instanceof E?t:new E(t)}function Wt(t,e){const n=t[Symbol.iterator](),r=new Set;for(const t of e){const e=qt(t);if(r.has(e))continue;let i,a;for(;({value:i,done:a}=n.next());){if(a)return !1;const t=qt(i);if(r.add(t),Object.is(e,t))break}}return !0}function qt(t){return null!==t&&"object"==typeof t?t.valueOf():t}function Ht(t,e){return Wt(e,t)}function Vt(...t){const e=new E;for(const n of t)for(const t of n)e.add(t);return e}function Gt(t){return t}var Xt=1e-6;function Zt(t){return "translate("+t+",0)"}function Qt(t){return "translate(0,"+t+")"}function Kt(t){return e=>+t(e)}function Jt(t,e){return e=Math.max(0,t.bandwidth()-2*e)/2,t.round()&&(e=Math.round(e)),n=>+t(n)+e}function te(){return !this.__axis}function ee(t,e){var n=[],r=null,i=null,a=6,o=6,s=3,c="undefined"!=typeof window&&window.devicePixelRatio>1?0:.5,l=1===t||4===t?-1:1,u=4===t||2===t?"x":"y",h=1===t||3===t?Zt:Qt;function f(f){var d=null==r?e.ticks?e.ticks.apply(e,n):e.domain():r,p=null==i?e.tickFormat?e.tickFormat.apply(e,n):Gt:i,g=Math.max(a,0)+s,y=e.range(),m=+y[0]+c,b=+y[y.length-1]+c,v=(e.bandwidth?Jt:Kt)(e.copy(),c),_=f.selection?f.selection():f,x=_.selectAll(".domain").data([null]),k=_.selectAll(".tick").data(d,e).order(),w=k.exit(),T=k.enter().append("g").attr("class","tick"),E=k.select("line"),C=k.select("text");x=x.merge(x.enter().insert("path",".tick").attr("class","domain").attr("stroke","currentColor")),k=k.merge(T),E=E.merge(T.append("line").attr("stroke","currentColor").attr(u+"2",l*a)),C=C.merge(T.append("text").attr("fill","currentColor").attr(u,l*g).attr("dy",1===t?"0em":3===t?"0.71em":"0.32em")),f!==_&&(x=x.transition(f),k=k.transition(f),E=E.transition(f),C=C.transition(f),w=w.transition(f).attr("opacity",Xt).attr("transform",(function(t){return isFinite(t=v(t))?h(t+c):this.getAttribute("transform")})),T.attr("opacity",Xt).attr("transform",(function(t){var e=this.parentNode.__axis;return h((e&&isFinite(e=e(t))?e:v(t))+c)}))),w.remove(),x.attr("d",4===t||2===t?o?"M"+l*o+","+m+"H"+c+"V"+b+"H"+l*o:"M"+c+","+m+"V"+b:o?"M"+m+","+l*o+"V"+c+"H"+b+"V"+l*o:"M"+m+","+c+"H"+b),k.attr("opacity",1).attr("transform",(function(t){return h(v(t)+c)})),E.attr(u+"2",l*a),C.attr(u,l*g).text(p),_.filter(te).attr("fill","none").attr("font-size",10).attr("font-family","sans-serif").attr("text-anchor",2===t?"start":4===t?"end":"middle"),_.each((function(){this.__axis=v;}));}return f.scale=function(t){return arguments.length?(e=t,f):e},f.ticks=function(){return n=Array.from(arguments),f},f.tickArguments=function(t){return arguments.length?(n=null==t?[]:Array.from(t),f):n.slice()},f.tickValues=function(t){return arguments.length?(r=null==t?null:Array.from(t),f):r&&r.slice()},f.tickFormat=function(t){return arguments.length?(i=t,f):i},f.tickSize=function(t){return arguments.length?(a=o=+t,f):a},f.tickSizeInner=function(t){return arguments.length?(a=+t,f):a},f.tickSizeOuter=function(t){return arguments.length?(o=+t,f):o},f.tickPadding=function(t){return arguments.length?(s=+t,f):s},f.offset=function(t){return arguments.length?(c=+t,f):c},f}function ne(t){return ee(1,t)}function re(t){return ee(2,t)}function ie(t){return ee(3,t)}function ae(t){return ee(4,t)}var oe={value:()=>{}};function se(){for(var t,e=0,n=arguments.length,r={};e<n;++e){if(!(t=arguments[e]+"")||t in r||/[\s.]/.test(t))throw new Error("illegal type: "+t);r[t]=[];}return new ce(r)}function ce(t){this._=t;}function le(t,e){return t.trim().split(/^|\s+/).map((function(t){var n="",r=t.indexOf(".");if(r>=0&&(n=t.slice(r+1),t=t.slice(0,r)),t&&!e.hasOwnProperty(t))throw new Error("unknown type: "+t);return {type:t,name:n}}))}function ue(t,e){for(var n,r=0,i=t.length;r<i;++r)if((n=t[r]).name===e)return n.value}function he(t,e,n){for(var r=0,i=t.length;r<i;++r)if(t[r].name===e){t[r]=oe,t=t.slice(0,r).concat(t.slice(r+1));break}return null!=n&&t.push({name:e,value:n}),t}ce.prototype=se.prototype={constructor:ce,on:function(t,e){var n,r=this._,i=le(t+"",r),a=-1,o=i.length;if(!(arguments.length<2)){if(null!=e&&"function"!=typeof e)throw new Error("invalid callback: "+e);for(;++a<o;)if(n=(t=i[a]).type)r[n]=he(r[n],t.name,e);else if(null==e)for(n in r)r[n]=he(r[n],t.name,null);return this}for(;++a<o;)if((n=(t=i[a]).type)&&(n=ue(r[n],t.name)))return n},copy:function(){var t={},e=this._;for(var n in e)t[n]=e[n].slice();return new ce(t)},call:function(t,e){if((n=arguments.length-2)>0)for(var n,r,i=new Array(n),a=0;a<n;++a)i[a]=arguments[a+2];if(!this._.hasOwnProperty(t))throw new Error("unknown type: "+t);for(a=0,n=(r=this._[t]).length;a<n;++a)r[a].value.apply(e,i);},apply:function(t,e,n){if(!this._.hasOwnProperty(t))throw new Error("unknown type: "+t);for(var r=this._[t],i=0,a=r.length;i<a;++i)r[i].value.apply(e,n);}};const fe=se;function de(){}function pe(t){return null==t?de:function(){return this.querySelector(t)}}function ge(t){return null==t?[]:Array.isArray(t)?t:Array.from(t)}function ye(){return []}function me(t){return null==t?ye:function(){return this.querySelectorAll(t)}}function be(t){return function(){return this.matches(t)}}function ve(t){return function(e){return e.matches(t)}}var _e=Array.prototype.find;function xe(){return this.firstElementChild}var ke=Array.prototype.filter;function we(){return Array.from(this.children)}function Te(t){return new Array(t.length)}function Ee(t,e){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=e;}function Ce(t){return function(){return t}}function Se(t,e,n,r,i,a){for(var o,s=0,c=e.length,l=a.length;s<l;++s)(o=e[s])?(o.__data__=a[s],r[s]=o):n[s]=new Ee(t,a[s]);for(;s<c;++s)(o=e[s])&&(i[s]=o);}function Ae(t,e,n,r,i,a,o){var s,c,l,u=new Map,h=e.length,f=a.length,d=new Array(h);for(s=0;s<h;++s)(c=e[s])&&(d[s]=l=o.call(c,c.__data__,s,e)+"",u.has(l)?i[s]=c:u.set(l,c));for(s=0;s<f;++s)l=o.call(t,a[s],s,a)+"",(c=u.get(l))?(r[s]=c,c.__data__=a[s],u.delete(l)):n[s]=new Ee(t,a[s]);for(s=0;s<h;++s)(c=e[s])&&u.get(d[s])===c&&(i[s]=c);}function Me(t){return t.__data__}function Ne(t){return "object"==typeof t&&"length"in t?t:Array.from(t)}function Oe(t,e){return t<e?-1:t>e?1:t>=e?0:NaN}Ee.prototype={constructor:Ee,appendChild:function(t){return this._parent.insertBefore(t,this._next)},insertBefore:function(t,e){return this._parent.insertBefore(t,e)},querySelector:function(t){return this._parent.querySelector(t)},querySelectorAll:function(t){return this._parent.querySelectorAll(t)}};var De="http://www.w3.org/1999/xhtml";const Be={svg:"http://www.w3.org/2000/svg",xhtml:De,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Le(t){var e=t+="",n=e.indexOf(":");return n>=0&&"xmlns"!==(e=t.slice(0,n))&&(t=t.slice(n+1)),Be.hasOwnProperty(e)?{space:Be[e],local:t}:t}function Ie(t){return function(){this.removeAttribute(t);}}function Fe(t){return function(){this.removeAttributeNS(t.space,t.local);}}function Re(t,e){return function(){this.setAttribute(t,e);}}function Pe(t,e){return function(){this.setAttributeNS(t.space,t.local,e);}}function je(t,e){return function(){var n=e.apply(this,arguments);null==n?this.removeAttribute(t):this.setAttribute(t,n);}}function ze(t,e){return function(){var n=e.apply(this,arguments);null==n?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,n);}}function Ye(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function Ue(t){return function(){this.style.removeProperty(t);}}function $e(t,e,n){return function(){this.style.setProperty(t,e,n);}}function We(t,e,n){return function(){var r=e.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,n);}}function qe(t,e){return t.style.getPropertyValue(e)||Ye(t).getComputedStyle(t,null).getPropertyValue(e)}function He(t){return function(){delete this[t];}}function Ve(t,e){return function(){this[t]=e;}}function Ge(t,e){return function(){var n=e.apply(this,arguments);null==n?delete this[t]:this[t]=n;}}function Xe(t){return t.trim().split(/^|\s+/)}function Ze(t){return t.classList||new Qe(t)}function Qe(t){this._node=t,this._names=Xe(t.getAttribute("class")||"");}function Ke(t,e){for(var n=Ze(t),r=-1,i=e.length;++r<i;)n.add(e[r]);}function Je(t,e){for(var n=Ze(t),r=-1,i=e.length;++r<i;)n.remove(e[r]);}function tn(t){return function(){Ke(this,t);}}function en(t){return function(){Je(this,t);}}function nn(t,e){return function(){(e.apply(this,arguments)?Ke:Je)(this,t);}}function rn(){this.textContent="";}function an(t){return function(){this.textContent=t;}}function on(t){return function(){var e=t.apply(this,arguments);this.textContent=null==e?"":e;}}function sn(){this.innerHTML="";}function cn(t){return function(){this.innerHTML=t;}}function ln(t){return function(){var e=t.apply(this,arguments);this.innerHTML=null==e?"":e;}}function un(){this.nextSibling&&this.parentNode.appendChild(this);}function hn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild);}function fn(t){return function(){var e=this.ownerDocument,n=this.namespaceURI;return n===De&&e.documentElement.namespaceURI===De?e.createElement(t):e.createElementNS(n,t)}}function dn(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}function pn(t){var e=Le(t);return (e.local?dn:fn)(e)}function gn(){return null}function yn(){var t=this.parentNode;t&&t.removeChild(this);}function mn(){var t=this.cloneNode(!1),e=this.parentNode;return e?e.insertBefore(t,this.nextSibling):t}function bn(){var t=this.cloneNode(!0),e=this.parentNode;return e?e.insertBefore(t,this.nextSibling):t}function vn(t){return t.trim().split(/^|\s+/).map((function(t){var e="",n=t.indexOf(".");return n>=0&&(e=t.slice(n+1),t=t.slice(0,n)),{type:t,name:e}}))}function _n(t){return function(){var e=this.__on;if(e){for(var n,r=0,i=-1,a=e.length;r<a;++r)n=e[r],t.type&&n.type!==t.type||n.name!==t.name?e[++i]=n:this.removeEventListener(n.type,n.listener,n.options);++i?e.length=i:delete this.__on;}}}function xn(t,e,n){return function(){var r,i=this.__on,a=function(t){return function(e){t.call(this,e,this.__data__);}}(e);if(i)for(var o=0,s=i.length;o<s;++o)if((r=i[o]).type===t.type&&r.name===t.name)return this.removeEventListener(r.type,r.listener,r.options),this.addEventListener(r.type,r.listener=a,r.options=n),void(r.value=e);this.addEventListener(t.type,a,n),r={type:t.type,name:t.name,value:e,listener:a,options:n},i?i.push(r):this.__on=[r];}}function kn(t,e,n){var r=Ye(t),i=r.CustomEvent;"function"==typeof i?i=new i(e,n):(i=r.document.createEvent("Event"),n?(i.initEvent(e,n.bubbles,n.cancelable),i.detail=n.detail):i.initEvent(e,!1,!1)),t.dispatchEvent(i);}function wn(t,e){return function(){return kn(this,t,e)}}function Tn(t,e){return function(){return kn(this,t,e.apply(this,arguments))}}Qe.prototype={add:function(t){this._names.indexOf(t)<0&&(this._names.push(t),this._node.setAttribute("class",this._names.join(" ")));},remove:function(t){var e=this._names.indexOf(t);e>=0&&(this._names.splice(e,1),this._node.setAttribute("class",this._names.join(" ")));},contains:function(t){return this._names.indexOf(t)>=0}};var En=[null];function Cn(t,e){this._groups=t,this._parents=e;}function Sn(){return new Cn([[document.documentElement]],En)}Cn.prototype=Sn.prototype={constructor:Cn,select:function(t){"function"!=typeof t&&(t=pe(t));for(var e=this._groups,n=e.length,r=new Array(n),i=0;i<n;++i)for(var a,o,s=e[i],c=s.length,l=r[i]=new Array(c),u=0;u<c;++u)(a=s[u])&&(o=t.call(a,a.__data__,u,s))&&("__data__"in a&&(o.__data__=a.__data__),l[u]=o);return new Cn(r,this._parents)},selectAll:function(t){t="function"==typeof t?function(t){return function(){return ge(t.apply(this,arguments))}}(t):me(t);for(var e=this._groups,n=e.length,r=[],i=[],a=0;a<n;++a)for(var o,s=e[a],c=s.length,l=0;l<c;++l)(o=s[l])&&(r.push(t.call(o,o.__data__,l,s)),i.push(o));return new Cn(r,i)},selectChild:function(t){return this.select(null==t?xe:function(t){return function(){return _e.call(this.children,t)}}("function"==typeof t?t:ve(t)))},selectChildren:function(t){return this.selectAll(null==t?we:function(t){return function(){return ke.call(this.children,t)}}("function"==typeof t?t:ve(t)))},filter:function(t){"function"!=typeof t&&(t=be(t));for(var e=this._groups,n=e.length,r=new Array(n),i=0;i<n;++i)for(var a,o=e[i],s=o.length,c=r[i]=[],l=0;l<s;++l)(a=o[l])&&t.call(a,a.__data__,l,o)&&c.push(a);return new Cn(r,this._parents)},data:function(t,e){if(!arguments.length)return Array.from(this,Me);var n=e?Ae:Se,r=this._parents,i=this._groups;"function"!=typeof t&&(t=Ce(t));for(var a=i.length,o=new Array(a),s=new Array(a),c=new Array(a),l=0;l<a;++l){var u=r[l],h=i[l],f=h.length,d=Ne(t.call(u,u&&u.__data__,l,r)),p=d.length,g=s[l]=new Array(p),y=o[l]=new Array(p),m=c[l]=new Array(f);n(u,h,g,y,m,d,e);for(var b,v,_=0,x=0;_<p;++_)if(b=g[_]){for(_>=x&&(x=_+1);!(v=y[x])&&++x<p;);b._next=v||null;}}return (o=new Cn(o,r))._enter=s,o._exit=c,o},enter:function(){return new Cn(this._enter||this._groups.map(Te),this._parents)},exit:function(){return new Cn(this._exit||this._groups.map(Te),this._parents)},join:function(t,e,n){var r=this.enter(),i=this,a=this.exit();return "function"==typeof t?(r=t(r))&&(r=r.selection()):r=r.append(t+""),null!=e&&(i=e(i))&&(i=i.selection()),null==n?a.remove():n(a),r&&i?r.merge(i).order():i},merge:function(t){for(var e=t.selection?t.selection():t,n=this._groups,r=e._groups,i=n.length,a=r.length,o=Math.min(i,a),s=new Array(i),c=0;c<o;++c)for(var l,u=n[c],h=r[c],f=u.length,d=s[c]=new Array(f),p=0;p<f;++p)(l=u[p]||h[p])&&(d[p]=l);for(;c<i;++c)s[c]=n[c];return new Cn(s,this._parents)},selection:function(){return this},order:function(){for(var t=this._groups,e=-1,n=t.length;++e<n;)for(var r,i=t[e],a=i.length-1,o=i[a];--a>=0;)(r=i[a])&&(o&&4^r.compareDocumentPosition(o)&&o.parentNode.insertBefore(r,o),o=r);return this},sort:function(t){function e(e,n){return e&&n?t(e.__data__,n.__data__):!e-!n}t||(t=Oe);for(var n=this._groups,r=n.length,i=new Array(r),a=0;a<r;++a){for(var o,s=n[a],c=s.length,l=i[a]=new Array(c),u=0;u<c;++u)(o=s[u])&&(l[u]=o);l.sort(e);}return new Cn(i,this._parents).order()},call:function(){var t=arguments[0];return arguments[0]=this,t.apply(null,arguments),this},nodes:function(){return Array.from(this)},node:function(){for(var t=this._groups,e=0,n=t.length;e<n;++e)for(var r=t[e],i=0,a=r.length;i<a;++i){var o=r[i];if(o)return o}return null},size:function(){let t=0;for(const e of this)++t;return t},empty:function(){return !this.node()},each:function(t){for(var e=this._groups,n=0,r=e.length;n<r;++n)for(var i,a=e[n],o=0,s=a.length;o<s;++o)(i=a[o])&&t.call(i,i.__data__,o,a);return this},attr:function(t,e){var n=Le(t);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((null==e?n.local?Fe:Ie:"function"==typeof e?n.local?ze:je:n.local?Pe:Re)(n,e))},style:function(t,e,n){return arguments.length>1?this.each((null==e?Ue:"function"==typeof e?We:$e)(t,e,null==n?"":n)):qe(this.node(),t)},property:function(t,e){return arguments.length>1?this.each((null==e?He:"function"==typeof e?Ge:Ve)(t,e)):this.node()[t]},classed:function(t,e){var n=Xe(t+"");if(arguments.length<2){for(var r=Ze(this.node()),i=-1,a=n.length;++i<a;)if(!r.contains(n[i]))return !1;return !0}return this.each(("function"==typeof e?nn:e?tn:en)(n,e))},text:function(t){return arguments.length?this.each(null==t?rn:("function"==typeof t?on:an)(t)):this.node().textContent},html:function(t){return arguments.length?this.each(null==t?sn:("function"==typeof t?ln:cn)(t)):this.node().innerHTML},raise:function(){return this.each(un)},lower:function(){return this.each(hn)},append:function(t){var e="function"==typeof t?t:pn(t);return this.select((function(){return this.appendChild(e.apply(this,arguments))}))},insert:function(t,e){var n="function"==typeof t?t:pn(t),r=null==e?gn:"function"==typeof e?e:pe(e);return this.select((function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)}))},remove:function(){return this.each(yn)},clone:function(t){return this.select(t?bn:mn)},datum:function(t){return arguments.length?this.property("__data__",t):this.node().__data__},on:function(t,e,n){var r,i,a=vn(t+""),o=a.length;if(!(arguments.length<2)){for(s=e?xn:_n,r=0;r<o;++r)this.each(s(a[r],e,n));return this}var s=this.node().__on;if(s)for(var c,l=0,u=s.length;l<u;++l)for(r=0,c=s[l];r<o;++r)if((i=a[r]).type===c.type&&i.name===c.name)return c.value},dispatch:function(t,e){return this.each(("function"==typeof e?Tn:wn)(t,e))},[Symbol.iterator]:function*(){for(var t=this._groups,e=0,n=t.length;e<n;++e)for(var r,i=t[e],a=0,o=i.length;a<o;++a)(r=i[a])&&(yield r);}};const An=Sn;function Mn(t){return "string"==typeof t?new Cn([[document.querySelector(t)]],[document.documentElement]):new Cn([[t]],En)}const Nn={passive:!1},On={capture:!0,passive:!1};function Dn(t){t.stopImmediatePropagation();}function Bn(t){t.preventDefault(),t.stopImmediatePropagation();}function Ln(t){var e=t.document.documentElement,n=Mn(t).on("dragstart.drag",Bn,On);"onselectstart"in e?n.on("selectstart.drag",Bn,On):(e.__noselect=e.style.MozUserSelect,e.style.MozUserSelect="none");}function In(t,e){var n=t.document.documentElement,r=Mn(t).on("dragstart.drag",null);e&&(r.on("click.drag",Bn,On),setTimeout((function(){r.on("click.drag",null);}),0)),"onselectstart"in n?r.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect);}function Fn(t,e,n){t.prototype=e.prototype=n,n.constructor=t;}function Rn(t,e){var n=Object.create(t.prototype);for(var r in e)n[r]=e[r];return n}function Pn(){}var jn=.7,zn=1/jn,Yn="\\s*([+-]?\\d+)\\s*",Un="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",$n="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",Wn=/^#([0-9a-f]{3,8})$/,qn=new RegExp("^rgb\\("+[Yn,Yn,Yn]+"\\)$"),Hn=new RegExp("^rgb\\("+[$n,$n,$n]+"\\)$"),Vn=new RegExp("^rgba\\("+[Yn,Yn,Yn,Un]+"\\)$"),Gn=new RegExp("^rgba\\("+[$n,$n,$n,Un]+"\\)$"),Xn=new RegExp("^hsl\\("+[Un,$n,$n]+"\\)$"),Zn=new RegExp("^hsla\\("+[Un,$n,$n,Un]+"\\)$"),Qn={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function Kn(){return this.rgb().formatHex()}function Jn(){return this.rgb().formatRgb()}function tr(t){var e,n;return t=(t+"").trim().toLowerCase(),(e=Wn.exec(t))?(n=e[1].length,e=parseInt(e[1],16),6===n?er(e):3===n?new ar(e>>8&15|e>>4&240,e>>4&15|240&e,(15&e)<<4|15&e,1):8===n?nr(e>>24&255,e>>16&255,e>>8&255,(255&e)/255):4===n?nr(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|240&e,((15&e)<<4|15&e)/255):null):(e=qn.exec(t))?new ar(e[1],e[2],e[3],1):(e=Hn.exec(t))?new ar(255*e[1]/100,255*e[2]/100,255*e[3]/100,1):(e=Vn.exec(t))?nr(e[1],e[2],e[3],e[4]):(e=Gn.exec(t))?nr(255*e[1]/100,255*e[2]/100,255*e[3]/100,e[4]):(e=Xn.exec(t))?lr(e[1],e[2]/100,e[3]/100,1):(e=Zn.exec(t))?lr(e[1],e[2]/100,e[3]/100,e[4]):Qn.hasOwnProperty(t)?er(Qn[t]):"transparent"===t?new ar(NaN,NaN,NaN,0):null}function er(t){return new ar(t>>16&255,t>>8&255,255&t,1)}function nr(t,e,n,r){return r<=0&&(t=e=n=NaN),new ar(t,e,n,r)}function rr(t){return t instanceof Pn||(t=tr(t)),t?new ar((t=t.rgb()).r,t.g,t.b,t.opacity):new ar}function ir(t,e,n,r){return 1===arguments.length?rr(t):new ar(t,e,n,null==r?1:r)}function ar(t,e,n,r){this.r=+t,this.g=+e,this.b=+n,this.opacity=+r;}function or(){return "#"+cr(this.r)+cr(this.g)+cr(this.b)}function sr(){var t=this.opacity;return (1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(1===t?")":", "+t+")")}function cr(t){return ((t=Math.max(0,Math.min(255,Math.round(t)||0)))<16?"0":"")+t.toString(16)}function lr(t,e,n,r){return r<=0?t=e=n=NaN:n<=0||n>=1?t=e=NaN:e<=0&&(t=NaN),new fr(t,e,n,r)}function ur(t){if(t instanceof fr)return new fr(t.h,t.s,t.l,t.opacity);if(t instanceof Pn||(t=tr(t)),!t)return new fr;if(t instanceof fr)return t;var e=(t=t.rgb()).r/255,n=t.g/255,r=t.b/255,i=Math.min(e,n,r),a=Math.max(e,n,r),o=NaN,s=a-i,c=(a+i)/2;return s?(o=e===a?(n-r)/s+6*(n<r):n===a?(r-e)/s+2:(e-n)/s+4,s/=c<.5?a+i:2-a-i,o*=60):s=c>0&&c<1?0:o,new fr(o,s,c,t.opacity)}function hr(t,e,n,r){return 1===arguments.length?ur(t):new fr(t,e,n,null==r?1:r)}function fr(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r;}function dr(t,e,n){return 255*(t<60?e+(n-e)*t/60:t<180?n:t<240?e+(n-e)*(240-t)/60:e)}function pr(t,e,n,r,i){var a=t*t,o=a*t;return ((1-3*t+3*a-o)*e+(4-6*a+3*o)*n+(1+3*t+3*a-3*o)*r+o*i)/6}function gr(t){var e=t.length-1;return function(n){var r=n<=0?n=0:n>=1?(n=1,e-1):Math.floor(n*e),i=t[r],a=t[r+1],o=r>0?t[r-1]:2*i-a,s=r<e-1?t[r+2]:2*a-i;return pr((n-r/e)*e,o,i,a,s)}}function yr(t){var e=t.length;return function(n){var r=Math.floor(((n%=1)<0?++n:n)*e),i=t[(r+e-1)%e],a=t[r%e],o=t[(r+1)%e],s=t[(r+2)%e];return pr((n-r/e)*e,i,a,o,s)}}Fn(Pn,tr,{copy:function(t){return Object.assign(new this.constructor,this,t)},displayable:function(){return this.rgb().displayable()},hex:Kn,formatHex:Kn,formatHsl:function(){return ur(this).formatHsl()},formatRgb:Jn,toString:Jn}),Fn(ar,ir,Rn(Pn,{brighter:function(t){return t=null==t?zn:Math.pow(zn,t),new ar(this.r*t,this.g*t,this.b*t,this.opacity)},darker:function(t){return t=null==t?jn:Math.pow(jn,t),new ar(this.r*t,this.g*t,this.b*t,this.opacity)},rgb:function(){return this},displayable:function(){return -.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:or,formatHex:or,formatRgb:sr,toString:sr})),Fn(fr,hr,Rn(Pn,{brighter:function(t){return t=null==t?zn:Math.pow(zn,t),new fr(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?jn:Math.pow(jn,t),new fr(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=this.h%360+360*(this.h<0),e=isNaN(t)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*e,i=2*n-r;return new ar(dr(t>=240?t-240:t+120,i,r),dr(t,i,r),dr(t<120?t+240:t-120,i,r),this.opacity)},displayable:function(){return (0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl:function(){var t=this.opacity;return (1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"hsl(":"hsla(")+(this.h||0)+", "+100*(this.s||0)+"%, "+100*(this.l||0)+"%"+(1===t?")":", "+t+")")}}));const mr=t=>()=>t;function br(t,e){return function(n){return t+n*e}}function vr(t,e){var n=e-t;return n?br(t,n>180||n<-180?n-360*Math.round(n/360):n):mr(isNaN(t)?e:t)}function _r(t,e){var n=e-t;return n?br(t,n):mr(isNaN(t)?e:t)}const xr=function t(e){var n=function(t){return 1==(t=+t)?_r:function(e,n){return n-e?function(t,e,n){return t=Math.pow(t,n),e=Math.pow(e,n)-t,n=1/n,function(r){return Math.pow(t+r*e,n)}}(e,n,t):mr(isNaN(e)?n:e)}}(e);function r(t,e){var r=n((t=ir(t)).r,(e=ir(e)).r),i=n(t.g,e.g),a=n(t.b,e.b),o=_r(t.opacity,e.opacity);return function(e){return t.r=r(e),t.g=i(e),t.b=a(e),t.opacity=o(e),t+""}}return r.gamma=t,r}(1);function kr(t){return function(e){var n,r,i=e.length,a=new Array(i),o=new Array(i),s=new Array(i);for(n=0;n<i;++n)r=ir(e[n]),a[n]=r.r||0,o[n]=r.g||0,s[n]=r.b||0;return a=t(a),o=t(o),s=t(s),r.opacity=1,function(t){return r.r=a(t),r.g=o(t),r.b=s(t),r+""}}}var wr=kr(gr),Tr=kr(yr);function Er(t,e){e||(e=[]);var n,r=t?Math.min(e.length,t.length):0,i=e.slice();return function(a){for(n=0;n<r;++n)i[n]=t[n]*(1-a)+e[n]*a;return i}}function Cr(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function Sr(t,e){return (Cr(e)?Er:Ar)(t,e)}function Ar(t,e){var n,r=e?e.length:0,i=t?Math.min(r,t.length):0,a=new Array(i),o=new Array(r);for(n=0;n<i;++n)a[n]=Ir(t[n],e[n]);for(;n<r;++n)o[n]=e[n];return function(t){for(n=0;n<i;++n)o[n]=a[n](t);return o}}function Mr(t,e){var n=new Date;return t=+t,e=+e,function(r){return n.setTime(t*(1-r)+e*r),n}}function Nr(t,e){return t=+t,e=+e,function(n){return t*(1-n)+e*n}}function Or(t,e){var n,r={},i={};for(n in null!==t&&"object"==typeof t||(t={}),null!==e&&"object"==typeof e||(e={}),e)n in t?r[n]=Ir(t[n],e[n]):i[n]=e[n];return function(t){for(n in r)i[n]=r[n](t);return i}}var Dr=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Br=new RegExp(Dr.source,"g");function Lr(t,e){var n,r,i,a=Dr.lastIndex=Br.lastIndex=0,o=-1,s=[],c=[];for(t+="",e+="";(n=Dr.exec(t))&&(r=Br.exec(e));)(i=r.index)>a&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(n=n[0])===(r=r[0])?s[o]?s[o]+=r:s[++o]=r:(s[++o]=null,c.push({i:o,x:Nr(n,r)})),a=Br.lastIndex;return a<e.length&&(i=e.slice(a),s[o]?s[o]+=i:s[++o]=i),s.length<2?c[0]?function(t){return function(e){return t(e)+""}}(c[0].x):function(t){return function(){return t}}(e):(e=c.length,function(t){for(var n,r=0;r<e;++r)s[(n=c[r]).i]=n.x(t);return s.join("")})}function Ir(t,e){var n,r=typeof e;return null==e||"boolean"===r?mr(e):("number"===r?Nr:"string"===r?(n=tr(e))?(e=n,xr):Lr:e instanceof tr?xr:e instanceof Date?Mr:Cr(e)?Er:Array.isArray(e)?Ar:"function"!=typeof e.valueOf&&"function"!=typeof e.toString||isNaN(e)?Or:Nr)(t,e)}function Fr(t){let e;for(;e=t.sourceEvent;)t=e;return t}function Rr(t,e){if(t=Fr(t),void 0===e&&(e=t.currentTarget),e){var n=e.ownerSVGElement||e;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=t.clientX,r.y=t.clientY,[(r=r.matrixTransform(e.getScreenCTM().inverse())).x,r.y]}if(e.getBoundingClientRect){var i=e.getBoundingClientRect();return [t.clientX-i.left-e.clientLeft,t.clientY-i.top-e.clientTop]}}return [t.pageX,t.pageY]}var Pr,jr,zr=0,Yr=0,Ur=0,$r=0,Wr=0,qr=0,Hr="object"==typeof performance&&performance.now?performance:Date,Vr="object"==typeof window&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(t){setTimeout(t,17);};function Gr(){return Wr||(Vr(Xr),Wr=Hr.now()+qr)}function Xr(){Wr=0;}function Zr(){this._call=this._time=this._next=null;}function Qr(t,e,n){var r=new Zr;return r.restart(t,e,n),r}function Kr(){Gr(),++zr;for(var t,e=Pr;e;)(t=Wr-e._time)>=0&&e._call.call(void 0,t),e=e._next;--zr;}function Jr(){Wr=($r=Hr.now())+qr,zr=Yr=0;try{Kr();}finally{zr=0,function(){for(var t,e,n=Pr,r=1/0;n;)n._call?(r>n._time&&(r=n._time),t=n,n=n._next):(e=n._next,n._next=null,n=t?t._next=e:Pr=e);jr=t,ei(r);}(),Wr=0;}}function ti(){var t=Hr.now(),e=t-$r;e>1e3&&(qr-=e,$r=t);}function ei(t){zr||(Yr&&(Yr=clearTimeout(Yr)),t-Wr>24?(t<1/0&&(Yr=setTimeout(Jr,t-Hr.now()-qr)),Ur&&(Ur=clearInterval(Ur))):(Ur||($r=Hr.now(),Ur=setInterval(ti,1e3)),zr=1,Vr(Jr)));}function ni(t,e,n){var r=new Zr;return e=null==e?0:+e,r.restart((n=>{r.stop(),t(n+e);}),e,n),r}Zr.prototype=Qr.prototype={constructor:Zr,restart:function(t,e,n){if("function"!=typeof t)throw new TypeError("callback is not a function");n=(null==n?Gr():+n)+(null==e?0:+e),this._next||jr===this||(jr?jr._next=this:Pr=this,jr=this),this._call=t,this._time=n,ei();},stop:function(){this._call&&(this._call=null,this._time=1/0,ei());}};var ri=fe("start","end","cancel","interrupt"),ii=[];function ai(t,e,n,r,i,a){var o=t.__transition;if(o){if(n in o)return}else t.__transition={};!function(t,e,n){var r,i=t.__transition;function a(c){var l,u,h,f;if(1!==n.state)return s();for(l in i)if((f=i[l]).name===n.name){if(3===f.state)return ni(a);4===f.state?(f.state=6,f.timer.stop(),f.on.call("interrupt",t,t.__data__,f.index,f.group),delete i[l]):+l<e&&(f.state=6,f.timer.stop(),f.on.call("cancel",t,t.__data__,f.index,f.group),delete i[l]);}if(ni((function(){3===n.state&&(n.state=4,n.timer.restart(o,n.delay,n.time),o(c));})),n.state=2,n.on.call("start",t,t.__data__,n.index,n.group),2===n.state){for(n.state=3,r=new Array(h=n.tween.length),l=0,u=-1;l<h;++l)(f=n.tween[l].value.call(t,t.__data__,n.index,n.group))&&(r[++u]=f);r.length=u+1;}}function o(e){for(var i=e<n.duration?n.ease.call(null,e/n.duration):(n.timer.restart(s),n.state=5,1),a=-1,o=r.length;++a<o;)r[a].call(t,i);5===n.state&&(n.on.call("end",t,t.__data__,n.index,n.group),s());}function s(){for(var r in n.state=6,n.timer.stop(),delete i[e],i)return;delete t.__transition;}i[e]=n,n.timer=Qr((function(t){n.state=1,n.timer.restart(a,n.delay,n.time),n.delay<=t&&a(t-n.delay);}),0,n.time);}(t,n,{name:e,index:r,group:i,on:ri,tween:ii,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:0});}function oi(t,e){var n=ci(t,e);if(n.state>0)throw new Error("too late; already scheduled");return n}function si(t,e){var n=ci(t,e);if(n.state>3)throw new Error("too late; already running");return n}function ci(t,e){var n=t.__transition;if(!n||!(n=n[e]))throw new Error("transition not found");return n}function li(t,e){var n,r,i,a=t.__transition,o=!0;if(a){for(i in e=null==e?null:e+"",a)(n=a[i]).name===e?(r=n.state>2&&n.state<5,n.state=6,n.timer.stop(),n.on.call(r?"interrupt":"cancel",t,t.__data__,n.index,n.group),delete a[i]):o=!1;o&&delete t.__transition;}}var ui,hi=180/Math.PI,fi={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function di(t,e,n,r,i,a){var o,s,c;return (o=Math.sqrt(t*t+e*e))&&(t/=o,e/=o),(c=t*n+e*r)&&(n-=t*c,r-=e*c),(s=Math.sqrt(n*n+r*r))&&(n/=s,r/=s,c/=s),t*r<e*n&&(t=-t,e=-e,c=-c,o=-o),{translateX:i,translateY:a,rotate:Math.atan2(e,t)*hi,skewX:Math.atan(c)*hi,scaleX:o,scaleY:s}}function pi(t,e,n,r){function i(t){return t.length?t.pop()+" ":""}return function(a,o){var s=[],c=[];return a=t(a),o=t(o),function(t,r,i,a,o,s){if(t!==i||r!==a){var c=o.push("translate(",null,e,null,n);s.push({i:c-4,x:Nr(t,i)},{i:c-2,x:Nr(r,a)});}else (i||a)&&o.push("translate("+i+e+a+n);}(a.translateX,a.translateY,o.translateX,o.translateY,s,c),function(t,e,n,a){t!==e?(t-e>180?e+=360:e-t>180&&(t+=360),a.push({i:n.push(i(n)+"rotate(",null,r)-2,x:Nr(t,e)})):e&&n.push(i(n)+"rotate("+e+r);}(a.rotate,o.rotate,s,c),function(t,e,n,a){t!==e?a.push({i:n.push(i(n)+"skewX(",null,r)-2,x:Nr(t,e)}):e&&n.push(i(n)+"skewX("+e+r);}(a.skewX,o.skewX,s,c),function(t,e,n,r,a,o){if(t!==n||e!==r){var s=a.push(i(a)+"scale(",null,",",null,")");o.push({i:s-4,x:Nr(t,n)},{i:s-2,x:Nr(e,r)});}else 1===n&&1===r||a.push(i(a)+"scale("+n+","+r+")");}(a.scaleX,a.scaleY,o.scaleX,o.scaleY,s,c),a=o=null,function(t){for(var e,n=-1,r=c.length;++n<r;)s[(e=c[n]).i]=e.x(t);return s.join("")}}}var gi=pi((function(t){const e=new("function"==typeof DOMMatrix?DOMMatrix:WebKitCSSMatrix)(t+"");return e.isIdentity?fi:di(e.a,e.b,e.c,e.d,e.e,e.f)}),"px, ","px)","deg)"),yi=pi((function(t){return null==t?fi:(ui||(ui=document.createElementNS("http://www.w3.org/2000/svg","g")),ui.setAttribute("transform",t),(t=ui.transform.baseVal.consolidate())?di((t=t.matrix).a,t.b,t.c,t.d,t.e,t.f):fi)}),", ",")",")");function mi(t,e){var n,r;return function(){var i=si(this,t),a=i.tween;if(a!==n)for(var o=0,s=(r=n=a).length;o<s;++o)if(r[o].name===e){(r=r.slice()).splice(o,1);break}i.tween=r;}}function bi(t,e,n){var r,i;if("function"!=typeof n)throw new Error;return function(){var a=si(this,t),o=a.tween;if(o!==r){i=(r=o).slice();for(var s={name:e,value:n},c=0,l=i.length;c<l;++c)if(i[c].name===e){i[c]=s;break}c===l&&i.push(s);}a.tween=i;}}function vi(t,e,n){var r=t._id;return t.each((function(){var t=si(this,r);(t.value||(t.value={}))[e]=n.apply(this,arguments);})),function(t){return ci(t,r).value[e]}}function _i(t,e){var n;return ("number"==typeof e?Nr:e instanceof tr?xr:(n=tr(e))?(e=n,xr):Lr)(t,e)}function xi(t){return function(){this.removeAttribute(t);}}function ki(t){return function(){this.removeAttributeNS(t.space,t.local);}}function wi(t,e,n){var r,i,a=n+"";return function(){var o=this.getAttribute(t);return o===a?null:o===r?i:i=e(r=o,n)}}function Ti(t,e,n){var r,i,a=n+"";return function(){var o=this.getAttributeNS(t.space,t.local);return o===a?null:o===r?i:i=e(r=o,n)}}function Ei(t,e,n){var r,i,a;return function(){var o,s,c=n(this);if(null!=c)return (o=this.getAttribute(t))===(s=c+"")?null:o===r&&s===i?a:(i=s,a=e(r=o,c));this.removeAttribute(t);}}function Ci(t,e,n){var r,i,a;return function(){var o,s,c=n(this);if(null!=c)return (o=this.getAttributeNS(t.space,t.local))===(s=c+"")?null:o===r&&s===i?a:(i=s,a=e(r=o,c));this.removeAttributeNS(t.space,t.local);}}function Si(t,e){return function(n){this.setAttribute(t,e.call(this,n));}}function Ai(t,e){return function(n){this.setAttributeNS(t.space,t.local,e.call(this,n));}}function Mi(t,e){var n,r;function i(){var i=e.apply(this,arguments);return i!==r&&(n=(r=i)&&Ai(t,i)),n}return i._value=e,i}function Ni(t,e){var n,r;function i(){var i=e.apply(this,arguments);return i!==r&&(n=(r=i)&&Si(t,i)),n}return i._value=e,i}function Oi(t,e){return function(){oi(this,t).delay=+e.apply(this,arguments);}}function Di(t,e){return e=+e,function(){oi(this,t).delay=e;}}function Bi(t,e){return function(){si(this,t).duration=+e.apply(this,arguments);}}function Li(t,e){return e=+e,function(){si(this,t).duration=e;}}function Ii(t,e){if("function"!=typeof e)throw new Error;return function(){si(this,t).ease=e;}}function Fi(t,e,n){var r,i,a=function(t){return (t+"").trim().split(/^|\s+/).every((function(t){var e=t.indexOf(".");return e>=0&&(t=t.slice(0,e)),!t||"start"===t}))}(e)?oi:si;return function(){var o=a(this,t),s=o.on;s!==r&&(i=(r=s).copy()).on(e,n),o.on=i;}}var Ri=An.prototype.constructor;function Pi(t){return function(){this.style.removeProperty(t);}}function ji(t,e,n){return function(r){this.style.setProperty(t,e.call(this,r),n);}}function zi(t,e,n){var r,i;function a(){var a=e.apply(this,arguments);return a!==i&&(r=(i=a)&&ji(t,a,n)),r}return a._value=e,a}function Yi(t){return function(e){this.textContent=t.call(this,e);}}function Ui(t){var e,n;function r(){var r=t.apply(this,arguments);return r!==n&&(e=(n=r)&&Yi(r)),e}return r._value=t,r}var $i=0;function Wi(t,e,n,r){this._groups=t,this._parents=e,this._name=n,this._id=r;}function qi(t){return An().transition(t)}function Hi(){return ++$i}var Vi=An.prototype;function Gi(t){return t*t*t}function Xi(t){return --t*t*t+1}function Zi(t){return ((t*=2)<=1?t*t*t:(t-=2)*t*t+2)/2}Wi.prototype=qi.prototype={constructor:Wi,select:function(t){var e=this._name,n=this._id;"function"!=typeof t&&(t=pe(t));for(var r=this._groups,i=r.length,a=new Array(i),o=0;o<i;++o)for(var s,c,l=r[o],u=l.length,h=a[o]=new Array(u),f=0;f<u;++f)(s=l[f])&&(c=t.call(s,s.__data__,f,l))&&("__data__"in s&&(c.__data__=s.__data__),h[f]=c,ai(h[f],e,n,f,h,ci(s,n)));return new Wi(a,this._parents,e,n)},selectAll:function(t){var e=this._name,n=this._id;"function"!=typeof t&&(t=me(t));for(var r=this._groups,i=r.length,a=[],o=[],s=0;s<i;++s)for(var c,l=r[s],u=l.length,h=0;h<u;++h)if(c=l[h]){for(var f,d=t.call(c,c.__data__,h,l),p=ci(c,n),g=0,y=d.length;g<y;++g)(f=d[g])&&ai(f,e,n,g,d,p);a.push(d),o.push(c);}return new Wi(a,o,e,n)},selectChild:Vi.selectChild,selectChildren:Vi.selectChildren,filter:function(t){"function"!=typeof t&&(t=be(t));for(var e=this._groups,n=e.length,r=new Array(n),i=0;i<n;++i)for(var a,o=e[i],s=o.length,c=r[i]=[],l=0;l<s;++l)(a=o[l])&&t.call(a,a.__data__,l,o)&&c.push(a);return new Wi(r,this._parents,this._name,this._id)},merge:function(t){if(t._id!==this._id)throw new Error;for(var e=this._groups,n=t._groups,r=e.length,i=n.length,a=Math.min(r,i),o=new Array(r),s=0;s<a;++s)for(var c,l=e[s],u=n[s],h=l.length,f=o[s]=new Array(h),d=0;d<h;++d)(c=l[d]||u[d])&&(f[d]=c);for(;s<r;++s)o[s]=e[s];return new Wi(o,this._parents,this._name,this._id)},selection:function(){return new Ri(this._groups,this._parents)},transition:function(){for(var t=this._name,e=this._id,n=Hi(),r=this._groups,i=r.length,a=0;a<i;++a)for(var o,s=r[a],c=s.length,l=0;l<c;++l)if(o=s[l]){var u=ci(o,e);ai(o,t,n,l,s,{time:u.time+u.delay+u.duration,delay:0,duration:u.duration,ease:u.ease});}return new Wi(r,this._parents,t,n)},call:Vi.call,nodes:Vi.nodes,node:Vi.node,size:Vi.size,empty:Vi.empty,each:Vi.each,on:function(t,e){var n=this._id;return arguments.length<2?ci(this.node(),n).on.on(t):this.each(Fi(n,t,e))},attr:function(t,e){var n=Le(t),r="transform"===n?yi:_i;return this.attrTween(t,"function"==typeof e?(n.local?Ci:Ei)(n,r,vi(this,"attr."+t,e)):null==e?(n.local?ki:xi)(n):(n.local?Ti:wi)(n,r,e))},attrTween:function(t,e){var n="attr."+t;if(arguments.length<2)return (n=this.tween(n))&&n._value;if(null==e)return this.tween(n,null);if("function"!=typeof e)throw new Error;var r=Le(t);return this.tween(n,(r.local?Mi:Ni)(r,e))},style:function(t,e,n){var r="transform"==(t+="")?gi:_i;return null==e?this.styleTween(t,function(t,e){var n,r,i;return function(){var a=qe(this,t),o=(this.style.removeProperty(t),qe(this,t));return a===o?null:a===n&&o===r?i:i=e(n=a,r=o)}}(t,r)).on("end.style."+t,Pi(t)):"function"==typeof e?this.styleTween(t,function(t,e,n){var r,i,a;return function(){var o=qe(this,t),s=n(this),c=s+"";return null==s&&(this.style.removeProperty(t),c=s=qe(this,t)),o===c?null:o===r&&c===i?a:(i=c,a=e(r=o,s))}}(t,r,vi(this,"style."+t,e))).each(function(t,e){var n,r,i,a,o="style."+e,s="end."+o;return function(){var c=si(this,t),l=c.on,u=null==c.value[o]?a||(a=Pi(e)):void 0;l===n&&i===u||(r=(n=l).copy()).on(s,i=u),c.on=r;}}(this._id,t)):this.styleTween(t,function(t,e,n){var r,i,a=n+"";return function(){var o=qe(this,t);return o===a?null:o===r?i:i=e(r=o,n)}}(t,r,e),n).on("end.style."+t,null)},styleTween:function(t,e,n){var r="style."+(t+="");if(arguments.length<2)return (r=this.tween(r))&&r._value;if(null==e)return this.tween(r,null);if("function"!=typeof e)throw new Error;return this.tween(r,zi(t,e,null==n?"":n))},text:function(t){return this.tween("text","function"==typeof t?function(t){return function(){var e=t(this);this.textContent=null==e?"":e;}}(vi(this,"text",t)):function(t){return function(){this.textContent=t;}}(null==t?"":t+""))},textTween:function(t){var e="text";if(arguments.length<1)return (e=this.tween(e))&&e._value;if(null==t)return this.tween(e,null);if("function"!=typeof t)throw new Error;return this.tween(e,Ui(t))},remove:function(){return this.on("end.remove",function(t){return function(){var e=this.parentNode;for(var n in this.__transition)if(+n!==t)return;e&&e.removeChild(this);}}(this._id))},tween:function(t,e){var n=this._id;if(t+="",arguments.length<2){for(var r,i=ci(this.node(),n).tween,a=0,o=i.length;a<o;++a)if((r=i[a]).name===t)return r.value;return null}return this.each((null==e?mi:bi)(n,t,e))},delay:function(t){var e=this._id;return arguments.length?this.each(("function"==typeof t?Oi:Di)(e,t)):ci(this.node(),e).delay},duration:function(t){var e=this._id;return arguments.length?this.each(("function"==typeof t?Bi:Li)(e,t)):ci(this.node(),e).duration},ease:function(t){var e=this._id;return arguments.length?this.each(Ii(e,t)):ci(this.node(),e).ease},easeVarying:function(t){if("function"!=typeof t)throw new Error;return this.each(function(t,e){return function(){var n=e.apply(this,arguments);if("function"!=typeof n)throw new Error;si(this,t).ease=n;}}(this._id,t))},end:function(){var t,e,n=this,r=n._id,i=n.size();return new Promise((function(a,o){var s={value:o},c={value:function(){0==--i&&a();}};n.each((function(){var n=si(this,r),i=n.on;i!==t&&((e=(t=i).copy())._.cancel.push(s),e._.interrupt.push(s),e._.end.push(c)),n.on=e;})),0===i&&a();}))},[Symbol.iterator]:Vi[Symbol.iterator]};var Qi={time:null,delay:0,duration:250,ease:Zi};function Ki(t,e){for(var n;!(n=t.__transition)||!(n=n[e]);)if(!(t=t.parentNode))throw new Error(`transition ${e} not found`);return n}An.prototype.interrupt=function(t){return this.each((function(){li(this,t);}))},An.prototype.transition=function(t){var e,n;t instanceof Wi?(e=t._id,t=t._name):(e=Hi(),(n=Qi).time=Gr(),t=null==t?null:t+"");for(var r=this._groups,i=r.length,a=0;a<i;++a)for(var o,s=r[a],c=s.length,l=0;l<c;++l)(o=s[l])&&ai(o,t,e,l,s,n||Ki(o,e));return new Wi(r,this._parents,t,e)};var Ji=[null];function ta(t,e){var n,r,i=t.__transition;if(i)for(r in e=null==e?null:e+"",i)if((n=i[r]).state>1&&n.name===e)return new Wi([[t]],Ji,e,+r);return null}const ea=t=>()=>t;function na(t,{sourceEvent:e,target:n,selection:r,mode:i,dispatch:a}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:e,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},selection:{value:r,enumerable:!0,configurable:!0},mode:{value:i,enumerable:!0,configurable:!0},_:{value:a}});}function ra(t){t.stopImmediatePropagation();}function ia(t){t.preventDefault(),t.stopImmediatePropagation();}var aa={name:"drag"},oa={name:"space"},sa={name:"handle"},ca={name:"center"};const{abs:la,max:ua,min:ha}=Math;function fa(t){return [+t[0],+t[1]]}function da(t){return [fa(t[0]),fa(t[1])]}var pa={name:"x",handles:["w","e"].map(ka),input:function(t,e){return null==t?null:[[+t[0],e[0][1]],[+t[1],e[1][1]]]},output:function(t){return t&&[t[0][0],t[1][0]]}},ga={name:"y",handles:["n","s"].map(ka),input:function(t,e){return null==t?null:[[e[0][0],+t[0]],[e[1][0],+t[1]]]},output:function(t){return t&&[t[0][1],t[1][1]]}},ya={name:"xy",handles:["n","w","e","s","nw","ne","sw","se"].map(ka),input:function(t){return null==t?null:da(t)},output:function(t){return t}},ma={overlay:"crosshair",selection:"move",n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},ba={e:"w",w:"e",nw:"ne",ne:"nw",se:"sw",sw:"se"},va={n:"s",s:"n",nw:"sw",ne:"se",se:"ne",sw:"nw"},_a={overlay:1,selection:1,n:null,e:1,s:null,w:-1,nw:-1,ne:1,se:1,sw:-1},xa={overlay:1,selection:1,n:-1,e:null,s:1,w:null,nw:-1,ne:-1,se:1,sw:1};function ka(t){return {type:t}}function wa(t){return !t.ctrlKey&&!t.button}function Ta(){var t=this.ownerSVGElement||this;return t.hasAttribute("viewBox")?[[(t=t.viewBox.baseVal).x,t.y],[t.x+t.width,t.y+t.height]]:[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]}function Ea(){return navigator.maxTouchPoints||"ontouchstart"in this}function Ca(t){for(;!t.__brush;)if(!(t=t.parentNode))return;return t.__brush}function Sa(t){return t[0][0]===t[1][0]||t[0][1]===t[1][1]}function Aa(t){var e=t.__brush;return e?e.dim.output(e.selection):null}function Ma(){return Da(pa)}function Na(){return Da(ga)}function Oa(){return Da(ya)}function Da(t){var e,n=Ta,r=wa,i=Ea,a=!0,o=fe("start","brush","end"),s=6;function c(e){var n=e.property("__brush",g).selectAll(".overlay").data([ka("overlay")]);n.enter().append("rect").attr("class","overlay").attr("pointer-events","all").attr("cursor",ma.overlay).merge(n).each((function(){var t=Ca(this).extent;Mn(this).attr("x",t[0][0]).attr("y",t[0][1]).attr("width",t[1][0]-t[0][0]).attr("height",t[1][1]-t[0][1]);})),e.selectAll(".selection").data([ka("selection")]).enter().append("rect").attr("class","selection").attr("cursor",ma.selection).attr("fill","#777").attr("fill-opacity",.3).attr("stroke","#fff").attr("shape-rendering","crispEdges");var r=e.selectAll(".handle").data(t.handles,(function(t){return t.type}));r.exit().remove(),r.enter().append("rect").attr("class",(function(t){return "handle handle--"+t.type})).attr("cursor",(function(t){return ma[t.type]})),e.each(l).attr("fill","none").attr("pointer-events","all").on("mousedown.brush",f).filter(i).on("touchstart.brush",f).on("touchmove.brush",d).on("touchend.brush touchcancel.brush",p).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)");}function l(){var t=Mn(this),e=Ca(this).selection;e?(t.selectAll(".selection").style("display",null).attr("x",e[0][0]).attr("y",e[0][1]).attr("width",e[1][0]-e[0][0]).attr("height",e[1][1]-e[0][1]),t.selectAll(".handle").style("display",null).attr("x",(function(t){return "e"===t.type[t.type.length-1]?e[1][0]-s/2:e[0][0]-s/2})).attr("y",(function(t){return "s"===t.type[0]?e[1][1]-s/2:e[0][1]-s/2})).attr("width",(function(t){return "n"===t.type||"s"===t.type?e[1][0]-e[0][0]+s:s})).attr("height",(function(t){return "e"===t.type||"w"===t.type?e[1][1]-e[0][1]+s:s}))):t.selectAll(".selection,.handle").style("display","none").attr("x",null).attr("y",null).attr("width",null).attr("height",null);}function u(t,e,n){var r=t.__brush.emitter;return !r||n&&r.clean?new h(t,e,n):r}function h(t,e,n){this.that=t,this.args=e,this.state=t.__brush,this.active=0,this.clean=n;}function f(n){if((!e||n.touches)&&r.apply(this,arguments)){var i,o,s,c,h,f,d,p,g,y,m,b=this,v=n.target.__data__.type,_="selection"===(a&&n.metaKey?v="overlay":v)?aa:a&&n.altKey?ca:sa,x=t===ga?null:_a[v],k=t===pa?null:xa[v],w=Ca(b),T=w.extent,E=w.selection,C=T[0][0],S=T[0][1],A=T[1][0],M=T[1][1],N=0,O=0,D=x&&k&&a&&n.shiftKey,B=Array.from(n.touches||[n],(t=>{const e=t.identifier;return (t=Rr(t,b)).point0=t.slice(),t.identifier=e,t}));li(b);var L=u(b,arguments,!0).beforestart();if("overlay"===v){E&&(g=!0);const e=[B[0],B[1]||B[0]];w.selection=E=[[i=t===ga?C:ha(e[0][0],e[1][0]),s=t===pa?S:ha(e[0][1],e[1][1])],[h=t===ga?A:ua(e[0][0],e[1][0]),d=t===pa?M:ua(e[0][1],e[1][1])]],B.length>1&&j(n);}else i=E[0][0],s=E[0][1],h=E[1][0],d=E[1][1];o=i,c=s,f=h,p=d;var I=Mn(b).attr("pointer-events","none"),F=I.selectAll(".overlay").attr("cursor",ma[v]);if(n.touches)L.moved=P,L.ended=z;else {var R=Mn(n.view).on("mousemove.brush",P,!0).on("mouseup.brush",z,!0);a&&R.on("keydown.brush",Y,!0).on("keyup.brush",U,!0),Ln(n.view);}l.call(b),L.start(n,_.name);}function P(t){for(const e of t.changedTouches||[t])for(const t of B)t.identifier===e.identifier&&(t.cur=Rr(e,b));if(D&&!y&&!m&&1===B.length){const t=B[0];la(t.cur[0]-t[0])>la(t.cur[1]-t[1])?m=!0:y=!0;}for(const t of B)t.cur&&(t[0]=t.cur[0],t[1]=t.cur[1]);g=!0,ia(t),j(t);}function j(t){const e=B[0],n=e.point0;var r;switch(N=e[0]-n[0],O=e[1]-n[1],_){case oa:case aa:x&&(N=ua(C-i,ha(A-h,N)),o=i+N,f=h+N),k&&(O=ua(S-s,ha(M-d,O)),c=s+O,p=d+O);break;case sa:B[1]?(x&&(o=ua(C,ha(A,B[0][0])),f=ua(C,ha(A,B[1][0])),x=1),k&&(c=ua(S,ha(M,B[0][1])),p=ua(S,ha(M,B[1][1])),k=1)):(x<0?(N=ua(C-i,ha(A-i,N)),o=i+N,f=h):x>0&&(N=ua(C-h,ha(A-h,N)),o=i,f=h+N),k<0?(O=ua(S-s,ha(M-s,O)),c=s+O,p=d):k>0&&(O=ua(S-d,ha(M-d,O)),c=s,p=d+O));break;case ca:x&&(o=ua(C,ha(A,i-N*x)),f=ua(C,ha(A,h+N*x))),k&&(c=ua(S,ha(M,s-O*k)),p=ua(S,ha(M,d+O*k)));}f<o&&(x*=-1,r=i,i=h,h=r,r=o,o=f,f=r,v in ba&&F.attr("cursor",ma[v=ba[v]])),p<c&&(k*=-1,r=s,s=d,d=r,r=c,c=p,p=r,v in va&&F.attr("cursor",ma[v=va[v]])),w.selection&&(E=w.selection),y&&(o=E[0][0],f=E[1][0]),m&&(c=E[0][1],p=E[1][1]),E[0][0]===o&&E[0][1]===c&&E[1][0]===f&&E[1][1]===p||(w.selection=[[o,c],[f,p]],l.call(b),L.brush(t,_.name));}function z(t){if(ra(t),t.touches){if(t.touches.length)return;e&&clearTimeout(e),e=setTimeout((function(){e=null;}),500);}else In(t.view,g),R.on("keydown.brush keyup.brush mousemove.brush mouseup.brush",null);I.attr("pointer-events","all"),F.attr("cursor",ma.overlay),w.selection&&(E=w.selection),Sa(E)&&(w.selection=null,l.call(b)),L.end(t,_.name);}function Y(t){switch(t.keyCode){case 16:D=x&&k;break;case 18:_===sa&&(x&&(h=f-N*x,i=o+N*x),k&&(d=p-O*k,s=c+O*k),_=ca,j(t));break;case 32:_!==sa&&_!==ca||(x<0?h=f-N:x>0&&(i=o-N),k<0?d=p-O:k>0&&(s=c-O),_=oa,F.attr("cursor",ma.selection),j(t));break;default:return}ia(t);}function U(t){switch(t.keyCode){case 16:D&&(y=m=D=!1,j(t));break;case 18:_===ca&&(x<0?h=f:x>0&&(i=o),k<0?d=p:k>0&&(s=c),_=sa,j(t));break;case 32:_===oa&&(t.altKey?(x&&(h=f-N*x,i=o+N*x),k&&(d=p-O*k,s=c+O*k),_=ca):(x<0?h=f:x>0&&(i=o),k<0?d=p:k>0&&(s=c),_=sa),F.attr("cursor",ma[v]),j(t));break;default:return}ia(t);}}function d(t){u(this,arguments).moved(t);}function p(t){u(this,arguments).ended(t);}function g(){var e=this.__brush||{selection:null};return e.extent=da(n.apply(this,arguments)),e.dim=t,e}return c.move=function(e,n,r){e.tween?e.on("start.brush",(function(t){u(this,arguments).beforestart().start(t);})).on("interrupt.brush end.brush",(function(t){u(this,arguments).end(t);})).tween("brush",(function(){var e=this,r=e.__brush,i=u(e,arguments),a=r.selection,o=t.input("function"==typeof n?n.apply(this,arguments):n,r.extent),s=Ir(a,o);function c(t){r.selection=1===t&&null===o?null:s(t),l.call(e),i.brush();}return null!==a&&null!==o?c:c(1)})):e.each((function(){var e=this,i=arguments,a=e.__brush,o=t.input("function"==typeof n?n.apply(e,i):n,a.extent),s=u(e,i).beforestart();li(e),a.selection=null===o?null:o,l.call(e),s.start(r).brush(r).end(r);}));},c.clear=function(t,e){c.move(t,null,e);},h.prototype={beforestart:function(){return 1==++this.active&&(this.state.emitter=this,this.starting=!0),this},start:function(t,e){return this.starting?(this.starting=!1,this.emit("start",t,e)):this.emit("brush",t),this},brush:function(t,e){return this.emit("brush",t,e),this},end:function(t,e){return 0==--this.active&&(delete this.state.emitter,this.emit("end",t,e)),this},emit:function(e,n,r){var i=Mn(this.that).datum();o.call(e,this.that,new na(e,{sourceEvent:n,target:c,selection:t.output(this.state.selection),mode:r,dispatch:o}),i);}},c.extent=function(t){return arguments.length?(n="function"==typeof t?t:ea(da(t)),c):n},c.filter=function(t){return arguments.length?(r="function"==typeof t?t:ea(!!t),c):r},c.touchable=function(t){return arguments.length?(i="function"==typeof t?t:ea(!!t),c):i},c.handleSize=function(t){return arguments.length?(s=+t,c):s},c.keyModifiers=function(t){return arguments.length?(a=!!t,c):a},c.on=function(){var t=o.on.apply(o,arguments);return t===o?c:t},c}var Ba=Math.abs,La=Math.cos,Ia=Math.sin,Fa=Math.PI,Ra=Fa/2,Pa=2*Fa,ja=Math.max,za=1e-12;function Ya(t,e){return Array.from({length:e-t},((e,n)=>t+n))}function Ua(t){return function(e,n){return t(e.source.value+e.target.value,n.source.value+n.target.value)}}function $a(){return Ha(!1,!1)}function Wa(){return Ha(!1,!0)}function qa(){return Ha(!0,!1)}function Ha(t,e){var n=0,r=null,i=null,a=null;function o(o){var s,c=o.length,l=new Array(c),u=Ya(0,c),h=new Array(c*c),f=new Array(c),d=0;o=Float64Array.from({length:c*c},e?(t,e)=>o[e%c][e/c|0]:(t,e)=>o[e/c|0][e%c]);for(let e=0;e<c;++e){let n=0;for(let r=0;r<c;++r)n+=o[e*c+r]+t*o[r*c+e];d+=l[e]=n;}s=(d=ja(0,Pa-n*c)/d)?n:Pa/c;{let e=0;r&&u.sort(((t,e)=>r(l[t],l[e])));for(const n of u){const r=e;if(t){const t=Ya(1+~c,c).filter((t=>t<0?o[~t*c+n]:o[n*c+t]));i&&t.sort(((t,e)=>i(t<0?-o[~t*c+n]:o[n*c+t],e<0?-o[~e*c+n]:o[n*c+e])));for(const r of t)r<0?(h[~r*c+n]||(h[~r*c+n]={source:null,target:null})).target={index:n,startAngle:e,endAngle:e+=o[~r*c+n]*d,value:o[~r*c+n]}:(h[n*c+r]||(h[n*c+r]={source:null,target:null})).source={index:n,startAngle:e,endAngle:e+=o[n*c+r]*d,value:o[n*c+r]};f[n]={index:n,startAngle:r,endAngle:e,value:l[n]};}else {const t=Ya(0,c).filter((t=>o[n*c+t]||o[t*c+n]));i&&t.sort(((t,e)=>i(o[n*c+t],o[n*c+e])));for(const r of t){let t;if(n<r?(t=h[n*c+r]||(h[n*c+r]={source:null,target:null}),t.source={index:n,startAngle:e,endAngle:e+=o[n*c+r]*d,value:o[n*c+r]}):(t=h[r*c+n]||(h[r*c+n]={source:null,target:null}),t.target={index:n,startAngle:e,endAngle:e+=o[n*c+r]*d,value:o[n*c+r]},n===r&&(t.source=t.target)),t.source&&t.target&&t.source.value<t.target.value){const e=t.source;t.source=t.target,t.target=e;}}f[n]={index:n,startAngle:r,endAngle:e,value:l[n]};}e+=s;}}return (h=Object.values(h)).groups=f,a?h.sort(a):h}return o.padAngle=function(t){return arguments.length?(n=ja(0,t),o):n},o.sortGroups=function(t){return arguments.length?(r=t,o):r},o.sortSubgroups=function(t){return arguments.length?(i=t,o):i},o.sortChords=function(t){return arguments.length?(null==t?a=null:(a=Ua(t))._=t,o):a&&a._},o}const Va=Math.PI,Ga=2*Va,Xa=1e-6,Za=Ga-Xa;function Qa(){this._x0=this._y0=this._x1=this._y1=null,this._="";}function Ka(){return new Qa}Qa.prototype=Ka.prototype={constructor:Qa,moveTo:function(t,e){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+e);},closePath:function(){null!==this._x1&&(this._x1=this._x0,this._y1=this._y0,this._+="Z");},lineTo:function(t,e){this._+="L"+(this._x1=+t)+","+(this._y1=+e);},quadraticCurveTo:function(t,e,n,r){this._+="Q"+ +t+","+ +e+","+(this._x1=+n)+","+(this._y1=+r);},bezierCurveTo:function(t,e,n,r,i,a){this._+="C"+ +t+","+ +e+","+ +n+","+ +r+","+(this._x1=+i)+","+(this._y1=+a);},arcTo:function(t,e,n,r,i){t=+t,e=+e,n=+n,r=+r,i=+i;var a=this._x1,o=this._y1,s=n-t,c=r-e,l=a-t,u=o-e,h=l*l+u*u;if(i<0)throw new Error("negative radius: "+i);if(null===this._x1)this._+="M"+(this._x1=t)+","+(this._y1=e);else if(h>Xa)if(Math.abs(u*s-c*l)>Xa&&i){var f=n-a,d=r-o,p=s*s+c*c,g=f*f+d*d,y=Math.sqrt(p),m=Math.sqrt(h),b=i*Math.tan((Va-Math.acos((p+h-g)/(2*y*m)))/2),v=b/m,_=b/y;Math.abs(v-1)>Xa&&(this._+="L"+(t+v*l)+","+(e+v*u)),this._+="A"+i+","+i+",0,0,"+ +(u*f>l*d)+","+(this._x1=t+_*s)+","+(this._y1=e+_*c);}else this._+="L"+(this._x1=t)+","+(this._y1=e);},arc:function(t,e,n,r,i,a){t=+t,e=+e,a=!!a;var o=(n=+n)*Math.cos(r),s=n*Math.sin(r),c=t+o,l=e+s,u=1^a,h=a?r-i:i-r;if(n<0)throw new Error("negative radius: "+n);null===this._x1?this._+="M"+c+","+l:(Math.abs(this._x1-c)>Xa||Math.abs(this._y1-l)>Xa)&&(this._+="L"+c+","+l),n&&(h<0&&(h=h%Ga+Ga),h>Za?this._+="A"+n+","+n+",0,1,"+u+","+(t-o)+","+(e-s)+"A"+n+","+n+",0,1,"+u+","+(this._x1=c)+","+(this._y1=l):h>Xa&&(this._+="A"+n+","+n+",0,"+ +(h>=Va)+","+u+","+(this._x1=t+n*Math.cos(i))+","+(this._y1=e+n*Math.sin(i))));},rect:function(t,e,n,r){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+e)+"h"+ +n+"v"+ +r+"h"+-n+"Z";},toString:function(){return this._}};const Ja=Ka;var to=Array.prototype.slice;function eo(t){return function(){return t}}function no(t){return t.source}function ro(t){return t.target}function io(t){return t.radius}function ao(t){return t.startAngle}function oo(t){return t.endAngle}function so(){return 0}function co(){return 10}function lo(t){var e=no,n=ro,r=io,i=io,a=ao,o=oo,s=so,c=null;function l(){var l,u=e.apply(this,arguments),h=n.apply(this,arguments),f=s.apply(this,arguments)/2,d=to.call(arguments),p=+r.apply(this,(d[0]=u,d)),g=a.apply(this,d)-Ra,y=o.apply(this,d)-Ra,m=+i.apply(this,(d[0]=h,d)),b=a.apply(this,d)-Ra,v=o.apply(this,d)-Ra;if(c||(c=l=Ja()),f>za&&(Ba(y-g)>2*f+za?y>g?(g+=f,y-=f):(g-=f,y+=f):g=y=(g+y)/2,Ba(v-b)>2*f+za?v>b?(b+=f,v-=f):(b-=f,v+=f):b=v=(b+v)/2),c.moveTo(p*La(g),p*Ia(g)),c.arc(0,0,p,g,y),g!==b||y!==v)if(t){var _=+t.apply(this,arguments),x=m-_,k=(b+v)/2;c.quadraticCurveTo(0,0,x*La(b),x*Ia(b)),c.lineTo(m*La(k),m*Ia(k)),c.lineTo(x*La(v),x*Ia(v));}else c.quadraticCurveTo(0,0,m*La(b),m*Ia(b)),c.arc(0,0,m,b,v);if(c.quadraticCurveTo(0,0,p*La(g),p*Ia(g)),c.closePath(),l)return c=null,l+""||null}return t&&(l.headRadius=function(e){return arguments.length?(t="function"==typeof e?e:eo(+e),l):t}),l.radius=function(t){return arguments.length?(r=i="function"==typeof t?t:eo(+t),l):r},l.sourceRadius=function(t){return arguments.length?(r="function"==typeof t?t:eo(+t),l):r},l.targetRadius=function(t){return arguments.length?(i="function"==typeof t?t:eo(+t),l):i},l.startAngle=function(t){return arguments.length?(a="function"==typeof t?t:eo(+t),l):a},l.endAngle=function(t){return arguments.length?(o="function"==typeof t?t:eo(+t),l):o},l.padAngle=function(t){return arguments.length?(s="function"==typeof t?t:eo(+t),l):s},l.source=function(t){return arguments.length?(e=t,l):e},l.target=function(t){return arguments.length?(n=t,l):n},l.context=function(t){return arguments.length?(c=null==t?null:t,l):c},l}function uo(){return lo()}function ho(){return lo(co)}const fo=Math.PI/180,po=180/Math.PI,go=.96422,yo=.82521,mo=4/29,bo=6/29,vo=3*bo*bo;function _o(t){if(t instanceof wo)return new wo(t.l,t.a,t.b,t.opacity);if(t instanceof Oo)return Do(t);t instanceof ar||(t=rr(t));var e,n,r=So(t.r),i=So(t.g),a=So(t.b),o=To((.2225045*r+.7168786*i+.0606169*a)/1);return r===i&&i===a?e=n=o:(e=To((.4360747*r+.3850649*i+.1430804*a)/go),n=To((.0139322*r+.0971045*i+.7141733*a)/yo)),new wo(116*o-16,500*(e-o),200*(o-n),t.opacity)}function xo(t,e){return new wo(t,0,0,null==e?1:e)}function ko(t,e,n,r){return 1===arguments.length?_o(t):new wo(t,e,n,null==r?1:r)}function wo(t,e,n,r){this.l=+t,this.a=+e,this.b=+n,this.opacity=+r;}function To(t){return t>.008856451679035631?Math.pow(t,1/3):t/vo+mo}function Eo(t){return t>bo?t*t*t:vo*(t-mo)}function Co(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function So(t){return (t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Ao(t){if(t instanceof Oo)return new Oo(t.h,t.c,t.l,t.opacity);if(t instanceof wo||(t=_o(t)),0===t.a&&0===t.b)return new Oo(NaN,0<t.l&&t.l<100?0:NaN,t.l,t.opacity);var e=Math.atan2(t.b,t.a)*po;return new Oo(e<0?e+360:e,Math.sqrt(t.a*t.a+t.b*t.b),t.l,t.opacity)}function Mo(t,e,n,r){return 1===arguments.length?Ao(t):new Oo(n,e,t,null==r?1:r)}function No(t,e,n,r){return 1===arguments.length?Ao(t):new Oo(t,e,n,null==r?1:r)}function Oo(t,e,n,r){this.h=+t,this.c=+e,this.l=+n,this.opacity=+r;}function Do(t){if(isNaN(t.h))return new wo(t.l,0,0,t.opacity);var e=t.h*fo;return new wo(t.l,Math.cos(e)*t.c,Math.sin(e)*t.c,t.opacity)}Fn(wo,ko,Rn(Pn,{brighter:function(t){return new wo(this.l+18*(null==t?1:t),this.a,this.b,this.opacity)},darker:function(t){return new wo(this.l-18*(null==t?1:t),this.a,this.b,this.opacity)},rgb:function(){var t=(this.l+16)/116,e=isNaN(this.a)?t:t+this.a/500,n=isNaN(this.b)?t:t-this.b/200;return new ar(Co(3.1338561*(e=go*Eo(e))-1.6168667*(t=1*Eo(t))-.4906146*(n=yo*Eo(n))),Co(-.9787684*e+1.9161415*t+.033454*n),Co(.0719453*e-.2289914*t+1.4052427*n),this.opacity)}})),Fn(Oo,No,Rn(Pn,{brighter:function(t){return new Oo(this.h,this.c,this.l+18*(null==t?1:t),this.opacity)},darker:function(t){return new Oo(this.h,this.c,this.l-18*(null==t?1:t),this.opacity)},rgb:function(){return Do(this).rgb()}}));var Bo=-.14861,Lo=1.78277,Io=-.29227,Fo=-.90649,Ro=1.97294,Po=Ro*Fo,jo=Ro*Lo,zo=Lo*Io-Fo*Bo;function Yo(t){if(t instanceof $o)return new $o(t.h,t.s,t.l,t.opacity);t instanceof ar||(t=rr(t));var e=t.r/255,n=t.g/255,r=t.b/255,i=(zo*r+Po*e-jo*n)/(zo+Po-jo),a=r-i,o=(Ro*(n-i)-Io*a)/Fo,s=Math.sqrt(o*o+a*a)/(Ro*i*(1-i)),c=s?Math.atan2(o,a)*po-120:NaN;return new $o(c<0?c+360:c,s,i,t.opacity)}function Uo(t,e,n,r){return 1===arguments.length?Yo(t):new $o(t,e,n,null==r?1:r)}function $o(t,e,n,r){this.h=+t,this.s=+e,this.l=+n,this.opacity=+r;}Fn($o,Uo,Rn(Pn,{brighter:function(t){return t=null==t?zn:Math.pow(zn,t),new $o(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?jn:Math.pow(jn,t),new $o(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=isNaN(this.h)?0:(this.h+120)*fo,e=+this.l,n=isNaN(this.s)?0:this.s*e*(1-e),r=Math.cos(t),i=Math.sin(t);return new ar(255*(e+n*(Bo*r+Lo*i)),255*(e+n*(Io*r+Fo*i)),255*(e+n*(Ro*r)),this.opacity)}}));var Wo=Array.prototype.slice;function qo(t,e){return t-e}const Ho=t=>()=>t;function Vo(t,e){for(var n,r=-1,i=e.length;++r<i;)if(n=Go(t,e[r]))return n;return 0}function Go(t,e){for(var n=e[0],r=e[1],i=-1,a=0,o=t.length,s=o-1;a<o;s=a++){var c=t[a],l=c[0],u=c[1],h=t[s],f=h[0],d=h[1];if(Xo(c,h,e))return 0;u>r!=d>r&&n<(f-l)*(r-u)/(d-u)+l&&(i=-i);}return i}function Xo(t,e,n){var r,i,a,o;return function(t,e,n){return (e[0]-t[0])*(n[1]-t[1])==(n[0]-t[0])*(e[1]-t[1])}(t,e,n)&&(i=t[r=+(t[0]===e[0])],a=n[r],o=e[r],i<=a&&a<=o||o<=a&&a<=i)}function Zo(){}var Qo=[[],[[[1,1.5],[.5,1]]],[[[1.5,1],[1,1.5]]],[[[1.5,1],[.5,1]]],[[[1,.5],[1.5,1]]],[[[1,1.5],[.5,1]],[[1,.5],[1.5,1]]],[[[1,.5],[1,1.5]]],[[[1,.5],[.5,1]]],[[[.5,1],[1,.5]]],[[[1,1.5],[1,.5]]],[[[.5,1],[1,.5]],[[1.5,1],[1,1.5]]],[[[1.5,1],[1,.5]]],[[[.5,1],[1.5,1]]],[[[1,1.5],[1.5,1]]],[[[.5,1],[1,1.5]]],[]];function Ko(){var t=1,e=1,n=rt,r=s;function i(t){var e=n(t);if(Array.isArray(e))e=e.slice().sort(qo);else {const n=_(t),r=et(n[0],n[1],e);e=J(Math.floor(n[0]/r)*r,Math.floor(n[1]/r-1)*r,e);}return e.map((e=>a(t,e)))}function a(n,i){var a=[],s=[];return function(n,r,i){var a,s,c,l,u,h,f=new Array,d=new Array;for(a=s=-1,l=n[0]>=r,Qo[l<<1].forEach(p);++a<t-1;)c=l,l=n[a+1]>=r,Qo[c|l<<1].forEach(p);for(Qo[l<<0].forEach(p);++s<e-1;){for(a=-1,l=n[s*t+t]>=r,u=n[s*t]>=r,Qo[l<<1|u<<2].forEach(p);++a<t-1;)c=l,l=n[s*t+t+a+1]>=r,h=u,u=n[s*t+a+1]>=r,Qo[c|l<<1|u<<2|h<<3].forEach(p);Qo[l|u<<3].forEach(p);}for(a=-1,u=n[s*t]>=r,Qo[u<<2].forEach(p);++a<t-1;)h=u,u=n[s*t+a+1]>=r,Qo[u<<2|h<<3].forEach(p);function p(t){var e,n,r=[t[0][0]+a,t[0][1]+s],c=[t[1][0]+a,t[1][1]+s],l=o(r),u=o(c);(e=d[l])?(n=f[u])?(delete d[e.end],delete f[n.start],e===n?(e.ring.push(c),i(e.ring)):f[e.start]=d[n.end]={start:e.start,end:n.end,ring:e.ring.concat(n.ring)}):(delete d[e.end],e.ring.push(c),d[e.end=u]=e):(e=f[u])?(n=d[l])?(delete f[e.start],delete d[n.end],e===n?(e.ring.push(c),i(e.ring)):f[n.start]=d[e.end]={start:n.start,end:e.end,ring:n.ring.concat(e.ring)}):(delete f[e.start],e.ring.unshift(r),f[e.start=l]=e):f[l]=d[u]={start:l,end:u,ring:[r,c]};}Qo[u<<3].forEach(p);}(n,i,(function(t){r(t,n,i),function(t){for(var e=0,n=t.length,r=t[n-1][1]*t[0][0]-t[n-1][0]*t[0][1];++e<n;)r+=t[e-1][1]*t[e][0]-t[e-1][0]*t[e][1];return r}(t)>0?a.push([t]):s.push(t);})),s.forEach((function(t){for(var e,n=0,r=a.length;n<r;++n)if(-1!==Vo((e=a[n])[0],t))return void e.push(t)})),{type:"MultiPolygon",value:i,coordinates:a}}function o(e){return 2*e[0]+e[1]*(t+1)*4}function s(n,r,i){n.forEach((function(n){var a,o=n[0],s=n[1],c=0|o,l=0|s,u=r[l*t+c];o>0&&o<t&&c===o&&(a=r[l*t+c-1],n[0]=o+(i-a)/(u-a)-.5),s>0&&s<e&&l===s&&(a=r[(l-1)*t+c],n[1]=s+(i-a)/(u-a)-.5);}));}return i.contour=a,i.size=function(n){if(!arguments.length)return [t,e];var r=Math.floor(n[0]),a=Math.floor(n[1]);if(!(r>=0&&a>=0))throw new Error("invalid size");return t=r,e=a,i},i.thresholds=function(t){return arguments.length?(n="function"==typeof t?t:Array.isArray(t)?Ho(Wo.call(t)):Ho(t),i):n},i.smooth=function(t){return arguments.length?(r=t?s:Zo,i):r===s},i}function Jo(t,e,n){for(var r=t.width,i=t.height,a=1+(n<<1),o=0;o<i;++o)for(var s=0,c=0;s<r+n;++s)s<r&&(c+=t.data[s+o*r]),s>=n&&(s>=a&&(c-=t.data[s-a+o*r]),e.data[s-n+o*r]=c/Math.min(s+1,r-1+a-s,a));}function ts(t,e,n){for(var r=t.width,i=t.height,a=1+(n<<1),o=0;o<r;++o)for(var s=0,c=0;s<i+n;++s)s<i&&(c+=t.data[o+s*r]),s>=n&&(s>=a&&(c-=t.data[o+(s-a)*r]),e.data[o+(s-n)*r]=c/Math.min(s+1,i-1+a-s,a));}function es(t){return t[0]}function ns(t){return t[1]}function rs(){return 1}function is(){var t=es,e=ns,n=rs,r=960,i=500,a=20,o=2,s=3*a,c=r+2*s>>o,l=i+2*s>>o,u=Ho(20);function h(r){var i=new Float32Array(c*l),h=new Float32Array(c*l),d=Math.pow(2,-o);r.forEach((function(r,a,o){var u=(t(r,a,o)+s)*d,h=(e(r,a,o)+s)*d,f=+n(r,a,o);if(u>=0&&u<c&&h>=0&&h<l){var p=Math.floor(u),g=Math.floor(h),y=u-p-.5,m=h-g-.5;i[p+g*c]+=(1-y)*(1-m)*f,i[p+1+g*c]+=y*(1-m)*f,i[p+1+(g+1)*c]+=y*m*f,i[p+(g+1)*c]+=(1-y)*m*f;}})),Jo({width:c,height:l,data:i},{width:c,height:l,data:h},a>>o),ts({width:c,height:l,data:h},{width:c,height:l,data:i},a>>o),Jo({width:c,height:l,data:i},{width:c,height:l,data:h},a>>o),ts({width:c,height:l,data:h},{width:c,height:l,data:i},a>>o),Jo({width:c,height:l,data:i},{width:c,height:l,data:h},a>>o),ts({width:c,height:l,data:h},{width:c,height:l,data:i},a>>o);var p=u(i);if(!Array.isArray(p)){var g=at(i);p=et(0,g,p),(p=xt(0,Math.floor(g/p)*p,p)).shift();}return Ko().thresholds(p).size([c,l])(i).map(f)}function f(t){return t.value*=Math.pow(2,-2*o),t.coordinates.forEach(d),t}function d(t){t.forEach(p);}function p(t){t.forEach(g);}function g(t){t[0]=t[0]*Math.pow(2,o)-s,t[1]=t[1]*Math.pow(2,o)-s;}function y(){return c=r+2*(s=3*a)>>o,l=i+2*s>>o,h}return h.x=function(e){return arguments.length?(t="function"==typeof e?e:Ho(+e),h):t},h.y=function(t){return arguments.length?(e="function"==typeof t?t:Ho(+t),h):e},h.weight=function(t){return arguments.length?(n="function"==typeof t?t:Ho(+t),h):n},h.size=function(t){if(!arguments.length)return [r,i];var e=+t[0],n=+t[1];if(!(e>=0&&n>=0))throw new Error("invalid size");return r=e,i=n,y()},h.cellSize=function(t){if(!arguments.length)return 1<<o;if(!((t=+t)>=1))throw new Error("invalid cell size");return o=Math.floor(Math.log(t)/Math.LN2),y()},h.thresholds=function(t){return arguments.length?(u="function"==typeof t?t:Array.isArray(t)?Ho(Wo.call(t)):Ho(t),h):u},h.bandwidth=function(t){if(!arguments.length)return Math.sqrt(a*(a+1));if(!((t=+t)>=0))throw new Error("invalid bandwidth");return a=Math.round((Math.sqrt(4*t*t+1)-1)/2),y()},h}const as=134217729;function os(t,e,n,r,i){let a,o,s,c,l=e[0],u=r[0],h=0,f=0;u>l==u>-l?(a=l,l=e[++h]):(a=u,u=r[++f]);let d=0;if(h<t&&f<n)for(u>l==u>-l?(o=l+a,s=a-(o-l),l=e[++h]):(o=u+a,s=a-(o-u),u=r[++f]),a=o,0!==s&&(i[d++]=s);h<t&&f<n;)u>l==u>-l?(o=a+l,c=o-a,s=a-(o-c)+(l-c),l=e[++h]):(o=a+u,c=o-a,s=a-(o-c)+(u-c),u=r[++f]),a=o,0!==s&&(i[d++]=s);for(;h<t;)o=a+l,c=o-a,s=a-(o-c)+(l-c),l=e[++h],a=o,0!==s&&(i[d++]=s);for(;f<n;)o=a+u,c=o-a,s=a-(o-c)+(u-c),u=r[++f],a=o,0!==s&&(i[d++]=s);return 0===a&&0!==d||(i[d++]=a),d}function ss(t){return new Float64Array(t)}const cs=ss(4),ls=ss(8),us=ss(12),hs=ss(16),fs=ss(4);function ds(t,e,n,r,i,a){const o=(e-a)*(n-i),s=(t-i)*(r-a),c=o-s;if(0===o||0===s||o>0!=s>0)return c;const l=Math.abs(o+s);return Math.abs(c)>=33306690738754716e-32*l?c:-function(t,e,n,r,i,a,o){let s,c,l,u,h,f,d,p,g,y,m,b,v,_,x,k,w,T;const E=t-i,C=n-i,S=e-a,A=r-a;_=E*A,f=as*E,d=f-(f-E),p=E-d,f=as*A,g=f-(f-A),y=A-g,x=p*y-(_-d*g-p*g-d*y),k=S*C,f=as*S,d=f-(f-S),p=S-d,f=as*C,g=f-(f-C),y=C-g,w=p*y-(k-d*g-p*g-d*y),m=x-w,h=x-m,cs[0]=x-(m+h)+(h-w),b=_+m,h=b-_,v=_-(b-h)+(m-h),m=v-k,h=v-m,cs[1]=v-(m+h)+(h-k),T=b+m,h=T-b,cs[2]=b-(T-h)+(m-h),cs[3]=T;let M=function(t,e){let n=e[0];for(let t=1;t<4;t++)n+=e[t];return n}(0,cs),N=22204460492503146e-32*o;if(M>=N||-M>=N)return M;if(h=t-E,s=t-(E+h)+(h-i),h=n-C,l=n-(C+h)+(h-i),h=e-S,c=e-(S+h)+(h-a),h=r-A,u=r-(A+h)+(h-a),0===s&&0===c&&0===l&&0===u)return M;if(N=11093356479670487e-47*o+33306690738754706e-32*Math.abs(M),M+=E*u+A*s-(S*l+C*c),M>=N||-M>=N)return M;_=s*A,f=as*s,d=f-(f-s),p=s-d,f=as*A,g=f-(f-A),y=A-g,x=p*y-(_-d*g-p*g-d*y),k=c*C,f=as*c,d=f-(f-c),p=c-d,f=as*C,g=f-(f-C),y=C-g,w=p*y-(k-d*g-p*g-d*y),m=x-w,h=x-m,fs[0]=x-(m+h)+(h-w),b=_+m,h=b-_,v=_-(b-h)+(m-h),m=v-k,h=v-m,fs[1]=v-(m+h)+(h-k),T=b+m,h=T-b,fs[2]=b-(T-h)+(m-h),fs[3]=T;const O=os(4,cs,4,fs,ls);_=E*u,f=as*E,d=f-(f-E),p=E-d,f=as*u,g=f-(f-u),y=u-g,x=p*y-(_-d*g-p*g-d*y),k=S*l,f=as*S,d=f-(f-S),p=S-d,f=as*l,g=f-(f-l),y=l-g,w=p*y-(k-d*g-p*g-d*y),m=x-w,h=x-m,fs[0]=x-(m+h)+(h-w),b=_+m,h=b-_,v=_-(b-h)+(m-h),m=v-k,h=v-m,fs[1]=v-(m+h)+(h-k),T=b+m,h=T-b,fs[2]=b-(T-h)+(m-h),fs[3]=T;const D=os(O,ls,4,fs,us);_=s*u,f=as*s,d=f-(f-s),p=s-d,f=as*u,g=f-(f-u),y=u-g,x=p*y-(_-d*g-p*g-d*y),k=c*l,f=as*c,d=f-(f-c),p=c-d,f=as*l,g=f-(f-l),y=l-g,w=p*y-(k-d*g-p*g-d*y),m=x-w,h=x-m,fs[0]=x-(m+h)+(h-w),b=_+m,h=b-_,v=_-(b-h)+(m-h),m=v-k,h=v-m,fs[1]=v-(m+h)+(h-k),T=b+m,h=T-b,fs[2]=b-(T-h)+(m-h),fs[3]=T;const B=os(D,us,4,fs,hs);return hs[B-1]}(t,e,n,r,i,a,l)}const ps=Math.pow(2,-52),gs=new Uint32Array(512);class ys{static from(t,e=ks,n=ws){const r=t.length,i=new Float64Array(2*r);for(let a=0;a<r;a++){const r=t[a];i[2*a]=e(r),i[2*a+1]=n(r);}return new ys(i)}constructor(t){const e=t.length>>1;if(e>0&&"number"!=typeof t[0])throw new Error("Expected coords to contain numbers.");this.coords=t;const n=Math.max(2*e-5,0);this._triangles=new Uint32Array(3*n),this._halfedges=new Int32Array(3*n),this._hashSize=Math.ceil(Math.sqrt(e)),this._hullPrev=new Uint32Array(e),this._hullNext=new Uint32Array(e),this._hullTri=new Uint32Array(e),this._hullHash=new Int32Array(this._hashSize).fill(-1),this._ids=new Uint32Array(e),this._dists=new Float64Array(e),this.update();}update(){const{coords:t,_hullPrev:e,_hullNext:n,_hullTri:r,_hullHash:i}=this,a=t.length>>1;let o=1/0,s=1/0,c=-1/0,l=-1/0;for(let e=0;e<a;e++){const n=t[2*e],r=t[2*e+1];n<o&&(o=n),r<s&&(s=r),n>c&&(c=n),r>l&&(l=r),this._ids[e]=e;}const u=(o+c)/2,h=(s+l)/2;let f,d,p,g=1/0;for(let e=0;e<a;e++){const n=ms(u,h,t[2*e],t[2*e+1]);n<g&&(f=e,g=n);}const y=t[2*f],m=t[2*f+1];g=1/0;for(let e=0;e<a;e++){if(e===f)continue;const n=ms(y,m,t[2*e],t[2*e+1]);n<g&&n>0&&(d=e,g=n);}let b=t[2*d],v=t[2*d+1],_=1/0;for(let e=0;e<a;e++){if(e===f||e===d)continue;const n=vs(y,m,b,v,t[2*e],t[2*e+1]);n<_&&(p=e,_=n);}let x=t[2*p],k=t[2*p+1];if(_===1/0){for(let e=0;e<a;e++)this._dists[e]=t[2*e]-t[0]||t[2*e+1]-t[1];_s(this._ids,this._dists,0,a-1);const e=new Uint32Array(a);let n=0;for(let t=0,r=-1/0;t<a;t++){const i=this._ids[t];this._dists[i]>r&&(e[n++]=i,r=this._dists[i]);}return this.hull=e.subarray(0,n),this.triangles=new Uint32Array(0),void(this.halfedges=new Uint32Array(0))}if(ds(y,m,b,v,x,k)<0){const t=d,e=b,n=v;d=p,b=x,v=k,p=t,x=e,k=n;}const w=function(t,e,n,r,i,a){const o=n-t,s=r-e,c=i-t,l=a-e,u=o*o+s*s,h=c*c+l*l,f=.5/(o*l-s*c);return {x:t+(l*u-s*h)*f,y:e+(o*h-c*u)*f}}(y,m,b,v,x,k);this._cx=w.x,this._cy=w.y;for(let e=0;e<a;e++)this._dists[e]=ms(t[2*e],t[2*e+1],w.x,w.y);_s(this._ids,this._dists,0,a-1),this._hullStart=f;let T=3;n[f]=e[p]=d,n[d]=e[f]=p,n[p]=e[d]=f,r[f]=0,r[d]=1,r[p]=2,i.fill(-1),i[this._hashKey(y,m)]=f,i[this._hashKey(b,v)]=d,i[this._hashKey(x,k)]=p,this.trianglesLen=0,this._addTriangle(f,d,p,-1,-1,-1);for(let a,o,s=0;s<this._ids.length;s++){const c=this._ids[s],l=t[2*c],u=t[2*c+1];if(s>0&&Math.abs(l-a)<=ps&&Math.abs(u-o)<=ps)continue;if(a=l,o=u,c===f||c===d||c===p)continue;let h=0;for(let t=0,e=this._hashKey(l,u);t<this._hashSize&&(h=i[(e+t)%this._hashSize],-1===h||h===n[h]);t++);h=e[h];let g,y=h;for(;g=n[y],ds(l,u,t[2*y],t[2*y+1],t[2*g],t[2*g+1])>=0;)if(y=g,y===h){y=-1;break}if(-1===y)continue;let m=this._addTriangle(y,c,n[y],-1,-1,r[y]);r[c]=this._legalize(m+2),r[y]=m,T++;let b=n[y];for(;g=n[b],ds(l,u,t[2*b],t[2*b+1],t[2*g],t[2*g+1])<0;)m=this._addTriangle(b,c,g,r[c],-1,r[b]),r[c]=this._legalize(m+2),n[b]=b,T--,b=g;if(y===h)for(;g=e[y],ds(l,u,t[2*g],t[2*g+1],t[2*y],t[2*y+1])<0;)m=this._addTriangle(g,c,y,-1,r[y],r[g]),this._legalize(m+2),r[g]=m,n[y]=y,T--,y=g;this._hullStart=e[c]=y,n[y]=e[b]=c,n[c]=b,i[this._hashKey(l,u)]=c,i[this._hashKey(t[2*y],t[2*y+1])]=y;}this.hull=new Uint32Array(T);for(let t=0,e=this._hullStart;t<T;t++)this.hull[t]=e,e=n[e];this.triangles=this._triangles.subarray(0,this.trianglesLen),this.halfedges=this._halfedges.subarray(0,this.trianglesLen);}_hashKey(t,e){return Math.floor(function(t,e){const n=t/(Math.abs(t)+Math.abs(e));return (e>0?3-n:1+n)/4}(t-this._cx,e-this._cy)*this._hashSize)%this._hashSize}_legalize(t){const{_triangles:e,_halfedges:n,coords:r}=this;let i=0,a=0;for(;;){const o=n[t],s=t-t%3;if(a=s+(t+2)%3,-1===o){if(0===i)break;t=gs[--i];continue}const c=o-o%3,l=s+(t+1)%3,u=c+(o+2)%3,h=e[a],f=e[t],d=e[l],p=e[u];if(bs(r[2*h],r[2*h+1],r[2*f],r[2*f+1],r[2*d],r[2*d+1],r[2*p],r[2*p+1])){e[t]=p,e[o]=h;const r=n[u];if(-1===r){let e=this._hullStart;do{if(this._hullTri[e]===u){this._hullTri[e]=t;break}e=this._hullPrev[e];}while(e!==this._hullStart)}this._link(t,r),this._link(o,n[a]),this._link(a,u);const s=c+(o+1)%3;i<gs.length&&(gs[i++]=s);}else {if(0===i)break;t=gs[--i];}}return a}_link(t,e){this._halfedges[t]=e,-1!==e&&(this._halfedges[e]=t);}_addTriangle(t,e,n,r,i,a){const o=this.trianglesLen;return this._triangles[o]=t,this._triangles[o+1]=e,this._triangles[o+2]=n,this._link(o,r),this._link(o+1,i),this._link(o+2,a),this.trianglesLen+=3,o}}function ms(t,e,n,r){const i=t-n,a=e-r;return i*i+a*a}function bs(t,e,n,r,i,a,o,s){const c=t-o,l=e-s,u=n-o,h=r-s,f=i-o,d=a-s,p=u*u+h*h,g=f*f+d*d;return c*(h*g-p*d)-l*(u*g-p*f)+(c*c+l*l)*(u*d-h*f)<0}function vs(t,e,n,r,i,a){const o=n-t,s=r-e,c=i-t,l=a-e,u=o*o+s*s,h=c*c+l*l,f=.5/(o*l-s*c),d=(l*u-s*h)*f,p=(o*h-c*u)*f;return d*d+p*p}function _s(t,e,n,r){if(r-n<=20)for(let i=n+1;i<=r;i++){const r=t[i],a=e[r];let o=i-1;for(;o>=n&&e[t[o]]>a;)t[o+1]=t[o--];t[o+1]=r;}else {let i=n+1,a=r;xs(t,n+r>>1,i),e[t[n]]>e[t[r]]&&xs(t,n,r),e[t[i]]>e[t[r]]&&xs(t,i,r),e[t[n]]>e[t[i]]&&xs(t,n,i);const o=t[i],s=e[o];for(;;){do{i++;}while(e[t[i]]<s);do{a--;}while(e[t[a]]>s);if(a<i)break;xs(t,i,a);}t[n+1]=t[a],t[a]=o,r-i+1>=a-n?(_s(t,e,i,r),_s(t,e,n,a-1)):(_s(t,e,n,a-1),_s(t,e,i,r));}}function xs(t,e,n){const r=t[e];t[e]=t[n],t[n]=r;}function ks(t){return t[0]}function ws(t){return t[1]}const Ts=1e-6;class Es{constructor(){this._x0=this._y0=this._x1=this._y1=null,this._="";}moveTo(t,e){this._+=`M${this._x0=this._x1=+t},${this._y0=this._y1=+e}`;}closePath(){null!==this._x1&&(this._x1=this._x0,this._y1=this._y0,this._+="Z");}lineTo(t,e){this._+=`L${this._x1=+t},${this._y1=+e}`;}arc(t,e,n){const r=(t=+t)+(n=+n),i=e=+e;if(n<0)throw new Error("negative radius");null===this._x1?this._+=`M${r},${i}`:(Math.abs(this._x1-r)>Ts||Math.abs(this._y1-i)>Ts)&&(this._+="L"+r+","+i),n&&(this._+=`A${n},${n},0,1,1,${t-n},${e}A${n},${n},0,1,1,${this._x1=r},${this._y1=i}`);}rect(t,e,n,r){this._+=`M${this._x0=this._x1=+t},${this._y0=this._y1=+e}h${+n}v${+r}h${-n}Z`;}value(){return this._||null}}class Cs{constructor(){this._=[];}moveTo(t,e){this._.push([t,e]);}closePath(){this._.push(this._[0].slice());}lineTo(t,e){this._.push([t,e]);}value(){return this._.length?this._:null}}class Ss{constructor(t,[e,n,r,i]=[0,0,960,500]){if(!((r=+r)>=(e=+e)&&(i=+i)>=(n=+n)))throw new Error("invalid bounds");this.delaunay=t,this._circumcenters=new Float64Array(2*t.points.length),this.vectors=new Float64Array(2*t.points.length),this.xmax=r,this.xmin=e,this.ymax=i,this.ymin=n,this._init();}update(){return this.delaunay.update(),this._init(),this}_init(){const{delaunay:{points:t,hull:e,triangles:n},vectors:r}=this,i=this.circumcenters=this._circumcenters.subarray(0,n.length/3*2);for(let e,r,a=0,o=0,s=n.length;a<s;a+=3,o+=2){const s=2*n[a],c=2*n[a+1],l=2*n[a+2],u=t[s],h=t[s+1],f=t[c],d=t[c+1],p=t[l],g=t[l+1],y=f-u,m=d-h,b=p-u,v=g-h,_=2*(y*v-m*b);if(Math.abs(_)<1e-9){let i=1e9;const a=2*n[0];i*=Math.sign((t[a]-u)*v-(t[a+1]-h)*b),e=(u+p)/2-i*v,r=(h+g)/2+i*b;}else {const t=1/_,n=y*y+m*m,i=b*b+v*v;e=u+(v*n-m*i)*t,r=h+(y*i-b*n)*t;}i[o]=e,i[o+1]=r;}let a,o,s,c=e[e.length-1],l=4*c,u=t[2*c],h=t[2*c+1];r.fill(0);for(let n=0;n<e.length;++n)c=e[n],a=l,o=u,s=h,l=4*c,u=t[2*c],h=t[2*c+1],r[a+2]=r[l]=s-h,r[a+3]=r[l+1]=u-o;}render(t){const e=null==t?t=new Es:void 0,{delaunay:{halfedges:n,inedges:r,hull:i},circumcenters:a,vectors:o}=this;if(i.length<=1)return null;for(let e=0,r=n.length;e<r;++e){const r=n[e];if(r<e)continue;const i=2*Math.floor(e/3),o=2*Math.floor(r/3),s=a[i],c=a[i+1],l=a[o],u=a[o+1];this._renderSegment(s,c,l,u,t);}let s,c=i[i.length-1];for(let e=0;e<i.length;++e){s=c,c=i[e];const n=2*Math.floor(r[c]/3),l=a[n],u=a[n+1],h=4*s,f=this._project(l,u,o[h+2],o[h+3]);f&&this._renderSegment(l,u,f[0],f[1],t);}return e&&e.value()}renderBounds(t){const e=null==t?t=new Es:void 0;return t.rect(this.xmin,this.ymin,this.xmax-this.xmin,this.ymax-this.ymin),e&&e.value()}renderCell(t,e){const n=null==e?e=new Es:void 0,r=this._clip(t);if(null===r||!r.length)return;e.moveTo(r[0],r[1]);let i=r.length;for(;r[0]===r[i-2]&&r[1]===r[i-1]&&i>1;)i-=2;for(let t=2;t<i;t+=2)r[t]===r[t-2]&&r[t+1]===r[t-1]||e.lineTo(r[t],r[t+1]);return e.closePath(),n&&n.value()}*cellPolygons(){const{delaunay:{points:t}}=this;for(let e=0,n=t.length/2;e<n;++e){const t=this.cellPolygon(e);t&&(t.index=e,yield t);}}cellPolygon(t){const e=new Cs;return this.renderCell(t,e),e.value()}_renderSegment(t,e,n,r,i){let a;const o=this._regioncode(t,e),s=this._regioncode(n,r);0===o&&0===s?(i.moveTo(t,e),i.lineTo(n,r)):(a=this._clipSegment(t,e,n,r,o,s))&&(i.moveTo(a[0],a[1]),i.lineTo(a[2],a[3]));}contains(t,e,n){return (e=+e)==e&&(n=+n)==n&&this.delaunay._step(t,e,n)===t}*neighbors(t){const e=this._clip(t);if(e)for(const n of this.delaunay.neighbors(t)){const t=this._clip(n);if(t)t:for(let r=0,i=e.length;r<i;r+=2)for(let a=0,o=t.length;a<o;a+=2)if(e[r]==t[a]&&e[r+1]==t[a+1]&&e[(r+2)%i]==t[(a+o-2)%o]&&e[(r+3)%i]==t[(a+o-1)%o]){yield n;break t}}}_cell(t){const{circumcenters:e,delaunay:{inedges:n,halfedges:r,triangles:i}}=this,a=n[t];if(-1===a)return null;const o=[];let s=a;do{const n=Math.floor(s/3);if(o.push(e[2*n],e[2*n+1]),s=s%3==2?s-2:s+1,i[s]!==t)break;s=r[s];}while(s!==a&&-1!==s);return o}_clip(t){if(0===t&&1===this.delaunay.hull.length)return [this.xmax,this.ymin,this.xmax,this.ymax,this.xmin,this.ymax,this.xmin,this.ymin];const e=this._cell(t);if(null===e)return null;const{vectors:n}=this,r=4*t;return n[r]||n[r+1]?this._clipInfinite(t,e,n[r],n[r+1],n[r+2],n[r+3]):this._clipFinite(t,e)}_clipFinite(t,e){const n=e.length;let r,i,a,o,s=null,c=e[n-2],l=e[n-1],u=this._regioncode(c,l),h=0;for(let f=0;f<n;f+=2)if(r=c,i=l,c=e[f],l=e[f+1],a=u,u=this._regioncode(c,l),0===a&&0===u)o=h,h=0,s?s.push(c,l):s=[c,l];else {let e,n,f,d,p;if(0===a){if(null===(e=this._clipSegment(r,i,c,l,a,u)))continue;[n,f,d,p]=e;}else {if(null===(e=this._clipSegment(c,l,r,i,u,a)))continue;[d,p,n,f]=e,o=h,h=this._edgecode(n,f),o&&h&&this._edge(t,o,h,s,s.length),s?s.push(n,f):s=[n,f];}o=h,h=this._edgecode(d,p),o&&h&&this._edge(t,o,h,s,s.length),s?s.push(d,p):s=[d,p];}if(s)o=h,h=this._edgecode(s[0],s[1]),o&&h&&this._edge(t,o,h,s,s.length);else if(this.contains(t,(this.xmin+this.xmax)/2,(this.ymin+this.ymax)/2))return [this.xmax,this.ymin,this.xmax,this.ymax,this.xmin,this.ymax,this.xmin,this.ymin];return s}_clipSegment(t,e,n,r,i,a){for(;;){if(0===i&&0===a)return [t,e,n,r];if(i&a)return null;let o,s,c=i||a;8&c?(o=t+(n-t)*(this.ymax-e)/(r-e),s=this.ymax):4&c?(o=t+(n-t)*(this.ymin-e)/(r-e),s=this.ymin):2&c?(s=e+(r-e)*(this.xmax-t)/(n-t),o=this.xmax):(s=e+(r-e)*(this.xmin-t)/(n-t),o=this.xmin),i?(t=o,e=s,i=this._regioncode(t,e)):(n=o,r=s,a=this._regioncode(n,r));}}_clipInfinite(t,e,n,r,i,a){let o,s=Array.from(e);if((o=this._project(s[0],s[1],n,r))&&s.unshift(o[0],o[1]),(o=this._project(s[s.length-2],s[s.length-1],i,a))&&s.push(o[0],o[1]),s=this._clipFinite(t,s))for(let e,n=0,r=s.length,i=this._edgecode(s[r-2],s[r-1]);n<r;n+=2)e=i,i=this._edgecode(s[n],s[n+1]),e&&i&&(n=this._edge(t,e,i,s,n),r=s.length);else this.contains(t,(this.xmin+this.xmax)/2,(this.ymin+this.ymax)/2)&&(s=[this.xmin,this.ymin,this.xmax,this.ymin,this.xmax,this.ymax,this.xmin,this.ymax]);return s}_edge(t,e,n,r,i){for(;e!==n;){let n,a;switch(e){case 5:e=4;continue;case 4:e=6,n=this.xmax,a=this.ymin;break;case 6:e=2;continue;case 2:e=10,n=this.xmax,a=this.ymax;break;case 10:e=8;continue;case 8:e=9,n=this.xmin,a=this.ymax;break;case 9:e=1;continue;case 1:e=5,n=this.xmin,a=this.ymin;}r[i]===n&&r[i+1]===a||!this.contains(t,n,a)||(r.splice(i,0,n,a),i+=2);}if(r.length>4)for(let t=0;t<r.length;t+=2){const e=(t+2)%r.length,n=(t+4)%r.length;(r[t]===r[e]&&r[e]===r[n]||r[t+1]===r[e+1]&&r[e+1]===r[n+1])&&(r.splice(e,2),t-=2);}return i}_project(t,e,n,r){let i,a,o,s=1/0;if(r<0){if(e<=this.ymin)return null;(i=(this.ymin-e)/r)<s&&(o=this.ymin,a=t+(s=i)*n);}else if(r>0){if(e>=this.ymax)return null;(i=(this.ymax-e)/r)<s&&(o=this.ymax,a=t+(s=i)*n);}if(n>0){if(t>=this.xmax)return null;(i=(this.xmax-t)/n)<s&&(a=this.xmax,o=e+(s=i)*r);}else if(n<0){if(t<=this.xmin)return null;(i=(this.xmin-t)/n)<s&&(a=this.xmin,o=e+(s=i)*r);}return [a,o]}_edgecode(t,e){return (t===this.xmin?1:t===this.xmax?2:0)|(e===this.ymin?4:e===this.ymax?8:0)}_regioncode(t,e){return (t<this.xmin?1:t>this.xmax?2:0)|(e<this.ymin?4:e>this.ymax?8:0)}}const As=2*Math.PI,Ms=Math.pow;function Ns(t){return t[0]}function Os(t){return t[1]}function Ds(t,e,n){return [t+Math.sin(t+e)*n,e+Math.cos(t-e)*n]}class Bs{static from(t,e=Ns,n=Os,r){return new Bs("length"in t?function(t,e,n,r){const i=t.length,a=new Float64Array(2*i);for(let o=0;o<i;++o){const i=t[o];a[2*o]=e.call(r,i,o,t),a[2*o+1]=n.call(r,i,o,t);}return a}(t,e,n,r):Float64Array.from(function*(t,e,n,r){let i=0;for(const a of t)yield e.call(r,a,i,t),yield n.call(r,a,i,t),++i;}(t,e,n,r)))}constructor(t){this._delaunator=new ys(t),this.inedges=new Int32Array(t.length/2),this._hullIndex=new Int32Array(t.length/2),this.points=this._delaunator.coords,this._init();}update(){return this._delaunator.update(),this._init(),this}_init(){const t=this._delaunator,e=this.points;if(t.hull&&t.hull.length>2&&function(t){const{triangles:e,coords:n}=t;for(let t=0;t<e.length;t+=3){const r=2*e[t],i=2*e[t+1],a=2*e[t+2];if((n[a]-n[r])*(n[i+1]-n[r+1])-(n[i]-n[r])*(n[a+1]-n[r+1])>1e-10)return !1}return !0}(t)){this.collinear=Int32Array.from({length:e.length/2},((t,e)=>e)).sort(((t,n)=>e[2*t]-e[2*n]||e[2*t+1]-e[2*n+1]));const t=this.collinear[0],n=this.collinear[this.collinear.length-1],r=[e[2*t],e[2*t+1],e[2*n],e[2*n+1]],i=1e-8*Math.hypot(r[3]-r[1],r[2]-r[0]);for(let t=0,n=e.length/2;t<n;++t){const n=Ds(e[2*t],e[2*t+1],i);e[2*t]=n[0],e[2*t+1]=n[1];}this._delaunator=new ys(e);}else delete this.collinear;const n=this.halfedges=this._delaunator.halfedges,r=this.hull=this._delaunator.hull,i=this.triangles=this._delaunator.triangles,a=this.inedges.fill(-1),o=this._hullIndex.fill(-1);for(let t=0,e=n.length;t<e;++t){const e=i[t%3==2?t-2:t+1];-1!==n[t]&&-1!==a[e]||(a[e]=t);}for(let t=0,e=r.length;t<e;++t)o[r[t]]=t;r.length<=2&&r.length>0&&(this.triangles=new Int32Array(3).fill(-1),this.halfedges=new Int32Array(3).fill(-1),this.triangles[0]=r[0],a[r[0]]=1,2===r.length&&(a[r[1]]=0,this.triangles[1]=r[1],this.triangles[2]=r[1]));}voronoi(t){return new Ss(this,t)}*neighbors(t){const{inedges:e,hull:n,_hullIndex:r,halfedges:i,triangles:a,collinear:o}=this;if(o){const e=o.indexOf(t);return e>0&&(yield o[e-1]),void(e<o.length-1&&(yield o[e+1]))}const s=e[t];if(-1===s)return;let c=s,l=-1;do{if(yield l=a[c],c=c%3==2?c-2:c+1,a[c]!==t)return;if(c=i[c],-1===c){const e=n[(r[t]+1)%n.length];return void(e!==l&&(yield e))}}while(c!==s)}find(t,e,n=0){if((t=+t)!=t||(e=+e)!=e)return -1;const r=n;let i;for(;(i=this._step(n,t,e))>=0&&i!==n&&i!==r;)n=i;return i}_step(t,e,n){const{inedges:r,hull:i,_hullIndex:a,halfedges:o,triangles:s,points:c}=this;if(-1===r[t]||!c.length)return (t+1)%(c.length>>1);let l=t,u=Ms(e-c[2*t],2)+Ms(n-c[2*t+1],2);const h=r[t];let f=h;do{let r=s[f];const h=Ms(e-c[2*r],2)+Ms(n-c[2*r+1],2);if(h<u&&(u=h,l=r),f=f%3==2?f-2:f+1,s[f]!==t)break;if(f=o[f],-1===f){if(f=i[(a[t]+1)%i.length],f!==r&&Ms(e-c[2*f],2)+Ms(n-c[2*f+1],2)<u)return f;break}}while(f!==h);return l}render(t){const e=null==t?t=new Es:void 0,{points:n,halfedges:r,triangles:i}=this;for(let e=0,a=r.length;e<a;++e){const a=r[e];if(a<e)continue;const o=2*i[e],s=2*i[a];t.moveTo(n[o],n[o+1]),t.lineTo(n[s],n[s+1]);}return this.renderHull(t),e&&e.value()}renderPoints(t,e){void 0!==e||t&&"function"==typeof t.moveTo||(e=t,t=null),e=null==e?2:+e;const n=null==t?t=new Es:void 0,{points:r}=this;for(let n=0,i=r.length;n<i;n+=2){const i=r[n],a=r[n+1];t.moveTo(i+e,a),t.arc(i,a,e,0,As);}return n&&n.value()}renderHull(t){const e=null==t?t=new Es:void 0,{hull:n,points:r}=this,i=2*n[0],a=n.length;t.moveTo(r[i],r[i+1]);for(let e=1;e<a;++e){const i=2*n[e];t.lineTo(r[i],r[i+1]);}return t.closePath(),e&&e.value()}hullPolygon(){const t=new Cs;return this.renderHull(t),t.value()}renderTriangle(t,e){const n=null==e?e=new Es:void 0,{points:r,triangles:i}=this,a=2*i[t*=3],o=2*i[t+1],s=2*i[t+2];return e.moveTo(r[a],r[a+1]),e.lineTo(r[o],r[o+1]),e.lineTo(r[s],r[s+1]),e.closePath(),n&&n.value()}*trianglePolygons(){const{triangles:t}=this;for(let e=0,n=t.length/3;e<n;++e)yield this.trianglePolygon(e);}trianglePolygon(t){const e=new Cs;return this.renderTriangle(t,e),e.value()}}const Ls=t=>()=>t;function Is(t,{sourceEvent:e,subject:n,target:r,identifier:i,active:a,x:o,y:s,dx:c,dy:l,dispatch:u}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:e,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:i,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:o,enumerable:!0,configurable:!0},y:{value:s,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:l,enumerable:!0,configurable:!0},_:{value:u}});}function Fs(t){return !t.ctrlKey&&!t.button}function Rs(){return this.parentNode}function Ps(t,e){return null==e?{x:t.x,y:t.y}:e}function js(){return navigator.maxTouchPoints||"ontouchstart"in this}function zs(){var t,e,n,r,i=Fs,a=Rs,o=Ps,s=js,c={},l=fe("start","drag","end"),u=0,h=0;function f(t){t.on("mousedown.drag",d).filter(s).on("touchstart.drag",y).on("touchmove.drag",m,Nn).on("touchend.drag touchcancel.drag",b).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)");}function d(o,s){if(!r&&i.call(this,o,s)){var c=v(this,a.call(this,o,s),o,s,"mouse");c&&(Mn(o.view).on("mousemove.drag",p,On).on("mouseup.drag",g,On),Ln(o.view),Dn(o),n=!1,t=o.clientX,e=o.clientY,c("start",o));}}function p(r){if(Bn(r),!n){var i=r.clientX-t,a=r.clientY-e;n=i*i+a*a>h;}c.mouse("drag",r);}function g(t){Mn(t.view).on("mousemove.drag mouseup.drag",null),In(t.view,n),Bn(t),c.mouse("end",t);}function y(t,e){if(i.call(this,t,e)){var n,r,o=t.changedTouches,s=a.call(this,t,e),c=o.length;for(n=0;n<c;++n)(r=v(this,s,t,e,o[n].identifier,o[n]))&&(Dn(t),r("start",t,o[n]));}}function m(t){var e,n,r=t.changedTouches,i=r.length;for(e=0;e<i;++e)(n=c[r[e].identifier])&&(Bn(t),n("drag",t,r[e]));}function b(t){var e,n,i=t.changedTouches,a=i.length;for(r&&clearTimeout(r),r=setTimeout((function(){r=null;}),500),e=0;e<a;++e)(n=c[i[e].identifier])&&(Dn(t),n("end",t,i[e]));}function v(t,e,n,r,i,a){var s,h,d,p=l.copy(),g=Rr(a||n,e);if(null!=(d=o.call(t,new Is("beforestart",{sourceEvent:n,target:f,identifier:i,active:u,x:g[0],y:g[1],dx:0,dy:0,dispatch:p}),r)))return s=d.x-g[0]||0,h=d.y-g[1]||0,function n(a,o,l){var y,m=g;switch(a){case"start":c[i]=n,y=u++;break;case"end":delete c[i],--u;case"drag":g=Rr(l||o,e),y=u;}p.call(a,t,new Is(a,{sourceEvent:o,subject:d,target:f,identifier:i,active:y,x:g[0]+s,y:g[1]+h,dx:g[0]-m[0],dy:g[1]-m[1],dispatch:p}),r);}}return f.filter=function(t){return arguments.length?(i="function"==typeof t?t:Ls(!!t),f):i},f.container=function(t){return arguments.length?(a="function"==typeof t?t:Ls(t),f):a},f.subject=function(t){return arguments.length?(o="function"==typeof t?t:Ls(t),f):o},f.touchable=function(t){return arguments.length?(s="function"==typeof t?t:Ls(!!t),f):s},f.on=function(){var t=l.on.apply(l,arguments);return t===l?f:t},f.clickDistance=function(t){return arguments.length?(h=(t=+t)*t,f):Math.sqrt(h)},f}Is.prototype.on=function(){var t=this._.on.apply(this._,arguments);return t===this._?this:t};var Ys={},Us={};function $s(t){return new Function("d","return {"+t.map((function(t,e){return JSON.stringify(t)+": d["+e+'] || ""'})).join(",")+"}")}function Ws(t){var e=Object.create(null),n=[];return t.forEach((function(t){for(var r in t)r in e||n.push(e[r]=r);})),n}function qs(t,e){var n=t+"",r=n.length;return r<e?new Array(e-r+1).join(0)+n:n}function Hs(t){var e=new RegExp('["'+t+"\n\r]"),n=t.charCodeAt(0);function r(t,e){var r,i=[],a=t.length,o=0,s=0,c=a<=0,l=!1;function u(){if(c)return Us;if(l)return l=!1,Ys;var e,r,i=o;if(34===t.charCodeAt(i)){for(;o++<a&&34!==t.charCodeAt(o)||34===t.charCodeAt(++o););return (e=o)>=a?c=!0:10===(r=t.charCodeAt(o++))?l=!0:13===r&&(l=!0,10===t.charCodeAt(o)&&++o),t.slice(i+1,e-1).replace(/""/g,'"')}for(;o<a;){if(10===(r=t.charCodeAt(e=o++)))l=!0;else if(13===r)l=!0,10===t.charCodeAt(o)&&++o;else if(r!==n)continue;return t.slice(i,e)}return c=!0,t.slice(i,a)}for(10===t.charCodeAt(a-1)&&--a,13===t.charCodeAt(a-1)&&--a;(r=u())!==Us;){for(var h=[];r!==Ys&&r!==Us;)h.push(r),r=u();e&&null==(h=e(h,s++))||i.push(h);}return i}function i(e,n){return e.map((function(e){return n.map((function(t){return o(e[t])})).join(t)}))}function a(e){return e.map(o).join(t)}function o(t){return null==t?"":t instanceof Date?function(t){var e=t.getUTCHours(),n=t.getUTCMinutes(),r=t.getUTCSeconds(),i=t.getUTCMilliseconds();return isNaN(t)?"Invalid Date":function(t){return t<0?"-"+qs(-t,6):t>9999?"+"+qs(t,6):qs(t,4)}(t.getUTCFullYear())+"-"+qs(t.getUTCMonth()+1,2)+"-"+qs(t.getUTCDate(),2)+(i?"T"+qs(e,2)+":"+qs(n,2)+":"+qs(r,2)+"."+qs(i,3)+"Z":r?"T"+qs(e,2)+":"+qs(n,2)+":"+qs(r,2)+"Z":n||e?"T"+qs(e,2)+":"+qs(n,2)+"Z":"")}(t):e.test(t+="")?'"'+t.replace(/"/g,'""')+'"':t}return {parse:function(t,e){var n,i,a=r(t,(function(t,r){if(n)return n(t,r-1);i=t,n=e?function(t,e){var n=$s(t);return function(r,i){return e(n(r),i,t)}}(t,e):$s(t);}));return a.columns=i||[],a},parseRows:r,format:function(e,n){return null==n&&(n=Ws(e)),[n.map(o).join(t)].concat(i(e,n)).join("\n")},formatBody:function(t,e){return null==e&&(e=Ws(t)),i(t,e).join("\n")},formatRows:function(t){return t.map(a).join("\n")},formatRow:a,formatValue:o}}var Vs=Hs(","),Gs=Vs.parse,Xs=Vs.parseRows,Zs=Vs.format,Qs=Vs.formatBody,Ks=Vs.formatRows,Js=Vs.formatRow,tc=Vs.formatValue,ec=Hs("\t"),nc=ec.parse,rc=ec.parseRows,ic=ec.format,ac=ec.formatBody,oc=ec.formatRows,sc=ec.formatRow,cc=ec.formatValue;function lc(t){for(var e in t){var n,r,i=t[e].trim();if(i)if("true"===i)i=!0;else if("false"===i)i=!1;else if("NaN"===i)i=NaN;else if(isNaN(n=+i)){if(!(r=i.match(/^([-+]\d{2})?\d{4}(-\d{2}(-\d{2})?)?(T\d{2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|[-+]\d{2}:\d{2})?)?$/)))continue;uc&&r[4]&&!r[7]&&(i=i.replace(/-/g,"/").replace(/T/," ")),i=new Date(i);}else i=n;else i=null;t[e]=i;}return t}const uc=new Date("2019-01-01T00:00").getHours()||new Date("2019-07-01T00:00").getHours(),hc=t=>+t;function fc(t){return t*t}function dc(t){return t*(2-t)}function pc(t){return ((t*=2)<=1?t*t:--t*(2-t)+1)/2}var gc=function t(e){function n(t){return Math.pow(t,e)}return e=+e,n.exponent=t,n}(3),yc=function t(e){function n(t){return 1-Math.pow(1-t,e)}return e=+e,n.exponent=t,n}(3),mc=function t(e){function n(t){return ((t*=2)<=1?Math.pow(t,e):2-Math.pow(2-t,e))/2}return e=+e,n.exponent=t,n}(3),bc=Math.PI,vc=bc/2;function _c(t){return 1==+t?1:1-Math.cos(t*vc)}function xc(t){return Math.sin(t*vc)}function kc(t){return (1-Math.cos(bc*t))/2}function wc(t){return 1.0009775171065494*(Math.pow(2,-10*t)-.0009765625)}function Tc(t){return wc(1-+t)}function Ec(t){return 1-wc(t)}function Cc(t){return ((t*=2)<=1?wc(1-t):2-wc(t-1))/2}function Sc(t){return 1-Math.sqrt(1-t*t)}function Ac(t){return Math.sqrt(1- --t*t)}function Mc(t){return ((t*=2)<=1?1-Math.sqrt(1-t*t):Math.sqrt(1-(t-=2)*t)+1)/2}var Nc=7.5625;function Oc(t){return 1-Dc(1-t)}function Dc(t){return (t=+t)<.36363636363636365?Nc*t*t:t<.7272727272727273?Nc*(t-=.5454545454545454)*t+.75:t<.9090909090909091?Nc*(t-=.8181818181818182)*t+.9375:Nc*(t-=.9545454545454546)*t+.984375}function Bc(t){return ((t*=2)<=1?1-Dc(1-t):Dc(t-1)+1)/2}var Lc=1.70158,Ic=function t(e){function n(t){return (t=+t)*t*(e*(t-1)+t)}return e=+e,n.overshoot=t,n}(Lc),Fc=function t(e){function n(t){return --t*t*((t+1)*e+t)+1}return e=+e,n.overshoot=t,n}(Lc),Rc=function t(e){function n(t){return ((t*=2)<1?t*t*((e+1)*t-e):(t-=2)*t*((e+1)*t+e)+2)/2}return e=+e,n.overshoot=t,n}(Lc),Pc=2*Math.PI,jc=function t(e,n){var r=Math.asin(1/(e=Math.max(1,e)))*(n/=Pc);function i(t){return e*wc(- --t)*Math.sin((r-t)/n)}return i.amplitude=function(e){return t(e,n*Pc)},i.period=function(n){return t(e,n)},i}(1,.3),zc=function t(e,n){var r=Math.asin(1/(e=Math.max(1,e)))*(n/=Pc);function i(t){return 1-e*wc(t=+t)*Math.sin((t+r)/n)}return i.amplitude=function(e){return t(e,n*Pc)},i.period=function(n){return t(e,n)},i}(1,.3),Yc=function t(e,n){var r=Math.asin(1/(e=Math.max(1,e)))*(n/=Pc);function i(t){return ((t=2*t-1)<0?e*wc(-t)*Math.sin((r-t)/n):2-e*wc(t)*Math.sin((r+t)/n))/2}return i.amplitude=function(e){return t(e,n*Pc)},i.period=function(n){return t(e,n)},i}(1,.3);function Uc(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.blob()}function $c(t,e){return fetch(t,e).then(Uc)}function Wc(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.arrayBuffer()}function qc(t,e){return fetch(t,e).then(Wc)}function Hc(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);return t.text()}function Vc(t,e){return fetch(t,e).then(Hc)}function Gc(t){return function(e,n,r){return 2===arguments.length&&"function"==typeof n&&(r=n,n=void 0),Vc(e,n).then((function(e){return t(e,r)}))}}function Xc(t,e,n,r){3===arguments.length&&"function"==typeof n&&(r=n,n=void 0);var i=Hs(t);return Vc(e,n).then((function(t){return i.parse(t,r)}))}var Zc=Gc(Gs),Qc=Gc(nc);function Kc(t,e){return new Promise((function(n,r){var i=new Image;for(var a in e)i[a]=e[a];i.onerror=r,i.onload=function(){n(i);},i.src=t;}))}function Jc(t){if(!t.ok)throw new Error(t.status+" "+t.statusText);if(204!==t.status&&205!==t.status)return t.json()}function tl(t,e){return fetch(t,e).then(Jc)}function el(t){return (e,n)=>Vc(e,n).then((e=>(new DOMParser).parseFromString(e,t)))}const nl=el("application/xml");var rl=el("text/html"),il=el("image/svg+xml");function al(t,e){var n,r=1;function i(){var i,a,o=n.length,s=0,c=0;for(i=0;i<o;++i)s+=(a=n[i]).x,c+=a.y;for(s=(s/o-t)*r,c=(c/o-e)*r,i=0;i<o;++i)(a=n[i]).x-=s,a.y-=c;}return null==t&&(t=0),null==e&&(e=0),i.initialize=function(t){n=t;},i.x=function(e){return arguments.length?(t=+e,i):t},i.y=function(t){return arguments.length?(e=+t,i):e},i.strength=function(t){return arguments.length?(r=+t,i):r},i}function ol(t,e,n,r){if(isNaN(e)||isNaN(n))return t;var i,a,o,s,c,l,u,h,f,d=t._root,p={data:r},g=t._x0,y=t._y0,m=t._x1,b=t._y1;if(!d)return t._root=p,t;for(;d.length;)if((l=e>=(a=(g+m)/2))?g=a:m=a,(u=n>=(o=(y+b)/2))?y=o:b=o,i=d,!(d=d[h=u<<1|l]))return i[h]=p,t;if(s=+t._x.call(null,d.data),c=+t._y.call(null,d.data),e===s&&n===c)return p.next=d,i?i[h]=p:t._root=p,t;do{i=i?i[h]=new Array(4):t._root=new Array(4),(l=e>=(a=(g+m)/2))?g=a:m=a,(u=n>=(o=(y+b)/2))?y=o:b=o;}while((h=u<<1|l)==(f=(c>=o)<<1|s>=a));return i[f]=d,i[h]=p,t}function sl(t,e,n,r,i){this.node=t,this.x0=e,this.y0=n,this.x1=r,this.y1=i;}function cl(t){return t[0]}function ll(t){return t[1]}function ul(t,e,n){var r=new hl(null==e?cl:e,null==n?ll:n,NaN,NaN,NaN,NaN);return null==t?r:r.addAll(t)}function hl(t,e,n,r,i,a){this._x=t,this._y=e,this._x0=n,this._y0=r,this._x1=i,this._y1=a,this._root=void 0;}function fl(t){for(var e={data:t.data},n=e;t=t.next;)n=n.next={data:t.data};return e}var dl=ul.prototype=hl.prototype;function pl(t){return function(){return t}}function gl(t){return 1e-6*(t()-.5)}function yl(t){return t.x+t.vx}function ml(t){return t.y+t.vy}function bl(t){var e,n,r,i=1,a=1;function o(){for(var t,o,c,l,u,h,f,d=e.length,p=0;p<a;++p)for(o=ul(e,yl,ml).visitAfter(s),t=0;t<d;++t)c=e[t],h=n[c.index],f=h*h,l=c.x+c.vx,u=c.y+c.vy,o.visit(g);function g(t,e,n,a,o){var s=t.data,d=t.r,p=h+d;if(!s)return e>l+p||a<l-p||n>u+p||o<u-p;if(s.index>c.index){var g=l-s.x-s.vx,y=u-s.y-s.vy,m=g*g+y*y;m<p*p&&(0===g&&(m+=(g=gl(r))*g),0===y&&(m+=(y=gl(r))*y),m=(p-(m=Math.sqrt(m)))/m*i,c.vx+=(g*=m)*(p=(d*=d)/(f+d)),c.vy+=(y*=m)*p,s.vx-=g*(p=1-p),s.vy-=y*p);}}}function s(t){if(t.data)return t.r=n[t.data.index];for(var e=t.r=0;e<4;++e)t[e]&&t[e].r>t.r&&(t.r=t[e].r);}function c(){if(e){var r,i,a=e.length;for(n=new Array(a),r=0;r<a;++r)i=e[r],n[i.index]=+t(i,r,e);}}return "function"!=typeof t&&(t=pl(null==t?1:+t)),o.initialize=function(t,n){e=t,r=n,c();},o.iterations=function(t){return arguments.length?(a=+t,o):a},o.strength=function(t){return arguments.length?(i=+t,o):i},o.radius=function(e){return arguments.length?(t="function"==typeof e?e:pl(+e),c(),o):t},o}function vl(t){return t.index}function _l(t,e){var n=t.get(e);if(!n)throw new Error("node not found: "+e);return n}function xl(t){var e,n,r,i,a,o,s=vl,c=function(t){return 1/Math.min(i[t.source.index],i[t.target.index])},l=pl(30),u=1;function h(r){for(var i=0,s=t.length;i<u;++i)for(var c,l,h,f,d,p,g,y=0;y<s;++y)l=(c=t[y]).source,f=(h=c.target).x+h.vx-l.x-l.vx||gl(o),d=h.y+h.vy-l.y-l.vy||gl(o),f*=p=((p=Math.sqrt(f*f+d*d))-n[y])/p*r*e[y],d*=p,h.vx-=f*(g=a[y]),h.vy-=d*g,l.vx+=f*(g=1-g),l.vy+=d*g;}function f(){if(r){var o,c,l=r.length,u=t.length,h=new Map(r.map(((t,e)=>[s(t,e,r),t])));for(o=0,i=new Array(l);o<u;++o)(c=t[o]).index=o,"object"!=typeof c.source&&(c.source=_l(h,c.source)),"object"!=typeof c.target&&(c.target=_l(h,c.target)),i[c.source.index]=(i[c.source.index]||0)+1,i[c.target.index]=(i[c.target.index]||0)+1;for(o=0,a=new Array(u);o<u;++o)c=t[o],a[o]=i[c.source.index]/(i[c.source.index]+i[c.target.index]);e=new Array(u),d(),n=new Array(u),p();}}function d(){if(r)for(var n=0,i=t.length;n<i;++n)e[n]=+c(t[n],n,t);}function p(){if(r)for(var e=0,i=t.length;e<i;++e)n[e]=+l(t[e],e,t);}return null==t&&(t=[]),h.initialize=function(t,e){r=t,o=e,f();},h.links=function(e){return arguments.length?(t=e,f(),h):t},h.id=function(t){return arguments.length?(s=t,h):s},h.iterations=function(t){return arguments.length?(u=+t,h):u},h.strength=function(t){return arguments.length?(c="function"==typeof t?t:pl(+t),d(),h):c},h.distance=function(t){return arguments.length?(l="function"==typeof t?t:pl(+t),p(),h):l},h}dl.copy=function(){var t,e,n=new hl(this._x,this._y,this._x0,this._y0,this._x1,this._y1),r=this._root;if(!r)return n;if(!r.length)return n._root=fl(r),n;for(t=[{source:r,target:n._root=new Array(4)}];r=t.pop();)for(var i=0;i<4;++i)(e=r.source[i])&&(e.length?t.push({source:e,target:r.target[i]=new Array(4)}):r.target[i]=fl(e));return n},dl.add=function(t){const e=+this._x.call(null,t),n=+this._y.call(null,t);return ol(this.cover(e,n),e,n,t)},dl.addAll=function(t){var e,n,r,i,a=t.length,o=new Array(a),s=new Array(a),c=1/0,l=1/0,u=-1/0,h=-1/0;for(n=0;n<a;++n)isNaN(r=+this._x.call(null,e=t[n]))||isNaN(i=+this._y.call(null,e))||(o[n]=r,s[n]=i,r<c&&(c=r),r>u&&(u=r),i<l&&(l=i),i>h&&(h=i));if(c>u||l>h)return this;for(this.cover(c,l).cover(u,h),n=0;n<a;++n)ol(this,o[n],s[n],t[n]);return this},dl.cover=function(t,e){if(isNaN(t=+t)||isNaN(e=+e))return this;var n=this._x0,r=this._y0,i=this._x1,a=this._y1;if(isNaN(n))i=(n=Math.floor(t))+1,a=(r=Math.floor(e))+1;else {for(var o,s,c=i-n||1,l=this._root;n>t||t>=i||r>e||e>=a;)switch(s=(e<r)<<1|t<n,(o=new Array(4))[s]=l,l=o,c*=2,s){case 0:i=n+c,a=r+c;break;case 1:n=i-c,a=r+c;break;case 2:i=n+c,r=a-c;break;case 3:n=i-c,r=a-c;}this._root&&this._root.length&&(this._root=l);}return this._x0=n,this._y0=r,this._x1=i,this._y1=a,this},dl.data=function(){var t=[];return this.visit((function(e){if(!e.length)do{t.push(e.data);}while(e=e.next)})),t},dl.extent=function(t){return arguments.length?this.cover(+t[0][0],+t[0][1]).cover(+t[1][0],+t[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]},dl.find=function(t,e,n){var r,i,a,o,s,c,l,u=this._x0,h=this._y0,f=this._x1,d=this._y1,p=[],g=this._root;for(g&&p.push(new sl(g,u,h,f,d)),null==n?n=1/0:(u=t-n,h=e-n,f=t+n,d=e+n,n*=n);c=p.pop();)if(!(!(g=c.node)||(i=c.x0)>f||(a=c.y0)>d||(o=c.x1)<u||(s=c.y1)<h))if(g.length){var y=(i+o)/2,m=(a+s)/2;p.push(new sl(g[3],y,m,o,s),new sl(g[2],i,m,y,s),new sl(g[1],y,a,o,m),new sl(g[0],i,a,y,m)),(l=(e>=m)<<1|t>=y)&&(c=p[p.length-1],p[p.length-1]=p[p.length-1-l],p[p.length-1-l]=c);}else {var b=t-+this._x.call(null,g.data),v=e-+this._y.call(null,g.data),_=b*b+v*v;if(_<n){var x=Math.sqrt(n=_);u=t-x,h=e-x,f=t+x,d=e+x,r=g.data;}}return r},dl.remove=function(t){if(isNaN(a=+this._x.call(null,t))||isNaN(o=+this._y.call(null,t)))return this;var e,n,r,i,a,o,s,c,l,u,h,f,d=this._root,p=this._x0,g=this._y0,y=this._x1,m=this._y1;if(!d)return this;if(d.length)for(;;){if((l=a>=(s=(p+y)/2))?p=s:y=s,(u=o>=(c=(g+m)/2))?g=c:m=c,e=d,!(d=d[h=u<<1|l]))return this;if(!d.length)break;(e[h+1&3]||e[h+2&3]||e[h+3&3])&&(n=e,f=h);}for(;d.data!==t;)if(r=d,!(d=d.next))return this;return (i=d.next)&&delete d.next,r?(i?r.next=i:delete r.next,this):e?(i?e[h]=i:delete e[h],(d=e[0]||e[1]||e[2]||e[3])&&d===(e[3]||e[2]||e[1]||e[0])&&!d.length&&(n?n[f]=d:this._root=d),this):(this._root=i,this)},dl.removeAll=function(t){for(var e=0,n=t.length;e<n;++e)this.remove(t[e]);return this},dl.root=function(){return this._root},dl.size=function(){var t=0;return this.visit((function(e){if(!e.length)do{++t;}while(e=e.next)})),t},dl.visit=function(t){var e,n,r,i,a,o,s=[],c=this._root;for(c&&s.push(new sl(c,this._x0,this._y0,this._x1,this._y1));e=s.pop();)if(!t(c=e.node,r=e.x0,i=e.y0,a=e.x1,o=e.y1)&&c.length){var l=(r+a)/2,u=(i+o)/2;(n=c[3])&&s.push(new sl(n,l,u,a,o)),(n=c[2])&&s.push(new sl(n,r,u,l,o)),(n=c[1])&&s.push(new sl(n,l,i,a,u)),(n=c[0])&&s.push(new sl(n,r,i,l,u));}return this},dl.visitAfter=function(t){var e,n=[],r=[];for(this._root&&n.push(new sl(this._root,this._x0,this._y0,this._x1,this._y1));e=n.pop();){var i=e.node;if(i.length){var a,o=e.x0,s=e.y0,c=e.x1,l=e.y1,u=(o+c)/2,h=(s+l)/2;(a=i[0])&&n.push(new sl(a,o,s,u,h)),(a=i[1])&&n.push(new sl(a,u,s,c,h)),(a=i[2])&&n.push(new sl(a,o,h,u,l)),(a=i[3])&&n.push(new sl(a,u,h,c,l));}r.push(e);}for(;e=r.pop();)t(e.node,e.x0,e.y0,e.x1,e.y1);return this},dl.x=function(t){return arguments.length?(this._x=t,this):this._x},dl.y=function(t){return arguments.length?(this._y=t,this):this._y};const kl=4294967296;function wl(t){return t.x}function Tl(t){return t.y}var El=Math.PI*(3-Math.sqrt(5));function Cl(t){var e,n=1,r=.001,i=1-Math.pow(r,1/300),a=0,o=.6,s=new Map,c=Qr(h),l=fe("tick","end"),u=function(){let t=1;return ()=>(t=(1664525*t+1013904223)%kl)/kl}();function h(){f(),l.call("tick",e),n<r&&(c.stop(),l.call("end",e));}function f(r){var c,l,u=t.length;void 0===r&&(r=1);for(var h=0;h<r;++h)for(n+=(a-n)*i,s.forEach((function(t){t(n);})),c=0;c<u;++c)null==(l=t[c]).fx?l.x+=l.vx*=o:(l.x=l.fx,l.vx=0),null==l.fy?l.y+=l.vy*=o:(l.y=l.fy,l.vy=0);return e}function d(){for(var e,n=0,r=t.length;n<r;++n){if((e=t[n]).index=n,null!=e.fx&&(e.x=e.fx),null!=e.fy&&(e.y=e.fy),isNaN(e.x)||isNaN(e.y)){var i=10*Math.sqrt(.5+n),a=n*El;e.x=i*Math.cos(a),e.y=i*Math.sin(a);}(isNaN(e.vx)||isNaN(e.vy))&&(e.vx=e.vy=0);}}function p(e){return e.initialize&&e.initialize(t,u),e}return null==t&&(t=[]),d(),e={tick:f,restart:function(){return c.restart(h),e},stop:function(){return c.stop(),e},nodes:function(n){return arguments.length?(t=n,d(),s.forEach(p),e):t},alpha:function(t){return arguments.length?(n=+t,e):n},alphaMin:function(t){return arguments.length?(r=+t,e):r},alphaDecay:function(t){return arguments.length?(i=+t,e):+i},alphaTarget:function(t){return arguments.length?(a=+t,e):a},velocityDecay:function(t){return arguments.length?(o=1-t,e):1-o},randomSource:function(t){return arguments.length?(u=t,s.forEach(p),e):u},force:function(t,n){return arguments.length>1?(null==n?s.delete(t):s.set(t,p(n)),e):s.get(t)},find:function(e,n,r){var i,a,o,s,c,l=0,u=t.length;for(null==r?r=1/0:r*=r,l=0;l<u;++l)(o=(i=e-(s=t[l]).x)*i+(a=n-s.y)*a)<r&&(c=s,r=o);return c},on:function(t,n){return arguments.length>1?(l.on(t,n),e):l.on(t)}}}function Sl(){var t,e,n,r,i,a=pl(-30),o=1,s=1/0,c=.81;function l(n){var i,a=t.length,o=ul(t,wl,Tl).visitAfter(h);for(r=n,i=0;i<a;++i)e=t[i],o.visit(f);}function u(){if(t){var e,n,r=t.length;for(i=new Array(r),e=0;e<r;++e)n=t[e],i[n.index]=+a(n,e,t);}}function h(t){var e,n,r,a,o,s=0,c=0;if(t.length){for(r=a=o=0;o<4;++o)(e=t[o])&&(n=Math.abs(e.value))&&(s+=e.value,c+=n,r+=n*e.x,a+=n*e.y);t.x=r/c,t.y=a/c;}else {(e=t).x=e.data.x,e.y=e.data.y;do{s+=i[e.data.index];}while(e=e.next)}t.value=s;}function f(t,a,l,u){if(!t.value)return !0;var h=t.x-e.x,f=t.y-e.y,d=u-a,p=h*h+f*f;if(d*d/c<p)return p<s&&(0===h&&(p+=(h=gl(n))*h),0===f&&(p+=(f=gl(n))*f),p<o&&(p=Math.sqrt(o*p)),e.vx+=h*t.value*r/p,e.vy+=f*t.value*r/p),!0;if(!(t.length||p>=s)){(t.data!==e||t.next)&&(0===h&&(p+=(h=gl(n))*h),0===f&&(p+=(f=gl(n))*f),p<o&&(p=Math.sqrt(o*p)));do{t.data!==e&&(d=i[t.data.index]*r/p,e.vx+=h*d,e.vy+=f*d);}while(t=t.next)}}return l.initialize=function(e,r){t=e,n=r,u();},l.strength=function(t){return arguments.length?(a="function"==typeof t?t:pl(+t),u(),l):a},l.distanceMin=function(t){return arguments.length?(o=t*t,l):Math.sqrt(o)},l.distanceMax=function(t){return arguments.length?(s=t*t,l):Math.sqrt(s)},l.theta=function(t){return arguments.length?(c=t*t,l):Math.sqrt(c)},l}function Al(t,e,n){var r,i,a,o=pl(.1);function s(t){for(var o=0,s=r.length;o<s;++o){var c=r[o],l=c.x-e||1e-6,u=c.y-n||1e-6,h=Math.sqrt(l*l+u*u),f=(a[o]-h)*i[o]*t/h;c.vx+=l*f,c.vy+=u*f;}}function c(){if(r){var e,n=r.length;for(i=new Array(n),a=new Array(n),e=0;e<n;++e)a[e]=+t(r[e],e,r),i[e]=isNaN(a[e])?0:+o(r[e],e,r);}}return "function"!=typeof t&&(t=pl(+t)),null==e&&(e=0),null==n&&(n=0),s.initialize=function(t){r=t,c();},s.strength=function(t){return arguments.length?(o="function"==typeof t?t:pl(+t),c(),s):o},s.radius=function(e){return arguments.length?(t="function"==typeof e?e:pl(+e),c(),s):t},s.x=function(t){return arguments.length?(e=+t,s):e},s.y=function(t){return arguments.length?(n=+t,s):n},s}function Ml(t){var e,n,r,i=pl(.1);function a(t){for(var i,a=0,o=e.length;a<o;++a)(i=e[a]).vx+=(r[a]-i.x)*n[a]*t;}function o(){if(e){var a,o=e.length;for(n=new Array(o),r=new Array(o),a=0;a<o;++a)n[a]=isNaN(r[a]=+t(e[a],a,e))?0:+i(e[a],a,e);}}return "function"!=typeof t&&(t=pl(null==t?0:+t)),a.initialize=function(t){e=t,o();},a.strength=function(t){return arguments.length?(i="function"==typeof t?t:pl(+t),o(),a):i},a.x=function(e){return arguments.length?(t="function"==typeof e?e:pl(+e),o(),a):t},a}function Nl(t){var e,n,r,i=pl(.1);function a(t){for(var i,a=0,o=e.length;a<o;++a)(i=e[a]).vy+=(r[a]-i.y)*n[a]*t;}function o(){if(e){var a,o=e.length;for(n=new Array(o),r=new Array(o),a=0;a<o;++a)n[a]=isNaN(r[a]=+t(e[a],a,e))?0:+i(e[a],a,e);}}return "function"!=typeof t&&(t=pl(null==t?0:+t)),a.initialize=function(t){e=t,o();},a.strength=function(t){return arguments.length?(i="function"==typeof t?t:pl(+t),o(),a):i},a.y=function(e){return arguments.length?(t="function"==typeof e?e:pl(+e),o(),a):t},a}function Ol(t,e){if((n=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"))<0)return null;var n,r=t.slice(0,n);return [r.length>1?r[0]+r.slice(2):r,+t.slice(n+1)]}function Dl(t){return (t=Ol(Math.abs(t)))?t[1]:NaN}var Bl,Ll=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Il(t){if(!(e=Ll.exec(t)))throw new Error("invalid format: "+t);var e;return new Fl({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}function Fl(t){this.fill=void 0===t.fill?" ":t.fill+"",this.align=void 0===t.align?">":t.align+"",this.sign=void 0===t.sign?"-":t.sign+"",this.symbol=void 0===t.symbol?"":t.symbol+"",this.zero=!!t.zero,this.width=void 0===t.width?void 0:+t.width,this.comma=!!t.comma,this.precision=void 0===t.precision?void 0:+t.precision,this.trim=!!t.trim,this.type=void 0===t.type?"":t.type+"";}function Rl(t,e){var n=Ol(t,e);if(!n)return t+"";var r=n[0],i=n[1];return i<0?"0."+new Array(-i).join("0")+r:r.length>i+1?r.slice(0,i+1)+"."+r.slice(i+1):r+new Array(i-r.length+2).join("0")}Il.prototype=Fl.prototype,Fl.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type};const Pl={"%":(t,e)=>(100*t).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:function(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)},e:(t,e)=>t.toExponential(e),f:(t,e)=>t.toFixed(e),g:(t,e)=>t.toPrecision(e),o:t=>Math.round(t).toString(8),p:(t,e)=>Rl(100*t,e),r:Rl,s:function(t,e){var n=Ol(t,e);if(!n)return t+"";var r=n[0],i=n[1],a=i-(Bl=3*Math.max(-8,Math.min(8,Math.floor(i/3))))+1,o=r.length;return a===o?r:a>o?r+new Array(a-o+1).join("0"):a>0?r.slice(0,a)+"."+r.slice(a):"0."+new Array(1-a).join("0")+Ol(t,Math.max(0,e+a-1))[0]},X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function jl(t){return t}var zl,Yl,Ul,$l=Array.prototype.map,Wl=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function ql(t){var e,n,r=void 0===t.grouping||void 0===t.thousands?jl:(e=$l.call(t.grouping,Number),n=t.thousands+"",function(t,r){for(var i=t.length,a=[],o=0,s=e[0],c=0;i>0&&s>0&&(c+s+1>r&&(s=Math.max(1,r-c)),a.push(t.substring(i-=s,i+s)),!((c+=s+1)>r));)s=e[o=(o+1)%e.length];return a.reverse().join(n)}),i=void 0===t.currency?"":t.currency[0]+"",a=void 0===t.currency?"":t.currency[1]+"",o=void 0===t.decimal?".":t.decimal+"",s=void 0===t.numerals?jl:function(t){return function(e){return e.replace(/[0-9]/g,(function(e){return t[+e]}))}}($l.call(t.numerals,String)),c=void 0===t.percent?"%":t.percent+"",l=void 0===t.minus?"":t.minus+"",u=void 0===t.nan?"NaN":t.nan+"";function h(t){var e=(t=Il(t)).fill,n=t.align,h=t.sign,f=t.symbol,d=t.zero,p=t.width,g=t.comma,y=t.precision,m=t.trim,b=t.type;"n"===b?(g=!0,b="g"):Pl[b]||(void 0===y&&(y=12),m=!0,b="g"),(d||"0"===e&&"="===n)&&(d=!0,e="0",n="=");var v="$"===f?i:"#"===f&&/[boxX]/.test(b)?"0"+b.toLowerCase():"",_="$"===f?a:/[%p]/.test(b)?c:"",x=Pl[b],k=/[defgprs%]/.test(b);function w(t){var i,a,c,f=v,w=_;if("c"===b)w=x(t)+w,t="";else {var T=(t=+t)<0||1/t<0;if(t=isNaN(t)?u:x(Math.abs(t),y),m&&(t=function(t){t:for(var e,n=t.length,r=1,i=-1;r<n;++r)switch(t[r]){case".":i=e=r;break;case"0":0===i&&(i=r),e=r;break;default:if(!+t[r])break t;i>0&&(i=0);}return i>0?t.slice(0,i)+t.slice(e+1):t}(t)),T&&0==+t&&"+"!==h&&(T=!1),f=(T?"("===h?h:l:"-"===h||"("===h?"":h)+f,w=("s"===b?Wl[8+Bl/3]:"")+w+(T&&"("===h?")":""),k)for(i=-1,a=t.length;++i<a;)if(48>(c=t.charCodeAt(i))||c>57){w=(46===c?o+t.slice(i+1):t.slice(i))+w,t=t.slice(0,i);break}}g&&!d&&(t=r(t,1/0));var E=f.length+t.length+w.length,C=E<p?new Array(p-E+1).join(e):"";switch(g&&d&&(t=r(C+t,C.length?p-w.length:1/0),C=""),n){case"<":t=f+t+w+C;break;case"=":t=f+C+t+w;break;case"^":t=C.slice(0,E=C.length>>1)+f+t+w+C.slice(E);break;default:t=C+f+t+w;}return s(t)}return y=void 0===y?6:/[gprs]/.test(b)?Math.max(1,Math.min(21,y)):Math.max(0,Math.min(20,y)),w.toString=function(){return t+""},w}return {format:h,formatPrefix:function(t,e){var n=h(((t=Il(t)).type="f",t)),r=3*Math.max(-8,Math.min(8,Math.floor(Dl(e)/3))),i=Math.pow(10,-r),a=Wl[8+r/3];return function(t){return n(i*t)+a}}}}function Hl(t){return zl=ql(t),Yl=zl.format,Ul=zl.formatPrefix,zl}function Vl(t){return Math.max(0,-Dl(Math.abs(t)))}function Gl(t,e){return Math.max(0,3*Math.max(-8,Math.min(8,Math.floor(Dl(e)/3)))-Dl(Math.abs(t)))}function Xl(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,Dl(e)-Dl(t))+1}Hl({thousands:",",grouping:[3],currency:["$",""]});var Zl=1e-6,Ql=1e-12,Kl=Math.PI,Jl=Kl/2,tu=Kl/4,eu=2*Kl,nu=180/Kl,ru=Kl/180,iu=Math.abs,au=Math.atan,ou=Math.atan2,su=Math.cos,cu=Math.ceil,lu=Math.exp,uu=(Math.hypot),hu=Math.log,fu=Math.pow,du=Math.sin,pu=Math.sign||function(t){return t>0?1:t<0?-1:0},gu=Math.sqrt,yu=Math.tan;function mu(t){return t>1?0:t<-1?Kl:Math.acos(t)}function bu(t){return t>1?Jl:t<-1?-Jl:Math.asin(t)}function vu(t){return (t=du(t/2))*t}function _u(){}function xu(t,e){t&&wu.hasOwnProperty(t.type)&&wu[t.type](t,e);}var ku={Feature:function(t,e){xu(t.geometry,e);},FeatureCollection:function(t,e){for(var n=t.features,r=-1,i=n.length;++r<i;)xu(n[r].geometry,e);}},wu={Sphere:function(t,e){e.sphere();},Point:function(t,e){t=t.coordinates,e.point(t[0],t[1],t[2]);},MultiPoint:function(t,e){for(var n=t.coordinates,r=-1,i=n.length;++r<i;)t=n[r],e.point(t[0],t[1],t[2]);},LineString:function(t,e){Tu(t.coordinates,e,0);},MultiLineString:function(t,e){for(var n=t.coordinates,r=-1,i=n.length;++r<i;)Tu(n[r],e,0);},Polygon:function(t,e){Eu(t.coordinates,e);},MultiPolygon:function(t,e){for(var n=t.coordinates,r=-1,i=n.length;++r<i;)Eu(n[r],e);},GeometryCollection:function(t,e){for(var n=t.geometries,r=-1,i=n.length;++r<i;)xu(n[r],e);}};function Tu(t,e,n){var r,i=-1,a=t.length-n;for(e.lineStart();++i<a;)r=t[i],e.point(r[0],r[1],r[2]);e.lineEnd();}function Eu(t,e){var n=-1,r=t.length;for(e.polygonStart();++n<r;)Tu(t[n],e,1);e.polygonEnd();}function Cu(t,e){t&&ku.hasOwnProperty(t.type)?ku[t.type](t,e):xu(t,e);}var Su,Au,Mu,Nu,Ou,Du,Bu,Lu,Iu,Fu,Ru,Pu,ju,zu,Yu,Uu,$u=new x,Wu=new x,qu={point:_u,lineStart:_u,lineEnd:_u,polygonStart:function(){$u=new x,qu.lineStart=Hu,qu.lineEnd=Vu;},polygonEnd:function(){var t=+$u;Wu.add(t<0?eu+t:t),this.lineStart=this.lineEnd=this.point=_u;},sphere:function(){Wu.add(eu);}};function Hu(){qu.point=Gu;}function Vu(){Xu(Su,Au);}function Gu(t,e){qu.point=Xu,Su=t,Au=e,Mu=t*=ru,Nu=su(e=(e*=ru)/2+tu),Ou=du(e);}function Xu(t,e){var n=(t*=ru)-Mu,r=n>=0?1:-1,i=r*n,a=su(e=(e*=ru)/2+tu),o=du(e),s=Ou*o,c=Nu*a+s*su(i),l=s*r*du(i);$u.add(ou(l,c)),Mu=t,Nu=a,Ou=o;}function Zu(t){return Wu=new x,Cu(t,qu),2*Wu}function Qu(t){return [ou(t[1],t[0]),bu(t[2])]}function Ku(t){var e=t[0],n=t[1],r=su(n);return [r*su(e),r*du(e),du(n)]}function Ju(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function th(t,e){return [t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function eh(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2];}function nh(t,e){return [t[0]*e,t[1]*e,t[2]*e]}function rh(t){var e=gu(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e;}var ih,ah,oh,sh,ch,lh,uh,hh,fh,dh,ph,gh,yh,mh,bh,vh,_h={point:xh,lineStart:wh,lineEnd:Th,polygonStart:function(){_h.point=Eh,_h.lineStart=Ch,_h.lineEnd=Sh,zu=new x,qu.polygonStart();},polygonEnd:function(){qu.polygonEnd(),_h.point=xh,_h.lineStart=wh,_h.lineEnd=Th,$u<0?(Du=-(Lu=180),Bu=-(Iu=90)):zu>Zl?Iu=90:zu<-1e-6&&(Bu=-90),Uu[0]=Du,Uu[1]=Lu;},sphere:function(){Du=-(Lu=180),Bu=-(Iu=90);}};function xh(t,e){Yu.push(Uu=[Du=t,Lu=t]),e<Bu&&(Bu=e),e>Iu&&(Iu=e);}function kh(t,e){var n=Ku([t*ru,e*ru]);if(ju){var r=th(ju,n),i=th([r[1],-r[0],0],r);rh(i),i=Qu(i);var a,o=t-Fu,s=o>0?1:-1,c=i[0]*nu*s,l=iu(o)>180;l^(s*Fu<c&&c<s*t)?(a=i[1]*nu)>Iu&&(Iu=a):l^(s*Fu<(c=(c+360)%360-180)&&c<s*t)?(a=-i[1]*nu)<Bu&&(Bu=a):(e<Bu&&(Bu=e),e>Iu&&(Iu=e)),l?t<Fu?Ah(Du,t)>Ah(Du,Lu)&&(Lu=t):Ah(t,Lu)>Ah(Du,Lu)&&(Du=t):Lu>=Du?(t<Du&&(Du=t),t>Lu&&(Lu=t)):t>Fu?Ah(Du,t)>Ah(Du,Lu)&&(Lu=t):Ah(t,Lu)>Ah(Du,Lu)&&(Du=t);}else Yu.push(Uu=[Du=t,Lu=t]);e<Bu&&(Bu=e),e>Iu&&(Iu=e),ju=n,Fu=t;}function wh(){_h.point=kh;}function Th(){Uu[0]=Du,Uu[1]=Lu,_h.point=xh,ju=null;}function Eh(t,e){if(ju){var n=t-Fu;zu.add(iu(n)>180?n+(n>0?360:-360):n);}else Ru=t,Pu=e;qu.point(t,e),kh(t,e);}function Ch(){qu.lineStart();}function Sh(){Eh(Ru,Pu),qu.lineEnd(),iu(zu)>Zl&&(Du=-(Lu=180)),Uu[0]=Du,Uu[1]=Lu,ju=null;}function Ah(t,e){return (e-=t)<0?e+360:e}function Mh(t,e){return t[0]-e[0]}function Nh(t,e){return t[0]<=t[1]?t[0]<=e&&e<=t[1]:e<t[0]||t[1]<e}function Oh(t){var e,n,r,i,a,o,s;if(Iu=Lu=-(Du=Bu=1/0),Yu=[],Cu(t,_h),n=Yu.length){for(Yu.sort(Mh),e=1,a=[r=Yu[0]];e<n;++e)Nh(r,(i=Yu[e])[0])||Nh(r,i[1])?(Ah(r[0],i[1])>Ah(r[0],r[1])&&(r[1]=i[1]),Ah(i[0],r[1])>Ah(r[0],r[1])&&(r[0]=i[0])):a.push(r=i);for(o=-1/0,e=0,r=a[n=a.length-1];e<=n;r=i,++e)i=a[e],(s=Ah(r[1],i[0]))>o&&(o=s,Du=i[0],Lu=r[1]);}return Yu=Uu=null,Du===1/0||Bu===1/0?[[NaN,NaN],[NaN,NaN]]:[[Du,Bu],[Lu,Iu]]}var Dh={sphere:_u,point:Bh,lineStart:Ih,lineEnd:Ph,polygonStart:function(){Dh.lineStart=jh,Dh.lineEnd=zh;},polygonEnd:function(){Dh.lineStart=Ih,Dh.lineEnd=Ph;}};function Bh(t,e){t*=ru;var n=su(e*=ru);Lh(n*su(t),n*du(t),du(e));}function Lh(t,e,n){++ih,oh+=(t-oh)/ih,sh+=(e-sh)/ih,ch+=(n-ch)/ih;}function Ih(){Dh.point=Fh;}function Fh(t,e){t*=ru;var n=su(e*=ru);mh=n*su(t),bh=n*du(t),vh=du(e),Dh.point=Rh,Lh(mh,bh,vh);}function Rh(t,e){t*=ru;var n=su(e*=ru),r=n*su(t),i=n*du(t),a=du(e),o=ou(gu((o=bh*a-vh*i)*o+(o=vh*r-mh*a)*o+(o=mh*i-bh*r)*o),mh*r+bh*i+vh*a);ah+=o,lh+=o*(mh+(mh=r)),uh+=o*(bh+(bh=i)),hh+=o*(vh+(vh=a)),Lh(mh,bh,vh);}function Ph(){Dh.point=Bh;}function jh(){Dh.point=Yh;}function zh(){Uh(gh,yh),Dh.point=Bh;}function Yh(t,e){gh=t,yh=e,t*=ru,e*=ru,Dh.point=Uh;var n=su(e);mh=n*su(t),bh=n*du(t),vh=du(e),Lh(mh,bh,vh);}function Uh(t,e){t*=ru;var n=su(e*=ru),r=n*su(t),i=n*du(t),a=du(e),o=bh*a-vh*i,s=vh*r-mh*a,c=mh*i-bh*r,l=uu(o,s,c),u=bu(l),h=l&&-u/l;fh.add(h*o),dh.add(h*s),ph.add(h*c),ah+=u,lh+=u*(mh+(mh=r)),uh+=u*(bh+(bh=i)),hh+=u*(vh+(vh=a)),Lh(mh,bh,vh);}function $h(t){ih=ah=oh=sh=ch=lh=uh=hh=0,fh=new x,dh=new x,ph=new x,Cu(t,Dh);var e=+fh,n=+dh,r=+ph,i=uu(e,n,r);return i<Ql&&(e=lh,n=uh,r=hh,ah<Zl&&(e=oh,n=sh,r=ch),(i=uu(e,n,r))<Ql)?[NaN,NaN]:[ou(n,e)*nu,bu(r/i)*nu]}function Wh(t){return function(){return t}}function qh(t,e){function n(n,r){return n=t(n,r),e(n[0],n[1])}return t.invert&&e.invert&&(n.invert=function(n,r){return (n=e.invert(n,r))&&t.invert(n[0],n[1])}),n}function Hh(t,e){return [iu(t)>Kl?t+Math.round(-t/eu)*eu:t,e]}function Vh(t,e,n){return (t%=eu)?e||n?qh(Xh(t),Zh(e,n)):Xh(t):e||n?Zh(e,n):Hh}function Gh(t){return function(e,n){return [(e+=t)>Kl?e-eu:e<-Kl?e+eu:e,n]}}function Xh(t){var e=Gh(t);return e.invert=Gh(-t),e}function Zh(t,e){var n=su(t),r=du(t),i=su(e),a=du(e);function o(t,e){var o=su(e),s=su(t)*o,c=du(t)*o,l=du(e),u=l*n+s*r;return [ou(c*i-u*a,s*n-l*r),bu(u*i+c*a)]}return o.invert=function(t,e){var o=su(e),s=su(t)*o,c=du(t)*o,l=du(e),u=l*i-c*a;return [ou(c*i+l*a,s*n+u*r),bu(u*n-s*r)]},o}function Qh(t){function e(e){return (e=t(e[0]*ru,e[1]*ru))[0]*=nu,e[1]*=nu,e}return t=Vh(t[0]*ru,t[1]*ru,t.length>2?t[2]*ru:0),e.invert=function(e){return (e=t.invert(e[0]*ru,e[1]*ru))[0]*=nu,e[1]*=nu,e},e}function Kh(t,e,n,r,i,a){if(n){var o=su(e),s=du(e),c=r*n;null==i?(i=e+r*eu,a=e-c/2):(i=Jh(o,i),a=Jh(o,a),(r>0?i<a:i>a)&&(i+=r*eu));for(var l,u=i;r>0?u>a:u<a;u-=c)l=Qu([o,-s*su(u),-s*du(u)]),t.point(l[0],l[1]);}}function Jh(t,e){(e=Ku(e))[0]-=t,rh(e);var n=mu(-e[1]);return ((-e[2]<0?-n:n)+eu-Zl)%eu}function tf(){var t,e,n=Wh([0,0]),r=Wh(90),i=Wh(6),a={point:function(n,r){t.push(n=e(n,r)),n[0]*=nu,n[1]*=nu;}};function o(){var o=n.apply(this,arguments),s=r.apply(this,arguments)*ru,c=i.apply(this,arguments)*ru;return t=[],e=Vh(-o[0]*ru,-o[1]*ru,0).invert,Kh(a,s,c,1),o={type:"Polygon",coordinates:[t]},t=e=null,o}return o.center=function(t){return arguments.length?(n="function"==typeof t?t:Wh([+t[0],+t[1]]),o):n},o.radius=function(t){return arguments.length?(r="function"==typeof t?t:Wh(+t),o):r},o.precision=function(t){return arguments.length?(i="function"==typeof t?t:Wh(+t),o):i},o}function ef(){var t,e=[];return {point:function(e,n,r){t.push([e,n,r]);},lineStart:function(){e.push(t=[]);},lineEnd:_u,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()));},result:function(){var n=e;return e=[],t=null,n}}}function nf(t,e){return iu(t[0]-e[0])<Zl&&iu(t[1]-e[1])<Zl}function rf(t,e,n,r){this.x=t,this.z=e,this.o=n,this.e=r,this.v=!1,this.n=this.p=null;}function af(t,e,n,r,i){var a,o,s=[],c=[];if(t.forEach((function(t){if(!((e=t.length-1)<=0)){var e,n,r=t[0],o=t[e];if(nf(r,o)){if(!r[2]&&!o[2]){for(i.lineStart(),a=0;a<e;++a)i.point((r=t[a])[0],r[1]);return void i.lineEnd()}o[0]+=2e-6;}s.push(n=new rf(r,t,null,!0)),c.push(n.o=new rf(r,null,n,!1)),s.push(n=new rf(o,t,null,!1)),c.push(n.o=new rf(o,null,n,!0));}})),s.length){for(c.sort(e),of(s),of(c),a=0,o=c.length;a<o;++a)c[a].e=n=!n;for(var l,u,h=s[0];;){for(var f=h,d=!0;f.v;)if((f=f.n)===h)return;l=f.z,i.lineStart();do{if(f.v=f.o.v=!0,f.e){if(d)for(a=0,o=l.length;a<o;++a)i.point((u=l[a])[0],u[1]);else r(f.x,f.n.x,1,i);f=f.n;}else {if(d)for(l=f.p.z,a=l.length-1;a>=0;--a)i.point((u=l[a])[0],u[1]);else r(f.x,f.p.x,-1,i);f=f.p;}l=(f=f.o).z,d=!d;}while(!f.v);i.lineEnd();}}}function of(t){if(e=t.length){for(var e,n,r=0,i=t[0];++r<e;)i.n=n=t[r],n.p=i,i=n;i.n=n=t[0],n.p=i;}}function sf(t){return iu(t[0])<=Kl?t[0]:pu(t[0])*((iu(t[0])+Kl)%eu-Kl)}function cf(t,e){var n=sf(e),r=e[1],i=du(r),a=[du(n),-su(n),0],o=0,s=0,c=new x;1===i?r=Jl+Zl:-1===i&&(r=-Jl-Zl);for(var l=0,u=t.length;l<u;++l)if(f=(h=t[l]).length)for(var h,f,d=h[f-1],p=sf(d),g=d[1]/2+tu,y=du(g),m=su(g),b=0;b<f;++b,p=_,y=w,m=T,d=v){var v=h[b],_=sf(v),k=v[1]/2+tu,w=du(k),T=su(k),E=_-p,C=E>=0?1:-1,S=C*E,A=S>Kl,M=y*w;if(c.add(ou(M*C*du(S),m*T+M*su(S))),o+=A?E+C*eu:E,A^p>=n^_>=n){var N=th(Ku(d),Ku(v));rh(N);var O=th(a,N);rh(O);var D=(A^E>=0?-1:1)*bu(O[2]);(r>D||r===D&&(N[0]||N[1]))&&(s+=A^E>=0?1:-1);}}return (o<-1e-6||o<Zl&&c<-1e-12)^1&s}function lf(t,e,n,r){return function(i){var a,o,s,c=e(i),l=ef(),u=e(l),h=!1,f={point:d,lineStart:g,lineEnd:y,polygonStart:function(){f.point=m,f.lineStart=b,f.lineEnd=v,o=[],a=[];},polygonEnd:function(){f.point=d,f.lineStart=g,f.lineEnd=y,o=yt(o);var t=cf(a,r);o.length?(h||(i.polygonStart(),h=!0),af(o,hf,t,n,i)):t&&(h||(i.polygonStart(),h=!0),i.lineStart(),n(null,null,1,i),i.lineEnd()),h&&(i.polygonEnd(),h=!1),o=a=null;},sphere:function(){i.polygonStart(),i.lineStart(),n(null,null,1,i),i.lineEnd(),i.polygonEnd();}};function d(e,n){t(e,n)&&i.point(e,n);}function p(t,e){c.point(t,e);}function g(){f.point=p,c.lineStart();}function y(){f.point=d,c.lineEnd();}function m(t,e){s.push([t,e]),u.point(t,e);}function b(){u.lineStart(),s=[];}function v(){m(s[0][0],s[0][1]),u.lineEnd();var t,e,n,r,c=u.clean(),f=l.result(),d=f.length;if(s.pop(),a.push(s),s=null,d)if(1&c){if((e=(n=f[0]).length-1)>0){for(h||(i.polygonStart(),h=!0),i.lineStart(),t=0;t<e;++t)i.point((r=n[t])[0],r[1]);i.lineEnd();}}else d>1&&2&c&&f.push(f.pop().concat(f.shift())),o.push(f.filter(uf));}return f}}function uf(t){return t.length>1}function hf(t,e){return ((t=t.x)[0]<0?t[1]-Jl-Zl:Jl-t[1])-((e=e.x)[0]<0?e[1]-Jl-Zl:Jl-e[1])}Hh.invert=Hh;const ff=lf((function(){return !0}),(function(t){var e,n=NaN,r=NaN,i=NaN;return {lineStart:function(){t.lineStart(),e=1;},point:function(a,o){var s=a>0?Kl:-Kl,c=iu(a-n);iu(c-Kl)<Zl?(t.point(n,r=(r+o)/2>0?Jl:-Jl),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(s,r),t.point(a,r),e=0):i!==s&&c>=Kl&&(iu(n-i)<Zl&&(n-=i*Zl),iu(a-s)<Zl&&(a-=s*Zl),r=function(t,e,n,r){var i,a,o=du(t-n);return iu(o)>Zl?au((du(e)*(a=su(r))*du(n)-du(r)*(i=su(e))*du(t))/(i*a*o)):(e+r)/2}(n,r,a,o),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(s,r),e=0),t.point(n=a,r=o),i=s;},lineEnd:function(){t.lineEnd(),n=r=NaN;},clean:function(){return 2-e}}}),(function(t,e,n,r){var i;if(null==t)i=n*Jl,r.point(-Kl,i),r.point(0,i),r.point(Kl,i),r.point(Kl,0),r.point(Kl,-i),r.point(0,-i),r.point(-Kl,-i),r.point(-Kl,0),r.point(-Kl,i);else if(iu(t[0]-e[0])>Zl){var a=t[0]<e[0]?Kl:-Kl;i=n*a/2,r.point(-a,i),r.point(0,i),r.point(a,i);}else r.point(e[0],e[1]);}),[-Kl,-Jl]);function df(t){var e=su(t),n=6*ru,r=e>0,i=iu(e)>Zl;function a(t,n){return su(t)*su(n)>e}function o(t,n,r){var i=[1,0,0],a=th(Ku(t),Ku(n)),o=Ju(a,a),s=a[0],c=o-s*s;if(!c)return !r&&t;var l=e*o/c,u=-e*s/c,h=th(i,a),f=nh(i,l);eh(f,nh(a,u));var d=h,p=Ju(f,d),g=Ju(d,d),y=p*p-g*(Ju(f,f)-1);if(!(y<0)){var m=gu(y),b=nh(d,(-p-m)/g);if(eh(b,f),b=Qu(b),!r)return b;var v,_=t[0],x=n[0],k=t[1],w=n[1];x<_&&(v=_,_=x,x=v);var T=x-_,E=iu(T-Kl)<Zl;if(!E&&w<k&&(v=k,k=w,w=v),E||T<Zl?E?k+w>0^b[1]<(iu(b[0]-_)<Zl?k:w):k<=b[1]&&b[1]<=w:T>Kl^(_<=b[0]&&b[0]<=x)){var C=nh(d,(-p+m)/g);return eh(C,f),[b,Qu(C)]}}}function s(e,n){var i=r?t:Kl-t,a=0;return e<-i?a|=1:e>i&&(a|=2),n<-i?a|=4:n>i&&(a|=8),a}return lf(a,(function(t){var e,n,c,l,u;return {lineStart:function(){l=c=!1,u=1;},point:function(h,f){var d,p=[h,f],g=a(h,f),y=r?g?0:s(h,f):g?s(h+(h<0?Kl:-Kl),f):0;if(!e&&(l=c=g)&&t.lineStart(),g!==c&&(!(d=o(e,p))||nf(e,d)||nf(p,d))&&(p[2]=1),g!==c)u=0,g?(t.lineStart(),d=o(p,e),t.point(d[0],d[1])):(d=o(e,p),t.point(d[0],d[1],2),t.lineEnd()),e=d;else if(i&&e&&r^g){var m;y&n||!(m=o(p,e,!0))||(u=0,r?(t.lineStart(),t.point(m[0][0],m[0][1]),t.point(m[1][0],m[1][1]),t.lineEnd()):(t.point(m[1][0],m[1][1]),t.lineEnd(),t.lineStart(),t.point(m[0][0],m[0][1],3)));}!g||e&&nf(e,p)||t.point(p[0],p[1]),e=p,c=g,n=y;},lineEnd:function(){c&&t.lineEnd(),e=null;},clean:function(){return u|(l&&c)<<1}}}),(function(e,r,i,a){Kh(a,t,n,i,e,r);}),r?[0,-t]:[-Kl,t-Kl])}var pf,gf,yf,mf,bf=1e9,vf=-bf;function _f(t,e,n,r){function i(i,a){return t<=i&&i<=n&&e<=a&&a<=r}function a(i,a,s,l){var u=0,h=0;if(null==i||(u=o(i,s))!==(h=o(a,s))||c(i,a)<0^s>0)do{l.point(0===u||3===u?t:n,u>1?r:e);}while((u=(u+s+4)%4)!==h);else l.point(a[0],a[1]);}function o(r,i){return iu(r[0]-t)<Zl?i>0?0:3:iu(r[0]-n)<Zl?i>0?2:1:iu(r[1]-e)<Zl?i>0?1:0:i>0?3:2}function s(t,e){return c(t.x,e.x)}function c(t,e){var n=o(t,1),r=o(e,1);return n!==r?n-r:0===n?e[1]-t[1]:1===n?t[0]-e[0]:2===n?t[1]-e[1]:e[0]-t[0]}return function(o){var c,l,u,h,f,d,p,g,y,m,b,v=o,_=ef(),x={point:k,lineStart:function(){x.point=w,l&&l.push(u=[]),m=!0,y=!1,p=g=NaN;},lineEnd:function(){c&&(w(h,f),d&&y&&_.rejoin(),c.push(_.result())),x.point=k,y&&v.lineEnd();},polygonStart:function(){v=_,c=[],l=[],b=!0;},polygonEnd:function(){var e=function(){for(var e=0,n=0,i=l.length;n<i;++n)for(var a,o,s=l[n],c=1,u=s.length,h=s[0],f=h[0],d=h[1];c<u;++c)a=f,o=d,f=(h=s[c])[0],d=h[1],o<=r?d>r&&(f-a)*(r-o)>(d-o)*(t-a)&&++e:d<=r&&(f-a)*(r-o)<(d-o)*(t-a)&&--e;return e}(),n=b&&e,i=(c=yt(c)).length;(n||i)&&(o.polygonStart(),n&&(o.lineStart(),a(null,null,1,o),o.lineEnd()),i&&af(c,s,e,a,o),o.polygonEnd()),v=o,c=l=u=null;}};function k(t,e){i(t,e)&&v.point(t,e);}function w(a,o){var s=i(a,o);if(l&&u.push([a,o]),m)h=a,f=o,d=s,m=!1,s&&(v.lineStart(),v.point(a,o));else if(s&&y)v.point(a,o);else {var c=[p=Math.max(vf,Math.min(bf,p)),g=Math.max(vf,Math.min(bf,g))],_=[a=Math.max(vf,Math.min(bf,a)),o=Math.max(vf,Math.min(bf,o))];!function(t,e,n,r,i,a){var o,s=t[0],c=t[1],l=0,u=1,h=e[0]-s,f=e[1]-c;if(o=n-s,h||!(o>0)){if(o/=h,h<0){if(o<l)return;o<u&&(u=o);}else if(h>0){if(o>u)return;o>l&&(l=o);}if(o=i-s,h||!(o<0)){if(o/=h,h<0){if(o>u)return;o>l&&(l=o);}else if(h>0){if(o<l)return;o<u&&(u=o);}if(o=r-c,f||!(o>0)){if(o/=f,f<0){if(o<l)return;o<u&&(u=o);}else if(f>0){if(o>u)return;o>l&&(l=o);}if(o=a-c,f||!(o<0)){if(o/=f,f<0){if(o>u)return;o>l&&(l=o);}else if(f>0){if(o<l)return;o<u&&(u=o);}return l>0&&(t[0]=s+l*h,t[1]=c+l*f),u<1&&(e[0]=s+u*h,e[1]=c+u*f),!0}}}}}(c,_,t,e,n,r)?s&&(v.lineStart(),v.point(a,o),b=!1):(y||(v.lineStart(),v.point(c[0],c[1])),v.point(_[0],_[1]),s||v.lineEnd(),b=!1);}p=a,g=o,y=s;}return x}}function xf(){var t,e,n,r=0,i=0,a=960,o=500;return n={stream:function(n){return t&&e===n?t:t=_f(r,i,a,o)(e=n)},extent:function(s){return arguments.length?(r=+s[0][0],i=+s[0][1],a=+s[1][0],o=+s[1][1],t=e=null,n):[[r,i],[a,o]]}}}var kf={sphere:_u,point:_u,lineStart:function(){kf.point=Tf,kf.lineEnd=wf;},lineEnd:_u,polygonStart:_u,polygonEnd:_u};function wf(){kf.point=kf.lineEnd=_u;}function Tf(t,e){gf=t*=ru,yf=du(e*=ru),mf=su(e),kf.point=Ef;}function Ef(t,e){t*=ru;var n=du(e*=ru),r=su(e),i=iu(t-gf),a=su(i),o=r*du(i),s=mf*n-yf*r*a,c=yf*n+mf*r*a;pf.add(ou(gu(o*o+s*s),c)),gf=t,yf=n,mf=r;}function Cf(t){return pf=new x,Cu(t,kf),+pf}var Sf=[null,null],Af={type:"LineString",coordinates:Sf};function Mf(t,e){return Sf[0]=t,Sf[1]=e,Cf(Af)}var Nf={Feature:function(t,e){return Df(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,i=n.length;++r<i;)if(Df(n[r].geometry,e))return !0;return !1}},Of={Sphere:function(){return !0},Point:function(t,e){return Bf(t.coordinates,e)},MultiPoint:function(t,e){for(var n=t.coordinates,r=-1,i=n.length;++r<i;)if(Bf(n[r],e))return !0;return !1},LineString:function(t,e){return Lf(t.coordinates,e)},MultiLineString:function(t,e){for(var n=t.coordinates,r=-1,i=n.length;++r<i;)if(Lf(n[r],e))return !0;return !1},Polygon:function(t,e){return If(t.coordinates,e)},MultiPolygon:function(t,e){for(var n=t.coordinates,r=-1,i=n.length;++r<i;)if(If(n[r],e))return !0;return !1},GeometryCollection:function(t,e){for(var n=t.geometries,r=-1,i=n.length;++r<i;)if(Df(n[r],e))return !0;return !1}};function Df(t,e){return !(!t||!Of.hasOwnProperty(t.type))&&Of[t.type](t,e)}function Bf(t,e){return 0===Mf(t,e)}function Lf(t,e){for(var n,r,i,a=0,o=t.length;a<o;a++){if(0===(r=Mf(t[a],e)))return !0;if(a>0&&(i=Mf(t[a],t[a-1]))>0&&n<=i&&r<=i&&(n+r-i)*(1-Math.pow((n-r)/i,2))<Ql*i)return !0;n=r;}return !1}function If(t,e){return !!cf(t.map(Ff),Rf(e))}function Ff(t){return (t=t.map(Rf)).pop(),t}function Rf(t){return [t[0]*ru,t[1]*ru]}function Pf(t,e){return (t&&Nf.hasOwnProperty(t.type)?Nf[t.type]:Df)(t,e)}function jf(t,e,n){var r=xt(t,e-Zl,n).concat(e);return function(t){return r.map((function(e){return [t,e]}))}}function zf(t,e,n){var r=xt(t,e-Zl,n).concat(e);return function(t){return r.map((function(e){return [e,t]}))}}function Yf(){var t,e,n,r,i,a,o,s,c,l,u,h,f=10,d=f,p=90,g=360,y=2.5;function m(){return {type:"MultiLineString",coordinates:b()}}function b(){return xt(cu(r/p)*p,n,p).map(u).concat(xt(cu(s/g)*g,o,g).map(h)).concat(xt(cu(e/f)*f,t,f).filter((function(t){return iu(t%p)>Zl})).map(c)).concat(xt(cu(a/d)*d,i,d).filter((function(t){return iu(t%g)>Zl})).map(l))}return m.lines=function(){return b().map((function(t){return {type:"LineString",coordinates:t}}))},m.outline=function(){return {type:"Polygon",coordinates:[u(r).concat(h(o).slice(1),u(n).reverse().slice(1),h(s).reverse().slice(1))]}},m.extent=function(t){return arguments.length?m.extentMajor(t).extentMinor(t):m.extentMinor()},m.extentMajor=function(t){return arguments.length?(r=+t[0][0],n=+t[1][0],s=+t[0][1],o=+t[1][1],r>n&&(t=r,r=n,n=t),s>o&&(t=s,s=o,o=t),m.precision(y)):[[r,s],[n,o]]},m.extentMinor=function(n){return arguments.length?(e=+n[0][0],t=+n[1][0],a=+n[0][1],i=+n[1][1],e>t&&(n=e,e=t,t=n),a>i&&(n=a,a=i,i=n),m.precision(y)):[[e,a],[t,i]]},m.step=function(t){return arguments.length?m.stepMajor(t).stepMinor(t):m.stepMinor()},m.stepMajor=function(t){return arguments.length?(p=+t[0],g=+t[1],m):[p,g]},m.stepMinor=function(t){return arguments.length?(f=+t[0],d=+t[1],m):[f,d]},m.precision=function(f){return arguments.length?(y=+f,c=jf(a,i,90),l=zf(e,t,y),u=jf(s,o,90),h=zf(r,n,y),m):y},m.extentMajor([[-180,-89.999999],[180,89.999999]]).extentMinor([[-180,-80.000001],[180,80.000001]])}function Uf(){return Yf()()}function $f(t,e){var n=t[0]*ru,r=t[1]*ru,i=e[0]*ru,a=e[1]*ru,o=su(r),s=du(r),c=su(a),l=du(a),u=o*su(n),h=o*du(n),f=c*su(i),d=c*du(i),p=2*bu(gu(vu(a-r)+o*c*vu(i-n))),g=du(p),y=p?function(t){var e=du(t*=p)/g,n=du(p-t)/g,r=n*u+e*f,i=n*h+e*d,a=n*s+e*l;return [ou(i,r)*nu,ou(a,gu(r*r+i*i))*nu]}:function(){return [n*nu,r*nu]};return y.distance=p,y}const Wf=t=>t;var qf,Hf,Vf,Gf,Xf=new x,Zf=new x,Qf={point:_u,lineStart:_u,lineEnd:_u,polygonStart:function(){Qf.lineStart=Kf,Qf.lineEnd=ed;},polygonEnd:function(){Qf.lineStart=Qf.lineEnd=Qf.point=_u,Xf.add(iu(Zf)),Zf=new x;},result:function(){var t=Xf/2;return Xf=new x,t}};function Kf(){Qf.point=Jf;}function Jf(t,e){Qf.point=td,qf=Vf=t,Hf=Gf=e;}function td(t,e){Zf.add(Gf*t-Vf*e),Vf=t,Gf=e;}function ed(){td(qf,Hf);}const nd=Qf;var rd=1/0,id=rd,ad=-rd,od=ad,sd={point:function(t,e){t<rd&&(rd=t),t>ad&&(ad=t),e<id&&(id=e),e>od&&(od=e);},lineStart:_u,lineEnd:_u,polygonStart:_u,polygonEnd:_u,result:function(){var t=[[rd,id],[ad,od]];return ad=od=-(id=rd=1/0),t}};const cd=sd;var ld,ud,hd,fd,dd=0,pd=0,gd=0,yd=0,md=0,bd=0,vd=0,_d=0,xd=0,kd={point:wd,lineStart:Td,lineEnd:Sd,polygonStart:function(){kd.lineStart=Ad,kd.lineEnd=Md;},polygonEnd:function(){kd.point=wd,kd.lineStart=Td,kd.lineEnd=Sd;},result:function(){var t=xd?[vd/xd,_d/xd]:bd?[yd/bd,md/bd]:gd?[dd/gd,pd/gd]:[NaN,NaN];return dd=pd=gd=yd=md=bd=vd=_d=xd=0,t}};function wd(t,e){dd+=t,pd+=e,++gd;}function Td(){kd.point=Ed;}function Ed(t,e){kd.point=Cd,wd(hd=t,fd=e);}function Cd(t,e){var n=t-hd,r=e-fd,i=gu(n*n+r*r);yd+=i*(hd+t)/2,md+=i*(fd+e)/2,bd+=i,wd(hd=t,fd=e);}function Sd(){kd.point=wd;}function Ad(){kd.point=Nd;}function Md(){Od(ld,ud);}function Nd(t,e){kd.point=Od,wd(ld=hd=t,ud=fd=e);}function Od(t,e){var n=t-hd,r=e-fd,i=gu(n*n+r*r);yd+=i*(hd+t)/2,md+=i*(fd+e)/2,bd+=i,vd+=(i=fd*t-hd*e)*(hd+t),_d+=i*(fd+e),xd+=3*i,wd(hd=t,fd=e);}const Dd=kd;function Bd(t){this._context=t;}Bd.prototype={_radius:4.5,pointRadius:function(t){return this._radius=t,this},polygonStart:function(){this._line=0;},polygonEnd:function(){this._line=NaN;},lineStart:function(){this._point=0;},lineEnd:function(){0===this._line&&this._context.closePath(),this._point=NaN;},point:function(t,e){switch(this._point){case 0:this._context.moveTo(t,e),this._point=1;break;case 1:this._context.lineTo(t,e);break;default:this._context.moveTo(t+this._radius,e),this._context.arc(t,e,this._radius,0,eu);}},result:_u};var Ld,Id,Fd,Rd,Pd,jd=new x,zd={point:_u,lineStart:function(){zd.point=Yd;},lineEnd:function(){Ld&&Ud(Id,Fd),zd.point=_u;},polygonStart:function(){Ld=!0;},polygonEnd:function(){Ld=null;},result:function(){var t=+jd;return jd=new x,t}};function Yd(t,e){zd.point=Ud,Id=Rd=t,Fd=Pd=e;}function Ud(t,e){Rd-=t,Pd-=e,jd.add(gu(Rd*Rd+Pd*Pd)),Rd=t,Pd=e;}const $d=zd;function Wd(){this._string=[];}function qd(t){return "m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}function Hd(t,e){var n,r,i=4.5;function a(t){return t&&("function"==typeof i&&r.pointRadius(+i.apply(this,arguments)),Cu(t,n(r))),r.result()}return a.area=function(t){return Cu(t,n(nd)),nd.result()},a.measure=function(t){return Cu(t,n($d)),$d.result()},a.bounds=function(t){return Cu(t,n(cd)),cd.result()},a.centroid=function(t){return Cu(t,n(Dd)),Dd.result()},a.projection=function(e){return arguments.length?(n=null==e?(t=null,Wf):(t=e).stream,a):t},a.context=function(t){return arguments.length?(r=null==t?(e=null,new Wd):new Bd(e=t),"function"!=typeof i&&r.pointRadius(i),a):e},a.pointRadius=function(t){return arguments.length?(i="function"==typeof t?t:(r.pointRadius(+t),+t),a):i},a.projection(t).context(e)}function Vd(t){return {stream:Gd(t)}}function Gd(t){return function(e){var n=new Xd;for(var r in t)n[r]=t[r];return n.stream=e,n}}function Xd(){}function Zd(t,e,n){var r=t.clipExtent&&t.clipExtent();return t.scale(150).translate([0,0]),null!=r&&t.clipExtent(null),Cu(n,t.stream(cd)),e(cd.result()),null!=r&&t.clipExtent(r),t}function Qd(t,e,n){return Zd(t,(function(n){var r=e[1][0]-e[0][0],i=e[1][1]-e[0][1],a=Math.min(r/(n[1][0]-n[0][0]),i/(n[1][1]-n[0][1])),o=+e[0][0]+(r-a*(n[1][0]+n[0][0]))/2,s=+e[0][1]+(i-a*(n[1][1]+n[0][1]))/2;t.scale(150*a).translate([o,s]);}),n)}function Kd(t,e,n){return Qd(t,[[0,0],e],n)}function Jd(t,e,n){return Zd(t,(function(n){var r=+e,i=r/(n[1][0]-n[0][0]),a=(r-i*(n[1][0]+n[0][0]))/2,o=-i*n[0][1];t.scale(150*i).translate([a,o]);}),n)}function tp(t,e,n){return Zd(t,(function(n){var r=+e,i=r/(n[1][1]-n[0][1]),a=-i*n[0][0],o=(r-i*(n[1][1]+n[0][1]))/2;t.scale(150*i).translate([a,o]);}),n)}Wd.prototype={_radius:4.5,_circle:qd(4.5),pointRadius:function(t){return (t=+t)!==this._radius&&(this._radius=t,this._circle=null),this},polygonStart:function(){this._line=0;},polygonEnd:function(){this._line=NaN;},lineStart:function(){this._point=0;},lineEnd:function(){0===this._line&&this._string.push("Z"),this._point=NaN;},point:function(t,e){switch(this._point){case 0:this._string.push("M",t,",",e),this._point=1;break;case 1:this._string.push("L",t,",",e);break;default:null==this._circle&&(this._circle=qd(this._radius)),this._string.push("M",t,",",e,this._circle);}},result:function(){if(this._string.length){var t=this._string.join("");return this._string=[],t}return null}},Xd.prototype={constructor:Xd,point:function(t,e){this.stream.point(t,e);},sphere:function(){this.stream.sphere();},lineStart:function(){this.stream.lineStart();},lineEnd:function(){this.stream.lineEnd();},polygonStart:function(){this.stream.polygonStart();},polygonEnd:function(){this.stream.polygonEnd();}};var ep=su(30*ru);function np(t,e){return +e?function(t,e){function n(r,i,a,o,s,c,l,u,h,f,d,p,g,y){var m=l-r,b=u-i,v=m*m+b*b;if(v>4*e&&g--){var _=o+f,x=s+d,k=c+p,w=gu(_*_+x*x+k*k),T=bu(k/=w),E=iu(iu(k)-1)<Zl||iu(a-h)<Zl?(a+h)/2:ou(x,_),C=t(E,T),S=C[0],A=C[1],M=S-r,N=A-i,O=b*M-m*N;(O*O/v>e||iu((m*M+b*N)/v-.5)>.3||o*f+s*d+c*p<ep)&&(n(r,i,a,o,s,c,S,A,E,_/=w,x/=w,k,g,y),y.point(S,A),n(S,A,E,_,x,k,l,u,h,f,d,p,g,y));}}return function(e){var r,i,a,o,s,c,l,u,h,f,d,p,g={point:y,lineStart:m,lineEnd:v,polygonStart:function(){e.polygonStart(),g.lineStart=_;},polygonEnd:function(){e.polygonEnd(),g.lineStart=m;}};function y(n,r){n=t(n,r),e.point(n[0],n[1]);}function m(){u=NaN,g.point=b,e.lineStart();}function b(r,i){var a=Ku([r,i]),o=t(r,i);n(u,h,l,f,d,p,u=o[0],h=o[1],l=r,f=a[0],d=a[1],p=a[2],16,e),e.point(u,h);}function v(){g.point=y,e.lineEnd();}function _(){m(),g.point=x,g.lineEnd=k;}function x(t,e){b(r=t,e),i=u,a=h,o=f,s=d,c=p,g.point=b;}function k(){n(u,h,l,f,d,p,i,a,r,o,s,c,16,e),g.lineEnd=v,v();}return g}}(t,e):function(t){return Gd({point:function(e,n){e=t(e,n),this.stream.point(e[0],e[1]);}})}(t)}var rp=Gd({point:function(t,e){this.stream.point(t*ru,e*ru);}});function ip(t,e,n,r,i,a){if(!a)return function(t,e,n,r,i){function a(a,o){return [e+t*(a*=r),n-t*(o*=i)]}return a.invert=function(a,o){return [(a-e)/t*r,(n-o)/t*i]},a}(t,e,n,r,i);var o=su(a),s=du(a),c=o*t,l=s*t,u=o/t,h=s/t,f=(s*n-o*e)/t,d=(s*e+o*n)/t;function p(t,a){return [c*(t*=r)-l*(a*=i)+e,n-l*t-c*a]}return p.invert=function(t,e){return [r*(u*t-h*e+f),i*(d-h*t-u*e)]},p}function ap(t){return op((function(){return t}))()}function op(t){var e,n,r,i,a,o,s,c,l,u,h=150,f=480,d=250,p=0,g=0,y=0,m=0,b=0,v=0,_=1,x=1,k=null,w=ff,T=null,E=Wf,C=.5;function S(t){return c(t[0]*ru,t[1]*ru)}function A(t){return (t=c.invert(t[0],t[1]))&&[t[0]*nu,t[1]*nu]}function M(){var t=ip(h,0,0,_,x,v).apply(null,e(p,g)),r=ip(h,f-t[0],d-t[1],_,x,v);return n=Vh(y,m,b),s=qh(e,r),c=qh(n,s),o=np(s,C),N()}function N(){return l=u=null,S}return S.stream=function(t){return l&&u===t?l:l=rp(function(t){return Gd({point:function(e,n){var r=t(e,n);return this.stream.point(r[0],r[1])}})}(n)(w(o(E(u=t)))))},S.preclip=function(t){return arguments.length?(w=t,k=void 0,N()):w},S.postclip=function(t){return arguments.length?(E=t,T=r=i=a=null,N()):E},S.clipAngle=function(t){return arguments.length?(w=+t?df(k=t*ru):(k=null,ff),N()):k*nu},S.clipExtent=function(t){return arguments.length?(E=null==t?(T=r=i=a=null,Wf):_f(T=+t[0][0],r=+t[0][1],i=+t[1][0],a=+t[1][1]),N()):null==T?null:[[T,r],[i,a]]},S.scale=function(t){return arguments.length?(h=+t,M()):h},S.translate=function(t){return arguments.length?(f=+t[0],d=+t[1],M()):[f,d]},S.center=function(t){return arguments.length?(p=t[0]%360*ru,g=t[1]%360*ru,M()):[p*nu,g*nu]},S.rotate=function(t){return arguments.length?(y=t[0]%360*ru,m=t[1]%360*ru,b=t.length>2?t[2]%360*ru:0,M()):[y*nu,m*nu,b*nu]},S.angle=function(t){return arguments.length?(v=t%360*ru,M()):v*nu},S.reflectX=function(t){return arguments.length?(_=t?-1:1,M()):_<0},S.reflectY=function(t){return arguments.length?(x=t?-1:1,M()):x<0},S.precision=function(t){return arguments.length?(o=np(s,C=t*t),N()):gu(C)},S.fitExtent=function(t,e){return Qd(S,t,e)},S.fitSize=function(t,e){return Kd(S,t,e)},S.fitWidth=function(t,e){return Jd(S,t,e)},S.fitHeight=function(t,e){return tp(S,t,e)},function(){return e=t.apply(this,arguments),S.invert=e.invert&&A,M()}}function sp(t){var e=0,n=Kl/3,r=op(t),i=r(e,n);return i.parallels=function(t){return arguments.length?r(e=t[0]*ru,n=t[1]*ru):[e*nu,n*nu]},i}function cp(t,e){var n=du(t),r=(n+du(e))/2;if(iu(r)<Zl)return function(t){var e=su(t);function n(t,n){return [t*e,du(n)/e]}return n.invert=function(t,n){return [t/e,bu(n*e)]},n}(t);var i=1+n*(2*r-n),a=gu(i)/r;function o(t,e){var n=gu(i-2*r*du(e))/r;return [n*du(t*=r),a-n*su(t)]}return o.invert=function(t,e){var n=a-e,o=ou(t,iu(n))*pu(n);return n*r<0&&(o-=Kl*pu(t)*pu(n)),[o/r,bu((i-(t*t+n*n)*r*r)/(2*r))]},o}function lp(){return sp(cp).scale(155.424).center([0,33.6442])}function up(){return lp().parallels([29.5,45.5]).scale(1070).translate([480,250]).rotate([96,0]).center([-.6,38.7])}function hp(){var t,e,n,r,i,a,o=up(),s=lp().rotate([154,0]).center([-2,58.5]).parallels([55,65]),c=lp().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(t,e){a=[t,e];}};function u(t){var e=t[0],o=t[1];return a=null,n.point(e,o),a||(r.point(e,o),a)||(i.point(e,o),a)}function h(){return t=e=null,u}return u.invert=function(t){var e=o.scale(),n=o.translate(),r=(t[0]-n[0])/e,i=(t[1]-n[1])/e;return (i>=.12&&i<.234&&r>=-.425&&r<-.214?s:i>=.166&&i<.234&&r>=-.214&&r<-.115?c:o).invert(t)},u.stream=function(n){return t&&e===n?t:(r=[o.stream(e=n),s.stream(n),c.stream(n)],i=r.length,t={point:function(t,e){for(var n=-1;++n<i;)r[n].point(t,e);},sphere:function(){for(var t=-1;++t<i;)r[t].sphere();},lineStart:function(){for(var t=-1;++t<i;)r[t].lineStart();},lineEnd:function(){for(var t=-1;++t<i;)r[t].lineEnd();},polygonStart:function(){for(var t=-1;++t<i;)r[t].polygonStart();},polygonEnd:function(){for(var t=-1;++t<i;)r[t].polygonEnd();}});var r,i;},u.precision=function(t){return arguments.length?(o.precision(t),s.precision(t),c.precision(t),h()):o.precision()},u.scale=function(t){return arguments.length?(o.scale(t),s.scale(.35*t),c.scale(t),u.translate(o.translate())):o.scale()},u.translate=function(t){if(!arguments.length)return o.translate();var e=o.scale(),a=+t[0],u=+t[1];return n=o.translate(t).clipExtent([[a-.455*e,u-.238*e],[a+.455*e,u+.238*e]]).stream(l),r=s.translate([a-.307*e,u+.201*e]).clipExtent([[a-.425*e+Zl,u+.12*e+Zl],[a-.214*e-Zl,u+.234*e-Zl]]).stream(l),i=c.translate([a-.205*e,u+.212*e]).clipExtent([[a-.214*e+Zl,u+.166*e+Zl],[a-.115*e-Zl,u+.234*e-Zl]]).stream(l),h()},u.fitExtent=function(t,e){return Qd(u,t,e)},u.fitSize=function(t,e){return Kd(u,t,e)},u.fitWidth=function(t,e){return Jd(u,t,e)},u.fitHeight=function(t,e){return tp(u,t,e)},u.scale(1070)}function fp(t){return function(e,n){var r=su(e),i=su(n),a=t(r*i);return a===1/0?[2,0]:[a*i*du(e),a*du(n)]}}function dp(t){return function(e,n){var r=gu(e*e+n*n),i=t(r),a=du(i),o=su(i);return [ou(e*a,r*o),bu(r&&n*a/r)]}}var pp=fp((function(t){return gu(2/(1+t))}));function gp(){return ap(pp).scale(124.75).clipAngle(179.999)}pp.invert=dp((function(t){return 2*bu(t/2)}));var yp=fp((function(t){return (t=mu(t))&&t/du(t)}));function mp(){return ap(yp).scale(79.4188).clipAngle(179.999)}function bp(t,e){return [t,hu(yu((Jl+e)/2))]}function vp(){return _p(bp).scale(961/eu)}function _p(t){var e,n,r,i=ap(t),a=i.center,o=i.scale,s=i.translate,c=i.clipExtent,l=null;function u(){var a=Kl*o(),s=i(Qh(i.rotate()).invert([0,0]));return c(null==l?[[s[0]-a,s[1]-a],[s[0]+a,s[1]+a]]:t===bp?[[Math.max(s[0]-a,l),e],[Math.min(s[0]+a,n),r]]:[[l,Math.max(s[1]-a,e)],[n,Math.min(s[1]+a,r)]])}return i.scale=function(t){return arguments.length?(o(t),u()):o()},i.translate=function(t){return arguments.length?(s(t),u()):s()},i.center=function(t){return arguments.length?(a(t),u()):a()},i.clipExtent=function(t){return arguments.length?(null==t?l=e=n=r=null:(l=+t[0][0],e=+t[0][1],n=+t[1][0],r=+t[1][1]),u()):null==l?null:[[l,e],[n,r]]},u()}function xp(t){return yu((Jl+t)/2)}function kp(t,e){var n=su(t),r=t===e?du(t):hu(n/su(e))/hu(xp(e)/xp(t)),i=n*fu(xp(t),r)/r;if(!r)return bp;function a(t,e){i>0?e<-Jl+Zl&&(e=-Jl+Zl):e>Jl-Zl&&(e=Jl-Zl);var n=i/fu(xp(e),r);return [n*du(r*t),i-n*su(r*t)]}return a.invert=function(t,e){var n=i-e,a=pu(r)*gu(t*t+n*n),o=ou(t,iu(n))*pu(n);return n*r<0&&(o-=Kl*pu(t)*pu(n)),[o/r,2*au(fu(i/a,1/r))-Jl]},a}function wp(){return sp(kp).scale(109.5).parallels([30,30])}function Tp(t,e){return [t,e]}function Ep(){return ap(Tp).scale(152.63)}function Cp(t,e){var n=su(t),r=t===e?du(t):(n-su(e))/(e-t),i=n/r+t;if(iu(r)<Zl)return Tp;function a(t,e){var n=i-e,a=r*t;return [n*du(a),i-n*su(a)]}return a.invert=function(t,e){var n=i-e,a=ou(t,iu(n))*pu(n);return n*r<0&&(a-=Kl*pu(t)*pu(n)),[a/r,i-pu(r)*gu(t*t+n*n)]},a}function Sp(){return sp(Cp).scale(131.154).center([0,13.9389])}yp.invert=dp((function(t){return t})),bp.invert=function(t,e){return [t,2*au(lu(e))-Jl]},Tp.invert=Tp;var Ap=1.340264,Mp=-.081106,Np=893e-6,Op=.003796,Dp=gu(3)/2;function Bp(t,e){var n=bu(Dp*du(e)),r=n*n,i=r*r*r;return [t*su(n)/(Dp*(Ap+3*Mp*r+i*(7*Np+9*Op*r))),n*(Ap+Mp*r+i*(Np+Op*r))]}function Lp(){return ap(Bp).scale(177.158)}function Ip(t,e){var n=su(e),r=su(t)*n;return [n*du(t)/r,du(e)/r]}function Fp(){return ap(Ip).scale(144.049).clipAngle(60)}function Rp(){var t,e,n,r,i,a,o,s=1,c=0,l=0,u=1,h=1,f=0,d=null,p=1,g=1,y=Gd({point:function(t,e){var n=v([t,e]);this.stream.point(n[0],n[1]);}}),m=Wf;function b(){return p=s*u,g=s*h,a=o=null,v}function v(n){var r=n[0]*p,i=n[1]*g;if(f){var a=i*t-r*e;r=r*t+i*e,i=a;}return [r+c,i+l]}return v.invert=function(n){var r=n[0]-c,i=n[1]-l;if(f){var a=i*t+r*e;r=r*t-i*e,i=a;}return [r/p,i/g]},v.stream=function(t){return a&&o===t?a:a=y(m(o=t))},v.postclip=function(t){return arguments.length?(m=t,d=n=r=i=null,b()):m},v.clipExtent=function(t){return arguments.length?(m=null==t?(d=n=r=i=null,Wf):_f(d=+t[0][0],n=+t[0][1],r=+t[1][0],i=+t[1][1]),b()):null==d?null:[[d,n],[r,i]]},v.scale=function(t){return arguments.length?(s=+t,b()):s},v.translate=function(t){return arguments.length?(c=+t[0],l=+t[1],b()):[c,l]},v.angle=function(n){return arguments.length?(e=du(f=n%360*ru),t=su(f),b()):f*nu},v.reflectX=function(t){return arguments.length?(u=t?-1:1,b()):u<0},v.reflectY=function(t){return arguments.length?(h=t?-1:1,b()):h<0},v.fitExtent=function(t,e){return Qd(v,t,e)},v.fitSize=function(t,e){return Kd(v,t,e)},v.fitWidth=function(t,e){return Jd(v,t,e)},v.fitHeight=function(t,e){return tp(v,t,e)},v}function Pp(t,e){var n=e*e,r=n*n;return [t*(.8707-.131979*n+r*(r*(.003971*n-.001529*r)-.013791)),e*(1.007226+n*(.015085+r*(.028874*n-.044475-.005916*r)))]}function jp(){return ap(Pp).scale(175.295)}function zp(t,e){return [su(e)*du(t),du(e)]}function Yp(){return ap(zp).scale(249.5).clipAngle(90.000001)}function Up(t,e){var n=su(e),r=1+su(t)*n;return [n*du(t)/r,du(e)/r]}function $p(){return ap(Up).scale(250).clipAngle(142)}function Wp(t,e){return [hu(yu((Jl+e)/2)),-t]}function qp(){var t=_p(Wp),e=t.center,n=t.rotate;return t.center=function(t){return arguments.length?e([-t[1],t[0]]):[(t=e())[1],-t[0]]},t.rotate=function(t){return arguments.length?n([t[0],t[1],t.length>2?t[2]+90:90]):[(t=n())[0],t[1],t[2]-90]},n([0,0,90]).scale(159.155)}function Hp(t,e){return t.parent===e.parent?1:2}function Vp(t,e){return t+e.x}function Gp(t,e){return Math.max(t,e.y)}function Xp(){var t=Hp,e=1,n=1,r=!1;function i(i){var a,o=0;i.eachAfter((function(e){var n=e.children;n?(e.x=function(t){return t.reduce(Vp,0)/t.length}(n),e.y=function(t){return 1+t.reduce(Gp,0)}(n)):(e.x=a?o+=t(e,a):0,e.y=0,a=e);}));var s=function(t){for(var e;e=t.children;)t=e[0];return t}(i),c=function(t){for(var e;e=t.children;)t=e[e.length-1];return t}(i),l=s.x-t(s,c)/2,u=c.x+t(c,s)/2;return i.eachAfter(r?function(t){t.x=(t.x-i.x)*e,t.y=(i.y-t.y)*n;}:function(t){t.x=(t.x-l)/(u-l)*e,t.y=(1-(i.y?t.y/i.y:1))*n;})}return i.separation=function(e){return arguments.length?(t=e,i):t},i.size=function(t){return arguments.length?(r=!1,e=+t[0],n=+t[1],i):r?null:[e,n]},i.nodeSize=function(t){return arguments.length?(r=!0,e=+t[0],n=+t[1],i):r?[e,n]:null},i}function Zp(t){var e=0,n=t.children,r=n&&n.length;if(r)for(;--r>=0;)e+=n[r].value;else e=1;t.value=e;}function Qp(t,e){t instanceof Map?(t=[void 0,t],void 0===e&&(e=Jp)):void 0===e&&(e=Kp);for(var n,r,i,a,o,s=new ng(t),c=[s];n=c.pop();)if((i=e(n.data))&&(o=(i=Array.from(i)).length))for(n.children=i,a=o-1;a>=0;--a)c.push(r=i[a]=new ng(i[a])),r.parent=n,r.depth=n.depth+1;return s.eachBefore(eg)}function Kp(t){return t.children}function Jp(t){return Array.isArray(t)?t[1]:null}function tg(t){void 0!==t.data.value&&(t.value=t.data.value),t.data=t.data.data;}function eg(t){var e=0;do{t.height=e;}while((t=t.parent)&&t.height<++e)}function ng(t){this.data=t,this.depth=this.height=0,this.parent=null;}function rg(t){for(var e,n,r=0,i=(t=function(t){for(var e,n,r=t.length;r;)n=Math.random()*r--|0,e=t[r],t[r]=t[n],t[n]=e;return t}(Array.from(t))).length,a=[];r<i;)e=t[r],n&&og(n,e)?++r:(n=cg(a=ig(a,e)),r=0);return n}function ig(t,e){var n,r;if(sg(e,t))return [e];for(n=0;n<t.length;++n)if(ag(e,t[n])&&sg(lg(t[n],e),t))return [t[n],e];for(n=0;n<t.length-1;++n)for(r=n+1;r<t.length;++r)if(ag(lg(t[n],t[r]),e)&&ag(lg(t[n],e),t[r])&&ag(lg(t[r],e),t[n])&&sg(ug(t[n],t[r],e),t))return [t[n],t[r],e];throw new Error}function ag(t,e){var n=t.r-e.r,r=e.x-t.x,i=e.y-t.y;return n<0||n*n<r*r+i*i}function og(t,e){var n=t.r-e.r+1e-9*Math.max(t.r,e.r,1),r=e.x-t.x,i=e.y-t.y;return n>0&&n*n>r*r+i*i}function sg(t,e){for(var n=0;n<e.length;++n)if(!og(t,e[n]))return !1;return !0}function cg(t){switch(t.length){case 1:return {x:(e=t[0]).x,y:e.y,r:e.r};case 2:return lg(t[0],t[1]);case 3:return ug(t[0],t[1],t[2])}var e;}function lg(t,e){var n=t.x,r=t.y,i=t.r,a=e.x,o=e.y,s=e.r,c=a-n,l=o-r,u=s-i,h=Math.sqrt(c*c+l*l);return {x:(n+a+c/h*u)/2,y:(r+o+l/h*u)/2,r:(h+i+s)/2}}function ug(t,e,n){var r=t.x,i=t.y,a=t.r,o=e.x,s=e.y,c=e.r,l=n.x,u=n.y,h=n.r,f=r-o,d=r-l,p=i-s,g=i-u,y=c-a,m=h-a,b=r*r+i*i-a*a,v=b-o*o-s*s+c*c,_=b-l*l-u*u+h*h,x=d*p-f*g,k=(p*_-g*v)/(2*x)-r,w=(g*y-p*m)/x,T=(d*v-f*_)/(2*x)-i,E=(f*m-d*y)/x,C=w*w+E*E-1,S=2*(a+k*w+T*E),A=k*k+T*T-a*a,M=-(C?(S+Math.sqrt(S*S-4*C*A))/(2*C):A/S);return {x:r+k+w*M,y:i+T+E*M,r:M}}function hg(t,e,n){var r,i,a,o,s=t.x-e.x,c=t.y-e.y,l=s*s+c*c;l?(i=e.r+n.r,i*=i,o=t.r+n.r,i>(o*=o)?(r=(l+o-i)/(2*l),a=Math.sqrt(Math.max(0,o/l-r*r)),n.x=t.x-r*s-a*c,n.y=t.y-r*c+a*s):(r=(l+i-o)/(2*l),a=Math.sqrt(Math.max(0,i/l-r*r)),n.x=e.x+r*s-a*c,n.y=e.y+r*c+a*s)):(n.x=e.x+n.r,n.y=e.y);}function fg(t,e){var n=t.r+e.r-1e-6,r=e.x-t.x,i=e.y-t.y;return n>0&&n*n>r*r+i*i}function dg(t){var e=t._,n=t.next._,r=e.r+n.r,i=(e.x*n.r+n.x*e.r)/r,a=(e.y*n.r+n.y*e.r)/r;return i*i+a*a}function pg(t){this._=t,this.next=null,this.previous=null;}function gg(t){if(!(a=(e=t,t="object"==typeof e&&"length"in e?e:Array.from(e)).length))return 0;var e,n,r,i,a,o,s,c,l,u,h,f;if((n=t[0]).x=0,n.y=0,!(a>1))return n.r;if(r=t[1],n.x=-r.r,r.x=n.r,r.y=0,!(a>2))return n.r+r.r;hg(r,n,i=t[2]),n=new pg(n),r=new pg(r),i=new pg(i),n.next=i.previous=r,r.next=n.previous=i,i.next=r.previous=n;t:for(c=3;c<a;++c){hg(n._,r._,i=t[c]),i=new pg(i),l=r.next,u=n.previous,h=r._.r,f=n._.r;do{if(h<=f){if(fg(l._,i._)){r=l,n.next=r,r.previous=n,--c;continue t}h+=l._.r,l=l.next;}else {if(fg(u._,i._)){(n=u).next=r,r.previous=n,--c;continue t}f+=u._.r,u=u.previous;}}while(l!==u.next);for(i.previous=n,i.next=r,n.next=r.previous=r=i,o=dg(n);(i=i.next)!==r;)(s=dg(i))<o&&(n=i,o=s);r=n.next;}for(n=[r._],i=r;(i=i.next)!==r;)n.push(i._);for(i=rg(n),c=0;c<a;++c)(n=t[c]).x-=i.x,n.y-=i.y;return i.r}function yg(t){return gg(t),t}function mg(t){return null==t?null:bg(t)}function bg(t){if("function"!=typeof t)throw new Error;return t}function vg(){return 0}function _g(t){return function(){return t}}function xg(t){return Math.sqrt(t.value)}function kg(){var t=null,e=1,n=1,r=vg;function i(i){return i.x=e/2,i.y=n/2,t?i.eachBefore(wg(t)).eachAfter(Tg(r,.5)).eachBefore(Eg(1)):i.eachBefore(wg(xg)).eachAfter(Tg(vg,1)).eachAfter(Tg(r,i.r/Math.min(e,n))).eachBefore(Eg(Math.min(e,n)/(2*i.r))),i}return i.radius=function(e){return arguments.length?(t=mg(e),i):t},i.size=function(t){return arguments.length?(e=+t[0],n=+t[1],i):[e,n]},i.padding=function(t){return arguments.length?(r="function"==typeof t?t:_g(+t),i):r},i}function wg(t){return function(e){e.children||(e.r=Math.max(0,+t(e)||0));}}function Tg(t,e){return function(n){if(r=n.children){var r,i,a,o=r.length,s=t(n)*e||0;if(s)for(i=0;i<o;++i)r[i].r+=s;if(a=gg(r),s)for(i=0;i<o;++i)r[i].r-=s;n.r=a+s;}}}function Eg(t){return function(e){var n=e.parent;e.r*=t,n&&(e.x=n.x+t*e.x,e.y=n.y+t*e.y);}}function Cg(t){t.x0=Math.round(t.x0),t.y0=Math.round(t.y0),t.x1=Math.round(t.x1),t.y1=Math.round(t.y1);}function Sg(t,e,n,r,i){for(var a,o=t.children,s=-1,c=o.length,l=t.value&&(r-e)/t.value;++s<c;)(a=o[s]).y0=n,a.y1=i,a.x0=e,a.x1=e+=a.value*l;}function Ag(){var t=1,e=1,n=0,r=!1;function i(i){var a=i.height+1;return i.x0=i.y0=n,i.x1=t,i.y1=e/a,i.eachBefore(function(t,e){return function(r){r.children&&Sg(r,r.x0,t*(r.depth+1)/e,r.x1,t*(r.depth+2)/e);var i=r.x0,a=r.y0,o=r.x1-n,s=r.y1-n;o<i&&(i=o=(i+o)/2),s<a&&(a=s=(a+s)/2),r.x0=i,r.y0=a,r.x1=o,r.y1=s;}}(e,a)),r&&i.eachBefore(Cg),i}return i.round=function(t){return arguments.length?(r=!!t,i):r},i.size=function(n){return arguments.length?(t=+n[0],e=+n[1],i):[t,e]},i.padding=function(t){return arguments.length?(n=+t,i):n},i}Bp.invert=function(t,e){for(var n,r=e,i=r*r,a=i*i*i,o=0;o<12&&(a=(i=(r-=n=(r*(Ap+Mp*i+a*(Np+Op*i))-e)/(Ap+3*Mp*i+a*(7*Np+9*Op*i)))*r)*i*i,!(iu(n)<Ql));++o);return [Dp*t*(Ap+3*Mp*i+a*(7*Np+9*Op*i))/su(r),bu(du(r)/Dp)]},Ip.invert=dp(au),Pp.invert=function(t,e){var n,r=e,i=25;do{var a=r*r,o=a*a;r-=n=(r*(1.007226+a*(.015085+o*(.028874*a-.044475-.005916*o)))-e)/(1.007226+a*(.045255+o*(.259866*a-.311325-.005916*11*o)));}while(iu(n)>Zl&&--i>0);return [t/(.8707+(a=r*r)*(a*(a*a*a*(.003971-.001529*a)-.013791)-.131979)),r]},zp.invert=dp(bu),Up.invert=dp((function(t){return 2*au(t)})),Wp.invert=function(t,e){return [-e,2*au(lu(t))-Jl]},ng.prototype=Qp.prototype={constructor:ng,count:function(){return this.eachAfter(Zp)},each:function(t,e){let n=-1;for(const r of this)t.call(e,r,++n,this);return this},eachAfter:function(t,e){for(var n,r,i,a=this,o=[a],s=[],c=-1;a=o.pop();)if(s.push(a),n=a.children)for(r=0,i=n.length;r<i;++r)o.push(n[r]);for(;a=s.pop();)t.call(e,a,++c,this);return this},eachBefore:function(t,e){for(var n,r,i=this,a=[i],o=-1;i=a.pop();)if(t.call(e,i,++o,this),n=i.children)for(r=n.length-1;r>=0;--r)a.push(n[r]);return this},find:function(t,e){let n=-1;for(const r of this)if(t.call(e,r,++n,this))return r},sum:function(t){return this.eachAfter((function(e){for(var n=+t(e.data)||0,r=e.children,i=r&&r.length;--i>=0;)n+=r[i].value;e.value=n;}))},sort:function(t){return this.eachBefore((function(e){e.children&&e.children.sort(t);}))},path:function(t){for(var e=this,n=function(t,e){if(t===e)return t;var n=t.ancestors(),r=e.ancestors(),i=null;for(t=n.pop(),e=r.pop();t===e;)i=t,t=n.pop(),e=r.pop();return i}(e,t),r=[e];e!==n;)e=e.parent,r.push(e);for(var i=r.length;t!==n;)r.splice(i,0,t),t=t.parent;return r},ancestors:function(){for(var t=this,e=[t];t=t.parent;)e.push(t);return e},descendants:function(){return Array.from(this)},leaves:function(){var t=[];return this.eachBefore((function(e){e.children||t.push(e);})),t},links:function(){var t=this,e=[];return t.each((function(n){n!==t&&e.push({source:n.parent,target:n});})),e},copy:function(){return Qp(this).eachBefore(tg)},[Symbol.iterator]:function*(){var t,e,n,r,i=this,a=[i];do{for(t=a.reverse(),a=[];i=t.pop();)if(yield i,e=i.children)for(n=0,r=e.length;n<r;++n)a.push(e[n]);}while(a.length)}};var Mg={depth:-1},Ng={},Og={};function Dg(t){return t.id}function Bg(t){return t.parentId}function Lg(){var t,e=Dg,n=Bg;function r(r){var i,a,o,s,c,l,u,h,f=Array.from(r),d=e,p=n,g=new Map;if(null!=t){const e=f.map(((e,n)=>function(t){let e=(t=`${t}`).length;return Fg(t,e-1)&&!Fg(t,e-2)&&(t=t.slice(0,-1)),"/"===t[0]?t:`/${t}`}(t(e,n,r)))),n=e.map(Ig),i=new Set(e).add("");for(const t of n)i.has(t)||(i.add(t),e.push(t),n.push(Ig(t)),f.push(Og));d=(t,n)=>e[n],p=(t,e)=>n[e];}for(o=0,i=f.length;o<i;++o)a=f[o],l=f[o]=new ng(a),null!=(u=d(a,o,r))&&(u+="")&&(h=l.id=u,g.set(h,g.has(h)?Ng:l)),null!=(u=p(a,o,r))&&(u+="")&&(l.parent=u);for(o=0;o<i;++o)if(u=(l=f[o]).parent){if(!(c=g.get(u)))throw new Error("missing: "+u);if(c===Ng)throw new Error("ambiguous: "+u);c.children?c.children.push(l):c.children=[l],l.parent=c;}else {if(s)throw new Error("multiple roots");s=l;}if(!s)throw new Error("no root");if(null!=t){for(;s.data===Og&&1===s.children.length;)s=s.children[0],--i;for(let t=f.length-1;t>=0&&(l=f[t],l.data===Og);--t)l.data=null;}if(s.parent=Mg,s.eachBefore((function(t){t.depth=t.parent.depth+1,--i;})).eachBefore(eg),s.parent=null,i>0)throw new Error("cycle");return s}return r.id=function(t){return arguments.length?(e=mg(t),r):e},r.parentId=function(t){return arguments.length?(n=mg(t),r):n},r.path=function(e){return arguments.length?(t=mg(e),r):t},r}function Ig(t){let e=t.length;if(e<2)return "";for(;--e>1&&!Fg(t,e););return t.slice(0,e)}function Fg(t,e){if("/"===t[e]){let n=0;for(;e>0&&"\\"===t[--e];)++n;if(0==(1&n))return !0}return !1}function Rg(t,e){return t.parent===e.parent?1:2}function Pg(t){var e=t.children;return e?e[0]:t.t}function jg(t){var e=t.children;return e?e[e.length-1]:t.t}function zg(t,e,n){var r=n/(e.i-t.i);e.c-=r,e.s+=n,t.c+=r,e.z+=n,e.m+=n;}function Yg(t,e,n){return t.a.parent===e.parent?t.a:n}function Ug(t,e){this._=t,this.parent=null,this.children=null,this.A=null,this.a=this,this.z=0,this.m=0,this.c=0,this.s=0,this.t=null,this.i=e;}function $g(){var t=Rg,e=1,n=1,r=null;function i(i){var c=function(t){for(var e,n,r,i,a,o=new Ug(t,0),s=[o];e=s.pop();)if(r=e._.children)for(e.children=new Array(a=r.length),i=a-1;i>=0;--i)s.push(n=e.children[i]=new Ug(r[i],i)),n.parent=e;return (o.parent=new Ug(null,0)).children=[o],o}(i);if(c.eachAfter(a),c.parent.m=-c.z,c.eachBefore(o),r)i.eachBefore(s);else {var l=i,u=i,h=i;i.eachBefore((function(t){t.x<l.x&&(l=t),t.x>u.x&&(u=t),t.depth>h.depth&&(h=t);}));var f=l===u?1:t(l,u)/2,d=f-l.x,p=e/(u.x+f+d),g=n/(h.depth||1);i.eachBefore((function(t){t.x=(t.x+d)*p,t.y=t.depth*g;}));}return i}function a(e){var n=e.children,r=e.parent.children,i=e.i?r[e.i-1]:null;if(n){!function(t){for(var e,n=0,r=0,i=t.children,a=i.length;--a>=0;)(e=i[a]).z+=n,e.m+=n,n+=e.s+(r+=e.c);}(e);var a=(n[0].z+n[n.length-1].z)/2;i?(e.z=i.z+t(e._,i._),e.m=e.z-a):e.z=a;}else i&&(e.z=i.z+t(e._,i._));e.parent.A=function(e,n,r){if(n){for(var i,a=e,o=e,s=n,c=a.parent.children[0],l=a.m,u=o.m,h=s.m,f=c.m;s=jg(s),a=Pg(a),s&&a;)c=Pg(c),(o=jg(o)).a=e,(i=s.z+h-a.z-l+t(s._,a._))>0&&(zg(Yg(s,e,r),e,i),l+=i,u+=i),h+=s.m,l+=a.m,f+=c.m,u+=o.m;s&&!jg(o)&&(o.t=s,o.m+=h-u),a&&!Pg(c)&&(c.t=a,c.m+=l-f,r=e);}return r}(e,i,e.parent.A||r[0]);}function o(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m;}function s(t){t.x*=e,t.y=t.depth*n;}return i.separation=function(e){return arguments.length?(t=e,i):t},i.size=function(t){return arguments.length?(r=!1,e=+t[0],n=+t[1],i):r?null:[e,n]},i.nodeSize=function(t){return arguments.length?(r=!0,e=+t[0],n=+t[1],i):r?[e,n]:null},i}function Wg(t,e,n,r,i){for(var a,o=t.children,s=-1,c=o.length,l=t.value&&(i-n)/t.value;++s<c;)(a=o[s]).x0=e,a.x1=r,a.y0=n,a.y1=n+=a.value*l;}Ug.prototype=Object.create(ng.prototype);var qg=(1+Math.sqrt(5))/2;function Hg(t,e,n,r,i,a){for(var o,s,c,l,u,h,f,d,p,g,y,m=[],b=e.children,v=0,_=0,x=b.length,k=e.value;v<x;){c=i-n,l=a-r;do{u=b[_++].value;}while(!u&&_<x);for(h=f=u,y=u*u*(g=Math.max(l/c,c/l)/(k*t)),p=Math.max(f/y,y/h);_<x;++_){if(u+=s=b[_].value,s<h&&(h=s),s>f&&(f=s),y=u*u*g,(d=Math.max(f/y,y/h))>p){u-=s;break}p=d;}m.push(o={value:u,dice:c<l,children:b.slice(v,_)}),o.dice?Sg(o,n,r,i,k?r+=l*u/k:a):Wg(o,n,r,k?n+=c*u/k:i,a),k-=u,v=_;}return m}const Vg=function t(e){function n(t,n,r,i,a){Hg(e,t,n,r,i,a);}return n.ratio=function(e){return t((e=+e)>1?e:1)},n}(qg);function Gg(){var t=Vg,e=!1,n=1,r=1,i=[0],a=vg,o=vg,s=vg,c=vg,l=vg;function u(t){return t.x0=t.y0=0,t.x1=n,t.y1=r,t.eachBefore(h),i=[0],e&&t.eachBefore(Cg),t}function h(e){var n=i[e.depth],r=e.x0+n,u=e.y0+n,h=e.x1-n,f=e.y1-n;h<r&&(r=h=(r+h)/2),f<u&&(u=f=(u+f)/2),e.x0=r,e.y0=u,e.x1=h,e.y1=f,e.children&&(n=i[e.depth+1]=a(e)/2,r+=l(e)-n,u+=o(e)-n,(h-=s(e)-n)<r&&(r=h=(r+h)/2),(f-=c(e)-n)<u&&(u=f=(u+f)/2),t(e,r,u,h,f));}return u.round=function(t){return arguments.length?(e=!!t,u):e},u.size=function(t){return arguments.length?(n=+t[0],r=+t[1],u):[n,r]},u.tile=function(e){return arguments.length?(t=bg(e),u):t},u.padding=function(t){return arguments.length?u.paddingInner(t).paddingOuter(t):u.paddingInner()},u.paddingInner=function(t){return arguments.length?(a="function"==typeof t?t:_g(+t),u):a},u.paddingOuter=function(t){return arguments.length?u.paddingTop(t).paddingRight(t).paddingBottom(t).paddingLeft(t):u.paddingTop()},u.paddingTop=function(t){return arguments.length?(o="function"==typeof t?t:_g(+t),u):o},u.paddingRight=function(t){return arguments.length?(s="function"==typeof t?t:_g(+t),u):s},u.paddingBottom=function(t){return arguments.length?(c="function"==typeof t?t:_g(+t),u):c},u.paddingLeft=function(t){return arguments.length?(l="function"==typeof t?t:_g(+t),u):l},u}function Xg(t,e,n,r,i){var a,o,s=t.children,c=s.length,l=new Array(c+1);for(l[0]=o=a=0;a<c;++a)l[a+1]=o+=s[a].value;!function t(e,n,r,i,a,o,c){if(e>=n-1){var u=s[e];return u.x0=i,u.y0=a,u.x1=o,void(u.y1=c)}for(var h=l[e],f=r/2+h,d=e+1,p=n-1;d<p;){var g=d+p>>>1;l[g]<f?d=g+1:p=g;}f-l[d-1]<l[d]-f&&e+1<d&&--d;var y=l[d]-h,m=r-y;if(o-i>c-a){var b=r?(i*m+o*y)/r:o;t(e,d,y,i,a,b,c),t(d,n,m,b,a,o,c);}else {var v=r?(a*m+c*y)/r:c;t(e,d,y,i,a,o,v),t(d,n,m,i,v,o,c);}}(0,c,t.value,e,n,r,i);}function Zg(t,e,n,r,i){(1&t.depth?Wg:Sg)(t,e,n,r,i);}const Qg=function t(e){function n(t,n,r,i,a){if((o=t._squarify)&&o.ratio===e)for(var o,s,c,l,u,h=-1,f=o.length,d=t.value;++h<f;){for(c=(s=o[h]).children,l=s.value=0,u=c.length;l<u;++l)s.value+=c[l].value;s.dice?Sg(s,n,r,i,d?r+=(a-r)*s.value/d:a):Wg(s,n,r,d?n+=(i-n)*s.value/d:i,a),d-=s.value;}else t._squarify=o=Hg(e,t,n,r,i,a),o.ratio=e;}return n.ratio=function(e){return t((e=+e)>1?e:1)},n}(qg);function Kg(t){var e=t.length;return function(n){return t[Math.max(0,Math.min(e-1,Math.floor(n*e)))]}}function Jg(t,e){var n=vr(+t,+e);return function(t){var e=n(t);return e-360*Math.floor(e/360)}}function ty(t,e){return t=+t,e=+e,function(n){return Math.round(t*(1-n)+e*n)}}function ey(t){return ((t=Math.exp(t))+1/t)/2}const ny=function t(e,n,r){function i(t,i){var a,o,s=t[0],c=t[1],l=t[2],u=i[0],h=i[1],f=i[2],d=u-s,p=h-c,g=d*d+p*p;if(g<1e-12)o=Math.log(f/l)/e,a=function(t){return [s+t*d,c+t*p,l*Math.exp(e*t*o)]};else {var y=Math.sqrt(g),m=(f*f-l*l+r*g)/(2*l*n*y),b=(f*f-l*l-r*g)/(2*f*n*y),v=Math.log(Math.sqrt(m*m+1)-m),_=Math.log(Math.sqrt(b*b+1)-b);o=(_-v)/e,a=function(t){var r,i=t*o,a=ey(v),u=l/(n*y)*(a*(r=e*i+v,((r=Math.exp(2*r))-1)/(r+1))-function(t){return ((t=Math.exp(t))-1/t)/2}(v));return [s+u*d,c+u*p,l*a/ey(e*i+v)]};}return a.duration=1e3*o*e/Math.SQRT2,a}return i.rho=function(e){var n=Math.max(.001,+e),r=n*n;return t(n,r,r*r)},i}(Math.SQRT2,2,4);function ry(t){return function(e,n){var r=t((e=hr(e)).h,(n=hr(n)).h),i=_r(e.s,n.s),a=_r(e.l,n.l),o=_r(e.opacity,n.opacity);return function(t){return e.h=r(t),e.s=i(t),e.l=a(t),e.opacity=o(t),e+""}}}const iy=ry(vr);var ay=ry(_r);function oy(t,e){var n=_r((t=ko(t)).l,(e=ko(e)).l),r=_r(t.a,e.a),i=_r(t.b,e.b),a=_r(t.opacity,e.opacity);return function(e){return t.l=n(e),t.a=r(e),t.b=i(e),t.opacity=a(e),t+""}}function sy(t){return function(e,n){var r=t((e=No(e)).h,(n=No(n)).h),i=_r(e.c,n.c),a=_r(e.l,n.l),o=_r(e.opacity,n.opacity);return function(t){return e.h=r(t),e.c=i(t),e.l=a(t),e.opacity=o(t),e+""}}}const cy=sy(vr);var ly=sy(_r);function uy(t){return function e(n){function r(e,r){var i=t((e=Uo(e)).h,(r=Uo(r)).h),a=_r(e.s,r.s),o=_r(e.l,r.l),s=_r(e.opacity,r.opacity);return function(t){return e.h=i(t),e.s=a(t),e.l=o(Math.pow(t,n)),e.opacity=s(t),e+""}}return n=+n,r.gamma=e,r}(1)}const hy=uy(vr);var fy=uy(_r);function dy(t,e){void 0===e&&(e=t,t=Ir);for(var n=0,r=e.length-1,i=e[0],a=new Array(r<0?0:r);n<r;)a[n]=t(i,i=e[++n]);return function(t){var e=Math.max(0,Math.min(r-1,Math.floor(t*=r)));return a[e](t-e)}}function py(t,e){for(var n=new Array(e),r=0;r<e;++r)n[r]=t(r/(e-1));return n}function gy(t){for(var e,n=-1,r=t.length,i=t[r-1],a=0;++n<r;)e=i,i=t[n],a+=e[1]*i[0]-e[0]*i[1];return a/2}function yy(t){for(var e,n,r=-1,i=t.length,a=0,o=0,s=t[i-1],c=0;++r<i;)e=s,s=t[r],c+=n=e[0]*s[1]-s[0]*e[1],a+=(e[0]+s[0])*n,o+=(e[1]+s[1])*n;return [a/(c*=3),o/c]}function my(t,e,n){return (e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0])}function by(t,e){return t[0]-e[0]||t[1]-e[1]}function vy(t){const e=t.length,n=[0,1];let r,i=2;for(r=2;r<e;++r){for(;i>1&&my(t[n[i-2]],t[n[i-1]],t[r])<=0;)--i;n[i++]=r;}return n.slice(0,i)}function _y(t){if((n=t.length)<3)return null;var e,n,r=new Array(n),i=new Array(n);for(e=0;e<n;++e)r[e]=[+t[e][0],+t[e][1],e];for(r.sort(by),e=0;e<n;++e)i[e]=[r[e][0],-r[e][1]];var a=vy(r),o=vy(i),s=o[0]===a[0],c=o[o.length-1]===a[a.length-1],l=[];for(e=a.length-1;e>=0;--e)l.push(t[r[a[e]][2]]);for(e=+s;e<o.length-c;++e)l.push(t[r[o[e]][2]]);return l}function xy(t,e){for(var n,r,i=t.length,a=t[i-1],o=e[0],s=e[1],c=a[0],l=a[1],u=!1,h=0;h<i;++h)n=(a=t[h])[0],(r=a[1])>s!=l>s&&o<(c-n)*(s-r)/(l-r)+n&&(u=!u),c=n,l=r;return u}function ky(t){for(var e,n,r=-1,i=t.length,a=t[i-1],o=a[0],s=a[1],c=0;++r<i;)e=o,n=s,e-=o=(a=t[r])[0],n-=s=a[1],c+=Math.hypot(e,n);return c}const wy=Math.random,Ty=function t(e){function n(t,n){return t=null==t?0:+t,n=null==n?1:+n,1===arguments.length?(n=t,t=0):n-=t,function(){return e()*n+t}}return n.source=t,n}(wy),Ey=function t(e){function n(t,n){return arguments.length<2&&(n=t,t=0),t=Math.floor(t),n=Math.floor(n)-t,function(){return Math.floor(e()*n+t)}}return n.source=t,n}(wy),Cy=function t(e){function n(t,n){var r,i;return t=null==t?0:+t,n=null==n?1:+n,function(){var a;if(null!=r)a=r,r=null;else do{r=2*e()-1,a=2*e()-1,i=r*r+a*a;}while(!i||i>1);return t+n*a*Math.sqrt(-2*Math.log(i)/i)}}return n.source=t,n}(wy),Sy=function t(e){var n=Cy.source(e);function r(){var t=n.apply(this,arguments);return function(){return Math.exp(t())}}return r.source=t,r}(wy),Ay=function t(e){function n(t){return (t=+t)<=0?()=>0:function(){for(var n=0,r=t;r>1;--r)n+=e();return n+r*e()}}return n.source=t,n}(wy),My=function t(e){var n=Ay.source(e);function r(t){if(0==(t=+t))return e;var r=n(t);return function(){return r()/t}}return r.source=t,r}(wy),Ny=function t(e){function n(t){return function(){return -Math.log1p(-e())/t}}return n.source=t,n}(wy),Oy=function t(e){function n(t){if((t=+t)<0)throw new RangeError("invalid alpha");return t=1/-t,function(){return Math.pow(1-e(),t)}}return n.source=t,n}(wy),Dy=function t(e){function n(t){if((t=+t)<0||t>1)throw new RangeError("invalid p");return function(){return Math.floor(e()+t)}}return n.source=t,n}(wy),By=function t(e){function n(t){if((t=+t)<0||t>1)throw new RangeError("invalid p");return 0===t?()=>1/0:1===t?()=>1:(t=Math.log1p(-t),function(){return 1+Math.floor(Math.log1p(-e())/t)})}return n.source=t,n}(wy),Ly=function t(e){var n=Cy.source(e)();function r(t,r){if((t=+t)<0)throw new RangeError("invalid k");if(0===t)return ()=>0;if(r=null==r?1:+r,1===t)return ()=>-Math.log1p(-e())*r;var i=(t<1?t+1:t)-1/3,a=1/(3*Math.sqrt(i)),o=t<1?()=>Math.pow(e(),1/t):()=>1;return function(){do{do{var t=n(),s=1+a*t;}while(s<=0);s*=s*s;var c=1-e();}while(c>=1-.0331*t*t*t*t&&Math.log(c)>=.5*t*t+i*(1-s+Math.log(s)));return i*s*o()*r}}return r.source=t,r}(wy),Iy=function t(e){var n=Ly.source(e);function r(t,e){var r=n(t),i=n(e);return function(){var t=r();return 0===t?0:t/(t+i())}}return r.source=t,r}(wy),Fy=function t(e){var n=By.source(e),r=Iy.source(e);function i(t,e){return t=+t,(e=+e)>=1?()=>t:e<=0?()=>0:function(){for(var i=0,a=t,o=e;a*o>16&&a*(1-o)>16;){var s=Math.floor((a+1)*o),c=r(s,a-s+1)();c<=o?(i+=s,a-=s,o=(o-c)/(1-c)):(a=s-1,o/=c);}for(var l=o<.5,u=n(l?o:1-o),h=u(),f=0;h<=a;++f)h+=u();return i+(l?f:a-f)}}return i.source=t,i}(wy),Ry=function t(e){function n(t,n,r){var i;return 0==(t=+t)?i=t=>-Math.log(t):(t=1/t,i=e=>Math.pow(e,t)),n=null==n?0:+n,r=null==r?1:+r,function(){return n+r*i(-Math.log1p(-e()))}}return n.source=t,n}(wy),Py=function t(e){function n(t,n){return t=null==t?0:+t,n=null==n?1:+n,function(){return t+n*Math.tan(Math.PI*e())}}return n.source=t,n}(wy),jy=function t(e){function n(t,n){return t=null==t?0:+t,n=null==n?1:+n,function(){var r=e();return t+n*Math.log(r/(1-r))}}return n.source=t,n}(wy),zy=function t(e){var n=Ly.source(e),r=Fy.source(e);function i(t){return function(){for(var i=0,a=t;a>16;){var o=Math.floor(.875*a),s=n(o)();if(s>a)return i+r(o-1,a/s)();i+=o,a-=s;}for(var c=-Math.log1p(-e()),l=0;c<=a;++l)c-=Math.log1p(-e());return i+l}}return i.source=t,i}(wy),Yy=1/4294967296;function Uy(t=Math.random()){let e=0|(0<=t&&t<1?t/Yy:Math.abs(t));return ()=>(e=1664525*e+1013904223|0,Yy*(e>>>0))}function $y(t,e){switch(arguments.length){case 0:break;case 1:this.range(t);break;default:this.range(e).domain(t);}return this}function Wy(t,e){switch(arguments.length){case 0:break;case 1:"function"==typeof t?this.interpolator(t):this.range(t);break;default:this.domain(t),"function"==typeof e?this.interpolator(e):this.range(e);}return this}const qy=Symbol("implicit");function Hy(){var t=new T,e=[],n=[],r=qy;function i(i){let a=t.get(i);if(void 0===a){if(r!==qy)return r;t.set(i,a=e.push(i)-1);}return n[a%n.length]}return i.domain=function(n){if(!arguments.length)return e.slice();e=[],t=new T;for(const r of n)t.has(r)||t.set(r,e.push(r)-1);return i},i.range=function(t){return arguments.length?(n=Array.from(t),i):n.slice()},i.unknown=function(t){return arguments.length?(r=t,i):r},i.copy=function(){return Hy(e,n).unknown(r)},$y.apply(i,arguments),i}function Vy(){var t,e,n=Hy().unknown(void 0),r=n.domain,i=n.range,a=0,o=1,s=!1,c=0,l=0,u=.5;function h(){var n=r().length,h=o<a,f=h?o:a,d=h?a:o;t=(d-f)/Math.max(1,n-c+2*l),s&&(t=Math.floor(t)),f+=(d-f-t*(n-c))*u,e=t*(1-c),s&&(f=Math.round(f),e=Math.round(e));var p=xt(n).map((function(e){return f+t*e}));return i(h?p.reverse():p)}return delete n.unknown,n.domain=function(t){return arguments.length?(r(t),h()):r()},n.range=function(t){return arguments.length?([a,o]=t,a=+a,o=+o,h()):[a,o]},n.rangeRound=function(t){return [a,o]=t,a=+a,o=+o,s=!0,h()},n.bandwidth=function(){return e},n.step=function(){return t},n.round=function(t){return arguments.length?(s=!!t,h()):s},n.padding=function(t){return arguments.length?(c=Math.min(1,l=+t),h()):c},n.paddingInner=function(t){return arguments.length?(c=Math.min(1,t),h()):c},n.paddingOuter=function(t){return arguments.length?(l=+t,h()):l},n.align=function(t){return arguments.length?(u=Math.max(0,Math.min(1,t)),h()):u},n.copy=function(){return Vy(r(),[a,o]).round(s).paddingInner(c).paddingOuter(l).align(u)},$y.apply(h(),arguments)}function Gy(t){var e=t.copy;return t.padding=t.paddingOuter,delete t.paddingInner,delete t.paddingOuter,t.copy=function(){return Gy(e())},t}function Xy(){return Gy(Vy.apply(null,arguments).paddingInner(1))}function Zy(t){return +t}var Qy=[0,1];function Ky(t){return t}function Jy(t,e){return (e-=t=+t)?function(n){return (n-t)/e}:(n=isNaN(e)?NaN:.5,function(){return n});var n;}function tm(t,e,n){var r=t[0],i=t[1],a=e[0],o=e[1];return i<r?(r=Jy(i,r),a=n(o,a)):(r=Jy(r,i),a=n(a,o)),function(t){return a(r(t))}}function em(t,e,n){var r=Math.min(t.length,e.length)-1,i=new Array(r),a=new Array(r),o=-1;for(t[r]<t[0]&&(t=t.slice().reverse(),e=e.slice().reverse());++o<r;)i[o]=Jy(t[o],t[o+1]),a[o]=n(e[o],e[o+1]);return function(e){var n=u(t,e,1,r)-1;return a[n](i[n](e))}}function nm(t,e){return e.domain(t.domain()).range(t.range()).interpolate(t.interpolate()).clamp(t.clamp()).unknown(t.unknown())}function rm(){var t,e,n,r,i,a,o=Qy,s=Qy,c=Ir,l=Ky;function u(){var t,e,n,c=Math.min(o.length,s.length);return l!==Ky&&(t=o[0],e=o[c-1],t>e&&(n=t,t=e,e=n),l=function(n){return Math.max(t,Math.min(e,n))}),r=c>2?em:tm,i=a=null,h}function h(e){return null==e||isNaN(e=+e)?n:(i||(i=r(o.map(t),s,c)))(t(l(e)))}return h.invert=function(n){return l(e((a||(a=r(s,o.map(t),Nr)))(n)))},h.domain=function(t){return arguments.length?(o=Array.from(t,Zy),u()):o.slice()},h.range=function(t){return arguments.length?(s=Array.from(t),u()):s.slice()},h.rangeRound=function(t){return s=Array.from(t),c=ty,u()},h.clamp=function(t){return arguments.length?(l=!!t||Ky,u()):l!==Ky},h.interpolate=function(t){return arguments.length?(c=t,u()):c},h.unknown=function(t){return arguments.length?(n=t,h):n},function(n,r){return t=n,e=r,u()}}function im(){return rm()(Ky,Ky)}function am(t,e,n,r){var i,a=et(t,e,n);switch((r=Il(null==r?",f":r)).type){case"s":var o=Math.max(Math.abs(t),Math.abs(e));return null!=r.precision||isNaN(i=Gl(a,o))||(r.precision=i),Ul(r,o);case"":case"e":case"g":case"p":case"r":null!=r.precision||isNaN(i=Xl(a,Math.max(Math.abs(t),Math.abs(e))))||(r.precision=i-("e"===r.type));break;case"f":case"%":null!=r.precision||isNaN(i=Vl(a))||(r.precision=i-2*("%"===r.type));}return Yl(r)}function om(t){var e=t.domain;return t.ticks=function(t){var n=e();return J(n[0],n[n.length-1],null==t?10:t)},t.tickFormat=function(t,n){var r=e();return am(r[0],r[r.length-1],null==t?10:t,n)},t.nice=function(n){null==n&&(n=10);var r,i,a=e(),o=0,s=a.length-1,c=a[o],l=a[s],u=10;for(l<c&&(i=c,c=l,l=i,i=o,o=s,s=i);u-- >0;){if((i=tt(c,l,n))===r)return a[o]=c,a[s]=l,e(a);if(i>0)c=Math.floor(c/i)*i,l=Math.ceil(l/i)*i;else {if(!(i<0))break;c=Math.ceil(c*i)/i,l=Math.floor(l*i)/i;}r=i;}return t},t}function sm(){var t=im();return t.copy=function(){return nm(t,sm())},$y.apply(t,arguments),om(t)}function cm(t){var e;function n(t){return null==t||isNaN(t=+t)?e:t}return n.invert=n,n.domain=n.range=function(e){return arguments.length?(t=Array.from(e,Zy),n):t.slice()},n.unknown=function(t){return arguments.length?(e=t,n):e},n.copy=function(){return cm(t).unknown(e)},t=arguments.length?Array.from(t,Zy):[0,1],om(n)}function lm(t,e){var n,r=0,i=(t=t.slice()).length-1,a=t[r],o=t[i];return o<a&&(n=r,r=i,i=n,n=a,a=o,o=n),t[r]=e.floor(a),t[i]=e.ceil(o),t}function um(t){return Math.log(t)}function hm(t){return Math.exp(t)}function fm(t){return -Math.log(-t)}function dm(t){return -Math.exp(-t)}function pm(t){return isFinite(t)?+("1e"+t):t<0?0:t}function gm(t){return (e,n)=>-t(-e,n)}function ym(t){const e=t(um,hm),n=e.domain;let r,i,a=10;function o(){return r=function(t){return t===Math.E?Math.log:10===t&&Math.log10||2===t&&Math.log2||(t=Math.log(t),e=>Math.log(e)/t)}(a),i=function(t){return 10===t?pm:t===Math.E?Math.exp:e=>Math.pow(t,e)}(a),n()[0]<0?(r=gm(r),i=gm(i),t(fm,dm)):t(um,hm),e}return e.base=function(t){return arguments.length?(a=+t,o()):a},e.domain=function(t){return arguments.length?(n(t),o()):n()},e.ticks=t=>{const e=n();let o=e[0],s=e[e.length-1];const c=s<o;c&&([o,s]=[s,o]);let l,u,h=r(o),f=r(s);const d=null==t?10:+t;let p=[];if(!(a%1)&&f-h<d){if(h=Math.floor(h),f=Math.ceil(f),o>0){for(;h<=f;++h)for(l=1;l<a;++l)if(u=h<0?l/i(-h):l*i(h),!(u<o)){if(u>s)break;p.push(u);}}else for(;h<=f;++h)for(l=a-1;l>=1;--l)if(u=h>0?l/i(-h):l*i(h),!(u<o)){if(u>s)break;p.push(u);}2*p.length<d&&(p=J(o,s,d));}else p=J(h,f,Math.min(f-h,d)).map(i);return c?p.reverse():p},e.tickFormat=(t,n)=>{if(null==t&&(t=10),null==n&&(n=10===a?"s":","),"function"!=typeof n&&(a%1||null!=(n=Il(n)).precision||(n.trim=!0),n=Yl(n)),t===1/0)return n;const o=Math.max(1,a*t/e.ticks().length);return t=>{let e=t/i(Math.round(r(t)));return e*a<a-.5&&(e*=a),e<=o?n(t):""}},e.nice=()=>n(lm(n(),{floor:t=>i(Math.floor(r(t))),ceil:t=>i(Math.ceil(r(t)))})),e}function mm(){const t=ym(rm()).domain([1,10]);return t.copy=()=>nm(t,mm()).base(t.base()),$y.apply(t,arguments),t}function bm(t){return function(e){return Math.sign(e)*Math.log1p(Math.abs(e/t))}}function vm(t){return function(e){return Math.sign(e)*Math.expm1(Math.abs(e))*t}}function _m(t){var e=1,n=t(bm(e),vm(e));return n.constant=function(n){return arguments.length?t(bm(e=+n),vm(e)):e},om(n)}function xm(){var t=_m(rm());return t.copy=function(){return nm(t,xm()).constant(t.constant())},$y.apply(t,arguments)}function km(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function wm(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function Tm(t){return t<0?-t*t:t*t}function Em(t){var e=t(Ky,Ky),n=1;function r(){return 1===n?t(Ky,Ky):.5===n?t(wm,Tm):t(km(n),km(1/n))}return e.exponent=function(t){return arguments.length?(n=+t,r()):n},om(e)}function Cm(){var t=Em(rm());return t.copy=function(){return nm(t,Cm()).exponent(t.exponent())},$y.apply(t,arguments),t}function Sm(){return Cm.apply(null,arguments).exponent(.5)}function Am(t){return Math.sign(t)*t*t}function Mm(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}function Nm(){var t,e=im(),n=[0,1],r=!1;function i(n){var i=Mm(e(n));return isNaN(i)?t:r?Math.round(i):i}return i.invert=function(t){return e.invert(Am(t))},i.domain=function(t){return arguments.length?(e.domain(t),i):e.domain()},i.range=function(t){return arguments.length?(e.range((n=Array.from(t,Zy)).map(Am)),i):n.slice()},i.rangeRound=function(t){return i.range(t).round(!0)},i.round=function(t){return arguments.length?(r=!!t,i):r},i.clamp=function(t){return arguments.length?(e.clamp(t),i):e.clamp()},i.unknown=function(e){return arguments.length?(t=e,i):t},i.copy=function(){return Nm(e.domain(),n).round(r).clamp(e.clamp()).unknown(t)},$y.apply(i,arguments),om(i)}function Om(){var t,e=[],n=[],i=[];function a(){var t=0,r=Math.max(1,n.length);for(i=new Array(r-1);++t<r;)i[t-1]=ut(e,t/r);return o}function o(e){return null==e||isNaN(e=+e)?t:n[u(i,e)]}return o.invertExtent=function(t){var r=n.indexOf(t);return r<0?[NaN,NaN]:[r>0?i[r-1]:e[0],r<i.length?i[r]:e[e.length-1]]},o.domain=function(t){if(!arguments.length)return e.slice();e=[];for(let n of t)null==n||isNaN(n=+n)||e.push(n);return e.sort(r),a()},o.range=function(t){return arguments.length?(n=Array.from(t),a()):n.slice()},o.unknown=function(e){return arguments.length?(t=e,o):t},o.quantiles=function(){return i.slice()},o.copy=function(){return Om().domain(e).range(n).unknown(t)},$y.apply(o,arguments)}function Dm(){var t,e=0,n=1,r=1,i=[.5],a=[0,1];function o(e){return null!=e&&e<=e?a[u(i,e,0,r)]:t}function s(){var t=-1;for(i=new Array(r);++t<r;)i[t]=((t+1)*n-(t-r)*e)/(r+1);return o}return o.domain=function(t){return arguments.length?([e,n]=t,e=+e,n=+n,s()):[e,n]},o.range=function(t){return arguments.length?(r=(a=Array.from(t)).length-1,s()):a.slice()},o.invertExtent=function(t){var o=a.indexOf(t);return o<0?[NaN,NaN]:o<1?[e,i[0]]:o>=r?[i[r-1],n]:[i[o-1],i[o]]},o.unknown=function(e){return arguments.length?(t=e,o):o},o.thresholds=function(){return i.slice()},o.copy=function(){return Dm().domain([e,n]).range(a).unknown(t)},$y.apply(om(o),arguments)}function Bm(){var t,e=[.5],n=[0,1],r=1;function i(i){return null!=i&&i<=i?n[u(e,i,0,r)]:t}return i.domain=function(t){return arguments.length?(e=Array.from(t),r=Math.min(e.length,n.length-1),i):e.slice()},i.range=function(t){return arguments.length?(n=Array.from(t),r=Math.min(e.length,n.length-1),i):n.slice()},i.invertExtent=function(t){var r=n.indexOf(t);return [e[r-1],e[r]]},i.unknown=function(e){return arguments.length?(t=e,i):t},i.copy=function(){return Bm().domain(e).range(n).unknown(t)},$y.apply(i,arguments)}const Lm=1e3,Im=6e4,Fm=36e5,Rm=864e5,Pm=6048e5,jm=31536e6;var zm=new Date,Ym=new Date;function Um(t,e,n,r){function i(e){return t(e=0===arguments.length?new Date:new Date(+e)),e}return i.floor=function(e){return t(e=new Date(+e)),e},i.ceil=function(n){return t(n=new Date(n-1)),e(n,1),t(n),n},i.round=function(t){var e=i(t),n=i.ceil(t);return t-e<n-t?e:n},i.offset=function(t,n){return e(t=new Date(+t),null==n?1:Math.floor(n)),t},i.range=function(n,r,a){var o,s=[];if(n=i.ceil(n),a=null==a?1:Math.floor(a),!(n<r&&a>0))return s;do{s.push(o=new Date(+n)),e(n,a),t(n);}while(o<n&&n<r);return s},i.filter=function(n){return Um((function(e){if(e>=e)for(;t(e),!n(e);)e.setTime(e-1);}),(function(t,r){if(t>=t)if(r<0)for(;++r<=0;)for(;e(t,-1),!n(t););else for(;--r>=0;)for(;e(t,1),!n(t););}))},n&&(i.count=function(e,r){return zm.setTime(+e),Ym.setTime(+r),t(zm),t(Ym),Math.floor(n(zm,Ym))},i.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?i.filter(r?function(e){return r(e)%t==0}:function(e){return i.count(0,e)%t==0}):i:null}),i}var $m=Um((function(){}),(function(t,e){t.setTime(+t+e);}),(function(t,e){return e-t}));$m.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?Um((function(e){e.setTime(Math.floor(e/t)*t);}),(function(e,n){e.setTime(+e+n*t);}),(function(e,n){return (n-e)/t})):$m:null};const Wm=$m;var qm=$m.range,Hm=Um((function(t){t.setTime(t-t.getMilliseconds());}),(function(t,e){t.setTime(+t+e*Lm);}),(function(t,e){return (e-t)/Lm}),(function(t){return t.getUTCSeconds()}));const Vm=Hm;var Gm=Hm.range,Xm=Um((function(t){t.setTime(t-t.getMilliseconds()-t.getSeconds()*Lm);}),(function(t,e){t.setTime(+t+e*Im);}),(function(t,e){return (e-t)/Im}),(function(t){return t.getMinutes()}));const Zm=Xm;var Qm=Xm.range,Km=Um((function(t){t.setTime(t-t.getMilliseconds()-t.getSeconds()*Lm-t.getMinutes()*Im);}),(function(t,e){t.setTime(+t+e*Fm);}),(function(t,e){return (e-t)/Fm}),(function(t){return t.getHours()}));const Jm=Km;var tb=Km.range,eb=Um((t=>t.setHours(0,0,0,0)),((t,e)=>t.setDate(t.getDate()+e)),((t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*Im)/Rm),(t=>t.getDate()-1));const nb=eb;var rb=eb.range;function ib(t){return Um((function(e){e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0);}),(function(t,e){t.setDate(t.getDate()+7*e);}),(function(t,e){return (e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*Im)/Pm}))}var ab=ib(0),ob=ib(1),sb=ib(2),cb=ib(3),lb=ib(4),ub=ib(5),hb=ib(6),fb=ab.range,db=ob.range,pb=sb.range,gb=cb.range,yb=lb.range,mb=ub.range,bb=hb.range,vb=Um((function(t){t.setDate(1),t.setHours(0,0,0,0);}),(function(t,e){t.setMonth(t.getMonth()+e);}),(function(t,e){return e.getMonth()-t.getMonth()+12*(e.getFullYear()-t.getFullYear())}),(function(t){return t.getMonth()}));const _b=vb;var xb=vb.range,kb=Um((function(t){t.setMonth(0,1),t.setHours(0,0,0,0);}),(function(t,e){t.setFullYear(t.getFullYear()+e);}),(function(t,e){return e.getFullYear()-t.getFullYear()}),(function(t){return t.getFullYear()}));kb.every=function(t){return isFinite(t=Math.floor(t))&&t>0?Um((function(e){e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0);}),(function(e,n){e.setFullYear(e.getFullYear()+n*t);})):null};const wb=kb;var Tb=kb.range,Eb=Um((function(t){t.setUTCSeconds(0,0);}),(function(t,e){t.setTime(+t+e*Im);}),(function(t,e){return (e-t)/Im}),(function(t){return t.getUTCMinutes()}));const Cb=Eb;var Sb=Eb.range,Ab=Um((function(t){t.setUTCMinutes(0,0,0);}),(function(t,e){t.setTime(+t+e*Fm);}),(function(t,e){return (e-t)/Fm}),(function(t){return t.getUTCHours()}));const Mb=Ab;var Nb=Ab.range,Ob=Um((function(t){t.setUTCHours(0,0,0,0);}),(function(t,e){t.setUTCDate(t.getUTCDate()+e);}),(function(t,e){return (e-t)/Rm}),(function(t){return t.getUTCDate()-1}));const Db=Ob;var Bb=Ob.range;function Lb(t){return Um((function(e){e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0);}),(function(t,e){t.setUTCDate(t.getUTCDate()+7*e);}),(function(t,e){return (e-t)/Pm}))}var Ib=Lb(0),Fb=Lb(1),Rb=Lb(2),Pb=Lb(3),jb=Lb(4),zb=Lb(5),Yb=Lb(6),Ub=Ib.range,$b=Fb.range,Wb=Rb.range,qb=Pb.range,Hb=jb.range,Vb=zb.range,Gb=Yb.range,Xb=Um((function(t){t.setUTCDate(1),t.setUTCHours(0,0,0,0);}),(function(t,e){t.setUTCMonth(t.getUTCMonth()+e);}),(function(t,e){return e.getUTCMonth()-t.getUTCMonth()+12*(e.getUTCFullYear()-t.getUTCFullYear())}),(function(t){return t.getUTCMonth()}));const Zb=Xb;var Qb=Xb.range,Kb=Um((function(t){t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0);}),(function(t,e){t.setUTCFullYear(t.getUTCFullYear()+e);}),(function(t,e){return e.getUTCFullYear()-t.getUTCFullYear()}),(function(t){return t.getUTCFullYear()}));Kb.every=function(t){return isFinite(t=Math.floor(t))&&t>0?Um((function(e){e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0);}),(function(e,n){e.setUTCFullYear(e.getUTCFullYear()+n*t);})):null};const Jb=Kb;var tv=Kb.range;function ev(t,e,n,r,a,o){const s=[[Vm,1,Lm],[Vm,5,5e3],[Vm,15,15e3],[Vm,30,3e4],[o,1,Im],[o,5,3e5],[o,15,9e5],[o,30,18e5],[a,1,Fm],[a,3,108e5],[a,6,216e5],[a,12,432e5],[r,1,Rm],[r,2,1728e5],[n,1,Pm],[e,1,2592e6],[e,3,7776e6],[t,1,jm]];function c(e,n,r){const a=Math.abs(n-e)/r,o=i((([,,t])=>t)).right(s,a);if(o===s.length)return t.every(et(e/jm,n/jm,r));if(0===o)return Wm.every(Math.max(et(e,n,r),1));const[c,l]=s[a/s[o-1][2]<s[o][2]/a?o-1:o];return c.every(l)}return [function(t,e,n){const r=e<t;r&&([t,e]=[e,t]);const i=n&&"function"==typeof n.range?n:c(t,e,n),a=i?i.range(t,+e+1):[];return r?a.reverse():a},c]}const[nv,rv]=ev(Jb,Zb,Ib,Db,Mb,Cb),[iv,av]=ev(wb,_b,ab,nb,Jm,Zm);function ov(t){if(0<=t.y&&t.y<100){var e=new Date(-1,t.m,t.d,t.H,t.M,t.S,t.L);return e.setFullYear(t.y),e}return new Date(t.y,t.m,t.d,t.H,t.M,t.S,t.L)}function sv(t){if(0<=t.y&&t.y<100){var e=new Date(Date.UTC(-1,t.m,t.d,t.H,t.M,t.S,t.L));return e.setUTCFullYear(t.y),e}return new Date(Date.UTC(t.y,t.m,t.d,t.H,t.M,t.S,t.L))}function cv(t,e,n){return {y:t,m:e,d:n,H:0,M:0,S:0,L:0}}function lv(t){var e=t.dateTime,n=t.date,r=t.time,i=t.periods,a=t.days,o=t.shortDays,s=t.months,c=t.shortMonths,l=xv(i),u=kv(i),h=xv(a),f=kv(a),d=xv(o),p=kv(o),g=xv(s),y=kv(s),m=xv(c),b=kv(c),v={a:function(t){return o[t.getDay()]},A:function(t){return a[t.getDay()]},b:function(t){return c[t.getMonth()]},B:function(t){return s[t.getMonth()]},c:null,d:$v,e:$v,f:Gv,g:a_,G:s_,H:Wv,I:qv,j:Hv,L:Vv,m:Xv,M:Zv,p:function(t){return i[+(t.getHours()>=12)]},q:function(t){return 1+~~(t.getMonth()/3)},Q:N_,s:O_,S:Qv,u:Kv,U:Jv,V:e_,w:n_,W:r_,x:null,X:null,y:i_,Y:o_,Z:c_,"%":M_},_={a:function(t){return o[t.getUTCDay()]},A:function(t){return a[t.getUTCDay()]},b:function(t){return c[t.getUTCMonth()]},B:function(t){return s[t.getUTCMonth()]},c:null,d:l_,e:l_,f:p_,g:E_,G:S_,H:u_,I:h_,j:f_,L:d_,m:g_,M:y_,p:function(t){return i[+(t.getUTCHours()>=12)]},q:function(t){return 1+~~(t.getUTCMonth()/3)},Q:N_,s:O_,S:m_,u:b_,U:v_,V:x_,w:k_,W:w_,x:null,X:null,y:T_,Y:C_,Z:A_,"%":M_},x={a:function(t,e,n){var r=d.exec(e.slice(n));return r?(t.w=p.get(r[0].toLowerCase()),n+r[0].length):-1},A:function(t,e,n){var r=h.exec(e.slice(n));return r?(t.w=f.get(r[0].toLowerCase()),n+r[0].length):-1},b:function(t,e,n){var r=m.exec(e.slice(n));return r?(t.m=b.get(r[0].toLowerCase()),n+r[0].length):-1},B:function(t,e,n){var r=g.exec(e.slice(n));return r?(t.m=y.get(r[0].toLowerCase()),n+r[0].length):-1},c:function(t,n,r){return T(t,e,n,r)},d:Bv,e:Bv,f:jv,g:Mv,G:Av,H:Iv,I:Iv,j:Lv,L:Pv,m:Dv,M:Fv,p:function(t,e,n){var r=l.exec(e.slice(n));return r?(t.p=u.get(r[0].toLowerCase()),n+r[0].length):-1},q:Ov,Q:Yv,s:Uv,S:Rv,u:Tv,U:Ev,V:Cv,w:wv,W:Sv,x:function(t,e,r){return T(t,n,e,r)},X:function(t,e,n){return T(t,r,e,n)},y:Mv,Y:Av,Z:Nv,"%":zv};function k(t,e){return function(n){var r,i,a,o=[],s=-1,c=0,l=t.length;for(n instanceof Date||(n=new Date(+n));++s<l;)37===t.charCodeAt(s)&&(o.push(t.slice(c,s)),null!=(i=gv[r=t.charAt(++s)])?r=t.charAt(++s):i="e"===r?" ":"0",(a=e[r])&&(r=a(n,i)),o.push(r),c=s+1);return o.push(t.slice(c,s)),o.join("")}}function w(t,e){return function(n){var r,i,a=cv(1900,void 0,1);if(T(a,t,n+="",0)!=n.length)return null;if("Q"in a)return new Date(a.Q);if("s"in a)return new Date(1e3*a.s+("L"in a?a.L:0));if(e&&!("Z"in a)&&(a.Z=0),"p"in a&&(a.H=a.H%12+12*a.p),void 0===a.m&&(a.m="q"in a?a.q:0),"V"in a){if(a.V<1||a.V>53)return null;"w"in a||(a.w=1),"Z"in a?(i=(r=sv(cv(a.y,0,1))).getUTCDay(),r=i>4||0===i?Fb.ceil(r):Fb(r),r=Db.offset(r,7*(a.V-1)),a.y=r.getUTCFullYear(),a.m=r.getUTCMonth(),a.d=r.getUTCDate()+(a.w+6)%7):(i=(r=ov(cv(a.y,0,1))).getDay(),r=i>4||0===i?ob.ceil(r):ob(r),r=nb.offset(r,7*(a.V-1)),a.y=r.getFullYear(),a.m=r.getMonth(),a.d=r.getDate()+(a.w+6)%7);}else ("W"in a||"U"in a)&&("w"in a||(a.w="u"in a?a.u%7:"W"in a?1:0),i="Z"in a?sv(cv(a.y,0,1)).getUTCDay():ov(cv(a.y,0,1)).getDay(),a.m=0,a.d="W"in a?(a.w+6)%7+7*a.W-(i+5)%7:a.w+7*a.U-(i+6)%7);return "Z"in a?(a.H+=a.Z/100|0,a.M+=a.Z%100,sv(a)):ov(a)}}function T(t,e,n,r){for(var i,a,o=0,s=e.length,c=n.length;o<s;){if(r>=c)return -1;if(37===(i=e.charCodeAt(o++))){if(i=e.charAt(o++),!(a=x[i in gv?e.charAt(o++):i])||(r=a(t,n,r))<0)return -1}else if(i!=n.charCodeAt(r++))return -1}return r}return v.x=k(n,v),v.X=k(r,v),v.c=k(e,v),_.x=k(n,_),_.X=k(r,_),_.c=k(e,_),{format:function(t){var e=k(t+="",v);return e.toString=function(){return t},e},parse:function(t){var e=w(t+="",!1);return e.toString=function(){return t},e},utcFormat:function(t){var e=k(t+="",_);return e.toString=function(){return t},e},utcParse:function(t){var e=w(t+="",!0);return e.toString=function(){return t},e}}}var uv,hv,fv,dv,pv,gv={"-":"",_:" ",0:"0"},yv=/^\s*\d+/,mv=/^%/,bv=/[\\^$*+?|[\]().{}]/g;function vv(t,e,n){var r=t<0?"-":"",i=(r?-t:t)+"",a=i.length;return r+(a<n?new Array(n-a+1).join(e)+i:i)}function _v(t){return t.replace(bv,"\\$&")}function xv(t){return new RegExp("^(?:"+t.map(_v).join("|")+")","i")}function kv(t){return new Map(t.map(((t,e)=>[t.toLowerCase(),e])))}function wv(t,e,n){var r=yv.exec(e.slice(n,n+1));return r?(t.w=+r[0],n+r[0].length):-1}function Tv(t,e,n){var r=yv.exec(e.slice(n,n+1));return r?(t.u=+r[0],n+r[0].length):-1}function Ev(t,e,n){var r=yv.exec(e.slice(n,n+2));return r?(t.U=+r[0],n+r[0].length):-1}function Cv(t,e,n){var r=yv.exec(e.slice(n,n+2));return r?(t.V=+r[0],n+r[0].length):-1}function Sv(t,e,n){var r=yv.exec(e.slice(n,n+2));return r?(t.W=+r[0],n+r[0].length):-1}function Av(t,e,n){var r=yv.exec(e.slice(n,n+4));return r?(t.y=+r[0],n+r[0].length):-1}function Mv(t,e,n){var r=yv.exec(e.slice(n,n+2));return r?(t.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function Nv(t,e,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(n,n+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),n+r[0].length):-1}function Ov(t,e,n){var r=yv.exec(e.slice(n,n+1));return r?(t.q=3*r[0]-3,n+r[0].length):-1}function Dv(t,e,n){var r=yv.exec(e.slice(n,n+2));return r?(t.m=r[0]-1,n+r[0].length):-1}function Bv(t,e,n){var r=yv.exec(e.slice(n,n+2));return r?(t.d=+r[0],n+r[0].length):-1}function Lv(t,e,n){var r=yv.exec(e.slice(n,n+3));return r?(t.m=0,t.d=+r[0],n+r[0].length):-1}function Iv(t,e,n){var r=yv.exec(e.slice(n,n+2));return r?(t.H=+r[0],n+r[0].length):-1}function Fv(t,e,n){var r=yv.exec(e.slice(n,n+2));return r?(t.M=+r[0],n+r[0].length):-1}function Rv(t,e,n){var r=yv.exec(e.slice(n,n+2));return r?(t.S=+r[0],n+r[0].length):-1}function Pv(t,e,n){var r=yv.exec(e.slice(n,n+3));return r?(t.L=+r[0],n+r[0].length):-1}function jv(t,e,n){var r=yv.exec(e.slice(n,n+6));return r?(t.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function zv(t,e,n){var r=mv.exec(e.slice(n,n+1));return r?n+r[0].length:-1}function Yv(t,e,n){var r=yv.exec(e.slice(n));return r?(t.Q=+r[0],n+r[0].length):-1}function Uv(t,e,n){var r=yv.exec(e.slice(n));return r?(t.s=+r[0],n+r[0].length):-1}function $v(t,e){return vv(t.getDate(),e,2)}function Wv(t,e){return vv(t.getHours(),e,2)}function qv(t,e){return vv(t.getHours()%12||12,e,2)}function Hv(t,e){return vv(1+nb.count(wb(t),t),e,3)}function Vv(t,e){return vv(t.getMilliseconds(),e,3)}function Gv(t,e){return Vv(t,e)+"000"}function Xv(t,e){return vv(t.getMonth()+1,e,2)}function Zv(t,e){return vv(t.getMinutes(),e,2)}function Qv(t,e){return vv(t.getSeconds(),e,2)}function Kv(t){var e=t.getDay();return 0===e?7:e}function Jv(t,e){return vv(ab.count(wb(t)-1,t),e,2)}function t_(t){var e=t.getDay();return e>=4||0===e?lb(t):lb.ceil(t)}function e_(t,e){return t=t_(t),vv(lb.count(wb(t),t)+(4===wb(t).getDay()),e,2)}function n_(t){return t.getDay()}function r_(t,e){return vv(ob.count(wb(t)-1,t),e,2)}function i_(t,e){return vv(t.getFullYear()%100,e,2)}function a_(t,e){return vv((t=t_(t)).getFullYear()%100,e,2)}function o_(t,e){return vv(t.getFullYear()%1e4,e,4)}function s_(t,e){var n=t.getDay();return vv((t=n>=4||0===n?lb(t):lb.ceil(t)).getFullYear()%1e4,e,4)}function c_(t){var e=t.getTimezoneOffset();return (e>0?"-":(e*=-1,"+"))+vv(e/60|0,"0",2)+vv(e%60,"0",2)}function l_(t,e){return vv(t.getUTCDate(),e,2)}function u_(t,e){return vv(t.getUTCHours(),e,2)}function h_(t,e){return vv(t.getUTCHours()%12||12,e,2)}function f_(t,e){return vv(1+Db.count(Jb(t),t),e,3)}function d_(t,e){return vv(t.getUTCMilliseconds(),e,3)}function p_(t,e){return d_(t,e)+"000"}function g_(t,e){return vv(t.getUTCMonth()+1,e,2)}function y_(t,e){return vv(t.getUTCMinutes(),e,2)}function m_(t,e){return vv(t.getUTCSeconds(),e,2)}function b_(t){var e=t.getUTCDay();return 0===e?7:e}function v_(t,e){return vv(Ib.count(Jb(t)-1,t),e,2)}function __(t){var e=t.getUTCDay();return e>=4||0===e?jb(t):jb.ceil(t)}function x_(t,e){return t=__(t),vv(jb.count(Jb(t),t)+(4===Jb(t).getUTCDay()),e,2)}function k_(t){return t.getUTCDay()}function w_(t,e){return vv(Fb.count(Jb(t)-1,t),e,2)}function T_(t,e){return vv(t.getUTCFullYear()%100,e,2)}function E_(t,e){return vv((t=__(t)).getUTCFullYear()%100,e,2)}function C_(t,e){return vv(t.getUTCFullYear()%1e4,e,4)}function S_(t,e){var n=t.getUTCDay();return vv((t=n>=4||0===n?jb(t):jb.ceil(t)).getUTCFullYear()%1e4,e,4)}function A_(){return "+0000"}function M_(){return "%"}function N_(t){return +t}function O_(t){return Math.floor(+t/1e3)}function D_(t){return uv=lv(t),hv=uv.format,fv=uv.parse,dv=uv.utcFormat,pv=uv.utcParse,uv}function B_(t){return new Date(t)}function L_(t){return t instanceof Date?+t:+new Date(+t)}function I_(t,e,n,r,i,a,o,s,c,l){var u=im(),h=u.invert,f=u.domain,d=l(".%L"),p=l(":%S"),g=l("%I:%M"),y=l("%I %p"),m=l("%a %d"),b=l("%b %d"),v=l("%B"),_=l("%Y");function x(t){return (c(t)<t?d:s(t)<t?p:o(t)<t?g:a(t)<t?y:r(t)<t?i(t)<t?m:b:n(t)<t?v:_)(t)}return u.invert=function(t){return new Date(h(t))},u.domain=function(t){return arguments.length?f(Array.from(t,L_)):f().map(B_)},u.ticks=function(e){var n=f();return t(n[0],n[n.length-1],null==e?10:e)},u.tickFormat=function(t,e){return null==e?x:l(e)},u.nice=function(t){var n=f();return t&&"function"==typeof t.range||(t=e(n[0],n[n.length-1],null==t?10:t)),t?f(lm(n,t)):u},u.copy=function(){return nm(u,I_(t,e,n,r,i,a,o,s,c,l))},u}function F_(){return $y.apply(I_(iv,av,wb,_b,ab,nb,Jm,Zm,Vm,hv).domain([new Date(2e3,0,1),new Date(2e3,0,2)]),arguments)}function R_(){return $y.apply(I_(nv,rv,Jb,Zb,Ib,Db,Mb,Cb,Vm,dv).domain([Date.UTC(2e3,0,1),Date.UTC(2e3,0,2)]),arguments)}function P_(){var t,e,n,r,i,a=0,o=1,s=Ky,c=!1;function l(e){return null==e||isNaN(e=+e)?i:s(0===n?.5:(e=(r(e)-t)*n,c?Math.max(0,Math.min(1,e)):e))}function u(t){return function(e){var n,r;return arguments.length?([n,r]=e,s=t(n,r),l):[s(0),s(1)]}}return l.domain=function(i){return arguments.length?([a,o]=i,t=r(a=+a),e=r(o=+o),n=t===e?0:1/(e-t),l):[a,o]},l.clamp=function(t){return arguments.length?(c=!!t,l):c},l.interpolator=function(t){return arguments.length?(s=t,l):s},l.range=u(Ir),l.rangeRound=u(ty),l.unknown=function(t){return arguments.length?(i=t,l):i},function(i){return r=i,t=i(a),e=i(o),n=t===e?0:1/(e-t),l}}function j_(t,e){return e.domain(t.domain()).interpolator(t.interpolator()).clamp(t.clamp()).unknown(t.unknown())}function z_(){var t=om(P_()(Ky));return t.copy=function(){return j_(t,z_())},Wy.apply(t,arguments)}function Y_(){var t=ym(P_()).domain([1,10]);return t.copy=function(){return j_(t,Y_()).base(t.base())},Wy.apply(t,arguments)}function U_(){var t=_m(P_());return t.copy=function(){return j_(t,U_()).constant(t.constant())},Wy.apply(t,arguments)}function $_(){var t=Em(P_());return t.copy=function(){return j_(t,$_()).exponent(t.exponent())},Wy.apply(t,arguments)}function W_(){return $_.apply(null,arguments).exponent(.5)}function q_(){var t=[],e=Ky;function n(n){if(null!=n&&!isNaN(n=+n))return e((u(t,n,1)-1)/(t.length-1))}return n.domain=function(e){if(!arguments.length)return t.slice();t=[];for(let n of e)null==n||isNaN(n=+n)||t.push(n);return t.sort(r),n},n.interpolator=function(t){return arguments.length?(e=t,n):e},n.range=function(){return t.map(((n,r)=>e(r/(t.length-1))))},n.quantiles=function(e){return Array.from({length:e+1},((n,r)=>lt(t,r/e)))},n.copy=function(){return q_(e).domain(t)},Wy.apply(n,arguments)}function H_(){var t,e,n,r,i,a,o,s=0,c=.5,l=1,u=1,h=Ky,f=!1;function d(t){return isNaN(t=+t)?o:(t=.5+((t=+a(t))-e)*(u*t<u*e?r:i),h(f?Math.max(0,Math.min(1,t)):t))}function p(t){return function(e){var n,r,i;return arguments.length?([n,r,i]=e,h=dy(t,[n,r,i]),d):[h(0),h(.5),h(1)]}}return d.domain=function(o){return arguments.length?([s,c,l]=o,t=a(s=+s),e=a(c=+c),n=a(l=+l),r=t===e?0:.5/(e-t),i=e===n?0:.5/(n-e),u=e<t?-1:1,d):[s,c,l]},d.clamp=function(t){return arguments.length?(f=!!t,d):f},d.interpolator=function(t){return arguments.length?(h=t,d):h},d.range=p(Ir),d.rangeRound=p(ty),d.unknown=function(t){return arguments.length?(o=t,d):o},function(o){return a=o,t=o(s),e=o(c),n=o(l),r=t===e?0:.5/(e-t),i=e===n?0:.5/(n-e),u=e<t?-1:1,d}}function V_(){var t=om(H_()(Ky));return t.copy=function(){return j_(t,V_())},Wy.apply(t,arguments)}function G_(){var t=ym(H_()).domain([.1,1,10]);return t.copy=function(){return j_(t,G_()).base(t.base())},Wy.apply(t,arguments)}function X_(){var t=_m(H_());return t.copy=function(){return j_(t,X_()).constant(t.constant())},Wy.apply(t,arguments)}function Z_(){var t=Em(H_());return t.copy=function(){return j_(t,Z_()).exponent(t.exponent())},Wy.apply(t,arguments)}function Q_(){return Z_.apply(null,arguments).exponent(.5)}function K_(t){for(var e=t.length/6|0,n=new Array(e),r=0;r<e;)n[r]="#"+t.slice(6*r,6*++r);return n}D_({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});const J_=K_("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf"),tx=K_("7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666"),ex=K_("1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666"),nx=K_("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928"),rx=K_("fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2"),ix=K_("b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc"),ax=K_("e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999"),ox=K_("66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3"),sx=K_("8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f"),cx=K_("4e79a7f28e2ce1575976b7b259a14fedc949af7aa1ff9da79c755fbab0ab"),lx=t=>wr(t[t.length-1]);var ux=new Array(3).concat("d8b365f5f5f55ab4ac","a6611adfc27d80cdc1018571","a6611adfc27df5f5f580cdc1018571","8c510ad8b365f6e8c3c7eae55ab4ac01665e","8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e","8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e","8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e","5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30","5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30").map(K_);const hx=lx(ux);var fx=new Array(3).concat("af8dc3f7f7f77fbf7b","7b3294c2a5cfa6dba0008837","7b3294c2a5cff7f7f7a6dba0008837","762a83af8dc3e7d4e8d9f0d37fbf7b1b7837","762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837","762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837","762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837","40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b","40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b").map(K_);const dx=lx(fx);var px=new Array(3).concat("e9a3c9f7f7f7a1d76a","d01c8bf1b6dab8e1864dac26","d01c8bf1b6daf7f7f7b8e1864dac26","c51b7de9a3c9fde0efe6f5d0a1d76a4d9221","c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221","c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221","c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221","8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419","8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419").map(K_);const gx=lx(px);var yx=new Array(3).concat("998ec3f7f7f7f1a340","5e3c99b2abd2fdb863e66101","5e3c99b2abd2f7f7f7fdb863e66101","542788998ec3d8daebfee0b6f1a340b35806","542788998ec3d8daebf7f7f7fee0b6f1a340b35806","5427888073acb2abd2d8daebfee0b6fdb863e08214b35806","5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806","2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08","2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08").map(K_);const mx=lx(yx);var bx=new Array(3).concat("ef8a62f7f7f767a9cf","ca0020f4a58292c5de0571b0","ca0020f4a582f7f7f792c5de0571b0","b2182bef8a62fddbc7d1e5f067a9cf2166ac","b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac","b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac","b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac","67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061","67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061").map(K_);const vx=lx(bx);var _x=new Array(3).concat("ef8a62ffffff999999","ca0020f4a582bababa404040","ca0020f4a582ffffffbababa404040","b2182bef8a62fddbc7e0e0e09999994d4d4d","b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d","b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d","b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d","67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a","67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a").map(K_);const xx=lx(_x);var kx=new Array(3).concat("fc8d59ffffbf91bfdb","d7191cfdae61abd9e92c7bb6","d7191cfdae61ffffbfabd9e92c7bb6","d73027fc8d59fee090e0f3f891bfdb4575b4","d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4","d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4","d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4","a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695","a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695").map(K_);const wx=lx(kx);var Tx=new Array(3).concat("fc8d59ffffbf91cf60","d7191cfdae61a6d96a1a9641","d7191cfdae61ffffbfa6d96a1a9641","d73027fc8d59fee08bd9ef8b91cf601a9850","d73027fc8d59fee08bffffbfd9ef8b91cf601a9850","d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850","d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850","a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837","a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837").map(K_);const Ex=lx(Tx);var Cx=new Array(3).concat("fc8d59ffffbf99d594","d7191cfdae61abdda42b83ba","d7191cfdae61ffffbfabdda42b83ba","d53e4ffc8d59fee08be6f59899d5943288bd","d53e4ffc8d59fee08bffffbfe6f59899d5943288bd","d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd","d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd","9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2","9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2").map(K_);const Sx=lx(Cx);var Ax=new Array(3).concat("e5f5f999d8c92ca25f","edf8fbb2e2e266c2a4238b45","edf8fbb2e2e266c2a42ca25f006d2c","edf8fbccece699d8c966c2a42ca25f006d2c","edf8fbccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(K_);const Mx=lx(Ax);var Nx=new Array(3).concat("e0ecf49ebcda8856a7","edf8fbb3cde38c96c688419d","edf8fbb3cde38c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(K_);const Ox=lx(Nx);var Dx=new Array(3).concat("e0f3dba8ddb543a2ca","f0f9e8bae4bc7bccc42b8cbe","f0f9e8bae4bc7bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(K_);const Bx=lx(Dx);var Lx=new Array(3).concat("fee8c8fdbb84e34a33","fef0d9fdcc8afc8d59d7301f","fef0d9fdcc8afc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(K_);const Ix=lx(Lx);var Fx=new Array(3).concat("ece2f0a6bddb1c9099","f6eff7bdc9e167a9cf02818a","f6eff7bdc9e167a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(K_);const Rx=lx(Fx);var Px=new Array(3).concat("ece7f2a6bddb2b8cbe","f1eef6bdc9e174a9cf0570b0","f1eef6bdc9e174a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(K_);const jx=lx(Px);var zx=new Array(3).concat("e7e1efc994c7dd1c77","f1eef6d7b5d8df65b0ce1256","f1eef6d7b5d8df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(K_);const Yx=lx(zx);var Ux=new Array(3).concat("fde0ddfa9fb5c51b8a","feebe2fbb4b9f768a1ae017e","feebe2fbb4b9f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(K_);const $x=lx(Ux);var Wx=new Array(3).concat("edf8b17fcdbb2c7fb8","ffffcca1dab441b6c4225ea8","ffffcca1dab441b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(K_);const qx=lx(Wx);var Hx=new Array(3).concat("f7fcb9addd8e31a354","ffffccc2e69978c679238443","ffffccc2e69978c67931a354006837","ffffccd9f0a3addd8e78c67931a354006837","ffffccd9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(K_);const Vx=lx(Hx);var Gx=new Array(3).concat("fff7bcfec44fd95f0e","ffffd4fed98efe9929cc4c02","ffffd4fed98efe9929d95f0e993404","ffffd4fee391fec44ffe9929d95f0e993404","ffffd4fee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(K_);const Xx=lx(Gx);var Zx=new Array(3).concat("ffeda0feb24cf03b20","ffffb2fecc5cfd8d3ce31a1c","ffffb2fecc5cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(K_);const Qx=lx(Zx);var Kx=new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ecae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(K_);const Jx=lx(Kx);var tk=new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(K_);const ek=lx(tk);var nk=new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(K_);const rk=lx(nk);var ik=new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(K_);const ak=lx(ik);var ok=new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(K_);const sk=lx(ok);var ck=new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(K_);const lk=lx(ck);function uk(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(-4.54-t*(35.34-t*(2381.73-t*(6402.7-t*(7024.72-2710.57*t)))))))+", "+Math.max(0,Math.min(255,Math.round(32.49+t*(170.73+t*(52.82-t*(131.46-t*(176.58-67.37*t)))))))+", "+Math.max(0,Math.min(255,Math.round(81.24+t*(442.36-t*(2482.43-t*(6167.24-t*(6614.94-2475.67*t)))))))+")"}const hk=fy(Uo(300,.5,0),Uo(-240,.5,1));var fk=fy(Uo(-100,.75,.35),Uo(80,1.5,.8)),dk=fy(Uo(260,.75,.35),Uo(80,1.5,.8)),pk=Uo();function gk(t){(t<0||t>1)&&(t-=Math.floor(t));var e=Math.abs(t-.5);return pk.h=360*t-100,pk.s=1.5-1.5*e,pk.l=.8-.9*e,pk+""}var yk=ir(),mk=Math.PI/3,bk=2*Math.PI/3;function vk(t){var e;return t=(.5-t)*Math.PI,yk.r=255*(e=Math.sin(t))*e,yk.g=255*(e=Math.sin(t+mk))*e,yk.b=255*(e=Math.sin(t+bk))*e,yk+""}function _k(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(34.61+t*(1172.33-t*(10793.56-t*(33300.12-t*(38394.49-14825.05*t)))))))+", "+Math.max(0,Math.min(255,Math.round(23.31+t*(557.33+t*(1225.33-t*(3574.96-t*(1073.77+707.56*t)))))))+", "+Math.max(0,Math.min(255,Math.round(27.2+t*(3211.1-t*(15327.97-t*(27814-t*(22569.18-6838.66*t)))))))+")"}function xk(t){var e=t.length;return function(n){return t[Math.max(0,Math.min(e-1,Math.floor(n*e)))]}}const kk=xk(K_("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725"));var wk=xk(K_("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),Tk=xk(K_("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),Ek=xk(K_("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));function Ck(t){return Mn(pn(t).call(document.documentElement))}var Sk=0;function Ak(){return new Mk}function Mk(){this._="@"+(++Sk).toString(36);}function Nk(t,e){return t.target&&(t=Fr(t),void 0===e&&(e=t.currentTarget),t=t.touches||[t]),Array.from(t,(t=>Rr(t,e)))}function Ok(t){return "string"==typeof t?new Cn([document.querySelectorAll(t)],[document.documentElement]):new Cn([ge(t)],En)}function Dk(t){return function(){return t}}Mk.prototype=Ak.prototype={constructor:Mk,get:function(t){for(var e=this._;!(e in t);)if(!(t=t.parentNode))return;return t[e]},set:function(t,e){return t[this._]=e},remove:function(t){return this._ in t&&delete t[this._]},toString:function(){return this._}};var Bk=Math.abs,Lk=Math.atan2,Ik=Math.cos,Fk=Math.max,Rk=Math.min,Pk=Math.sin,jk=Math.sqrt,zk=1e-12,Yk=Math.PI,Uk=Yk/2,$k=2*Yk;function Wk(t){return t>1?0:t<-1?Yk:Math.acos(t)}function qk(t){return t>=1?Uk:t<=-1?-Uk:Math.asin(t)}function Hk(t){return t.innerRadius}function Vk(t){return t.outerRadius}function Gk(t){return t.startAngle}function Xk(t){return t.endAngle}function Zk(t){return t&&t.padAngle}function Qk(t,e,n,r,i,a,o,s){var c=n-t,l=r-e,u=o-i,h=s-a,f=h*c-u*l;if(!(f*f<zk))return [t+(f=(u*(e-a)-h*(t-i))/f)*c,e+f*l]}function Kk(t,e,n,r,i,a,o){var s=t-n,c=e-r,l=(o?a:-a)/jk(s*s+c*c),u=l*c,h=-l*s,f=t+u,d=e+h,p=n+u,g=r+h,y=(f+p)/2,m=(d+g)/2,b=p-f,v=g-d,_=b*b+v*v,x=i-a,k=f*g-p*d,w=(v<0?-1:1)*jk(Fk(0,x*x*_-k*k)),T=(k*v-b*w)/_,E=(-k*b-v*w)/_,C=(k*v+b*w)/_,S=(-k*b+v*w)/_,A=T-y,M=E-m,N=C-y,O=S-m;return A*A+M*M>N*N+O*O&&(T=C,E=S),{cx:T,cy:E,x01:-u,y01:-h,x11:T*(i/x-1),y11:E*(i/x-1)}}function Jk(){var t=Hk,e=Vk,n=Dk(0),r=null,i=Gk,a=Xk,o=Zk,s=null;function c(){var c,l,u=+t.apply(this,arguments),h=+e.apply(this,arguments),f=i.apply(this,arguments)-Uk,d=a.apply(this,arguments)-Uk,p=Bk(d-f),g=d>f;if(s||(s=c=Ja()),h<u&&(l=h,h=u,u=l),h>zk)if(p>$k-zk)s.moveTo(h*Ik(f),h*Pk(f)),s.arc(0,0,h,f,d,!g),u>zk&&(s.moveTo(u*Ik(d),u*Pk(d)),s.arc(0,0,u,d,f,g));else {var y,m,b=f,v=d,_=f,x=d,k=p,w=p,T=o.apply(this,arguments)/2,E=T>zk&&(r?+r.apply(this,arguments):jk(u*u+h*h)),C=Rk(Bk(h-u)/2,+n.apply(this,arguments)),S=C,A=C;if(E>zk){var M=qk(E/u*Pk(T)),N=qk(E/h*Pk(T));(k-=2*M)>zk?(_+=M*=g?1:-1,x-=M):(k=0,_=x=(f+d)/2),(w-=2*N)>zk?(b+=N*=g?1:-1,v-=N):(w=0,b=v=(f+d)/2);}var O=h*Ik(b),D=h*Pk(b),B=u*Ik(x),L=u*Pk(x);if(C>zk){var I,F=h*Ik(v),R=h*Pk(v),P=u*Ik(_),j=u*Pk(_);if(p<Yk&&(I=Qk(O,D,P,j,F,R,B,L))){var z=O-I[0],Y=D-I[1],U=F-I[0],$=R-I[1],W=1/Pk(Wk((z*U+Y*$)/(jk(z*z+Y*Y)*jk(U*U+$*$)))/2),q=jk(I[0]*I[0]+I[1]*I[1]);S=Rk(C,(u-q)/(W-1)),A=Rk(C,(h-q)/(W+1));}}w>zk?A>zk?(y=Kk(P,j,O,D,h,A,g),m=Kk(F,R,B,L,h,A,g),s.moveTo(y.cx+y.x01,y.cy+y.y01),A<C?s.arc(y.cx,y.cy,A,Lk(y.y01,y.x01),Lk(m.y01,m.x01),!g):(s.arc(y.cx,y.cy,A,Lk(y.y01,y.x01),Lk(y.y11,y.x11),!g),s.arc(0,0,h,Lk(y.cy+y.y11,y.cx+y.x11),Lk(m.cy+m.y11,m.cx+m.x11),!g),s.arc(m.cx,m.cy,A,Lk(m.y11,m.x11),Lk(m.y01,m.x01),!g))):(s.moveTo(O,D),s.arc(0,0,h,b,v,!g)):s.moveTo(O,D),u>zk&&k>zk?S>zk?(y=Kk(B,L,F,R,u,-S,g),m=Kk(O,D,P,j,u,-S,g),s.lineTo(y.cx+y.x01,y.cy+y.y01),S<C?s.arc(y.cx,y.cy,S,Lk(y.y01,y.x01),Lk(m.y01,m.x01),!g):(s.arc(y.cx,y.cy,S,Lk(y.y01,y.x01),Lk(y.y11,y.x11),!g),s.arc(0,0,u,Lk(y.cy+y.y11,y.cx+y.x11),Lk(m.cy+m.y11,m.cx+m.x11),g),s.arc(m.cx,m.cy,S,Lk(m.y11,m.x11),Lk(m.y01,m.x01),!g))):s.arc(0,0,u,x,_,g):s.lineTo(B,L);}else s.moveTo(0,0);if(s.closePath(),c)return s=null,c+""||null}return c.centroid=function(){var n=(+t.apply(this,arguments)+ +e.apply(this,arguments))/2,r=(+i.apply(this,arguments)+ +a.apply(this,arguments))/2-Yk/2;return [Ik(r)*n,Pk(r)*n]},c.innerRadius=function(e){return arguments.length?(t="function"==typeof e?e:Dk(+e),c):t},c.outerRadius=function(t){return arguments.length?(e="function"==typeof t?t:Dk(+t),c):e},c.cornerRadius=function(t){return arguments.length?(n="function"==typeof t?t:Dk(+t),c):n},c.padRadius=function(t){return arguments.length?(r=null==t?null:"function"==typeof t?t:Dk(+t),c):r},c.startAngle=function(t){return arguments.length?(i="function"==typeof t?t:Dk(+t),c):i},c.endAngle=function(t){return arguments.length?(a="function"==typeof t?t:Dk(+t),c):a},c.padAngle=function(t){return arguments.length?(o="function"==typeof t?t:Dk(+t),c):o},c.context=function(t){return arguments.length?(s=null==t?null:t,c):s},c}var tw=Array.prototype.slice;function ew(t){return "object"==typeof t&&"length"in t?t:Array.from(t)}function nw(t){this._context=t;}function rw(t){return new nw(t)}function iw(t){return t[0]}function aw(t){return t[1]}function ow(t,e){var n=Dk(!0),r=null,i=rw,a=null;function o(o){var s,c,l,u=(o=ew(o)).length,h=!1;for(null==r&&(a=i(l=Ja())),s=0;s<=u;++s)!(s<u&&n(c=o[s],s,o))===h&&((h=!h)?a.lineStart():a.lineEnd()),h&&a.point(+t(c,s,o),+e(c,s,o));if(l)return a=null,l+""||null}return t="function"==typeof t?t:void 0===t?iw:Dk(t),e="function"==typeof e?e:void 0===e?aw:Dk(e),o.x=function(e){return arguments.length?(t="function"==typeof e?e:Dk(+e),o):t},o.y=function(t){return arguments.length?(e="function"==typeof t?t:Dk(+t),o):e},o.defined=function(t){return arguments.length?(n="function"==typeof t?t:Dk(!!t),o):n},o.curve=function(t){return arguments.length?(i=t,null!=r&&(a=i(r)),o):i},o.context=function(t){return arguments.length?(null==t?r=a=null:a=i(r=t),o):r},o}function sw(t,e,n){var r=null,i=Dk(!0),a=null,o=rw,s=null;function c(c){var l,u,h,f,d,p=(c=ew(c)).length,g=!1,y=new Array(p),m=new Array(p);for(null==a&&(s=o(d=Ja())),l=0;l<=p;++l){if(!(l<p&&i(f=c[l],l,c))===g)if(g=!g)u=l,s.areaStart(),s.lineStart();else {for(s.lineEnd(),s.lineStart(),h=l-1;h>=u;--h)s.point(y[h],m[h]);s.lineEnd(),s.areaEnd();}g&&(y[l]=+t(f,l,c),m[l]=+e(f,l,c),s.point(r?+r(f,l,c):y[l],n?+n(f,l,c):m[l]));}if(d)return s=null,d+""||null}function l(){return ow().defined(i).curve(o).context(a)}return t="function"==typeof t?t:void 0===t?iw:Dk(+t),e="function"==typeof e?e:Dk(void 0===e?0:+e),n="function"==typeof n?n:void 0===n?aw:Dk(+n),c.x=function(e){return arguments.length?(t="function"==typeof e?e:Dk(+e),r=null,c):t},c.x0=function(e){return arguments.length?(t="function"==typeof e?e:Dk(+e),c):t},c.x1=function(t){return arguments.length?(r=null==t?null:"function"==typeof t?t:Dk(+t),c):r},c.y=function(t){return arguments.length?(e="function"==typeof t?t:Dk(+t),n=null,c):e},c.y0=function(t){return arguments.length?(e="function"==typeof t?t:Dk(+t),c):e},c.y1=function(t){return arguments.length?(n=null==t?null:"function"==typeof t?t:Dk(+t),c):n},c.lineX0=c.lineY0=function(){return l().x(t).y(e)},c.lineY1=function(){return l().x(t).y(n)},c.lineX1=function(){return l().x(r).y(e)},c.defined=function(t){return arguments.length?(i="function"==typeof t?t:Dk(!!t),c):i},c.curve=function(t){return arguments.length?(o=t,null!=a&&(s=o(a)),c):o},c.context=function(t){return arguments.length?(null==t?a=s=null:s=o(a=t),c):a},c}function cw(t,e){return e<t?-1:e>t?1:e>=t?0:NaN}function lw(t){return t}function uw(){var t=lw,e=cw,n=null,r=Dk(0),i=Dk($k),a=Dk(0);function o(o){var s,c,l,u,h,f=(o=ew(o)).length,d=0,p=new Array(f),g=new Array(f),y=+r.apply(this,arguments),m=Math.min($k,Math.max(-$k,i.apply(this,arguments)-y)),b=Math.min(Math.abs(m)/f,a.apply(this,arguments)),v=b*(m<0?-1:1);for(s=0;s<f;++s)(h=g[p[s]=s]=+t(o[s],s,o))>0&&(d+=h);for(null!=e?p.sort((function(t,n){return e(g[t],g[n])})):null!=n&&p.sort((function(t,e){return n(o[t],o[e])})),s=0,l=d?(m-f*v)/d:0;s<f;++s,y=u)c=p[s],u=y+((h=g[c])>0?h*l:0)+v,g[c]={data:o[c],index:s,value:h,startAngle:y,endAngle:u,padAngle:b};return g}return o.value=function(e){return arguments.length?(t="function"==typeof e?e:Dk(+e),o):t},o.sortValues=function(t){return arguments.length?(e=t,n=null,o):e},o.sort=function(t){return arguments.length?(n=t,e=null,o):n},o.startAngle=function(t){return arguments.length?(r="function"==typeof t?t:Dk(+t),o):r},o.endAngle=function(t){return arguments.length?(i="function"==typeof t?t:Dk(+t),o):i},o.padAngle=function(t){return arguments.length?(a="function"==typeof t?t:Dk(+t),o):a},o}nw.prototype={areaStart:function(){this._line=0;},areaEnd:function(){this._line=NaN;},lineStart:function(){this._point=0;},lineEnd:function(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line;},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._context.lineTo(t,e);}}};var hw=dw(rw);function fw(t){this._curve=t;}function dw(t){function e(e){return new fw(t(e))}return e._curve=t,e}function pw(t){var e=t.curve;return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t.curve=function(t){return arguments.length?e(dw(t)):e()._curve},t}function gw(){return pw(ow().curve(hw))}function yw(){var t=sw().curve(hw),e=t.curve,n=t.lineX0,r=t.lineX1,i=t.lineY0,a=t.lineY1;return t.angle=t.x,delete t.x,t.startAngle=t.x0,delete t.x0,t.endAngle=t.x1,delete t.x1,t.radius=t.y,delete t.y,t.innerRadius=t.y0,delete t.y0,t.outerRadius=t.y1,delete t.y1,t.lineStartAngle=function(){return pw(n())},delete t.lineX0,t.lineEndAngle=function(){return pw(r())},delete t.lineX1,t.lineInnerRadius=function(){return pw(i())},delete t.lineY0,t.lineOuterRadius=function(){return pw(a())},delete t.lineY1,t.curve=function(t){return arguments.length?e(dw(t)):e()._curve},t}function mw(t,e){return [(e=+e)*Math.cos(t-=Math.PI/2),e*Math.sin(t)]}function bw(t){return t.source}function vw(t){return t.target}function _w(t){var e=bw,n=vw,r=iw,i=aw,a=null;function o(){var o,s=tw.call(arguments),c=e.apply(this,s),l=n.apply(this,s);if(a||(a=o=Ja()),t(a,+r.apply(this,(s[0]=c,s)),+i.apply(this,s),+r.apply(this,(s[0]=l,s)),+i.apply(this,s)),o)return a=null,o+""||null}return o.source=function(t){return arguments.length?(e=t,o):e},o.target=function(t){return arguments.length?(n=t,o):n},o.x=function(t){return arguments.length?(r="function"==typeof t?t:Dk(+t),o):r},o.y=function(t){return arguments.length?(i="function"==typeof t?t:Dk(+t),o):i},o.context=function(t){return arguments.length?(a=null==t?null:t,o):a},o}function xw(t,e,n,r,i){t.moveTo(e,n),t.bezierCurveTo(e=(e+r)/2,n,e,i,r,i);}function kw(t,e,n,r,i){t.moveTo(e,n),t.bezierCurveTo(e,n=(n+i)/2,r,n,r,i);}function ww(t,e,n,r,i){var a=mw(e,n),o=mw(e,n=(n+i)/2),s=mw(r,n),c=mw(r,i);t.moveTo(a[0],a[1]),t.bezierCurveTo(o[0],o[1],s[0],s[1],c[0],c[1]);}function Tw(){return _w(xw)}function Ew(){return _w(kw)}function Cw(){var t=_w(ww);return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t}fw.prototype={areaStart:function(){this._curve.areaStart();},areaEnd:function(){this._curve.areaEnd();},lineStart:function(){this._curve.lineStart();},lineEnd:function(){this._curve.lineEnd();},point:function(t,e){this._curve.point(e*Math.sin(t),e*-Math.cos(t));}};const Sw={draw:function(t,e){var n=Math.sqrt(e/Yk);t.moveTo(n,0),t.arc(0,0,n,0,$k);}},Aw={draw:function(t,e){var n=Math.sqrt(e/5)/2;t.moveTo(-3*n,-n),t.lineTo(-n,-n),t.lineTo(-n,-3*n),t.lineTo(n,-3*n),t.lineTo(n,-n),t.lineTo(3*n,-n),t.lineTo(3*n,n),t.lineTo(n,n),t.lineTo(n,3*n),t.lineTo(-n,3*n),t.lineTo(-n,n),t.lineTo(-3*n,n),t.closePath();}};var Mw=Math.sqrt(1/3),Nw=2*Mw;const Ow={draw:function(t,e){var n=Math.sqrt(e/Nw),r=n*Mw;t.moveTo(0,-n),t.lineTo(r,0),t.lineTo(0,n),t.lineTo(-r,0),t.closePath();}};var Dw=Math.sin(Yk/10)/Math.sin(7*Yk/10),Bw=Math.sin($k/10)*Dw,Lw=-Math.cos($k/10)*Dw;const Iw={draw:function(t,e){var n=Math.sqrt(.8908130915292852*e),r=Bw*n,i=Lw*n;t.moveTo(0,-n),t.lineTo(r,i);for(var a=1;a<5;++a){var o=$k*a/5,s=Math.cos(o),c=Math.sin(o);t.lineTo(c*n,-s*n),t.lineTo(s*r-c*i,c*r+s*i);}t.closePath();}},Fw={draw:function(t,e){var n=Math.sqrt(e),r=-n/2;t.rect(r,r,n,n);}};var Rw=Math.sqrt(3);const Pw={draw:function(t,e){var n=-Math.sqrt(e/(3*Rw));t.moveTo(0,2*n),t.lineTo(-Rw*n,-n),t.lineTo(Rw*n,-n),t.closePath();}};var jw=-.5,zw=Math.sqrt(3)/2,Yw=1/Math.sqrt(12),Uw=3*(Yw/2+1);const $w={draw:function(t,e){var n=Math.sqrt(e/Uw),r=n/2,i=n*Yw,a=r,o=n*Yw+n,s=-a,c=o;t.moveTo(r,i),t.lineTo(a,o),t.lineTo(s,c),t.lineTo(jw*r-zw*i,zw*r+jw*i),t.lineTo(jw*a-zw*o,zw*a+jw*o),t.lineTo(jw*s-zw*c,zw*s+jw*c),t.lineTo(jw*r+zw*i,jw*i-zw*r),t.lineTo(jw*a+zw*o,jw*o-zw*a),t.lineTo(jw*s+zw*c,jw*c-zw*s),t.closePath();}};var Ww=[Sw,Aw,Ow,Fw,Iw,Pw,$w];function qw(t,e){var n=null;function r(){var r;if(n||(n=r=Ja()),t.apply(this,arguments).draw(n,+e.apply(this,arguments)),r)return n=null,r+""||null}return t="function"==typeof t?t:Dk(t||Sw),e="function"==typeof e?e:Dk(void 0===e?64:+e),r.type=function(e){return arguments.length?(t="function"==typeof e?e:Dk(e),r):t},r.size=function(t){return arguments.length?(e="function"==typeof t?t:Dk(+t),r):e},r.context=function(t){return arguments.length?(n=null==t?null:t,r):n},r}function Hw(){}function Vw(t,e,n){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+e)/6,(t._y0+4*t._y1+n)/6);}function Gw(t){this._context=t;}function Xw(t){return new Gw(t)}function Zw(t){this._context=t;}function Qw(t){return new Zw(t)}function Kw(t){this._context=t;}function Jw(t){return new Kw(t)}Gw.prototype={areaStart:function(){this._line=0;},areaEnd:function(){this._line=NaN;},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0;},lineEnd:function(){switch(this._point){case 3:Vw(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line;},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:Vw(this,t,e);}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e;}},Zw.prototype={areaStart:Hw,areaEnd:Hw,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0;},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x2=t,this._y2=e;break;case 1:this._point=2,this._x3=t,this._y3=e;break;case 2:this._point=3,this._x4=t,this._y4=e,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+e)/6);break;default:Vw(this,t,e);}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e;}},Kw.prototype={areaStart:function(){this._line=0;},areaEnd:function(){this._line=NaN;},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0;},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line;},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+t)/6,r=(this._y0+4*this._y1+e)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:Vw(this,t,e);}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e;}};class tT{constructor(t,e){this._context=t,this._x=e;}areaStart(){this._line=0;}areaEnd(){this._line=NaN;}lineStart(){this._point=0;}lineEnd(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line;}point(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,e,t,e):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+e)/2,t,this._y0,t,e);}this._x0=t,this._y0=e;}}function eT(t){return new tT(t,!0)}function nT(t){return new tT(t,!1)}function rT(t,e){this._basis=new Gw(t),this._beta=e;}rT.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart();},lineEnd:function(){var t=this._x,e=this._y,n=t.length-1;if(n>0)for(var r,i=t[0],a=e[0],o=t[n]-i,s=e[n]-a,c=-1;++c<=n;)r=c/n,this._basis.point(this._beta*t[c]+(1-this._beta)*(i+r*o),this._beta*e[c]+(1-this._beta)*(a+r*s));this._x=this._y=null,this._basis.lineEnd();},point:function(t,e){this._x.push(+t),this._y.push(+e);}};const iT=function t(e){function n(t){return 1===e?new Gw(t):new rT(t,e)}return n.beta=function(e){return t(+e)},n}(.85);function aT(t,e,n){t._context.bezierCurveTo(t._x1+t._k*(t._x2-t._x0),t._y1+t._k*(t._y2-t._y0),t._x2+t._k*(t._x1-e),t._y2+t._k*(t._y1-n),t._x2,t._y2);}function oT(t,e){this._context=t,this._k=(1-e)/6;}oT.prototype={areaStart:function(){this._line=0;},areaEnd:function(){this._line=NaN;},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0;},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:aT(this,this._x1,this._y1);}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line;},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2,this._x1=t,this._y1=e;break;case 2:this._point=3;default:aT(this,t,e);}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e;}};const sT=function t(e){function n(t){return new oT(t,e)}return n.tension=function(e){return t(+e)},n}(0);function cT(t,e){this._context=t,this._k=(1-e)/6;}cT.prototype={areaStart:Hw,areaEnd:Hw,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0;},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x3=t,this._y3=e;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=e);break;case 2:this._point=3,this._x5=t,this._y5=e;break;default:aT(this,t,e);}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e;}};const lT=function t(e){function n(t){return new cT(t,e)}return n.tension=function(e){return t(+e)},n}(0);function uT(t,e){this._context=t,this._k=(1-e)/6;}uT.prototype={areaStart:function(){this._line=0;},areaEnd:function(){this._line=NaN;},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0;},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line;},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:aT(this,t,e);}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e;}};const hT=function t(e){function n(t){return new uT(t,e)}return n.tension=function(e){return t(+e)},n}(0);function fT(t,e,n){var r=t._x1,i=t._y1,a=t._x2,o=t._y2;if(t._l01_a>zk){var s=2*t._l01_2a+3*t._l01_a*t._l12_a+t._l12_2a,c=3*t._l01_a*(t._l01_a+t._l12_a);r=(r*s-t._x0*t._l12_2a+t._x2*t._l01_2a)/c,i=(i*s-t._y0*t._l12_2a+t._y2*t._l01_2a)/c;}if(t._l23_a>zk){var l=2*t._l23_2a+3*t._l23_a*t._l12_a+t._l12_2a,u=3*t._l23_a*(t._l23_a+t._l12_a);a=(a*l+t._x1*t._l23_2a-e*t._l12_2a)/u,o=(o*l+t._y1*t._l23_2a-n*t._l12_2a)/u;}t._context.bezierCurveTo(r,i,a,o,t._x2,t._y2);}function dT(t,e){this._context=t,this._alpha=e;}dT.prototype={areaStart:function(){this._line=0;},areaEnd:function(){this._line=NaN;},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0;},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2);}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line;},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha));}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3;default:fT(this,t,e);}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e;}};const pT=function t(e){function n(t){return e?new dT(t,e):new oT(t,0)}return n.alpha=function(e){return t(+e)},n}(.5);function gT(t,e){this._context=t,this._alpha=e;}gT.prototype={areaStart:Hw,areaEnd:Hw,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0;},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);}},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha));}switch(this._point){case 0:this._point=1,this._x3=t,this._y3=e;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=e);break;case 2:this._point=3,this._x5=t,this._y5=e;break;default:fT(this,t,e);}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e;}};const yT=function t(e){function n(t){return e?new gT(t,e):new cT(t,0)}return n.alpha=function(e){return t(+e)},n}(.5);function mT(t,e){this._context=t,this._alpha=e;}mT.prototype={areaStart:function(){this._line=0;},areaEnd:function(){this._line=NaN;},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0;},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line;},point:function(t,e){if(t=+t,e=+e,this._point){var n=this._x2-t,r=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha));}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:fT(this,t,e);}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e;}};const bT=function t(e){function n(t){return e?new mT(t,e):new uT(t,0)}return n.alpha=function(e){return t(+e)},n}(.5);function vT(t){this._context=t;}function _T(t){return new vT(t)}function xT(t){return t<0?-1:1}function kT(t,e,n){var r=t._x1-t._x0,i=e-t._x1,a=(t._y1-t._y0)/(r||i<0&&-0),o=(n-t._y1)/(i||r<0&&-0),s=(a*i+o*r)/(r+i);return (xT(a)+xT(o))*Math.min(Math.abs(a),Math.abs(o),.5*Math.abs(s))||0}function wT(t,e){var n=t._x1-t._x0;return n?(3*(t._y1-t._y0)/n-e)/2:e}function TT(t,e,n){var r=t._x0,i=t._y0,a=t._x1,o=t._y1,s=(a-r)/3;t._context.bezierCurveTo(r+s,i+s*e,a-s,o-s*n,a,o);}function ET(t){this._context=t;}function CT(t){this._context=new ST(t);}function ST(t){this._context=t;}function AT(t){return new ET(t)}function MT(t){return new CT(t)}function NT(t){this._context=t;}function OT(t){var e,n,r=t.length-1,i=new Array(r),a=new Array(r),o=new Array(r);for(i[0]=0,a[0]=2,o[0]=t[0]+2*t[1],e=1;e<r-1;++e)i[e]=1,a[e]=4,o[e]=4*t[e]+2*t[e+1];for(i[r-1]=2,a[r-1]=7,o[r-1]=8*t[r-1]+t[r],e=1;e<r;++e)n=i[e]/a[e-1],a[e]-=n,o[e]-=n*o[e-1];for(i[r-1]=o[r-1]/a[r-1],e=r-2;e>=0;--e)i[e]=(o[e]-i[e+1])/a[e];for(a[r-1]=(t[r]+i[r-1])/2,e=0;e<r-1;++e)a[e]=2*t[e+1]-i[e+1];return [i,a]}function DT(t){return new NT(t)}function BT(t,e){this._context=t,this._t=e;}function LT(t){return new BT(t,.5)}function IT(t){return new BT(t,0)}function FT(t){return new BT(t,1)}function RT(t,e){if((i=t.length)>1)for(var n,r,i,a=1,o=t[e[0]],s=o.length;a<i;++a)for(r=o,o=t[e[a]],n=0;n<s;++n)o[n][1]+=o[n][0]=isNaN(r[n][1])?r[n][0]:r[n][1];}function PT(t){for(var e=t.length,n=new Array(e);--e>=0;)n[e]=e;return n}function jT(t,e){return t[e]}function zT(t){const e=[];return e.key=t,e}function YT(){var t=Dk([]),e=PT,n=RT,r=jT;function i(i){var a,o,s=Array.from(t.apply(this,arguments),zT),c=s.length,l=-1;for(const t of i)for(a=0,++l;a<c;++a)(s[a][l]=[0,+r(t,s[a].key,l,i)]).data=t;for(a=0,o=ew(e(s));a<c;++a)s[o[a]].index=a;return n(s,o),s}return i.keys=function(e){return arguments.length?(t="function"==typeof e?e:Dk(Array.from(e)),i):t},i.value=function(t){return arguments.length?(r="function"==typeof t?t:Dk(+t),i):r},i.order=function(t){return arguments.length?(e=null==t?PT:"function"==typeof t?t:Dk(Array.from(t)),i):e},i.offset=function(t){return arguments.length?(n=null==t?RT:t,i):n},i}function UT(t,e){if((r=t.length)>0){for(var n,r,i,a=0,o=t[0].length;a<o;++a){for(i=n=0;n<r;++n)i+=t[n][a][1]||0;if(i)for(n=0;n<r;++n)t[n][a][1]/=i;}RT(t,e);}}function $T(t,e){if((s=t.length)>0)for(var n,r,i,a,o,s,c=0,l=t[e[0]].length;c<l;++c)for(a=o=0,n=0;n<s;++n)(i=(r=t[e[n]][c])[1]-r[0])>0?(r[0]=a,r[1]=a+=i):i<0?(r[1]=o,r[0]=o+=i):(r[0]=0,r[1]=i);}function WT(t,e){if((n=t.length)>0){for(var n,r=0,i=t[e[0]],a=i.length;r<a;++r){for(var o=0,s=0;o<n;++o)s+=t[o][r][1]||0;i[r][1]+=i[r][0]=-s/2;}RT(t,e);}}function qT(t,e){if((i=t.length)>0&&(r=(n=t[e[0]]).length)>0){for(var n,r,i,a=0,o=1;o<r;++o){for(var s=0,c=0,l=0;s<i;++s){for(var u=t[e[s]],h=u[o][1]||0,f=(h-(u[o-1][1]||0))/2,d=0;d<s;++d){var p=t[e[d]];f+=(p[o][1]||0)-(p[o-1][1]||0);}c+=h,l+=f*h;}n[o-1][1]+=n[o-1][0]=a,c&&(a-=l/c);}n[o-1][1]+=n[o-1][0]=a,RT(t,e);}}function HT(t){var e=t.map(VT);return PT(t).sort((function(t,n){return e[t]-e[n]}))}function VT(t){for(var e,n=-1,r=0,i=t.length,a=-1/0;++n<i;)(e=+t[n][1])>a&&(a=e,r=n);return r}function GT(t){var e=t.map(XT);return PT(t).sort((function(t,n){return e[t]-e[n]}))}function XT(t){for(var e,n=0,r=-1,i=t.length;++r<i;)(e=+t[r][1])&&(n+=e);return n}function ZT(t){return GT(t).reverse()}function QT(t){var e,n,r=t.length,i=t.map(XT),a=HT(t),o=0,s=0,c=[],l=[];for(e=0;e<r;++e)n=a[e],o<s?(o+=i[n],c.push(n)):(s+=i[n],l.push(n));return l.reverse().concat(c)}function KT(t){return PT(t).reverse()}vT.prototype={areaStart:Hw,areaEnd:Hw,lineStart:function(){this._point=0;},lineEnd:function(){this._point&&this._context.closePath();},point:function(t,e){t=+t,e=+e,this._point?this._context.lineTo(t,e):(this._point=1,this._context.moveTo(t,e));}},ET.prototype={areaStart:function(){this._line=0;},areaEnd:function(){this._line=NaN;},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0;},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:TT(this,this._t0,wT(this,this._t0));}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line;},point:function(t,e){var n=NaN;if(e=+e,(t=+t)!==this._x1||e!==this._y1){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,TT(this,wT(this,n=kT(this,t,e)),n);break;default:TT(this,this._t0,n=kT(this,t,e));}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e,this._t0=n;}}},(CT.prototype=Object.create(ET.prototype)).point=function(t,e){ET.prototype.point.call(this,e,t);},ST.prototype={moveTo:function(t,e){this._context.moveTo(e,t);},closePath:function(){this._context.closePath();},lineTo:function(t,e){this._context.lineTo(e,t);},bezierCurveTo:function(t,e,n,r,i,a){this._context.bezierCurveTo(e,t,r,n,a,i);}},NT.prototype={areaStart:function(){this._line=0;},areaEnd:function(){this._line=NaN;},lineStart:function(){this._x=[],this._y=[];},lineEnd:function(){var t=this._x,e=this._y,n=t.length;if(n)if(this._line?this._context.lineTo(t[0],e[0]):this._context.moveTo(t[0],e[0]),2===n)this._context.lineTo(t[1],e[1]);else for(var r=OT(t),i=OT(e),a=0,o=1;o<n;++a,++o)this._context.bezierCurveTo(r[0][a],i[0][a],r[1][a],i[1][a],t[o],e[o]);(this._line||0!==this._line&&1===n)&&this._context.closePath(),this._line=1-this._line,this._x=this._y=null;},point:function(t,e){this._x.push(+t),this._y.push(+e);}},BT.prototype={areaStart:function(){this._line=0;},areaEnd:function(){this._line=NaN;},lineStart:function(){this._x=this._y=NaN,this._point=0;},lineEnd:function(){0<this._t&&this._t<1&&2===this._point&&this._context.lineTo(this._x,this._y),(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line>=0&&(this._t=1-this._t,this._line=1-this._line);},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,e),this._context.lineTo(t,e);else {var n=this._x*(1-this._t)+t*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,e);}}this._x=t,this._y=e;}};var JT="%Y-%m-%dT%H:%M:%S.%LZ",tE=Date.prototype.toISOString?function(t){return t.toISOString()}:dv(JT);const eE=tE;var nE=+new Date("2000-01-01T00:00:00.000Z")?function(t){var e=new Date(t);return isNaN(e)?null:e}:pv(JT);const rE=nE;function iE(t,e,n){var r=new Zr,i=e;return null==e?(r.restart(t,e,n),r):(r._restart=r.restart,r.restart=function(t,e,n){e=+e,n=null==n?Gr():+n,r._restart((function a(o){o+=i,r._restart(a,i+=e,n),t(o);}),e,n);},r.restart(t,e,n),r)}const aE=t=>()=>t;function oE(t,{sourceEvent:e,target:n,transform:r,dispatch:i}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:e,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:i}});}function sE(t,e,n){this.k=t,this.x=e,this.y=n;}sE.prototype={constructor:sE,scale:function(t){return 1===t?this:new sE(this.k*t,this.x,this.y)},translate:function(t,e){return 0===t&0===e?this:new sE(this.k,this.x+this.k*t,this.y+this.k*e)},apply:function(t){return [t[0]*this.k+this.x,t[1]*this.k+this.y]},applyX:function(t){return t*this.k+this.x},applyY:function(t){return t*this.k+this.y},invert:function(t){return [(t[0]-this.x)/this.k,(t[1]-this.y)/this.k]},invertX:function(t){return (t-this.x)/this.k},invertY:function(t){return (t-this.y)/this.k},rescaleX:function(t){return t.copy().domain(t.range().map(this.invertX,this).map(t.invert,t))},rescaleY:function(t){return t.copy().domain(t.range().map(this.invertY,this).map(t.invert,t))},toString:function(){return "translate("+this.x+","+this.y+") scale("+this.k+")"}};var cE=new sE(1,0,0);function lE(t){for(;!t.__zoom;)if(!(t=t.parentNode))return cE;return t.__zoom}function uE(t){t.stopImmediatePropagation();}function hE(t){t.preventDefault(),t.stopImmediatePropagation();}function fE(t){return !(t.ctrlKey&&"wheel"!==t.type||t.button)}function dE(){var t=this;return t instanceof SVGElement?(t=t.ownerSVGElement||t).hasAttribute("viewBox")?[[(t=t.viewBox.baseVal).x,t.y],[t.x+t.width,t.y+t.height]]:[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]:[[0,0],[t.clientWidth,t.clientHeight]]}function pE(){return this.__zoom||cE}function gE(t){return -t.deltaY*(1===t.deltaMode?.05:t.deltaMode?1:.002)*(t.ctrlKey?10:1)}function yE(){return navigator.maxTouchPoints||"ontouchstart"in this}function mE(t,e,n){var r=t.invertX(e[0][0])-n[0][0],i=t.invertX(e[1][0])-n[1][0],a=t.invertY(e[0][1])-n[0][1],o=t.invertY(e[1][1])-n[1][1];return t.translate(i>r?(r+i)/2:Math.min(0,r)||Math.max(0,i),o>a?(a+o)/2:Math.min(0,a)||Math.max(0,o))}function bE(){var t,e,n,r=fE,i=dE,a=mE,o=gE,s=yE,c=[0,1/0],l=[[-1/0,-1/0],[1/0,1/0]],u=250,h=ny,f=fe("start","zoom","end"),d=500,p=0,g=10;function y(t){t.property("__zoom",pE).on("wheel.zoom",w,{passive:!1}).on("mousedown.zoom",T).on("dblclick.zoom",E).filter(s).on("touchstart.zoom",C).on("touchmove.zoom",S).on("touchend.zoom touchcancel.zoom",A).style("-webkit-tap-highlight-color","rgba(0,0,0,0)");}function m(t,e){return (e=Math.max(c[0],Math.min(c[1],e)))===t.k?t:new sE(e,t.x,t.y)}function b(t,e,n){var r=e[0]-n[0]*t.k,i=e[1]-n[1]*t.k;return r===t.x&&i===t.y?t:new sE(t.k,r,i)}function v(t){return [(+t[0][0]+ +t[1][0])/2,(+t[0][1]+ +t[1][1])/2]}function _(t,e,n,r){t.on("start.zoom",(function(){x(this,arguments).event(r).start();})).on("interrupt.zoom end.zoom",(function(){x(this,arguments).event(r).end();})).tween("zoom",(function(){var t=this,a=arguments,o=x(t,a).event(r),s=i.apply(t,a),c=null==n?v(s):"function"==typeof n?n.apply(t,a):n,l=Math.max(s[1][0]-s[0][0],s[1][1]-s[0][1]),u=t.__zoom,f="function"==typeof e?e.apply(t,a):e,d=h(u.invert(c).concat(l/u.k),f.invert(c).concat(l/f.k));return function(t){if(1===t)t=f;else {var e=d(t),n=l/e[2];t=new sE(n,c[0]-e[0]*n,c[1]-e[1]*n);}o.zoom(null,t);}}));}function x(t,e,n){return !n&&t.__zooming||new k(t,e)}function k(t,e){this.that=t,this.args=e,this.active=0,this.sourceEvent=null,this.extent=i.apply(t,e),this.taps=0;}function w(t,...e){if(r.apply(this,arguments)){var n=x(this,e).event(t),i=this.__zoom,s=Math.max(c[0],Math.min(c[1],i.k*Math.pow(2,o.apply(this,arguments)))),u=Rr(t);if(n.wheel)n.mouse[0][0]===u[0]&&n.mouse[0][1]===u[1]||(n.mouse[1]=i.invert(n.mouse[0]=u)),clearTimeout(n.wheel);else {if(i.k===s)return;n.mouse=[u,i.invert(u)],li(this),n.start();}hE(t),n.wheel=setTimeout(h,150),n.zoom("mouse",a(b(m(i,s),n.mouse[0],n.mouse[1]),n.extent,l));}function h(){n.wheel=null,n.end();}}function T(t,...e){if(!n&&r.apply(this,arguments)){var i=t.currentTarget,o=x(this,e,!0).event(t),s=Mn(t.view).on("mousemove.zoom",f,!0).on("mouseup.zoom",d,!0),c=Rr(t,i),u=t.clientX,h=t.clientY;Ln(t.view),uE(t),o.mouse=[c,this.__zoom.invert(c)],li(this),o.start();}function f(t){if(hE(t),!o.moved){var e=t.clientX-u,n=t.clientY-h;o.moved=e*e+n*n>p;}o.event(t).zoom("mouse",a(b(o.that.__zoom,o.mouse[0]=Rr(t,i),o.mouse[1]),o.extent,l));}function d(t){s.on("mousemove.zoom mouseup.zoom",null),In(t.view,o.moved),hE(t),o.event(t).end();}}function E(t,...e){if(r.apply(this,arguments)){var n=this.__zoom,o=Rr(t.changedTouches?t.changedTouches[0]:t,this),s=n.invert(o),c=n.k*(t.shiftKey?.5:2),h=a(b(m(n,c),o,s),i.apply(this,e),l);hE(t),u>0?Mn(this).transition().duration(u).call(_,h,o,t):Mn(this).call(y.transform,h,o,t);}}function C(n,...i){if(r.apply(this,arguments)){var a,o,s,c,l=n.touches,u=l.length,h=x(this,i,n.changedTouches.length===u).event(n);for(uE(n),o=0;o<u;++o)c=[c=Rr(s=l[o],this),this.__zoom.invert(c),s.identifier],h.touch0?h.touch1||h.touch0[2]===c[2]||(h.touch1=c,h.taps=0):(h.touch0=c,a=!0,h.taps=1+!!t);t&&(t=clearTimeout(t)),a&&(h.taps<2&&(e=c[0],t=setTimeout((function(){t=null;}),d)),li(this),h.start());}}function S(t,...e){if(this.__zooming){var n,r,i,o,s=x(this,e).event(t),c=t.changedTouches,u=c.length;for(hE(t),n=0;n<u;++n)i=Rr(r=c[n],this),s.touch0&&s.touch0[2]===r.identifier?s.touch0[0]=i:s.touch1&&s.touch1[2]===r.identifier&&(s.touch1[0]=i);if(r=s.that.__zoom,s.touch1){var h=s.touch0[0],f=s.touch0[1],d=s.touch1[0],p=s.touch1[1],g=(g=d[0]-h[0])*g+(g=d[1]-h[1])*g,y=(y=p[0]-f[0])*y+(y=p[1]-f[1])*y;r=m(r,Math.sqrt(g/y)),i=[(h[0]+d[0])/2,(h[1]+d[1])/2],o=[(f[0]+p[0])/2,(f[1]+p[1])/2];}else {if(!s.touch0)return;i=s.touch0[0],o=s.touch0[1];}s.zoom("touch",a(b(r,i,o),s.extent,l));}}function A(t,...r){if(this.__zooming){var i,a,o=x(this,r).event(t),s=t.changedTouches,c=s.length;for(uE(t),n&&clearTimeout(n),n=setTimeout((function(){n=null;}),d),i=0;i<c;++i)a=s[i],o.touch0&&o.touch0[2]===a.identifier?delete o.touch0:o.touch1&&o.touch1[2]===a.identifier&&delete o.touch1;if(o.touch1&&!o.touch0&&(o.touch0=o.touch1,delete o.touch1),o.touch0)o.touch0[1]=this.__zoom.invert(o.touch0[0]);else if(o.end(),2===o.taps&&(a=Rr(a,this),Math.hypot(e[0]-a[0],e[1]-a[1])<g)){var l=Mn(this).on("dblclick.zoom");l&&l.apply(this,arguments);}}}return y.transform=function(t,e,n,r){var i=t.selection?t.selection():t;i.property("__zoom",pE),t!==i?_(t,e,n,r):i.interrupt().each((function(){x(this,arguments).event(r).start().zoom(null,"function"==typeof e?e.apply(this,arguments):e).end();}));},y.scaleBy=function(t,e,n,r){y.scaleTo(t,(function(){var t=this.__zoom.k,n="function"==typeof e?e.apply(this,arguments):e;return t*n}),n,r);},y.scaleTo=function(t,e,n,r){y.transform(t,(function(){var t=i.apply(this,arguments),r=this.__zoom,o=null==n?v(t):"function"==typeof n?n.apply(this,arguments):n,s=r.invert(o),c="function"==typeof e?e.apply(this,arguments):e;return a(b(m(r,c),o,s),t,l)}),n,r);},y.translateBy=function(t,e,n,r){y.transform(t,(function(){return a(this.__zoom.translate("function"==typeof e?e.apply(this,arguments):e,"function"==typeof n?n.apply(this,arguments):n),i.apply(this,arguments),l)}),null,r);},y.translateTo=function(t,e,n,r,o){y.transform(t,(function(){var t=i.apply(this,arguments),o=this.__zoom,s=null==r?v(t):"function"==typeof r?r.apply(this,arguments):r;return a(cE.translate(s[0],s[1]).scale(o.k).translate("function"==typeof e?-e.apply(this,arguments):-e,"function"==typeof n?-n.apply(this,arguments):-n),t,l)}),r,o);},k.prototype={event:function(t){return t&&(this.sourceEvent=t),this},start:function(){return 1==++this.active&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(t,e){return this.mouse&&"mouse"!==t&&(this.mouse[1]=e.invert(this.mouse[0])),this.touch0&&"touch"!==t&&(this.touch0[1]=e.invert(this.touch0[0])),this.touch1&&"touch"!==t&&(this.touch1[1]=e.invert(this.touch1[0])),this.that.__zoom=e,this.emit("zoom"),this},end:function(){return 0==--this.active&&(delete this.that.__zooming,this.emit("end")),this},emit:function(t){var e=Mn(this.that).datum();f.call(t,this.that,new oE(t,{sourceEvent:this.sourceEvent,target:y,type:t,transform:this.that.__zoom,dispatch:f}),e);}},y.wheelDelta=function(t){return arguments.length?(o="function"==typeof t?t:aE(+t),y):o},y.filter=function(t){return arguments.length?(r="function"==typeof t?t:aE(!!t),y):r},y.touchable=function(t){return arguments.length?(s="function"==typeof t?t:aE(!!t),y):s},y.extent=function(t){return arguments.length?(i="function"==typeof t?t:aE([[+t[0][0],+t[0][1]],[+t[1][0],+t[1][1]]]),y):i},y.scaleExtent=function(t){return arguments.length?(c[0]=+t[0],c[1]=+t[1],y):[c[0],c[1]]},y.translateExtent=function(t){return arguments.length?(l[0][0]=+t[0][0],l[1][0]=+t[1][0],l[0][1]=+t[0][1],l[1][1]=+t[1][1],y):[[l[0][0],l[0][1]],[l[1][0],l[1][1]]]},y.constrain=function(t){return arguments.length?(a=t,y):a},y.duration=function(t){return arguments.length?(u=+t,y):u},y.interpolate=function(t){return arguments.length?(h=t,y):h},y.on=function(){var t=f.on.apply(f,arguments);return t===f?y:t},y.clickDistance=function(t){return arguments.length?(p=(t=+t)*t,y):Math.sqrt(p)},y.tapDistance=function(t){return arguments.length?(g=+t,y):g},y}lE.prototype=sE.prototype;}},e={};function n(r){var i=e[r];if(void 0!==i)return i.exports;var a=e[r]={id:r,loaded:!1,exports:{}};return t[r].call(a.exports,a,a.exports,n),a.loaded=!0,a.exports}n.c=e,n.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return n.d(e,{a:e}),e},n.d=(t,e)=>{for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]});},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),n.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),n.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0});},n.nmd=t=>(t.paths=[],t.children||(t.children=[]),t);var r=n(n.s=6187).Z;
/**
* Copyright (C) 2021 THL A29 Limited, a Tencent company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var mermaidAPI = r === null || r === void 0 ? void 0 : r.mermaidAPI;
Cherry.usePlugin(MermaidCodeEngine, {
mermaidAPI: mermaidAPI,
theme: 'default',
sequence: {
useMaxWidth: false
}
});
Cherry.usePlugin(PlantUMLCodeEngine, {});
exports.MenuHookBase = MenuBase;
exports.SyntaxHookBase = SyntaxBase;
exports.default = Cherry;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=cherry-markdown.js.map